hexsha stringlengths 40 40 | size int64 19 11.4M | ext stringclasses 13
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 3 270 | max_stars_repo_name stringlengths 5 110 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count float64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 3 270 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 78 | max_issues_repo_licenses listlengths 1 9 | max_issues_count float64 1 67k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 3 270 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 78 | max_forks_repo_licenses listlengths 1 9 | max_forks_count float64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 19 11.4M | avg_line_length float64 1.93 229k | max_line_length int64 12 688k | alphanum_fraction float64 0.07 0.99 | matches listlengths 1 10 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
80f2aa5bdc99cb320153ec83d6f25c91e46d5641 | 4,357 | hpp | C++ | src/api/dcps/isocpp2/include/dds/sub/detail/TQueryImpl.hpp | agenihorganization/opensplice | 314d3a4538474f2b8e22acffe3c206f4ac38b66b | [
"Apache-2.0"
] | null | null | null | src/api/dcps/isocpp2/include/dds/sub/detail/TQueryImpl.hpp | agenihorganization/opensplice | 314d3a4538474f2b8e22acffe3c206f4ac38b66b | [
"Apache-2.0"
] | null | null | null | src/api/dcps/isocpp2/include/dds/sub/detail/TQueryImpl.hpp | agenihorganization/opensplice | 314d3a4538474f2b8e22acffe3c206f4ac38b66b | [
"Apache-2.0"
] | null | null | null | /*
* OpenSplice DDS
*
* This software and documentation are Copyright 2006 to TO_YEAR PrismTech
* Limited, its affiliated companies and licensors. All rights reserved.
*
* 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
*
* 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.
*
*/
#ifndef OSPL_DDS_SUB_DETAIL_QUERY_IMPL_HPP_
#define OSPL_DDS_SUB_DETAIL_QUERY_IMPL_HPP_
/**
* @file
*/
// Implementation
#include <dds/sub/TQuery.hpp>
template <typename DELEGATE>
dds::sub::TQuery<DELEGATE>::TQuery(
const dds::sub::AnyDataReader& dr,
const std::string& expression) :
dds::core::Reference<DELEGATE>(new DELEGATE(AnyDataReader(dr), expression))
{
}
/** @cond
* Somehow, these cause functions duplicates in doxygen documentation.
*/
template <typename DELEGATE>
template<typename FWIterator>
dds::sub::TQuery<DELEGATE>::TQuery(
const dds::sub::AnyDataReader& dr,
const std::string& expression,
const FWIterator& params_begin,
const FWIterator& params_end) :
dds::core::Reference<DELEGATE>(new DELEGATE(AnyDataReader(dr), expression))
{
ISOCPP_REPORT_STACK_DDS_BEGIN(dr);
for (FWIterator it = params_begin; it != params_end; ++it) {
add_parameter(*it);
}
}
/** @endcond */
template <typename DELEGATE>
dds::sub::TQuery<DELEGATE>::TQuery(
const dds::sub::AnyDataReader& dr,
const std::string& expression,
const std::vector<std::string>& params) :
dds::core::Reference<DELEGATE>(new DELEGATE(AnyDataReader(dr), expression, params))
{
}
template <typename DELEGATE>
const std::string& dds::sub::TQuery<DELEGATE>::expression() const
{
ISOCPP_REPORT_STACK_DDS_BEGIN(*this);
return this->delegate()->expression();
}
template <typename DELEGATE>
void dds::sub::TQuery<DELEGATE>::expression(const std::string& expr)
{
ISOCPP_REPORT_STACK_DDS_BEGIN(*this);
this->delegate()->expression(expr);
}
/**
* Provides the begin iterator to the parameter list.
*/
template <typename DELEGATE>
typename dds::sub::TQuery<DELEGATE>::const_iterator dds::sub::TQuery<DELEGATE>::begin() const
{
ISOCPP_REPORT_STACK_DDS_BEGIN(*this);
return this->delegate()->begin();
}
/**
* The end iterator to the parameter list.
*/
template <typename DELEGATE>
typename dds::sub::TQuery<DELEGATE>::const_iterator dds::sub::TQuery<DELEGATE>::end() const
{
ISOCPP_REPORT_STACK_DDS_BEGIN(*this);
return this->delegate()->end();
}
/**
* Provides the begin iterator to the parameter list.
*/
template <typename DELEGATE>
typename dds::sub::TQuery<DELEGATE>::iterator dds::sub::TQuery<DELEGATE>::begin()
{
ISOCPP_REPORT_STACK_DDS_BEGIN(*this);
return this->delegate()->begin();
}
/**
* The end iterator to the parameter list.
*/
template <typename DELEGATE>
typename dds::sub::TQuery<DELEGATE>::iterator dds::sub::TQuery<DELEGATE>::end()
{
ISOCPP_REPORT_STACK_DDS_BEGIN(*this);
return this->delegate()->end();
}
template <typename DELEGATE>
template<typename FWIterator>
void dds::sub::TQuery<DELEGATE>::parameters(
const FWIterator& begin,
const FWIterator end)
{
ISOCPP_REPORT_STACK_DDS_BEGIN(*this);
for (FWIterator it = begin; it != end; ++it) {
add_parameter(*it);
}
}
template <typename DELEGATE>
void dds::sub::TQuery<DELEGATE>::add_parameter(
const std::string& param)
{
ISOCPP_REPORT_STACK_DDS_BEGIN(*this);
this->delegate()->add_parameter(param);
}
template <typename DELEGATE>
uint32_t dds::sub::TQuery<DELEGATE>::parameters_length() const
{
ISOCPP_REPORT_STACK_DDS_BEGIN(*this);
return this->delegate()->parameters_length();
}
template <typename DELEGATE>
const dds::sub::AnyDataReader&
dds::sub::TQuery<DELEGATE>::data_reader() const
{
ISOCPP_REPORT_STACK_DDS_BEGIN(*this);
return this->delegate()->data_reader();
}
#endif /* OSPL_DDS_SUB_DETAIL_QUERY_IMPL_HPP_ */
| 25.479532 | 93 | 0.707597 | [
"vector"
] |
80f35cd7994ce76580eb0fe5d2d2e65a44e1e2a7 | 77,076 | cc | C++ | tensorflow/core/grappler/optimizers/auto_mixed_precision.cc | juheerizwana/tensorflow | eb67de2735cb0350c2bac9fbdf6635670aabd5ae | [
"Apache-2.0"
] | 2 | 2018-06-04T09:14:10.000Z | 2019-02-10T10:39:44.000Z | tensorflow/core/grappler/optimizers/auto_mixed_precision.cc | Hunterlcf/tensorflow | c7f3bb27278a2392b55cde6e3bd6714556511f9d | [
"Apache-2.0"
] | null | null | null | tensorflow/core/grappler/optimizers/auto_mixed_precision.cc | Hunterlcf/tensorflow | c7f3bb27278a2392b55cde6e3bd6714556511f9d | [
"Apache-2.0"
] | 1 | 2021-02-06T12:37:08.000Z | 2021-02-06T12:37:08.000Z | /* Copyright 2017 The TensorFlow Authors. All Rights Reserved.
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
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 "tensorflow/core/grappler/optimizers/auto_mixed_precision.h"
#include <fstream>
#include "absl/container/flat_hash_map.h"
#include "absl/container/flat_hash_set.h"
#include "tensorflow/core/framework/attr_value_util.h"
#include "tensorflow/core/framework/node_def.pb.h"
#include "tensorflow/core/framework/op.h"
#include "tensorflow/core/framework/op_kernel.h"
#include "tensorflow/core/framework/types.h"
#include "tensorflow/core/grappler/clusters/cluster.h"
#include "tensorflow/core/grappler/costs/virtual_placer.h"
#include "tensorflow/core/grappler/devices.h"
#include "tensorflow/core/grappler/grappler_item.h"
#include "tensorflow/core/grappler/mutable_graph_view.h"
#include "tensorflow/core/grappler/op_types.h"
#include "tensorflow/core/grappler/optimizers/auto_mixed_precision_lists.h"
#include "tensorflow/core/grappler/optimizers/custom_graph_optimizer_registry.h"
#include "tensorflow/core/grappler/utils.h"
#include "tensorflow/core/lib/io/path.h"
#include "tensorflow/core/lib/strings/numbers.h"
#include "tensorflow/core/lib/strings/str_util.h"
#include "tensorflow/core/lib/strings/strcat.h"
#include "tensorflow/core/platform/logging.h"
#include "tensorflow/core/util/env_var.h"
namespace tensorflow {
namespace grappler {
namespace {
const std::pair<int, int> kMinGPUArch = {7, 0};
const char kSuffix[] = "AutoMixedPrecision";
const char kCastToFp16[] = "CastToFp16";
const char kCastToFp32[] = "CastToFp32";
// Instances of this class represent unique type attribute identifiers within a
// node. It handles regular type attributes, list type attributes (where
// type_index is set to the index in the type list), and fixed types.
struct TypeAttrId {
static const int kSingleType = -1;
explicit TypeAttrId(const string& _attr_name, int _type_index = kSingleType)
: attr_name(_attr_name),
type_index(_type_index),
fixed_type(DT_INVALID) {}
explicit TypeAttrId(DataType _fixed_type)
: attr_name(), type_index(kSingleType), fixed_type(_fixed_type) {}
bool operator==(const TypeAttrId& other) const {
return attr_name == other.attr_name && type_index == other.type_index &&
fixed_type == other.fixed_type;
}
bool operator<(const TypeAttrId& other) const {
return std::make_tuple(attr_name, type_index, fixed_type) <
std::make_tuple(other.attr_name, other.type_index, other.fixed_type);
}
template <typename H>
friend H AbslHashValue(H h, const TypeAttrId& ta) {
return H::combine(std::move(h), ta.attr_name, ta.type_index, ta.fixed_type);
}
string DebugString() const {
if (!attr_name.empty()) {
if (type_index == kSingleType) {
return attr_name;
} else {
return strings::StrCat(attr_name, "[", type_index, "]");
}
} else {
return tensorflow::DataTypeString(fixed_type);
}
}
string attr_name;
// If attr_name is a list(type), this is the index into the list. Otherwise
// this is kSingleType.
int type_index;
DataType fixed_type;
};
// Returns the data type of the given type attribute, or DT_INVALID if the type
// attribute is invalid.
DataType GetDataType(const NodeDef& node, const TypeAttrId& type_attr) {
if (type_attr.attr_name.empty()) {
return type_attr.fixed_type;
}
if (!node.attr().count(type_attr.attr_name)) {
return DT_INVALID;
}
const AttrValue& attr_value = node.attr().at(type_attr.attr_name);
if (type_attr.type_index == TypeAttrId::kSingleType) {
return attr_value.type();
} else {
if (type_attr.type_index < 0 ||
type_attr.type_index >= attr_value.list().type_size()) {
return DT_INVALID;
}
return attr_value.list().type(type_attr.type_index);
}
}
// Sets the data type of the given type attribute. Returns false if the type
// attribute is invalid, otherwise true.
bool SetDataType(NodeDef* node, const TypeAttrId& type_attr, DataType type) {
if (type_attr.attr_name.empty() || !node->attr().count(type_attr.attr_name)) {
return false;
}
AttrValue& attr_value = node->mutable_attr()->at(type_attr.attr_name);
if (type_attr.type_index == TypeAttrId::kSingleType) {
attr_value.set_type(type);
} else {
if (type_attr.type_index < 0 ||
type_attr.type_index >= attr_value.list().type_size()) {
return false;
}
attr_value.mutable_list()->set_type(type_attr.type_index, type);
}
return true;
}
std::vector<std::pair<int, int>> ArgDefIndexes(const NodeDef& node, int arg_idx,
const OpDef::ArgDef& arg_def) {
std::vector<std::pair<int, int>> argdef_inds;
if (!arg_def.type_list_attr().empty()) {
int num_types = node.attr().at(arg_def.type_list_attr()).list().type_size();
for (int type_idx = 0; type_idx < num_types; ++type_idx) {
argdef_inds.push_back({arg_idx, type_idx});
}
} else {
int num_repeat = 1;
if (node.attr().count(arg_def.number_attr())) {
num_repeat = node.attr().at(arg_def.number_attr()).i();
}
argdef_inds.insert(argdef_inds.end(), num_repeat, {arg_idx, -1});
}
return argdef_inds;
}
// Returns a pair (arg_index, type_index) for each input to the node, where
// arg_index is the index of the input_arg in op_def and type_index is the index
// of the type in type_list_attr (only defined for list arguments).
std::vector<std::pair<int, int>> InputPortArgDefIndexes(const NodeDef& node,
const OpDef& op_def) {
std::vector<std::pair<int, int>> argdef_inds;
argdef_inds.reserve(op_def.input_arg_size()); // Final size may differ.
for (int arg_idx = 0; arg_idx < op_def.input_arg_size(); ++arg_idx) {
const OpDef::ArgDef& arg_def = op_def.input_arg(arg_idx);
auto arg_results = ArgDefIndexes(node, arg_idx, arg_def);
argdef_inds.insert(argdef_inds.end(), arg_results.begin(),
arg_results.end());
}
return argdef_inds;
}
// Returns a pair (arg_index, type_index) for each output to the node, where
// arg_index is the index of the output_arg in op_def and type_index is the
// index of the type in type_list_attr (only defined for list arguments).
std::vector<std::pair<int, int>> OutputPortArgDefIndexes(const NodeDef& node,
const OpDef& op_def) {
std::vector<std::pair<int, int>> argdef_inds;
argdef_inds.reserve(op_def.output_arg_size()); // Final size may differ.
for (int arg_idx = 0; arg_idx < op_def.output_arg_size(); ++arg_idx) {
const OpDef::ArgDef& arg_def = op_def.output_arg(arg_idx);
auto arg_results = ArgDefIndexes(node, arg_idx, arg_def);
argdef_inds.insert(argdef_inds.end(), arg_results.begin(),
arg_results.end());
}
return argdef_inds;
}
TypeAttrId GetTypeAttrId(const OpDef::ArgDef& arg_def, int arg_type_index) {
if (!arg_def.type_list_attr().empty()) {
return TypeAttrId(arg_def.type_list_attr(), arg_type_index);
} else if (!arg_def.type_attr().empty()) {
return TypeAttrId(arg_def.type_attr());
} else {
return TypeAttrId(arg_def.type());
}
}
std::vector<int> NonControlInputs(const NodeDef& node) {
std::vector<int> pos;
for (int i = 0; i < node.input_size(); i++) {
if (!IsControlInput(node.input(i))) {
pos.push_back(i);
}
}
return pos;
}
// A utility class to lookup node type attributes and type attribute <->
// input/output port mappings.
class NodeTypeAttrMap {
public:
NodeTypeAttrMap() {}
explicit NodeTypeAttrMap(const GraphDef& graph) { TF_CHECK_OK(Init(graph)); }
Status Init(const GraphDef& graph) {
if (graph_ != nullptr) {
return errors::InvalidArgument("NodeTypeAttrMap is already initialized.");
}
graph_ = &graph;
function_library_.reset(
new FunctionLibraryDefinition(OpRegistry::Global(), graph.library()));
for (const NodeDef& node : graph.node()) {
TF_RETURN_IF_ERROR(AddNode(node));
}
return Status::OK();
}
bool is_initialized() const { return graph_ != nullptr; }
// Returns the set of all type attributes in the given node.
absl::flat_hash_set<TypeAttrId> GetTypeAttrs(const NodeDef& node) const {
DCHECK(is_initialized()) << "NodeTypeAttrMap is not initialized";
absl::flat_hash_set<TypeAttrId> type_attrs;
const auto iter = type2io_.find(&node);
CHECK(iter != type2io_.end()); // Crash Ok
for (const auto& key_value : iter->second) {
type_attrs.insert(key_value.first);
}
return type_attrs;
}
const absl::flat_hash_set<int>& GetInputPorts(
const NodeDef& node, const TypeAttrId& type_attr) const {
DCHECK(is_initialized()) << "NodeTypeAttrMap is not initialized";
return type2io_.at(&node).at(type_attr).first;
}
const absl::flat_hash_set<int>& GetOutputPorts(
const NodeDef& node, const TypeAttrId& type_attr) const {
DCHECK(is_initialized()) << "NodeTypeAttrMap is not initialized";
return type2io_.at(&node).at(type_attr).second;
}
TypeAttrId GetInputTypeAttr(const NodeDef& node, int port) const {
DCHECK(is_initialized()) << "NodeTypeAttrMap is not initialized";
auto type_vec = io2type_.at(&node).first;
CHECK_GE(port, 0); // Crash Ok
CHECK_LT(port, type_vec.size()); // Crash Ok
return type_vec[port];
}
TypeAttrId GetOutputTypeAttr(const NodeDef& node, int port) const {
DCHECK(is_initialized()) << "NodeTypeAttrMap is not initialized";
auto type_vec = io2type_.at(&node).second;
CHECK_GE(port, 0); // Crash Ok
CHECK_LT(port, type_vec.size()); // Crash Ok
return type_vec[port];
}
private:
Status AddNode(const NodeDef& node) {
const OpDef* op_def_ptr = nullptr;
TF_RETURN_IF_ERROR(function_library_->LookUpOpDef(node.op(), &op_def_ptr));
const OpDef& op_def = *op_def_ptr;
auto& type2io_entry = type2io_[&node];
auto& io2type_entry = io2type_[&node];
auto input_arg_inds = InputPortArgDefIndexes(node, op_def);
if (NonControlInputs(node).size() != input_arg_inds.size()) {
return errors::InvalidArgument(
"Expected ", node.op(), " node ", node.name(), " to have ",
input_arg_inds.size(), " non-control input(s), but got ",
node.input_size());
}
// Note that the mappings generated here include inputs/outputs with fixed
// types. This makes the mappings complete (all inputs and outputs are
// included), and allows the graph rewriter to propagate black paint
// from/through ops with fixed types.
io2type_entry.first.reserve(input_arg_inds.size());
for (int i = 0; i < static_cast<int>(input_arg_inds.size()); ++i) {
const auto& arg_inds = input_arg_inds[i];
const OpDef::ArgDef& arg_def = op_def.input_arg(arg_inds.first);
TypeAttrId type_attr = GetTypeAttrId(arg_def, arg_inds.second);
if (!type_attr.attr_name.empty() &&
!node.attr().count(type_attr.attr_name)) {
return errors::InvalidArgument("Type attribute ", type_attr.attr_name,
" is not present in node ", node.name());
}
type2io_entry[type_attr].first.insert(i);
io2type_entry.first.push_back(type_attr);
}
auto output_arg_inds = OutputPortArgDefIndexes(node, op_def);
io2type_entry.second.reserve(output_arg_inds.size());
for (int i = 0; i < static_cast<int>(output_arg_inds.size()); ++i) {
const auto& arg_inds = output_arg_inds[i];
const OpDef::ArgDef& arg_def = op_def.output_arg(arg_inds.first);
TypeAttrId type_attr = GetTypeAttrId(arg_def, arg_inds.second);
if (!type_attr.attr_name.empty() &&
!node.attr().count(type_attr.attr_name)) {
return errors::InvalidArgument("Type attribute ", type_attr.attr_name,
" is not present in node ", node.name());
}
type2io_entry[type_attr].second.insert(i);
io2type_entry.second.push_back(type_attr);
}
// Also ensure that type attributes that aren't associated with any inputs
// or outputs (e.g., StackV2's elem_type) are added to the map.
for (const auto& attr : node.attr()) {
const string& attr_name = attr.first;
if (!attr_name.empty() && attr_name[0] == '_') continue;
const AttrValue& attr_value = attr.second;
const OpDef::AttrDef* attr_def = FindAttr(attr_name, op_def);
if (!attr_def) {
return errors::InvalidArgument("AttrDef not found for attribute ",
attr_name, " of node ", node.name());
}
if (attr_def->type() == "type") {
type2io_entry[TypeAttrId(attr_name)];
} else if (attr_def->type() == "list(type)") {
for (int i = 0; i < attr_value.list().type_size(); ++i) {
type2io_entry[TypeAttrId(attr_name, i)];
}
}
}
return Status::OK();
}
// WARN: `graph_` must outlive this object (node pointers must remain valid).
const GraphDef* graph_ = nullptr; // do not own
std::unique_ptr<FunctionLibraryDefinition> function_library_;
typedef absl::flat_hash_set<int> IntSet;
// Maps a type attr id -> (input port set, output port set)
typedef absl::flat_hash_map<TypeAttrId, std::pair<IntSet, IntSet>> Type2IOMap;
// Maps a node -> type attr mapping
absl::flat_hash_map<const NodeDef*, Type2IOMap> type2io_;
// Maps a port -> type attr id
typedef std::vector<TypeAttrId> TypeAttrIdVec;
// Maps a node -> (input port mapping, output port mapping)
absl::flat_hash_map<const NodeDef*, std::pair<TypeAttrIdVec, TypeAttrIdVec>>
io2type_;
};
struct NodeTypeId {
NodeTypeId(const NodeDef* _node, const TypeAttrId& _type_attr)
: node(_node), type_attr(_type_attr) {}
const NodeDef* node;
TypeAttrId type_attr;
bool operator==(const NodeTypeId& other) const {
return node == other.node && type_attr == other.type_attr;
}
template <typename H>
friend H AbslHashValue(H h, const NodeTypeId& nt) {
return H::combine(std::move(h), nt.node, nt.type_attr);
}
};
struct NodeTypeIdEdge {
NodeTypeIdEdge(const NodeTypeId& _src, const NodeTypeId& _dst)
: src(_src), dst(_dst) {}
NodeTypeId src;
NodeTypeId dst;
};
// TODO(benbarsdell): Investigate whether the existing GraphTopologyView can be
// used instead of this modified version.
// This is just like GraphTopologyView but with (NodeDef, TypeAttrId) pairs as
// the vertices instead of just NodeDef.
// For example, if node A has output A:0 with TypeAttrId 'T', and node B has
// input B:0 with TypeAttrId 'U', and input B:0 connects to output A:0, there
// will be an edge from (A, T) to (B, U).
class GraphTypeTopologyView {
public:
GraphTypeTopologyView() = default;
explicit GraphTypeTopologyView(bool skip_invalid_edges)
: skip_invalid_edges_(skip_invalid_edges) {}
// Initialize graph topology view from the graph. It's possible to pass
// additional edges that do not exist in a graph, but must be respected when
// computing graph topology. Example: Tensorflow runtime allows concurrent
// execution of dequeue/enqueue ops from the same queue resource, but we might
// want to enforce ordering between them for the purpose of graph analysis.
Status InitializeFromGraph(const GraphDef& graph,
const NodeTypeAttrMap& node_type_map,
absl::Span<const NodeTypeIdEdge> ephemeral_edges);
Status InitializeFromGraph(const GraphDef& graph,
const NodeTypeAttrMap& node_type_map);
bool is_initialized() const { return graph_ != nullptr; }
int num_nodes() const { return num_nodes_; }
const GraphDef* graph() const { return graph_; }
// Returns true iff the node exists in the underlying graph.
bool HasNode(absl::string_view node_name, const TypeAttrId& type_attr) const;
// Finds a node by name or returns `nullptr` if it's not in the graph.
const NodeTypeId* GetNode(absl::string_view node_name,
const TypeAttrId& type_attr) const;
// Returns a node corresponding to the given node index.
const NodeTypeId* GetNode(int node_idx) const;
// Returns a node index for the given node name, if the name exists in the
// underlying graph. Otherwise returns empty optional.
const absl::optional<int> GetNodeIndex(absl::string_view node_name,
const TypeAttrId& type_attr) const;
// Returns a node index for the given node, if the node belongs to the
// underlying graph. Otherwise returns empty optional.
const absl::optional<int> GetNodeIndex(const NodeTypeId& node) const;
// Returns all the node indexes that are in the direct fanin of the given
// node. If the `node_idx` is outside of [0, num_nodes_) returns empty vector.
const absl::InlinedVector<int, 4>& GetFanin(int node_idx) const;
// Returns all the node indexes that are in the direct fanout of the given
// node. If the `node_idx` is outside of [0, num_nodes_) returns empty vector.
const absl::InlinedVector<int, 2>& GetFanout(int node_idx) const;
private:
// The key type used to uniquely identify a type attribute on a node.
struct NodeTypeKey : public std::pair<absl::string_view, TypeAttrId> {
typedef std::pair<absl::string_view, TypeAttrId> Base;
// Inherit the set of constructors.
using Base::pair;
template <typename H>
friend H AbslHashValue(H h, const NodeTypeKey& nt) {
return H::combine(std::move(h), nt.first, nt.second);
}
};
// If true, all invalid edges and inputs (srd, dst or input node not found in
// a graph) will be skipped, otherwise initialization will fail with error.
bool skip_invalid_edges_ = false;
// WARN: `graph_` must outlive this object and graph nodes must not be
// destructed, because node names captured with absl::string_view.
const GraphDef* graph_ = nullptr; // do not own
int num_nodes_ = 0;
std::vector<NodeTypeId> node_type_attrs_;
absl::flat_hash_map<absl::string_view, int> node_name_to_index_;
absl::flat_hash_map<NodeTypeKey, int> node_type_name_to_index_;
std::vector<absl::InlinedVector<int, 4>> fanins_;
std::vector<absl::InlinedVector<int, 2>> fanouts_;
// We need a valid reference to return from GetFanin/GetFanout if the
// `node_idx` argument is outside of the [0, num_nodes_) range.
absl::InlinedVector<int, 4> empty_fanin_;
absl::InlinedVector<int, 2> empty_fanout_;
};
template <typename T>
inline void SortAndRemoveDuplicates(T* v) {
std::sort(v->begin(), v->end());
v->erase(std::unique(v->begin(), v->end()), v->end());
}
Status GraphTypeTopologyView::InitializeFromGraph(
const GraphDef& graph, const NodeTypeAttrMap& node_type_map,
absl::Span<const NodeTypeIdEdge> ephemeral_edges) {
if (graph_ != nullptr) {
return errors::InvalidArgument(
"GraphTypeTopologyView is already initialized.");
}
graph_ = &graph;
int num_nodedefs = graph.node_size();
node_name_to_index_.rehash(num_nodedefs);
// Build maps from name to index.
node_type_attrs_.reserve(num_nodedefs); // Only approximate.
node_type_name_to_index_.rehash(num_nodedefs); // Only approximate.
for (int node_idx = 0; node_idx < num_nodedefs; ++node_idx) {
const NodeDef& node = graph.node(node_idx);
node_name_to_index_.emplace(node.name(), node_idx);
for (const TypeAttrId& type_attr : node_type_map.GetTypeAttrs(node)) {
int node_type_idx = node_type_attrs_.size();
node_type_name_to_index_.emplace(NodeTypeKey(node.name(), type_attr),
node_type_idx);
node_type_attrs_.emplace_back(&node, type_attr);
}
}
num_nodes_ = node_type_attrs_.size();
fanins_.resize(num_nodes_);
fanouts_.resize(num_nodes_);
// 1. Add ephemeral edges to the adjacency lists.
for (const NodeTypeIdEdge& edge : ephemeral_edges) {
const auto src = node_name_to_index_.find(edge.src.node->name());
const bool valid_src = src != node_name_to_index_.end();
if (!valid_src) {
const string error_message =
absl::StrCat("Non-existent src node: ", edge.src.node->name());
if (skip_invalid_edges_) {
VLOG(0) << "Skip error: " << error_message;
} else {
return errors::InvalidArgument(error_message);
}
}
const auto dst = node_name_to_index_.find(edge.dst.node->name());
const bool valid_dst = dst != node_name_to_index_.end();
if (!valid_dst) {
const string error_message =
absl::StrCat("Non-existent dst node: ", edge.dst.node->name());
if (skip_invalid_edges_) {
VLOG(0) << "Skip error: " << error_message;
} else {
return errors::InvalidArgument(error_message);
}
}
if (valid_dst && valid_src) {
// TODO(benbarsdell): Check for failure.
int src_node_type_idx = node_type_name_to_index_.at(
NodeTypeKey(edge.src.node->name(), edge.src.type_attr));
int dst_node_type_idx = node_type_name_to_index_.at(
NodeTypeKey(edge.dst.node->name(), edge.dst.type_attr));
fanins_[dst_node_type_idx].push_back(src_node_type_idx);
fanouts_[src_node_type_idx].push_back(dst_node_type_idx);
}
}
// 2. Add graph edges to the adjacency lists.
for (int node_type_idx = 0; node_type_idx < num_nodes_; ++node_type_idx) {
const NodeTypeId& node_type = node_type_attrs_.at(node_type_idx);
auto input_ports =
node_type_map.GetInputPorts(*node_type.node, node_type.type_attr);
fanins_[node_type_idx].reserve(input_ports.size());
for (int port : input_ports) {
const string& input = node_type.node->input(port);
TensorId tensor = ParseTensorName(input);
const auto it = node_name_to_index_.find(tensor.node());
const bool valid_input = it != node_name_to_index_.end();
if (!valid_input) {
const string error_message = absl::StrCat(
"Non-existent input ", input, " in node ", node_type.node->name());
if (skip_invalid_edges_) {
VLOG(3) << "Skip error: " << error_message;
} else {
return errors::InvalidArgument(error_message);
}
}
if (valid_input) {
const int input_idx = it->second;
const NodeDef& input_node = graph_->node(input_idx);
TypeAttrId input_type_attr =
node_type_map.GetOutputTypeAttr(input_node, tensor.index());
const auto it2 = node_type_name_to_index_.find(
NodeTypeKey(input_node.name(), input_type_attr));
if (it2 == node_type_name_to_index_.end()) {
if (!skip_invalid_edges_) {
return errors::InvalidArgument("Did not find type attr ",
input_type_attr.DebugString(),
" in node ", input_node.name());
}
continue;
}
int input_node_type_idx = it2->second;
fanins_[node_type_idx].push_back(input_node_type_idx);
fanouts_[input_node_type_idx].push_back(node_type_idx);
}
}
// Dedup the input list while it's still hot in cache.
SortAndRemoveDuplicates(&fanins_[node_type_idx]);
}
// Dedup outputs for all the graph nodes.
for (int node_type_idx = 0; node_type_idx < num_nodes_; ++node_type_idx) {
SortAndRemoveDuplicates(&fanouts_[node_type_idx]);
}
return Status::OK();
}
Status GraphTypeTopologyView::InitializeFromGraph(
const GraphDef& graph, const NodeTypeAttrMap& node_type_map) {
return InitializeFromGraph(graph, node_type_map,
absl::Span<const NodeTypeIdEdge>());
}
bool GraphTypeTopologyView::HasNode(absl::string_view node_name,
const TypeAttrId& type_attr) const {
DCHECK(is_initialized()) << "GraphTypeTopologyView is not initialized";
NodeTypeKey key(node_name, type_attr);
const auto it = node_type_name_to_index_.find(key);
return it != node_type_name_to_index_.end();
}
const NodeTypeId* GraphTypeTopologyView::GetNode(
absl::string_view node_name, const TypeAttrId& type_attr) const {
DCHECK(is_initialized()) << "GraphTypeTopologyView is not initialized";
NodeTypeKey key(node_name, type_attr);
const auto it = node_type_name_to_index_.find(key);
return it == node_type_name_to_index_.end()
? nullptr
: &node_type_attrs_.at(it->second);
}
const NodeTypeId* GraphTypeTopologyView::GetNode(int node_idx) const {
DCHECK(is_initialized()) << "GraphTypeTopologyView is not initialized";
DCHECK(node_idx >= 0 && node_idx < num_nodes_) << "node_idx is out of range";
return &node_type_attrs_.at(node_idx);
}
const absl::optional<int> GraphTypeTopologyView::GetNodeIndex(
absl::string_view node_name, const TypeAttrId& type_attr) const {
DCHECK(is_initialized()) << "GraphTypeTopologyView is not initialized";
NodeTypeKey key(node_name, type_attr);
const auto it = node_type_name_to_index_.find(key);
DCHECK(it != node_type_name_to_index_.end())
<< "Node doesn't exist in a graph";
return it == node_type_name_to_index_.end() ? absl::nullopt
: absl::make_optional(it->second);
}
const absl::optional<int> GraphTypeTopologyView::GetNodeIndex(
const NodeTypeId& node) const {
return GetNodeIndex(node.node->name(), node.type_attr);
}
const absl::InlinedVector<int, 4>& GraphTypeTopologyView::GetFanin(
int node_idx) const {
DCHECK(is_initialized()) << "GraphTypeTopologyView is not initialized";
const bool is_valid_node_idx = node_idx >= 0 && node_idx < num_nodes_;
DCHECK(is_valid_node_idx) << "node_idx is out of range";
return is_valid_node_idx ? fanins_[node_idx] : empty_fanin_;
}
const absl::InlinedVector<int, 2>& GraphTypeTopologyView::GetFanout(
int node_idx) const {
DCHECK(is_initialized()) << "GraphTypeTopologyView is not initialized";
const bool is_valid_node_idx = node_idx >= 0 && node_idx < num_nodes_;
DCHECK(is_valid_node_idx) << "node_idx is out of range";
return is_valid_node_idx ? fanouts_[node_idx] : empty_fanout_;
}
enum class TypeTraversalDirection {
kFollowInputs,
kFollowOutputs,
kFollowInputsAndOutputs,
};
// Encapsulate DFS callbacks that will be called during the graph traversal.
//
// If non-empty, the `pre_order` and `post_order` functors will be called on
// each reachable node (including the `from` nodes) in pre and post order. If
// loops are found, the `on_back_edge` functor will be called on the
// corresponding back edges. Moreover, the pre and post order will assume that
// these back edges will be cut.
struct DfsTypeCallbacks {
DfsTypeCallbacks() = default;
DfsTypeCallbacks(std::function<void(int)> pre, std::function<void(int)> post,
std::function<void(int, int)> back_edge)
: pre_order(std::move(pre)),
post_order(std::move(post)),
on_back_edge(std::move(back_edge)) {}
static DfsTypeCallbacks PreOrder(std::function<void(int)> pre) {
return DfsTypeCallbacks(std::move(pre), nullptr, nullptr);
}
static DfsTypeCallbacks PostOrder(std::function<void(int)> post) {
return DfsTypeCallbacks(nullptr, std::move(post), nullptr);
}
std::function<void(int)> pre_order;
std::function<void(int)> post_order;
std::function<void(int, int)> on_back_edge;
};
// Encapsulate DFS predicates for traversing the graph.
//
// The `enter` predicate decides if traversal should enter the node, and the
// `advance` predicate decides if the traversal should follow inputs/outputs
// from the node.
//
// If predicates are empty (default initialized), it's assumed that we can enter
// into any node and advance from any node respectively.
struct DfsTypePredicates {
DfsTypePredicates() = default;
DfsTypePredicates(std::function<bool(int)> enter,
std::function<bool(int)> advance)
: enter(std::move(enter)), advance(std::move(advance)) {}
static DfsTypePredicates Enter(std::function<bool(int)> enter) {
return DfsTypePredicates(std::move(enter), nullptr);
}
static DfsTypePredicates Advance(std::function<bool(int)> advance) {
return DfsTypePredicates(nullptr, std::move(advance));
}
std::function<bool(int)> enter;
std::function<bool(int)> advance;
};
struct DfsStackElem {
DfsStackElem(int node, bool children_visited, int src)
: node(node), children_visited(children_visited), src(src) {}
explicit DfsStackElem(int node) : DfsStackElem(node, false, -1) {}
// Index of the node in the graph ∊ [0, num_nodes).
int node;
// `True` if visited all the input/output nodes (pushed all input/output nodes
// to the stack).
bool children_visited;
// Index of the node in the graph, from which we entered the `node`.
int src;
};
enum class NodeState { kNotVisited, kVisiting, kDone };
void DfsTypeTraversal(const GraphTypeTopologyView& graph_type_view,
const absl::Span<const NodeTypeId* const> from,
const TypeTraversalDirection direction,
const DfsTypePredicates& predicates,
const DfsTypeCallbacks& callbacks) {
std::vector<DfsStackElem> stack;
stack.reserve(from.size());
for (const NodeTypeId* node : from) {
const absl::optional<int> node_idx = graph_type_view.GetNodeIndex(*node);
DCHECK(node_idx.has_value())
<< "Illegal start node: " << node->node->name();
if (node_idx.has_value()) {
stack.emplace_back(node_idx.value());
}
}
absl::flat_hash_map<int, NodeState> node_state;
while (!stack.empty()) {
DfsStackElem w = stack.back();
stack.pop_back();
NodeState& state = node_state[w.node];
if (state == NodeState::kDone) continue;
// Skip nodes that we should not enter.
if (predicates.enter && !predicates.enter(w.node)) {
state = NodeState::kDone;
continue;
}
// We've processed all the children of this node.
if (w.children_visited) {
state = NodeState::kDone;
if (callbacks.post_order) {
callbacks.post_order(w.node);
}
continue;
}
// Loop detected.
if (state == NodeState::kVisiting) {
if (callbacks.on_back_edge) {
callbacks.on_back_edge(w.src, w.node);
}
continue;
}
state = NodeState::kVisiting;
if (callbacks.pre_order) {
callbacks.pre_order(w.node);
}
// Enqueue the node again with the children_visited flag set to true.
stack.emplace_back(w.node, true, w.src);
// Check if we can continue traversal from the current node.
if (predicates.advance && !predicates.advance(w.node)) {
continue;
}
// Now enqueue the fanin/fanout nodes.
if (direction == TypeTraversalDirection::kFollowInputs ||
direction == TypeTraversalDirection::kFollowInputsAndOutputs) {
for (const int fanin : graph_type_view.GetFanin(w.node)) {
stack.emplace_back(fanin, false, w.node);
}
}
if (direction == TypeTraversalDirection::kFollowOutputs ||
direction == TypeTraversalDirection::kFollowInputsAndOutputs) {
for (const int fanout : graph_type_view.GetFanout(w.node)) {
stack.emplace_back(fanout, false, w.node);
}
}
}
}
DataTypeSet AllowedDataTypes(const OpDef::AttrDef& attr_def) {
const auto& allowed_types = attr_def.allowed_values().list().type();
if (allowed_types.empty()) {
return AllTypes();
}
uint32 dtype_mask = 0;
for (int dtype : allowed_types) {
dtype_mask |= 1u << dtype;
}
return DataTypeSet(dtype_mask);
}
DataTypeSet AllowedDataTypes(const OpDef& op_def, const TypeAttrId& t_attr_id) {
if (t_attr_id.attr_name.empty()) {
return ToSet(t_attr_id.fixed_type);
}
const OpDef::AttrDef* attr_def = FindAttr(t_attr_id.attr_name, op_def);
CHECK(attr_def); // Crash Ok
return AllowedDataTypes(*attr_def);
}
NodeDef BuildCastNode(const MutableGraphView::OutputPort& src, bool to_fp16,
const string& device) {
const char* cast_string = to_fp16 ? kCastToFp16 : kCastToFp32;
string name = strings::StrCat(src.node->name(), "-", src.port_id, "-",
cast_string, "-", kSuffix);
NodeDef node;
node.set_name(name);
node.set_op("Cast");
node.set_device(device);
node.add_input(strings::StrCat(src.node->name(), ":", src.port_id));
(*node.mutable_attr())["SrcT"].set_type(to_fp16 ? DT_FLOAT : DT_HALF);
(*node.mutable_attr())["DstT"].set_type(to_fp16 ? DT_HALF : DT_FLOAT);
(*node.mutable_attr())["Truncate"].set_b(false);
return node;
}
Status ValidateLists(const gtl::FlatSet<string>& white_list,
const gtl::FlatSet<string>& black_list,
const gtl::FlatSet<string>& gray_list,
const gtl::FlatSet<string>& clear_list) {
std::vector<gtl::FlatSet<string>> lists{white_list, black_list, gray_list,
clear_list};
std::multiset<string> counts;
for (auto list : lists) {
counts.insert(list.begin(), list.end());
}
bool duplicates = false;
for (auto s : counts) {
if (counts.count(s) > 1) {
duplicates = true;
LOG(ERROR) << "Op present in multiple lists: " << s;
}
}
if (duplicates) {
return errors::InvalidArgument("Op lists have conflicting entries");
} else {
return Status::OK();
}
}
bool HasInputOrOutputRefs(const NodeDef& node) {
const OpDef* op_def;
Status status = OpRegistry::Global()->LookUpOpDef(node.op(), &op_def);
if (!status.ok()) {
return true;
}
for (const auto& input : op_def->input_arg()) {
if (input.is_ref()) {
return true;
}
}
for (const auto& output : op_def->output_arg()) {
if (output.is_ref()) {
return true;
}
}
return false;
}
// See TF issue 25977 for no-FP16 on SCEWL
bool CanForceFP16(const NodeDef& node) {
return node.op() != "Const" && node.op() != "SoftmaxCrossEntropyWithLogits" &&
!IsStateful(node) && !HasInputOrOutputRefs(node);
}
int GetCudaVersion(const Cluster& cluster) {
auto devices = cluster.GetDevices();
for (const auto& device : devices) {
const DeviceProperties& device_properties = device.second;
if (device_properties.type() == "GPU") {
const auto& device_env = device_properties.environment();
auto it = device_env.find("cuda");
if (it != device_env.end()) {
string cuda_version_str = it->second;
return std::stoi(cuda_version_str);
}
}
}
return 0;
}
class AutoMixedPrecisionImpl {
public:
AutoMixedPrecisionImpl(Cluster* cluster,
const std::unordered_set<string>& nodes_to_preserve,
GraphDef* graph, string id)
: virtual_placer_(cluster->GetDevices()),
nodes_to_preserve_(nodes_to_preserve),
graph_(graph),
id_(id),
graph_view_(graph),
cuda_version_(GetCudaVersion(*cluster)) {}
Status Optimize();
private:
typedef absl::flat_hash_set<NodeTypeId> NodeTypeIdSet;
// Maps data structure object ops (e.g., StackV2) to the sets of nodes that
// write (e.g., StackPushV2) and read (e.g., StackPopV2) from them.
typedef absl::flat_hash_map<NodeTypeId,
std::pair<NodeTypeIdSet, NodeTypeIdSet>>
DataStructureOpsMap;
Status PrintDebugLogs(bool preop, size_t timestamp);
void LogSkippedNode(const NodeDef& node) const;
bool MustPreserve(const NodeDef& node) const;
bool IsOnGPU(const NodeDef& node) const;
bool IsOnSuitableGPUArch(const NodeDef& node) const;
bool ShouldProcess(const NodeDef& node) const;
bool NodeHasFP16KernelForTypeAttr(const NodeDef& node, TypeAttrId taid) const;
bool NodeImplicitlyReadsNonResourceVariable(const NodeDef& node) const;
void ConvertBatchNormOpsToV2();
bool SupportsFloat16(const NodeTypeId& node_type) const;
const NodeDef* GetTailOfChain(
const NodeDef& node, const absl::flat_hash_set<string>& match_ops) const;
Status AddDataStructureOpsToMap(
const absl::flat_hash_set<string>& data_structure_ops,
TypeAttrId data_structure_type_attr,
const absl::flat_hash_map<string, TypeAttrId>& write_ops,
const absl::flat_hash_map<string, TypeAttrId>& read_ops,
DataStructureOpsMap* object_clients_map) const;
void AddWhitelistOps(absl::flat_hash_set<int>* white_set) const;
void PropagateBlackFwdThroughClearAndGray(
absl::flat_hash_set<int>* black_set) const;
void ForceColorMatchBetweenDataStructureOps(
const DataStructureOpsMap& object_clients_map,
absl::flat_hash_set<int>* white_set,
absl::flat_hash_set<int>* black_set) const;
void AddClearAndGrayToWhiteIfBetweenWhite(
const absl::flat_hash_set<int>& black_set,
absl::flat_hash_set<int>* white_set) const;
void PropagateWhiteThroughClear(const absl::flat_hash_set<int>& black_set,
absl::flat_hash_set<int>* white_set) const;
Status ForceColorMatchOnRecurrentEdges(
absl::flat_hash_set<int>* white_set) const;
void MakeCastsWhiteIfAllOutputsWhite(
absl::flat_hash_set<int>* white_set) const;
Status ChangeTypeAttrsAndAddCasts(const absl::flat_hash_set<int>& white_set);
VirtualPlacer virtual_placer_;
std::unordered_set<string> nodes_to_preserve_;
GraphDef* graph_;
string id_;
MutableGraphView graph_view_;
int cuda_version_;
NodeTypeAttrMap node_type_map_;
GraphTypeTopologyView graph_type_view_;
bool force_all_fp16_;
gtl::FlatSet<string> fp16_whitelist_;
gtl::FlatSet<string> fp16_blacklist_;
gtl::FlatSet<string> fp16_graylist_;
gtl::FlatSet<string> fp16_clearlist_;
absl::flat_hash_set<const NodeDef*> should_process_nodes_;
};
bool AutoMixedPrecisionImpl::NodeHasFP16KernelForTypeAttr(
const NodeDef& node, TypeAttrId taid) const {
NodeDef node_copy(node);
if (node.device().empty()) {
string device_name = virtual_placer_.get_canonical_device_name(node);
node_copy.set_device(device_name);
}
if (!SetDataType(&node_copy, taid, DataType::DT_HALF)) {
return false;
}
return IsKernelRegisteredForNode(node_copy).ok();
}
Status AutoMixedPrecisionImpl::PrintDebugLogs(bool preop, size_t timestamp) {
string prepend_path;
TF_RETURN_IF_ERROR(ReadStringFromEnvVar(
"TF_AUTO_MIXED_PRECISION_GRAPH_REWRITE_LOG_PATH", "", &prepend_path));
if (prepend_path.empty()) return Status::OK();
string suffix =
strings::StrCat("_", preop ? "preop" : kSuffix, "_", id_, "_", timestamp);
string fname =
io::JoinPath(prepend_path, strings::StrCat("graphdef", suffix, ".pb"));
std::fstream f;
f.open(fname.c_str(), std::fstream::out | std::fstream::binary);
f << graph_->SerializeAsString();
f.close();
LOG(INFO) << "Saved " << (preop ? "pre-optimization" : "post-optimization")
<< " graph as binary to " << fname;
fname = io::JoinPath(prepend_path,
strings::StrCat("graphdef", suffix, ".pb.txt"));
f.open(fname.c_str(), std::fstream::out);
f << graph_->DebugString();
f.close();
LOG(INFO) << "Saved " << (preop ? "pre-optimization" : "post-optimization")
<< " graph as text to " << fname;
if (!preop) {
fname = io::JoinPath(prepend_path,
strings::StrCat("paintbuckets", suffix, ".txt"));
f.open(fname.c_str(), std::fstream::out);
f << "WhiteList:\n";
for (auto x : AutoMixedPrecisionLists::WhiteList(cuda_version_)) {
f << x << "\n";
}
f << "\nBlackList:\n";
for (auto x : AutoMixedPrecisionLists::BlackList()) {
f << x << "\n";
}
f << "\nGrayList:\n";
for (auto x : AutoMixedPrecisionLists::GrayList()) {
f << x << "\n";
}
f << "\nClearList:\n";
for (auto x : AutoMixedPrecisionLists::ClearList()) {
f << x << "\n";
}
f.close();
LOG(INFO) << "Saved paint bucket info to " << fname;
}
return Status::OK();
}
void AutoMixedPrecisionImpl::LogSkippedNode(const NodeDef& node) const {
VLOG(2) << "Skipping " << node.op() << " node " << node.name()
<< " because it "
<< (MustPreserve(node)
? "must be preserved"
: "is not on the GPU, or the GPU arch is not suitable");
}
bool AutoMixedPrecisionImpl::MustPreserve(const NodeDef& node) const {
return nodes_to_preserve_.count(node.name());
}
bool AutoMixedPrecisionImpl::IsOnGPU(const NodeDef& node) const {
string device_name;
if (node.device().empty()) {
device_name = virtual_placer_.get_canonical_device_name(node);
} else {
device_name = node.device();
}
string device;
string not_used;
if (DeviceNameUtils::SplitDeviceName(device_name, ¬_used, &device) &&
absl::StrContains(absl::AsciiStrToLower(device),
absl::AsciiStrToLower(DEVICE_GPU))) {
return true;
}
return false;
}
// Returns the GPU architecture (compute capability) as a (major, minor) pair.
std::pair<int, int> GetDeviceGPUArch(
const DeviceProperties& device_properties) {
if (device_properties.type() != "GPU") return {0, 0};
string arch_str = device_properties.environment().at("architecture");
std::vector<string> split_arch_str = str_util::Split(arch_str, '.');
if (split_arch_str.empty()) {
return {0, 0};
}
int major, minor;
if (!strings::safe_strto32(split_arch_str[0], &major)) {
return {0, 0};
}
if (split_arch_str.size() > 1) {
if (strings::safe_strto32(split_arch_str[1], &minor)) {
return {major, minor};
} else {
return {0, 0};
}
} else {
return {major, 0};
}
}
bool AutoMixedPrecisionImpl::IsOnSuitableGPUArch(const NodeDef& node) const {
return GetDeviceGPUArch(virtual_placer_.get_device(node)) >= kMinGPUArch;
}
bool AutoMixedPrecisionImpl::ShouldProcess(const NodeDef& node) const {
return should_process_nodes_.count(&node);
}
bool IsFloat32(const NodeTypeId& node_type) {
return GetDataType(*node_type.node, node_type.type_attr) ==
DataType::DT_FLOAT;
}
bool AutoMixedPrecisionImpl::SupportsFloat16(
const NodeTypeId& node_type) const {
const OpDef* op_def;
Status status =
OpRegistry::Global()->LookUpOpDef(node_type.node->op(), &op_def);
if (!status.ok()) return false;
return AllowedDataTypes(*op_def, node_type.type_attr)
.Contains(DataType::DT_HALF) &&
NodeHasFP16KernelForTypeAttr(*node_type.node, node_type.type_attr);
}
// TODO(mconley): Make this change the node's name (to aid debugging). Need to
// make sure that doing this won't break anything.
void AutoMixedPrecisionImpl::ConvertBatchNormOpsToV2() {
for (int node_idx = 0; node_idx < graph_->node_size(); ++node_idx) {
NodeDef* node = graph_->mutable_node(node_idx);
if (!ShouldProcess(*node)) continue;
bool changed = false;
if (node->op() == "FusedBatchNorm") {
VLOG(2) << "Changing op of " << node->op() << " node " << node->name()
<< " to FusedBatchNormV2";
node->set_op("FusedBatchNormV2");
changed = true;
} else if (node->op() == "FusedBatchNormGrad") {
VLOG(2) << "Changing op of " << node->op() << " node " << node->name()
<< " to FusedBatchNormGradV2";
node->set_op("FusedBatchNormGradV2");
changed = true;
}
if (changed) {
(*node->mutable_attr())["U"].set_type(DT_FLOAT);
}
}
}
// A helper function to decide whether to ignore the effect on performance when
// rewriting the graph. This can be useful for testing the numerical effects of
// reduced precision on systems that have poor mixed precision performance.
bool ShouldIgnorePerformance() {
static bool is_enabled = [] {
bool ret = false;
TF_CHECK_OK(ReadBoolFromEnvVar(
"TF_AUTO_MIXED_PRECISION_GRAPH_REWRITE_IGNORE_PERFORMANCE",
/*default_val=*/false, &ret));
return ret;
}();
return is_enabled;
}
Status AutoMixedPrecisionImpl::Optimize() {
string optimization_level;
TF_RETURN_IF_ERROR(ReadStringFromEnvVar(
"TF_AUTO_MIXED_PRECISION_GRAPH_REWRITE_LEVEL", "", &optimization_level));
optimization_level = absl::AsciiStrToUpper(optimization_level);
force_all_fp16_ = optimization_level == "UNSAFE_FORCE_ALL";
fp16_whitelist_ = AutoMixedPrecisionLists::WhiteList(cuda_version_);
fp16_blacklist_ = AutoMixedPrecisionLists::BlackList();
fp16_graylist_ = AutoMixedPrecisionLists::GrayList();
fp16_clearlist_ = AutoMixedPrecisionLists::ClearList();
TF_RETURN_IF_ERROR(ValidateLists(fp16_whitelist_, fp16_blacklist_,
fp16_graylist_, fp16_clearlist_));
size_t timestamp = Env::Default()->NowMicros() / 1000;
TF_RETURN_IF_ERROR(PrintDebugLogs(/* preop = */ true, timestamp));
VLOG(2) << "Identifying nodes that should be processed";
for (const NodeDef& node : graph_->node()) {
if (!MustPreserve(node) && IsOnGPU(node) &&
(ShouldIgnorePerformance() || IsOnSuitableGPUArch(node))) {
should_process_nodes_.insert(&node);
} else {
LogSkippedNode(node);
}
}
VLOG(2) << "Converting FusedBatchNorm* ops to V2";
ConvertBatchNormOpsToV2();
VLOG(2) << "Building node type map for graph";
TF_RETURN_IF_ERROR(node_type_map_.Init(*graph_));
// Note: If an op is added to this list that has a data type attribute, it
// should also be added to the AddDataStructureOpsToMap call below (and to the
// clearlist if it involves data flow).
// TODO(benbarsdell): Add support for TensorListPushBackBatch and
// TensorListConcatLists. They require special handling because they connect
// multiple list objects together. Currently if they appear in the graph then
// we have no choice but to disallow changing any tensor list ops, as
// otherwise we risk breaking the graph if some are changed and some are not
// (within a connected cluster of tensor list nodes).
const gtl::FlatSet<string> supported_list_ops = {
"EmptyTensorList",
"TensorListSplit",
"TensorListFromTensor",
"TensorListReserve",
"TensorListScatter",
"TensorListScatterV2",
"TensorListPushBack",
"TensorListSetItem",
"TensorListScatterIntoExistingList",
"TensorListPopBack",
"TensorListStack",
"TensorListConcat",
"TensorListConcatV2",
"TensorListGetItem",
"TensorListGather",
"TensorListLength",
"TensorListElementShape",
"TensorListResize"};
bool can_change_tensor_list_ops = true;
for (const NodeDef& node : graph_->node()) {
if (absl::StartsWith(node.op(), "TensorList") &&
!supported_list_ops.count(node.op())) {
LOG(WARNING) << "Unsupported " << node.op() << " node found in graph ("
<< node.name()
<< "), tensor list ops will not be converted.";
can_change_tensor_list_ops = false;
break;
}
}
DataStructureOpsMap object_clients_map;
if (can_change_tensor_list_ops) {
VLOG(2) << "Identifying TensorList* nodes";
TF_RETURN_IF_ERROR(AddDataStructureOpsToMap(
{"EmptyTensorList", "TensorListSplit", "TensorListFromTensor",
"TensorListReserve", "TensorListScatter", "TensorListScatterV2"},
TypeAttrId("element_dtype"),
{{"TensorListPushBack", TypeAttrId("element_dtype")},
{"TensorListSetItem", TypeAttrId("element_dtype")},
{"TensorListScatterIntoExistingList", TypeAttrId("element_dtype")}},
{{"TensorListPopBack", TypeAttrId("element_dtype")},
{"TensorListStack", TypeAttrId("element_dtype")},
{"TensorListConcat", TypeAttrId("element_dtype")},
{"TensorListConcatV2", TypeAttrId("element_dtype")},
{"TensorListGetItem", TypeAttrId("element_dtype")},
{"TensorListGather", TypeAttrId("element_dtype")}},
&object_clients_map));
} else {
for (const string& list_op : supported_list_ops) {
fp16_whitelist_.erase(list_op);
fp16_graylist_.erase(list_op);
fp16_clearlist_.erase(list_op);
}
}
// Create ephemeral edges between writers and readers of data structure ops.
std::vector<NodeTypeIdEdge> ephemeral_edges;
for (const auto& object_clients : object_clients_map) {
const auto& client_nodes = object_clients.second;
for (const NodeTypeId& write_node_type : client_nodes.first) {
for (const NodeTypeId& read_node_type : client_nodes.second) {
ephemeral_edges.emplace_back(write_node_type, read_node_type);
}
}
const NodeTypeId& object_node_type = object_clients.first;
// These object types also act as writers because they initialize the object
// from an input tensor.
if (object_node_type.node->op() == "TensorListSplit" ||
object_node_type.node->op() == "TensorListFromTensor" ||
object_node_type.node->op() == "TensorListScatter" ||
object_node_type.node->op() == "TensorListScatterV2") {
for (const NodeTypeId& read_node_type : client_nodes.second) {
ephemeral_edges.emplace_back(object_node_type, read_node_type);
}
}
}
VLOG(2) << "Constructing graph type attribute topology view";
TF_RETURN_IF_ERROR(graph_type_view_.InitializeFromGraph(
*graph_, node_type_map_, ephemeral_edges));
// The goal here is to change performance-critical ops to fp16, and to do so
// with the minimal number of casts, subject to the constraint that the
// model's convergence is not affected. This is achieved by first identifying
// which nodes should be changed to fp16 and then inserting casts at the
// boundaries between fp16/non-fp16 nodes.
// The algorithm for deciding which nodes to change to fp16 is as follows:
// 1) Add all performance-critical ops (aka "whitelist" ops) to the white_set.
// This is done under the assumption that whitelist ops are always
// numerically-safe in fp16 and that they are the most important ops for
// improving performance.
// 2) Add nodes to the black_set iff they are numerically-dangerous (aka
// "blacklist" ops) or they are on a forward path from a blacklist node to
// a black/gray node (including the node at the end of the path) through
// non-numerically-dangerous ops (aka "greylist" and "clearlist" ops).
// This is done to prevent numerically-dangerous ops and their downstream
// effects from being changed to fp16, which would risk breaking the
// numerical accuracy of the model.
// 3) For all remaining nodes that are not considered dangerous (greylist
// and clearlist ops), find those that are between (i.e., both upstream
// and downstream of) white nodes, and add them to the white_set.
// This is done to avoid unnecessary casts between whitelist ops.
// 4) For all remaining clearlist nodes, add them to the white_set if they are
// connected to a node in the white_set via other clearlist nodes.
// This is done to increase the number of ops in the white_set without
// affecting numerical stability.
absl::flat_hash_set<int> white_set;
VLOG(2) << "Beginning pass 1 to add whitelist ops";
AddWhitelistOps(&white_set);
VLOG(2) << "Finished pass 1";
if (white_set.empty()) {
LOG(INFO) << "No whitelist ops found, nothing to do";
return Status::OK();
}
absl::flat_hash_set<int> black_set;
VLOG(2) << "Beginning pass 2 to propagate black forwards from blacklist ops "
"through clear/graylist ops";
PropagateBlackFwdThroughClearAndGray(&black_set);
VLOG(2) << "Finished pass 2";
VLOG(2) << "Forcing color match between data structure ops";
ForceColorMatchBetweenDataStructureOps(object_clients_map, &white_set,
&black_set);
VLOG(2) << "Beginning pass 3 to set clear and gray nodes to white if they "
"are between white ops";
AddClearAndGrayToWhiteIfBetweenWhite(black_set, &white_set);
VLOG(2) << "Finished pass 3";
VLOG(2) << "Beginning pass 4 to propagate white from white nodes through "
"clearlist ops";
PropagateWhiteThroughClear(black_set, &white_set);
VLOG(2) << "Finished pass 4";
VLOG(2) << "Forcing color match between data structure ops";
ForceColorMatchBetweenDataStructureOps(object_clients_map, &white_set,
&black_set);
VLOG(2) << "Forcing color match on loop edges";
TF_RETURN_IF_ERROR(ForceColorMatchOnRecurrentEdges(&white_set));
VLOG(2) << "Finding existing casts that can be made white";
MakeCastsWhiteIfAllOutputsWhite(&white_set);
VLOG(2) << "Beginning final pass to change type attributes and insert Cast "
"ops at paint boundaries";
TF_RETURN_IF_ERROR(ChangeTypeAttrsAndAddCasts(white_set));
VLOG(2) << "Finished final pass";
TF_RETURN_IF_ERROR(PrintDebugLogs(/* preop = */ false, timestamp));
return Status::OK();
}
// Finds data structure object ops (e.g., StackV2) and the sets of nodes that
// write (e.g., StackPushV2) and read (e.g., StackPopV2) from them.
Status AutoMixedPrecisionImpl::AddDataStructureOpsToMap(
const absl::flat_hash_set<string>& data_structure_ops,
TypeAttrId data_structure_type_attr,
const absl::flat_hash_map<string, TypeAttrId>& write_ops,
const absl::flat_hash_map<string, TypeAttrId>& read_ops,
DataStructureOpsMap* object_clients_map) const {
for (const NodeDef& node : graph_->node()) {
const auto write_iter = write_ops.find(node.op());
const auto read_iter = read_ops.find(node.op());
bool is_writer = write_iter != write_ops.end();
bool is_reader = read_iter != read_ops.end();
if (is_writer || is_reader) {
const NodeDef* object_node = GetTailOfChain(node, data_structure_ops);
if (!object_node) {
return errors::FailedPrecondition(
"No data structure op found upstream of ", node.op(), " node ",
node.name());
}
NodeTypeId object_node_type(object_node, data_structure_type_attr);
TypeAttrId type_attr = is_writer ? write_iter->second : read_iter->second;
NodeTypeId node_type(&node, type_attr);
auto* value = &(*object_clients_map)[object_node_type];
auto* node_set = is_writer ? &value->first : &value->second;
node_set->insert(node_type);
}
}
return Status::OK();
}
void AutoMixedPrecisionImpl::AddWhitelistOps(
absl::flat_hash_set<int>* white_set) const {
// Add whitelisted ops to white_set.
for (int root_idx = 0; root_idx < graph_type_view_.num_nodes(); ++root_idx) {
const NodeTypeId& root = *graph_type_view_.GetNode(root_idx);
if (!ShouldProcess(*root.node)) continue;
bool force_white = force_all_fp16_ && CanForceFP16(*root.node);
if (fp16_whitelist_.count(root.node->op()) || force_white) {
bool inserted = white_set->insert(root_idx).second;
if (VLOG_IS_ON(2) && inserted) {
VLOG(2) << "Painting type " << root.type_attr.DebugString()
<< " of node " << root.node->name() << " WHITE because its op "
<< root.node->op() << " is on the whitelist";
}
}
}
}
// Adds nodes to black_set iff they are on the blacklist or they are on a
// forward path from a blacklist node to a black/gray node (including the node
// at the end of the path) through clear and gray nodes.
// E.g., black -> gray -> clear -> gray -> clear -> white -> gray
// becomes: black -> black -> black -> black -> clear -> white -> gray.
void AutoMixedPrecisionImpl::PropagateBlackFwdThroughClearAndGray(
absl::flat_hash_set<int>* black_set) const {
if (force_all_fp16_) return;
// Find clear nodes that are upstream of black or gray.
absl::flat_hash_set<int> upstream_of_black_or_gray_set;
for (int root_idx = 0; root_idx < graph_type_view_.num_nodes(); ++root_idx) {
const NodeTypeId& root = *graph_type_view_.GetNode(root_idx);
if (!(fp16_blacklist_.count(root.node->op()) ||
fp16_graylist_.count(root.node->op()))) {
continue;
}
DfsTypeTraversal(graph_type_view_, {&root},
TypeTraversalDirection::kFollowInputs,
DfsTypePredicates::Enter([&](int idx) -> bool {
const NodeTypeId& item = *graph_type_view_.GetNode(idx);
return idx == root_idx ||
(!upstream_of_black_or_gray_set.count(idx) &&
fp16_clearlist_.count(item.node->op()));
}),
DfsTypeCallbacks::PreOrder([&](int idx) {
upstream_of_black_or_gray_set.insert(idx);
}));
}
// Propagate black forward through nodes in upstream_of_black_or_gray_set.
for (int root_idx = 0; root_idx < graph_type_view_.num_nodes(); ++root_idx) {
const NodeTypeId& root = *graph_type_view_.GetNode(root_idx);
if (black_set->count(root_idx) || !fp16_blacklist_.count(root.node->op())) {
continue;
}
DfsTypeTraversal(
graph_type_view_, {&root}, TypeTraversalDirection::kFollowOutputs,
DfsTypePredicates::Enter([&](int idx) -> bool {
return idx == root_idx || (!black_set->count(idx) &&
upstream_of_black_or_gray_set.count(idx));
}),
DfsTypeCallbacks::PreOrder([&](int idx) {
bool inserted = black_set->insert(idx).second;
if (VLOG_IS_ON(2) && inserted) {
const NodeTypeId& item = *graph_type_view_.GetNode(idx);
VLOG(2) << "Painting type " << item.type_attr.DebugString()
<< " of " << item.node->op() << " node "
<< item.node->name() << " BLACK";
}
}));
}
}
void AutoMixedPrecisionImpl::AddClearAndGrayToWhiteIfBetweenWhite(
const absl::flat_hash_set<int>& black_set,
absl::flat_hash_set<int>* white_set) const {
// Find clear/graylist ops that are downstream of white ops.
absl::flat_hash_set<int> downstream_of_white_set;
for (int root_idx = 0; root_idx < graph_type_view_.num_nodes(); ++root_idx) {
const NodeTypeId& root = *graph_type_view_.GetNode(root_idx);
if (!ShouldProcess(*root.node) || !fp16_whitelist_.count(root.node->op())) {
continue;
}
DfsTypeTraversal(
graph_type_view_, {&root}, TypeTraversalDirection::kFollowOutputs,
DfsTypePredicates::Enter([&](int idx) -> bool {
const NodeTypeId& item = *graph_type_view_.GetNode(idx);
return idx == root_idx ||
(!downstream_of_white_set.count(idx) &&
!fp16_whitelist_.count(item.node->op()) &&
!black_set.count(idx) && ShouldProcess(*item.node) &&
// TODO(benbarsdell): Consider allowing propagation through
// ops that are already float16 in order to reduce the number
// of casts.
IsFloat32(item) && SupportsFloat16(item) &&
(fp16_clearlist_.count(item.node->op()) ||
fp16_graylist_.count(item.node->op())));
}),
DfsTypeCallbacks::PreOrder(
[&](int idx) { downstream_of_white_set.insert(idx); }));
}
// Set nodes that are both downstream and upstream of white ops to white.
absl::flat_hash_set<int> upstream_of_white_set;
for (int root_idx = 0; root_idx < graph_type_view_.num_nodes(); ++root_idx) {
const NodeTypeId& root = *graph_type_view_.GetNode(root_idx);
if (!ShouldProcess(*root.node) || upstream_of_white_set.count(root_idx) ||
!fp16_whitelist_.count(root.node->op())) {
continue;
}
DfsTypeTraversal(
graph_type_view_, {&root}, TypeTraversalDirection::kFollowInputs,
DfsTypePredicates::Enter([&](int idx) -> bool {
return idx == root_idx || (!upstream_of_white_set.count(idx) &&
downstream_of_white_set.count(idx));
}),
DfsTypeCallbacks::PreOrder([&](int idx) {
upstream_of_white_set.insert(idx);
bool inserted = white_set->insert(idx).second;
if (VLOG_IS_ON(2) && inserted) {
const NodeTypeId& item = *graph_type_view_.GetNode(idx);
VLOG(2) << "Painting type " << item.type_attr.DebugString()
<< " of " << item.node->op() << " node "
<< item.node->name() << " WHITE";
}
}));
}
}
void AutoMixedPrecisionImpl::PropagateWhiteThroughClear(
const absl::flat_hash_set<int>& black_set,
absl::flat_hash_set<int>* white_set) const {
// Propagate white from white nodes through clearlist ops.
absl::flat_hash_set<int> clear_prop_set;
for (int root_idx = 0; root_idx < graph_type_view_.num_nodes(); ++root_idx) {
const NodeTypeId& root = *graph_type_view_.GetNode(root_idx);
if (!ShouldProcess(*root.node) || clear_prop_set.count(root_idx) ||
!white_set->count(root_idx)) {
continue;
}
DfsTypeTraversal(
graph_type_view_, {&root},
TypeTraversalDirection::kFollowInputsAndOutputs,
DfsTypePredicates::Enter([&](int idx) -> bool {
const NodeTypeId& item = *graph_type_view_.GetNode(idx);
return idx == root_idx ||
(!white_set->count(idx) && !black_set.count(idx) &&
ShouldProcess(*item.node) && IsFloat32(item) &&
SupportsFloat16(item) &&
(fp16_clearlist_.count(item.node->op())) &&
// We don't propagate (backwards) through nodes that read
// Variables because it can break the behavior of TensorBoard
// visualization and/or (in the case of Enter nodes) the model
// itself. This is only a problem for non-resource variables.
!NodeImplicitlyReadsNonResourceVariable(*item.node));
}),
DfsTypeCallbacks::PreOrder([&](int idx) {
clear_prop_set.insert(idx);
bool inserted = white_set->insert(idx).second;
if (VLOG_IS_ON(2) && inserted) {
const NodeTypeId& item = *graph_type_view_.GetNode(idx);
VLOG(2) << "Painting type " << item.type_attr.DebugString()
<< " of " << item.node->op() << " node "
<< item.node->name() << " WHITE";
}
}));
}
}
// Forces NextIteration nodes and their output Merge node(s) to have the same
// color. Specifically, it removes them all from white_set if any of the Merge
// nodes is not in white_set, otherwise it adds the NextIteration node to
// white_set.
Status AutoMixedPrecisionImpl::ForceColorMatchOnRecurrentEdges(
absl::flat_hash_set<int>* white_set) const {
for (const NodeDef& node : graph_->node()) {
if (node.op() == "NextIteration") {
GraphView::OutputPort output_port(&node, 0);
const auto& fanout = graph_view_.GetFanout(output_port);
std::vector<int> merge_idxs;
merge_idxs.reserve(fanout.size());
bool any_merge_is_not_white = false;
for (const auto& output : fanout) {
const NodeDef& merge_node = *output.node;
if (merge_node.op() != "Merge") {
return errors::FailedPrecondition(
"Expected Merge node after NextIteration, got ", merge_node.op());
}
const absl::optional<int> maybe_merge_idx =
graph_type_view_.GetNodeIndex(merge_node.name(), TypeAttrId("T"));
if (!maybe_merge_idx.has_value()) {
return errors::Internal("Type attribute T of Merge node ",
merge_node.name(),
" not found in graph view");
}
int merge_idx = maybe_merge_idx.value();
merge_idxs.push_back(merge_idx);
any_merge_is_not_white =
any_merge_is_not_white || !white_set->count(merge_idx);
}
const absl::optional<int> maybe_nextiter_idx =
graph_type_view_.GetNodeIndex(node.name(), TypeAttrId("T"));
if (!maybe_nextiter_idx.has_value()) {
return errors::Internal("Type attribute T of NextIteration node ",
node.name(), " not found in graph view");
}
int nextiter_idx = maybe_nextiter_idx.value();
if (any_merge_is_not_white) {
for (int merge_idx : merge_idxs) {
if (white_set->erase(merge_idx)) {
VLOG(2) << "Painting type T of Merge node "
<< graph_type_view_.GetNode(merge_idx)->node->name()
<< " BLACK to match the color of its sibling Merge nodes "
"with common NextIteration node "
<< node.name();
}
}
if (white_set->erase(nextiter_idx)) {
VLOG(2) << "Painting type T of NextIteration node " << node.name()
<< " BLACK to match the color of its output Merge node(s)";
}
} else {
if (white_set->insert(nextiter_idx).second) {
VLOG(2) << "Painting type T of NextIteration node " << node.name()
<< " WHITE to match the color of its output Merge node(s)";
}
}
}
}
return Status::OK();
}
// Returns the last node in the simple chain starting at node and traversing
// backwards through the input(0) edge from each node until one with a matching
// op is found, or nullptr if no matching node is found.
const NodeDef* AutoMixedPrecisionImpl::GetTailOfChain(
const NodeDef& node, const absl::flat_hash_set<string>& match_ops) const {
const NodeDef* node_ptr = &node;
do {
GraphView::InputPort node_input(node_ptr, 0);
MutableGraphView::OutputPort prev_output =
graph_view_.GetRegularFanin(node_input);
node_ptr = prev_output.node;
} while (node_ptr && !match_ops.count(node_ptr->op()));
return node_ptr;
}
// Ensures that data structure nodes (e.g., StackV2) and all of their associated
// client nodes (e.g., StackPushV2 and StackPopV2) are in the same color set.
void AutoMixedPrecisionImpl::ForceColorMatchBetweenDataStructureOps(
const DataStructureOpsMap& object_clients_map,
absl::flat_hash_set<int>* white_set,
absl::flat_hash_set<int>* black_set) const {
for (const auto& object_clients : object_clients_map) {
const NodeTypeId& object_node_type = object_clients.first;
const auto& client_nodes = object_clients.second;
NodeTypeIdSet all_client_nodes = client_nodes.first;
all_client_nodes.insert(client_nodes.second.begin(),
client_nodes.second.end());
// The object node may be considered a client too (e.g.,
// TensorListFromTensor).
all_client_nodes.insert(object_node_type);
bool any_black = false;
bool any_white = false;
for (const NodeTypeId& node_type : all_client_nodes) {
const absl::optional<int> maybe_node_idx =
graph_type_view_.GetNodeIndex(node_type);
DCHECK(maybe_node_idx.has_value())
<< "Type attribute " << node_type.type_attr.DebugString()
<< " of node " << node_type.node->name()
<< " not found in graph view";
int node_idx = maybe_node_idx.value();
if (black_set->count(node_idx)) {
any_black = true;
break;
} else if (white_set->count(node_idx)) {
any_white = true;
}
}
if (any_black || any_white) {
for (const NodeTypeId& node_type : all_client_nodes) {
VLOG(2) << "Painting type " << node_type.type_attr.DebugString()
<< " of " << node_type.node->op() << " node "
<< node_type.node->name() << " "
<< (any_black ? "BLACK" : "WHITE")
<< " because at least one of its siblings is "
<< (any_black ? "BLACK" : "WHITE");
const absl::optional<int> maybe_node_idx =
graph_type_view_.GetNodeIndex(node_type);
DCHECK(maybe_node_idx.has_value())
<< "Type attribute " << node_type.type_attr.DebugString()
<< " of node " << node_type.node->name()
<< " not found in graph view";
int node_idx = maybe_node_idx.value();
if (any_black) {
white_set->erase(node_idx);
black_set->insert(node_idx);
} else {
white_set->insert(node_idx);
}
}
}
}
}
bool AutoMixedPrecisionImpl::NodeImplicitlyReadsNonResourceVariable(
const NodeDef& node) const {
if (node.op() == "Identity" || node.op() == "Enter") {
GraphView::InputPort node_input(&node, 0);
MutableGraphView::OutputPort prev_output =
graph_view_.GetRegularFanin(node_input);
const NodeDef* input = prev_output.node;
if (input && ((node.op() == "Identity" && (input->op() == "Variable" ||
input->op() == "VariableV2")) ||
(node.op() == "Enter" &&
NodeImplicitlyReadsNonResourceVariable(*input)))) {
return true;
}
}
return false;
}
// This adds existing Cast nodes to white_set if all of their outputs are white,
// avoiding the need to add a new Cast node after an existing Cast.
void AutoMixedPrecisionImpl::MakeCastsWhiteIfAllOutputsWhite(
absl::flat_hash_set<int>* white_set) const {
int num_nodes_preop = graph_->node_size();
for (int node_idx = 0; node_idx < num_nodes_preop; ++node_idx) {
NodeDef* node = graph_->mutable_node(node_idx);
NodeTypeId node_type(node, TypeAttrId("DstT"));
if (node->op() != "Cast" || !IsFloat32(node_type)) {
continue;
}
bool all_fanouts_white = true;
MutableGraphView::OutputPort src(node, 0);
const auto& fanout = graph_view_.GetFanout(src);
for (const MutableGraphView::InputPort& dst : fanout) {
TypeAttrId dst_type_attr =
node_type_map_.GetInputTypeAttr(*dst.node, dst.port_id);
const absl::optional<int> maybe_dst_type_idx =
graph_type_view_.GetNodeIndex(dst.node->name(), dst_type_attr);
DCHECK(maybe_dst_type_idx.has_value())
<< "Type attribute " << dst_type_attr.DebugString() << " of node "
<< dst.node->name() << " not found in graph view";
int dst_type_idx = maybe_dst_type_idx.value();
bool dst_is_white = white_set->count(dst_type_idx);
if (!dst_is_white) {
all_fanouts_white = false;
break;
}
}
if (!fanout.empty() && all_fanouts_white) {
const absl::optional<int> maybe_node_type_idx =
graph_type_view_.GetNodeIndex(node_type);
DCHECK(maybe_node_type_idx.has_value())
<< "Type attribute " << node_type.type_attr.DebugString()
<< " of node " << node_type.node->name()
<< " not found in graph view";
int node_type_idx = maybe_node_type_idx.value();
white_set->insert(node_type_idx);
}
}
}
// Changes all white-painted type attributes to DT_HALF, and inserts Cast nodes
// at node outputs for all edges that connect white-painted <->
// non-white-painted type attributes.
Status AutoMixedPrecisionImpl::ChangeTypeAttrsAndAddCasts(
const absl::flat_hash_set<int>& white_set) {
int num_nodes_changed = 0;
int num_nonvar_casts_to_fp16 = 0;
int num_nodes_preop = graph_->node_size();
for (int node_idx = 0; node_idx < num_nodes_preop; ++node_idx) {
NodeDef* node = graph_->mutable_node(node_idx);
for (const TypeAttrId& type_attr : node_type_map_.GetTypeAttrs(*node)) {
const absl::optional<int> maybe_node_type_idx =
graph_type_view_.GetNodeIndex(node->name(), type_attr);
if (!maybe_node_type_idx.has_value()) {
return errors::Internal("Type attribute ", type_attr.DebugString(),
" of ", node->op(), " node ", node->name(),
" not found in graph view");
}
int node_type_idx = maybe_node_type_idx.value();
if (!IsFloat32(*graph_type_view_.GetNode(node_type_idx))) continue;
bool src_is_white = white_set.count(node_type_idx);
if (src_is_white) {
VLOG(1) << "Changing type " << type_attr.DebugString() << " of "
<< node->op() << " node " << node->name() << " to DT_HALF";
if (!SetDataType(node, type_attr, DT_HALF)) {
return errors::Internal("Failed to set type attribute");
}
++num_nodes_changed;
}
for (int output_port : node_type_map_.GetOutputPorts(*node, type_attr)) {
MutableGraphView::OutputPort src(node, output_port);
NodeDef* added_cast_node = nullptr;
// Note: This is copied so that edges can be modified inside the loop.
auto fanout = graph_view_.GetFanout(src);
for (const MutableGraphView::InputPort& dst : fanout) {
TypeAttrId dst_type_attr =
node_type_map_.GetInputTypeAttr(*dst.node, dst.port_id);
const absl::optional<int> maybe_dst_type_idx =
graph_type_view_.GetNodeIndex(dst.node->name(), dst_type_attr);
if (!maybe_dst_type_idx.has_value()) {
return errors::Internal("Type attribute ",
dst_type_attr.DebugString(), " of ",
dst.node->op(), " node ", dst.node->name(),
" not found in graph view");
}
int dst_type_idx = maybe_dst_type_idx.value();
bool dst_is_white = white_set.count(dst_type_idx);
if (src_is_white != dst_is_white) {
if (!added_cast_node) {
bool to_fp16 = dst_is_white;
VLOG(1) << "Inserting cast to "
<< (to_fp16 ? "DT_HALF" : "DT_FLOAT") << " at "
<< src.node->op() << " " << src.node->name() << ":"
<< src.port_id;
added_cast_node = graph_view_.AddNode(
BuildCastNode(src, to_fp16, src.node->device()));
if (to_fp16 && !IsConstant(*node) && !IsVariable(*node) &&
!NodeImplicitlyReadsNonResourceVariable(*node)) {
++num_nonvar_casts_to_fp16;
}
}
TF_RETURN_IF_ERROR(graph_view_.UpdateRegularFaninByPort(
dst.node->name(), dst.port_id, {added_cast_node->name(), 0}));
}
}
}
}
}
LOG(INFO) << "Converted " << num_nodes_changed << "/" << num_nodes_preop
<< " nodes to float16 precision using " << num_nonvar_casts_to_fp16
<< " cast(s) to float16 (excluding Const and Variable casts)";
return Status::OK();
}
int GetNumGPUs(const Cluster& cluster,
const std::pair<int, int>& min_arch = {0, 0}) {
auto devices = cluster.GetDevices();
int num_gpus = 0;
for (const auto& device : devices) {
const DeviceProperties& device_properties = device.second;
std::pair<int, int> arch = GetDeviceGPUArch(device_properties);
if (device_properties.type() == "GPU" && arch >= min_arch) {
num_gpus++;
}
}
return num_gpus;
}
} // end namespace
Status AutoMixedPrecision::Optimize(Cluster* cluster, const GrapplerItem& item,
GraphDef* output) {
if (cluster == nullptr) {
return errors::InvalidArgument("cluster == nullptr");
}
// Start by copying input graph to output.
*output = item.graph;
int num_gpus = ShouldIgnorePerformance() ? GetNumGPUs(*cluster)
: GetNumGPUs(*cluster, kMinGPUArch);
if (num_gpus < 1) {
// AutoMixedPrecision is currently only tuned for GPU.
LOG(WARNING) << "No (suitable) GPUs detected, skipping " << name()
<< " graph optimizer";
return Status::OK();
}
// Optimize the output graph in-place.
AutoMixedPrecisionImpl optimizer(cluster, item.NodesToPreserve(), output,
item.id);
if (item.id == "tf_graph") {
LOG(INFO) << "Running " << name() << " graph optimizer";
} else {
VLOG(1) << "Running " << name() << " graph optimizer on " << item.id;
}
Status status = optimizer.Optimize();
if (!status.ok()) {
// Restore the original graph.
*output = item.graph;
LOG(WARNING) << name() << " graph optimizer FAILED: " << status.ToString();
}
return status;
}
void AutoMixedPrecision::Feedback(Cluster* cluster, const GrapplerItem& item,
const GraphDef& optimize_output,
double result) {
// Nothing to do for AutoMixedPrecision.
}
} // end namespace grappler
} // end namespace tensorflow
| 40.523659 | 80 | 0.659946 | [
"object",
"vector",
"model"
] |
80f86c15890f9e602ae6a181b7f299ea670e88a9 | 9,871 | cc | C++ | FWCore/ParameterSet/src/ParameterWildcard.cc | ckamtsikis/cmssw | ea19fe642bb7537cbf58451dcf73aa5fd1b66250 | [
"Apache-2.0"
] | 852 | 2015-01-11T21:03:51.000Z | 2022-03-25T21:14:00.000Z | FWCore/ParameterSet/src/ParameterWildcard.cc | ckamtsikis/cmssw | ea19fe642bb7537cbf58451dcf73aa5fd1b66250 | [
"Apache-2.0"
] | 30,371 | 2015-01-02T00:14:40.000Z | 2022-03-31T23:26:05.000Z | FWCore/ParameterSet/src/ParameterWildcard.cc | ckamtsikis/cmssw | ea19fe642bb7537cbf58451dcf73aa5fd1b66250 | [
"Apache-2.0"
] | 3,240 | 2015-01-02T05:53:18.000Z | 2022-03-31T17:24:21.000Z | #include "FWCore/ParameterSet/interface/ParameterWildcard.h"
#include "FWCore/ParameterSet/interface/DocFormatHelper.h"
#include "FWCore/ParameterSet/interface/ParameterSetDescription.h"
#include "FWCore/ParameterSet/interface/VParameterSetEntry.h"
#include "FWCore/Utilities/interface/Algorithms.h"
#include <cassert>
#include <iomanip>
#include <ostream>
namespace edm {
ParameterWildcard<ParameterSetDescription>::ParameterWildcard(std::string const& pattern,
WildcardValidationCriteria criteria,
bool isTracked)
: ParameterWildcardBase(k_PSet, isTracked, criteria), psetDesc_() {
throwIfInvalidPattern(pattern);
}
ParameterWildcard<ParameterSetDescription>::ParameterWildcard(char const* pattern,
WildcardValidationCriteria criteria,
bool isTracked)
: ParameterWildcardBase(k_PSet, isTracked, criteria), psetDesc_() {
throwIfInvalidPattern(pattern);
}
ParameterWildcard<ParameterSetDescription>::ParameterWildcard(std::string const& pattern,
WildcardValidationCriteria criteria,
bool isTracked,
ParameterSetDescription const& desc)
: ParameterWildcardBase(k_PSet, isTracked, criteria), psetDesc_(new ParameterSetDescription(desc)) {
throwIfInvalidPattern(pattern);
}
ParameterWildcard<ParameterSetDescription>::ParameterWildcard(char const* pattern,
WildcardValidationCriteria criteria,
bool isTracked,
ParameterSetDescription const& desc)
: ParameterWildcardBase(k_PSet, isTracked, criteria), psetDesc_(new ParameterSetDescription(desc)) {
throwIfInvalidPattern(pattern);
}
ParameterWildcard<ParameterSetDescription>::~ParameterWildcard() {}
ParameterDescriptionNode* ParameterWildcard<ParameterSetDescription>::clone() const {
return new ParameterWildcard(*this);
}
void ParameterWildcard<ParameterSetDescription>::validate_(ParameterSet& pset,
std::set<std::string>& validatedLabels,
bool optional) const {
std::vector<std::string> parameterNames = pset.getParameterNamesForType<ParameterSet>(isTracked());
validateMatchingNames(parameterNames, validatedLabels, optional);
if (psetDesc_) {
for_all(parameterNames,
std::bind(&ParameterWildcard<ParameterSetDescription>::validateDescription,
this,
std::placeholders::_1,
std::ref(pset)));
}
}
void ParameterWildcard<ParameterSetDescription>::validateDescription(std::string const& parameterName,
ParameterSet& pset) const {
ParameterSet* containedPSet = pset.getPSetForUpdate(parameterName);
psetDesc_->validate(*containedPSet);
}
bool ParameterWildcard<ParameterSetDescription>::hasNestedContent_() const {
if (psetDesc_)
return true;
return false;
}
void ParameterWildcard<ParameterSetDescription>::printNestedContent_(std::ostream& os,
bool /*optional*/,
DocFormatHelper& dfh) const {
int indentation = dfh.indentation();
if (dfh.parent() != DocFormatHelper::TOP) {
indentation -= DocFormatHelper::offsetSectionContent();
}
printSpaces(os, indentation);
os << "Section " << dfh.section() << "." << dfh.counter() << " description of PSet matching wildcard:";
os << "\n";
if (!dfh.brief())
os << "\n";
std::stringstream ss;
ss << dfh.section() << "." << dfh.counter();
std::string newSection = ss.str();
DocFormatHelper new_dfh(dfh);
new_dfh.setSection(newSection);
new_dfh.setIndentation(indentation + DocFormatHelper::offsetSectionContent());
new_dfh.setParent(DocFormatHelper::OTHER);
psetDesc_->print(os, new_dfh);
}
bool ParameterWildcard<ParameterSetDescription>::exists_(ParameterSet const& pset) const {
if (criteria() == RequireZeroOrMore)
return true;
std::vector<std::string> parameterNames = pset.getParameterNamesForType<ParameterSet>(isTracked());
if (criteria() == RequireAtLeastOne)
return !parameterNames.empty();
return parameterNames.size() == 1U;
}
// -------------------------------------------------------------------------
ParameterWildcard<std::vector<ParameterSet> >::ParameterWildcard(std::string const& pattern,
WildcardValidationCriteria criteria,
bool isTracked)
: ParameterWildcardBase(k_VPSet, isTracked, criteria), psetDesc_() {
throwIfInvalidPattern(pattern);
}
ParameterWildcard<std::vector<ParameterSet> >::ParameterWildcard(char const* pattern,
WildcardValidationCriteria criteria,
bool isTracked)
: ParameterWildcardBase(k_VPSet, isTracked, criteria), psetDesc_() {
throwIfInvalidPattern(pattern);
}
ParameterWildcard<std::vector<ParameterSet> >::ParameterWildcard(std::string const& pattern,
WildcardValidationCriteria criteria,
bool isTracked,
ParameterSetDescription const& desc)
: ParameterWildcardBase(k_VPSet, isTracked, criteria), psetDesc_(new ParameterSetDescription(desc)) {
throwIfInvalidPattern(pattern);
}
ParameterWildcard<std::vector<ParameterSet> >::ParameterWildcard(char const* pattern,
WildcardValidationCriteria criteria,
bool isTracked,
ParameterSetDescription const& desc)
: ParameterWildcardBase(k_VPSet, isTracked, criteria), psetDesc_(new ParameterSetDescription(desc)) {
throwIfInvalidPattern(pattern);
}
ParameterWildcard<std::vector<ParameterSet> >::~ParameterWildcard() {}
ParameterDescriptionNode* ParameterWildcard<std::vector<ParameterSet> >::clone() const {
return new ParameterWildcard(*this);
}
void ParameterWildcard<std::vector<ParameterSet> >::validate_(ParameterSet& pset,
std::set<std::string>& validatedLabels,
bool optional) const {
std::vector<std::string> parameterNames = pset.getParameterNamesForType<std::vector<ParameterSet> >(isTracked());
validateMatchingNames(parameterNames, validatedLabels, optional);
if (psetDesc_) {
for_all(parameterNames,
std::bind(&ParameterWildcard<std::vector<ParameterSet> >::validatePSetVector,
this,
std::placeholders::_1,
std::ref(pset)));
}
}
void ParameterWildcard<std::vector<ParameterSet> >::validatePSetVector(std::string const& parameterName,
ParameterSet& pset) const {
VParameterSetEntry* vpsetEntry = pset.getPSetVectorForUpdate(parameterName);
assert(vpsetEntry);
for (unsigned i = 0; i < vpsetEntry->size(); ++i) {
psetDesc_->validate(vpsetEntry->psetInVector(i));
}
}
bool ParameterWildcard<std::vector<ParameterSet> >::hasNestedContent_() const {
if (psetDesc_)
return true;
return false;
}
void ParameterWildcard<std::vector<ParameterSet> >::printNestedContent_(std::ostream& os,
bool /*optional*/,
DocFormatHelper& dfh) const {
int indentation = dfh.indentation();
if (dfh.parent() != DocFormatHelper::TOP) {
indentation -= DocFormatHelper::offsetSectionContent();
}
printSpaces(os, indentation);
os << "Section " << dfh.section() << "." << dfh.counter()
<< " description used to validate all PSets which are in the VPSet matching the wildcard:";
os << "\n";
if (!dfh.brief())
os << "\n";
std::stringstream ss;
ss << dfh.section() << "." << dfh.counter();
std::string newSection = ss.str();
DocFormatHelper new_dfh(dfh);
new_dfh.setSection(newSection);
new_dfh.setIndentation(indentation + DocFormatHelper::offsetSectionContent());
new_dfh.setParent(DocFormatHelper::OTHER);
psetDesc_->print(os, new_dfh);
}
bool ParameterWildcard<std::vector<ParameterSet> >::exists_(ParameterSet const& pset) const {
if (criteria() == RequireZeroOrMore)
return true;
std::vector<std::string> parameterNames = pset.getParameterNamesForType<std::vector<ParameterSet> >(isTracked());
if (criteria() == RequireAtLeastOne)
return !parameterNames.empty();
return parameterNames.size() == 1U;
}
} // namespace edm
| 44.868182 | 117 | 0.570965 | [
"vector"
] |
80ffa56e0ca368d3eb922194d3f514c47666ebe6 | 10,732 | cc | C++ | demo_drivers/navier_stokes/circular_driven_cavity/circular_driven_cavity.cc | PuneetMatharu/oomph-lib | edd590cbb4f3ef9940b9738f18275ea2fb828c55 | [
"RSA-MD"
] | null | null | null | demo_drivers/navier_stokes/circular_driven_cavity/circular_driven_cavity.cc | PuneetMatharu/oomph-lib | edd590cbb4f3ef9940b9738f18275ea2fb828c55 | [
"RSA-MD"
] | 1 | 2022-03-23T16:16:41.000Z | 2022-03-23T16:16:41.000Z | demo_drivers/navier_stokes/circular_driven_cavity/circular_driven_cavity.cc | PuneetMatharu/oomph-lib | edd590cbb4f3ef9940b9738f18275ea2fb828c55 | [
"RSA-MD"
] | null | null | null | //LIC// ====================================================================
//LIC// This file forms part of oomph-lib, the object-oriented,
//LIC// multi-physics finite-element library, available
//LIC// at http://www.oomph-lib.org.
//LIC//
//LIC// Copyright (C) 2006-2022 Matthias Heil and Andrew Hazel
//LIC//
//LIC// This library is free software; you can redistribute it and/or
//LIC// modify it under the terms of the GNU Lesser General Public
//LIC// License as published by the Free Software Foundation; either
//LIC// version 2.1 of the License, or (at your option) any later version.
//LIC//
//LIC// This library is distributed in the hope that it will be useful,
//LIC// but WITHOUT ANY WARRANTY; without even the implied warranty of
//LIC// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
//LIC// Lesser General Public License for more details.
//LIC//
//LIC// You should have received a copy of the GNU Lesser General Public
//LIC// License along with this library; if not, write to the Free Software
//LIC// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
//LIC// 02110-1301 USA.
//LIC//
//LIC// The authors may be contacted at oomph-lib@maths.man.ac.uk.
//LIC//
//LIC//====================================================================
// Driver for adaptive 2D quarter circle driven cavity. Solved with black
// box adaptation, using Taylor Hood and Crouzeix Raviart elements.
// Generic oomph-lib header
#include "generic.h"
// Navier Stokes headers
#include "navier_stokes.h"
// The mesh
#include "meshes/quarter_circle_sector_mesh.h"
using namespace std;
using namespace oomph;
//==start_of_namespace===================================================
/// Namespace for physical parameters
//=======================================================================
namespace Global_Physical_Variables
{
/// Reynolds number
double Re=100;
/// Reynolds/Froude number
double Re_invFr=100;
/// Gravity vector
Vector<double> Gravity(2);
/// Functional body force
void body_force(const double& time, const Vector<double>& x,
Vector<double>& result)
{
result[0]=0.0;
result[1]=-Re_invFr;
}
/// Zero functional body force
void zero_body_force(const double& time, const Vector<double>& x,
Vector<double>& result)
{
result[0]=0.0;
result[1]=0.0;
}
} // end_of_namespace
/// ///////////////////////////////////////////////////////////////////
/// ///////////////////////////////////////////////////////////////////
/// ///////////////////////////////////////////////////////////////////
//==start_of_problem_class============================================
/// Driven cavity problem in quarter circle domain, templated
/// by element type.
//====================================================================
template<class ELEMENT>
class QuarterCircleDrivenCavityProblem : public Problem
{
public:
/// Constructor
QuarterCircleDrivenCavityProblem(
NavierStokesEquations<2>::NavierStokesBodyForceFctPt body_force_fct_pt);
/// Destructor: Empty
~QuarterCircleDrivenCavityProblem() {}
/// Update the after solve (empty)
void actions_after_newton_solve() {}
/// Update the problem specs before solve.
/// (Re-)set velocity boundary conditions just to be on the safe side...
void actions_before_newton_solve()
{
// Setup tangential flow along boundary 0:
unsigned ibound=0;
unsigned num_nod= mesh_pt()->nboundary_node(ibound);
for (unsigned inod=0;inod<num_nod;inod++)
{
// Tangential flow
unsigned i=0;
mesh_pt()->boundary_node_pt(ibound,inod)->set_value(i,1.0);
// No penetration
i=1;
mesh_pt()->boundary_node_pt(ibound,inod)->set_value(i,0.0);
}
// Overwrite with no flow along all other boundaries
unsigned num_bound = mesh_pt()->nboundary();
for(unsigned ibound=1;ibound<num_bound;ibound++)
{
unsigned num_nod= mesh_pt()->nboundary_node(ibound);
for (unsigned inod=0;inod<num_nod;inod++)
{
for (unsigned i=0;i<2;i++)
{
mesh_pt()->boundary_node_pt(ibound,inod)->set_value(i,0.0);
}
}
}
} // end_of_actions_before_newton_solve
/// After adaptation: Unpin pressure and pin redudant pressure dofs.
void actions_after_adapt()
{
// Unpin all pressure dofs
RefineableNavierStokesEquations<2>::
unpin_all_pressure_dofs(mesh_pt()->element_pt());
// Pin redundant pressure dofs
RefineableNavierStokesEquations<2>::
pin_redundant_nodal_pressures(mesh_pt()->element_pt());
// Now pin the first pressure dof in the first element and set it to 0.0
fix_pressure(0,0,0.0);
} // end_of_actions_after_adapt
/// Doc the solution
void doc_solution(DocInfo& doc_info);
private:
/// Pointer to body force function
NavierStokesEquations<2>::NavierStokesBodyForceFctPt Body_force_fct_pt;
/// Fix pressure in element e at pressure dof pdof and set to pvalue
void fix_pressure(const unsigned &e, const unsigned &pdof,
const double &pvalue)
{
//Cast to proper element and fix pressure
dynamic_cast<ELEMENT*>(mesh_pt()->element_pt(e))->
fix_pressure(pdof,pvalue);
} // end_of_fix_pressure
}; // end_of_problem_class
//==start_of_constructor==================================================
/// Constructor for driven cavity problem in quarter circle domain
//========================================================================
template<class ELEMENT>
QuarterCircleDrivenCavityProblem<ELEMENT>::QuarterCircleDrivenCavityProblem(
NavierStokesEquations<2>::NavierStokesBodyForceFctPt body_force_fct_pt) :
Body_force_fct_pt(body_force_fct_pt)
{
// Build geometric object that parametrises the curved boundary
// of the domain
// Half axes for ellipse
double a_ellipse=1.0;
double b_ellipse=1.0;
// Setup elliptical ring
GeomObject* Wall_pt=new Ellipse(a_ellipse,b_ellipse);
// End points for wall
double xi_lo=0.0;
double xi_hi=2.0*atan(1.0);
//Now create the mesh
double fract_mid=0.5;
Problem::mesh_pt() = new
RefineableQuarterCircleSectorMesh<ELEMENT>(
Wall_pt,xi_lo,fract_mid,xi_hi);
// Set error estimator
Z2ErrorEstimator* error_estimator_pt=new Z2ErrorEstimator;
dynamic_cast<RefineableQuarterCircleSectorMesh<ELEMENT>*>(
mesh_pt())->spatial_error_estimator_pt()=error_estimator_pt;
// Set the boundary conditions for this problem: All nodes are
// free by default -- just pin the ones that have Dirichlet conditions
// here: All boundaries are Dirichlet boundaries.
unsigned num_bound = mesh_pt()->nboundary();
for(unsigned ibound=0;ibound<num_bound;ibound++)
{
unsigned num_nod= mesh_pt()->nboundary_node(ibound);
for (unsigned inod=0;inod<num_nod;inod++)
{
// Loop over values (u and v velocities)
for (unsigned i=0;i<2;i++)
{
mesh_pt()->boundary_node_pt(ibound,inod)->pin(i);
}
}
} // end loop over boundaries
//Find number of elements in mesh
unsigned n_element = mesh_pt()->nelement();
// Loop over the elements to set up element-specific
// things that cannot be handled by constructor: Pass pointer to Reynolds
// number
for(unsigned e=0;e<n_element;e++)
{
// Upcast from GeneralisedElement to the present element
ELEMENT* el_pt = dynamic_cast<ELEMENT*>(mesh_pt()->element_pt(e));
//Set the Reynolds number, etc
el_pt->re_pt() = &Global_Physical_Variables::Re;
//Set the Re/Fr
el_pt->re_invfr_pt() = &Global_Physical_Variables::Re_invFr;
//Set Gravity vector
el_pt->g_pt() = &Global_Physical_Variables::Gravity;
//set body force function
el_pt->body_force_fct_pt() = Body_force_fct_pt;
} // end loop over elements
// Initial refinement level
refine_uniformly();
refine_uniformly();
// Pin redudant pressure dofs
RefineableNavierStokesEquations<2>::
pin_redundant_nodal_pressures(mesh_pt()->element_pt());
// Now pin the first pressure dof in the first element and set it to 0.0
fix_pressure(0,0,0.0);
// Setup equation numbering scheme
cout <<"Number of equations: " << assign_eqn_numbers() << std::endl;
} // end_of_constructor
//==start_of_doc_solution=================================================
/// Doc the solution
//========================================================================
template<class ELEMENT>
void QuarterCircleDrivenCavityProblem<ELEMENT>::doc_solution(DocInfo& doc_info)
{
ofstream some_file;
char filename[100];
// Number of plot points
unsigned npts=5;
// Output solution
sprintf(filename,"%s/soln%i.dat",doc_info.directory().c_str(),
doc_info.number());
some_file.open(filename);
mesh_pt()->output(some_file,npts);
some_file.close();
} // end_of_doc_solution
//==start_of_main======================================================
/// Driver for QuarterCircleDrivenCavityProblem test problem
//=====================================================================
int main()
{
// Set output directory and initialise count
DocInfo doc_info;
doc_info.set_directory("RESLT");
// Set max. number of black-box adaptation
unsigned max_adapt=3;
// Solve problem 1 with Taylor-Hood elements
//--------------------------------------------
{
// Set up downwards-Gravity vector
Global_Physical_Variables::Gravity[0] = 0.0;
Global_Physical_Variables::Gravity[1] = -1.0;
// Set up Gamma vector for stress-divergence form
NavierStokesEquations<2>::Gamma[0]=1;
NavierStokesEquations<2>::Gamma[1]=1;
// Build problem with Gravity vector in stress divergence form,
// using zero body force function
QuarterCircleDrivenCavityProblem<RefineableQTaylorHoodElement<2> >
problem(&Global_Physical_Variables::zero_body_force);
// Solve the problem with automatic adaptation
problem.newton_solve(max_adapt);
// Step number
doc_info.number()=0;
// Output solution
problem.doc_solution(doc_info);
} // end of problem 1
// Solve problem 2 with Taylor Hood elements
//--------------------------------------------
{
// Set up zero-Gravity vector
Global_Physical_Variables::Gravity[0] = 0.0;
Global_Physical_Variables::Gravity[1] = 0.0;
// Set up Gamma vector for simplified form
NavierStokesEquations<2>::Gamma[0]=0;
NavierStokesEquations<2>::Gamma[1]=0;
// Build problem with body force function and simplified form,
// using body force function
QuarterCircleDrivenCavityProblem<RefineableQTaylorHoodElement<2> >
problem(&Global_Physical_Variables::body_force);
// Solve the problem with automatic adaptation
problem.newton_solve(max_adapt);
// Step number
doc_info.number()=1;
// Output solution
problem.doc_solution(doc_info);
} // end of problem 2
} // end_of_main
| 30.061625 | 79 | 0.6489 | [
"mesh",
"object",
"vector"
] |
80ffef034b9cc4f8a44e1305d122d46477360da3 | 1,899 | cpp | C++ | utils.cpp | gwint/distributed-key-value-store | 4450c1381f993fa4b094583db216e494cd58bc7f | [
"MIT"
] | 5 | 2020-08-01T14:41:19.000Z | 2022-01-16T03:26:33.000Z | utils.cpp | gwint/distributed-key-value-store | 4450c1381f993fa4b094583db216e494cd58bc7f | [
"MIT"
] | 2 | 2021-06-18T00:56:51.000Z | 2021-07-05T15:26:39.000Z | utils.cpp | gwint/distributed-key-value-store | 4450c1381f993fa4b094583db216e494cd58bc7f | [
"MIT"
] | null | null | null | #include <stdlib.h>
#include <sstream>
#include <iostream>
#include "dotenv.h"
#include "constants.hpp"
#include "utils.hpp"
#include "replicaservice_types.h"
#include "ReplicaService.h"
Entry
getEmptyLogEntry() {
Entry emptyLogEntry;
emptyLogEntry.type = EntryType::EMPTY_ENTRY;
emptyLogEntry.key = "";
emptyLogEntry.value = "";
emptyLogEntry.term = -1;
emptyLogEntry.clientIdentifier = "";
emptyLogEntry.requestIdentifier = std::numeric_limits<int>::max();
return emptyLogEntry;
}
unsigned int
getElectionTimeout() {
unsigned int minTimeMS = atoi(dotenv::env[MIN_ELECTION_TIMEOUT_ENV_VAR_NAME].c_str());
unsigned int maxTimeMS = atoi(dotenv::env[MAX_ELECTION_TIMEOUT_ENV_VAR_NAME].c_str());
std::cout << minTimeMS << "\n";
std::cout << maxTimeMS << "\n";
srand(time(0));
return (rand() % (maxTimeMS - minTimeMS)) + minTimeMS;
}
std::vector<ID>
getMemberIDs(const std::vector<std::string>& socketAddrs) {
std::vector<ID> membership;
for(const std::string& addr : socketAddrs) {
std::stringstream ss(addr);
std::string host;
std::string portStr;
getline(ss, host, ':');
getline(ss, portStr, ':');
ID id;
id.hostname = host;
id.port = atoi(portStr.c_str());
membership.push_back(id);
}
return membership;
}
ID
getNullID() {
ID nullID;
nullID.hostname = "";
nullID.port = 0;
return nullID;
}
bool
isANullID(const ID& id) {
return id.hostname == "" && id.port == 0;
}
bool
areAMajorityGreaterThanOrEqual(std::vector<int> numLst, int num) {
unsigned int numForMajority = (numLst.size() / 2) + 1;
unsigned int numGreaterThanOrEqual = 0;
for(const int& currNum : numLst) {
if(currNum >= num) {
++numGreaterThanOrEqual;
}
}
return numGreaterThanOrEqual >= numForMajority;
}
| 21.827586 | 90 | 0.63981 | [
"vector"
] |
44015af4c09e00bcf0b6f8dce6b74112fedd94a5 | 16,123 | cpp | C++ | src/spell_fireball.cpp | libtcod/treeburner | ace0eab18d55db77475f509f1bcd8b647cc46c3b | [
"MIT"
] | null | null | null | src/spell_fireball.cpp | libtcod/treeburner | ace0eab18d55db77475f509f1bcd8b647cc46c3b | [
"MIT"
] | null | null | null | src/spell_fireball.cpp | libtcod/treeburner | ace0eab18d55db77475f509f1bcd8b647cc46c3b | [
"MIT"
] | null | null | null | /*
* Copyright (c) 2009 Jice
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * The name of Jice may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY Jice ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL Jice BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <math.h>
#include <stdio.h>
#include "main.hpp"
float FireBall::incanRange=0.0f;
float FireBall::incanLife=0.0f;
float FireBall::sparkleSpeed=0.0f;
int FireBall::nbSparkles=0;
float FireBall::damage=0;
float FireBall::range=0;
bool FireBall::sparkleThrough=false;
bool FireBall::sparkleBounce=false;
bool FireBall::incandescence=false;
bool FireBall::sparkle=false;
TCODList<FireBall *> FireBall::incandescences;
FireBall::FireBall(float xFrom,float yFrom, int xTo, int yTo, FireBallType type, const char * subtype) : type(type) {
if ( damage == 0 ) {
damage=config.getFloatProperty("config.spells.fireball.baseDamage");
range=config.getFloatProperty("config.spells.fireball.baseRange");
}
x=xFrom;
fx=x;
y=yFrom;
fy=y;
light.x=x*2;
light.y=y*2;
dx = xTo-xFrom;
dy = yTo-yFrom;
float l=1.0f/sqrt(dx*dx+dy*dy);
dx*=l;
dy*=l;
effect=FIREBALL_MOVE;
gameEngine->dungeon->addLight(&light);
fxLife=1.0f;
typeData = getType(subtype);
light.color=typeData->lightColor;
light.range=typeData->lightRange*range;
light.randomRad=typeData->lightRandomRad;
heatTimer=0.0f;
}
FireBall::Type *FireBall::getType(const char *name) {
static TCODList<const char *> names;
static TCODList<Type *> types;
int i=0;
for ( const char **it=names.begin(); it!=names.end(); it++,i++) {
if (strcmp(name,*it) ==0 ) return types.get(i);
}
Type *type=new Type();
char buf[128];
// this sucks. libtcod parser should have variadic functions
sprintf(buf,"config.spells.%s.trailLength",name);
type->trailLength=config.getIntProperty(buf);
sprintf(buf,"config.spells.%s.lightColor",name);
type->lightColor=getHDRColorProperty(config,buf);
sprintf(buf,"config.spells.%s.lightRange",name);
type->lightRange=config.getFloatProperty(buf);
sprintf(buf,"config.spells.%s.lightRandomRad",name);
type->lightRandomRad=config.getBoolProperty(buf);
sprintf(buf,"config.spells.%s.speed",name);
type->speed=config.getFloatProperty(buf);
sprintf(buf,"config.spells.%s.standardLife",name);
type->standardLife=config.getFloatProperty(buf);
sprintf(buf,"config.spells.%s.sparkLife",name);
type->sparkLife=config.getFloatProperty(buf);
sprintf(buf,"config.spells.%s.sparkleLife",name);
type->sparkleLife=config.getFloatProperty(buf);
sprintf(buf,"config.spells.%s.sparkleSpeed",name);
type->sparkleSpeed=config.getFloatProperty(buf);
sprintf(buf,"config.spells.%s.stunDelay",name);
type->stunDelay=config.getFloatProperty(buf);
names.push(strdup(name));
types.push(type);
return type;
}
FireBall::~FireBall() {
gameEngine->dungeon->removeLight(&light);
}
void FireBall::render(LightMap *lightMap) {
if ( effect == FIREBALL_MOVE ) {
float curx=fx*2-gameEngine->xOffset*2;
float cury=fy*2-gameEngine->yOffset*2;
HDRColor col=typeData->lightColor;
for (int i=0; i < typeData->trailLength; i++ ) {
int icurx=(int)curx;
int icury=(int)cury;
if ( IN_RECTANGLE(icurx,icury,lightMap->width,lightMap->height) ) {
HDRColor lcol=lightMap->getColor2x(icurx,icury);
lcol=lcol+col;
lightMap->setColor2x(icurx,icury,lcol);
}
curx -= dx;
cury -= dy;
col = col*0.8f;
}
} else if ( effect == FIREBALL_SPARKLE ) {
for ( Sparkle **it=sparkles.begin(); it != sparkles.end(); it++ ) {
int lmx=(int)((*it)->x)-gameEngine->xOffset*2;
int lmy=(int)((*it)->y)-gameEngine->yOffset*2;
if ( IN_RECTANGLE(lmx,lmy,lightMap->width,lightMap->height) ) {
if ( gameEngine->dungeon->map2x->isInFov((int)((*it)->x),(int)((*it)->y))) {
HDRColor lcol=lightMap->getColor2x(lmx,lmy);
lcol=lcol+light.color;
lightMap->setColor2x(lmx,lmy,lcol);
}
}
}
}
}
void FireBall::render(TCODImage *ground) {
if ( effect == FIREBALL_MOVE ) {
float curx=fx*2-gameEngine->xOffset*2;
float cury=fy*2-gameEngine->yOffset*2;
TCODColor col=typeData->lightColor;
for (int i=0; i < typeData->trailLength; i++ ) {
int icurx=(int)curx;
int icury=(int)cury;
if ( IN_RECTANGLE(icurx,icury,CON_W*2,CON_H*2) ) {
TCODColor lcol=ground->getPixel(icurx,icury);
lcol=lcol+col;
ground->putPixel(icurx,icury,lcol);
}
curx -= dx;
cury -= dy;
col = col*0.8f;
}
} else if ( effect == FIREBALL_SPARKLE ) {
for ( Sparkle **it=sparkles.begin(); it != sparkles.end(); it++ ) {
int lmx=(int)((*it)->x)-gameEngine->xOffset*2;
int lmy=(int)((*it)->y)-gameEngine->yOffset*2;
if ( IN_RECTANGLE(lmx,lmy,CON_W*2,CON_H*2) ) {
if ( gameEngine->dungeon->map2x->isInFov((int)((*it)->x),(int)((*it)->y))) {
TCODColor lcol=ground->getPixel(lmx,lmy);
lcol=lcol+light.color;
ground->putPixel(lmx,lmy,lcol);
}
}
}
}
}
bool FireBall::updateMove(float elapsed) {
GameEngine* game=gameEngine;
Dungeon *dungeon=game->dungeon;
int oldx=(int)x;
int oldy=(int)y;
fx+=dx*typeData->speed;
fy+=dy*typeData->speed;
x=(int)fx;
y=(int)fy;
light.x=x*2;
light.y=y*2;
if ( type == FB_SPARK ) {
fxLife-= elapsed/typeData->sparkLife;
if ( fxLife < 0.0f ) return false;
}
// check if we hit a wall
TCODLine::init(oldx,oldy,(int)x,(int)y);
int oldoldx=oldx;
int oldoldy=oldy;
while ( ! TCODLine::step(&oldx,&oldy) ) {
bool end=false, wallhit=false;
if (!IN_RECTANGLE(oldx,oldy,dungeon->width,dungeon->height)) {
// wall hit
// last ground cell before the wall
x=oldoldx;y=oldoldy;
end=true;
wallhit=true;
} else {
static int deltax[]={0,1,-1,0,0};
static int deltay[]={0,0,0,1,-1};
if ( type == FB_STANDARD ) {
for (FireBall **fb=gameEngine->fireballs.begin(); fb != gameEngine->fireballs.end(); fb++) {
if ( (*fb)->effect == FIREBALL_MOVE
&& (*fb)->type == FB_INCANDESCENCE
&& ABS((*fb)->x-x)<(*fb)->light.range/2 && ABS((*fb)->y-y)< (*fb)->light.range/2 ) {
float newdx = (*fb)->dx;
float newdy = (*fb)->dy;
float angle=atan2f(newdy,newdx);
angle += 0.78f;
(*fb)->dx = cosf(angle);
(*fb)->dy = sinf(angle);
type=FB_INCANDESCENCE;
typeData = getType("fireball2");
light.color=typeData->lightColor;
light.range=typeData->lightRange*range;
light.randomRad=typeData->lightRandomRad;
angle -= 2*0.78f;
dx = cosf(angle);
dy = sinf(angle);
x=(*fb)->x;
y=(*fb)->y;
end=true;
break;
}
}
}
if ( end ) return true;
if (
dungeon->hasCreature(oldx,oldy)
|| dungeon->hasCreature(oldx+1,oldy)
|| dungeon->hasCreature(oldx-1,oldy)
|| dungeon->hasCreature(oldx,oldy+1)
|| dungeon->hasCreature(oldx,oldy-1)
) {
// creature hit
for (int i=0; i < 5; i++ ) {
Creature *cr=dungeon->getCreature(oldx+deltax[i],oldy+deltay[i]);
if (cr) {
float dmg=TCODRandom::getInstance()->getFloat(damage/2,damage);
if ( type == FB_BURST ) dmg *= 4;
cr->takeDamage(dmg);
cr->stun(typeData->stunDelay);
end=true;
}
}
x=oldx;y=oldy;
}
if ( dungeon->hasItem(oldx,oldy)
|| dungeon->hasItem(oldx+1,oldy)
|| dungeon->hasItem(oldx-1,oldy)
|| dungeon->hasItem(oldx,oldy+1)
|| dungeon->hasItem(oldx,oldy-1)
) {
// item hit
for (int i=0; i < 5; i++ ) {
TCODList<Item *> *items=dungeon->getItems(oldx+deltax[i],oldy+deltay[i]);
if (items && items->size()>0) {
for (Item **it=items->begin();it!=items->end();it++) {
ItemFeature *feat=(*it)->getFeature(ITEM_FEAT_FIRE_EFFECT);
if ( feat ) {
float dmg=TCODRandom::getInstance()->getFloat(damage/2,damage);
(*it)->fireResistance -= dmg;
}
end=true;
}
}
}
}
if (! end && ! dungeon->map->isWalkable(oldx,oldy) ) {
// wall hit
// last ground cell before the wall
x=oldoldx;y=oldoldy;
end=true;
wallhit=true;
}
if ( end && dungeon->hasRipples(x,y) ) {
gameEngine->startRipple((int)x,(int)y,damage/5);
}
}
if ( end ) {
light.x=x*2;light.y=y*2;
// start effect
fxLife=1.0f;
switch(type) {
case FB_SPARK : return false; break;
case FB_STANDARD :
effect=FIREBALL_STANDARD;
break;
case FB_INCANDESCENCE :
effect=FIREBALL_TORCH;
light.color = light.color*1.5f;
curRange=0.0f;
incandescences.push(this);
break;
case FB_BURST :
effect=FIREBALL_SPARKLE;
for (int i=0; i< nbSparkles; i++) {
Sparkle *sparkle=new Sparkle();
sparkle->x=x*2;
sparkle->y=y*2;
float sparkleAngle=atan2f(-dy,-dx);
if ( wallhit ) {
sparkleAngle+=TCODRandom::getInstance()->getFloat(-1.5f,1.5f);
} else {
sparkleAngle+=TCODRandom::getInstance()->getFloat(-M_PI,M_PI);
}
sparkle->dx=cosf(sparkleAngle) * sparkleSpeed;
sparkle->dy=sinf(sparkleAngle) * sparkleSpeed;
if (IN_RECTANGLE(sparkle->x,sparkle->y,
dungeon->width*2,dungeon->height*2)) {
sparkles.push(sparkle);
} else {
delete sparkle;
}
}
break;
}
break; // exit bresenham loop
} else {
oldoldx=oldx;
oldoldy=oldy;
}
}
return true;
}
bool FireBall::updateStandard(float elapsed) {
fxLife-= elapsed*typeData->standardLife;
if ( fxLife < 0.0f ) return false;
light.range=range*(3.0-2*fxLife);
light.color=typeData->lightColor*fxLife;
return true;
}
bool FireBall::updateTorch(float elapsed) {
GameEngine* game=gameEngine;
Dungeon *dungeon=game->dungeon;
float f;
fxLife-= elapsed/incanLife;
if ( fxLife < 0.0f ) {
incandescences.removeFast(this);
return false;
}
f=noiseOffset+fxLife*250.0f;
float var=0.2*(4.0f+noise1d.get(&f));
curRange=incanRange*(2.0-fxLife)*var;
light.range=2*curRange;
/*
for (Creature **cr=dungeon->creatures.begin(); cr != dungeon->creatures.end(); cr++) {
if ( ABS((*cr)->x-x)<curRange && ABS((*cr)->y-y)< curRange ) {
// do not set fire through walls
if ( dungeon->hasLos((int)((*cr)->x),(int)((*cr)->y),(int)x,(int)y,true) ) (*cr)->burn=true;
}
}
*/
heatTimer += elapsed;
if ( heatTimer > 1.0f) {
// warm up adjacent items
heatTimer = 0.0f;
float radius=curRange;
for (int tx=-(int)floor(radius); tx <= (int)ceil(radius); tx++) {
if ( (int)(x)+tx >= 0 && (int)(x)+tx < dungeon->width) {
int dy=(int)(sqrtf(radius*radius - tx*tx));
for (int ty=-dy; ty <= dy; ty++) {
if ( (int)(y)+ty >= 0 && (int)(y)+ty < dungeon->height ) {
TCODList<Item *> *items=dungeon->getItems((int)(x)+tx,(int)(y)+ty);
for ( Item **it=items->begin(); it!=items->end(); it++) {
// found an adjacent item
ItemFeature *fireFeat=(*it)->getFeature(ITEM_FEAT_FIRE_EFFECT);
if ( fireFeat ) {
// item is affected by fire
(*it)->fireResistance -= damage/4;
}
}
Creature *cr=dungeon->getCreature((int)(x)+tx,(int)(y)+ty);
if ( cr ) {
cr->burn=true;
cr->takeDamage(damage/4);
}
}
}
}
}
}
if ( fxLife < 0.25f ) {
light.color=typeData->lightColor*fxLife*4;
}
return true;
}
bool FireBall::updateSparkle(float elapsed) {
GameEngine* game=gameEngine;
Dungeon *dungeon=game->dungeon;
bool firstFrame= (fxLife == 1.0f);
fxLife-= elapsed/typeData->sparkleLife;
if ( fxLife < 0.0f ) {
sparkles.clearAndDelete();
return false;
}
if (firstFrame) {
// burst flash
light.range=range*4.0;
light.color=typeData->lightColor*3.0f;
} else {
light.range=range*(3.0-2*fxLife);
light.color=typeData->lightColor*fxLife;
}
for ( Sparkle **it=sparkles.begin(); it != sparkles.end(); it++ ) {
Sparkle *sparkle=*it;
float speed=typeData->sparkleSpeed*fxLife;
sparkle->x+=sparkle->dx*speed;
sparkle->y+=sparkle->dy*speed;
int dungeonx=(int)(sparkle->x)/2;
int dungeony=(int)(sparkle->y)/2;
Creature *cr=NULL;
bool del=false;
for (FireBall **fb=incandescences.begin(); fb != incandescences.end(); fb++) {
if ( ABS((*fb)->x-sparkle->x/2)<(*fb)->curRange && ABS((*fb)->y-sparkle->y/2)< (*fb)->curRange ) {
FireBall *fb=new FireBall(sparkle->x/2,sparkle->y/2,(int)(sparkle->x/2+sparkle->dx*10),(int)(sparkle->y/2+sparkle->dy*10),FB_STANDARD);
gameEngine->addFireball(fb);
it = sparkles.removeFast(it);
delete sparkle;
del=true;
break;
}
}
if ( del ) continue;
if ( dungeon->hasCreature(dungeonx,dungeony)) {
cr=dungeon->getCreature(dungeonx,dungeony);
cr->takeDamage(TCODRandom::getInstance()->getFloat(damage,3*damage/2));
}
if ( (cr && !sparkleThrough )
|| ! IN_RECTANGLE(sparkle->x,sparkle->y,dungeon->width*2,dungeon->height*2 )
|| (! sparkleBounce && ! dungeon->map->isWalkable(dungeonx,dungeony)) ) {
// sparkle hit an obstacle. delete it
it=sparkles.removeFast(it);
delete sparkle;
} else if ( sparkleBounce && ! dungeon->map->isWalkable(dungeonx,dungeony)) {
// sparkle bounces
int oldx=(int)(sparkle->x-sparkle->dx*speed)/2;
int oldy=(int)(sparkle->y-sparkle->dy*speed)/2;
int newx=dungeonx;
int newy=dungeony;
int cdx=newx-oldx;
int cdy=newy-oldy;
if ( cdx == 0 ) {
// hit horizontal wall
sparkle->dy=-sparkle->dy;
} else if (cdy == 0 ) {
// hit vertical wall
sparkle->dx=-sparkle->dx;
} else {
bool xwalk=dungeon->map->isWalkable(oldx+cdx,oldy);
bool ywalk=dungeon->map->isWalkable(oldx,oldy+cdy);
if ( xwalk && ywalk ) {
// outer corner bounce. detect which side of the cell is hit
// TODO : this does not work
float fdx=newx+0.5f - (sparkle->x-sparkle->dx*speed);
float fdy=newy+0.5f - (sparkle->y-sparkle->dy*speed);
fdx=ABS(fdx);
fdy=ABS(fdy);
if ( fdx >= fdy ) sparkle->dx=-sparkle->dx;
if ( fdy >= fdx ) sparkle->dy=-sparkle->dy;
} else if (! xwalk ) {
if ( ywalk ) {
// vertical wall bounce
sparkle->dx=-sparkle->dx;
} else {
// inner corner bounce
sparkle->dx=-sparkle->dx;sparkle->dy=-sparkle->dy;
}
} else {
// horizontal wall bounce
sparkle->dy=-sparkle->dy;
}
}
}
}
return true;
}
bool FireBall::update(float elapsed) {
switch (effect) {
case FIREBALL_MOVE : return updateMove(elapsed); break;
case FIREBALL_TORCH : return updateTorch(elapsed); break;
case FIREBALL_SPARKLE : return updateSparkle(elapsed); break;
case FIREBALL_STANDARD : return updateStandard(elapsed); break;
}
return true;
}
| 31.926733 | 140 | 0.622961 | [
"render"
] |
4407cdef4ef34847dbdc0686ec85c4d90923687b | 4,657 | cpp | C++ | Source/CQOR/ndbm.cpp | mfaithfull/QOR | 0fa51789344da482e8c2726309265d56e7271971 | [
"BSL-1.0"
] | 9 | 2016-05-27T01:00:39.000Z | 2021-04-01T08:54:46.000Z | Source/CQOR/ndbm.cpp | mfaithfull/QOR | 0fa51789344da482e8c2726309265d56e7271971 | [
"BSL-1.0"
] | 1 | 2016-03-03T22:54:08.000Z | 2016-03-03T22:54:08.000Z | Source/CQOR/ndbm.cpp | mfaithfull/QOR | 0fa51789344da482e8c2726309265d56e7271971 | [
"BSL-1.0"
] | 4 | 2016-05-27T01:00:43.000Z | 2018-08-19T08:47:49.000Z | //ndbm.cpp
// Copyright Querysoft Limited 2013
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
#include "CQOR/CQORPolicy.h"
#include <ndbm.h>
#include <errno.h>
#include "SystemQOR.h"
#include QOR_SYS_PLATFORMHEADER(ndbm.h)
#include "CodeQOR/Tracing/FunctionContextBase.h"
#include "CodeQOR/ErrorSystem/Error.h"
#include "CQOR.h"
//--------------------------------------------------------------------------------
namespace
{
nsPlatform::Cndbm _ndbm;
}//anonymous
__QCMP_STARTLINKAGE_C
//--------------------------------------------------------------------------------
__QOR_INTERFACE( __CQOR ) int dbm_clearerr( DBM* db )
{
__QCS_FCONTEXT( "dbm_clearerr" );
int iResult = 0;
__QCS_PROTECT
{
iResult = _ndbm.dbm_clearerr( db );
}__QCS_ENDPROTECT
return iResult;
}
//--------------------------------------------------------------------------------
__QOR_INTERFACE( __CQOR ) void dbm_close( DBM* db )
{
__QCS_FCONTEXT( "dbm_close" );
__QCS_PROTECT
{
_ndbm.dbm_close( db );
}__QCS_ENDPROTECT
}
//--------------------------------------------------------------------------------
__QOR_INTERFACE( __CQOR ) int dbm_delete( DBM* db, datum key )
{
__QCS_FCONTEXT( "dbm_delete" );
int iResult = 0;
__QCS_PROTECT
{
iResult = _ndbm.dbm_delete( db, key );
}__QCS_ENDPROTECT
return iResult;
}
//--------------------------------------------------------------------------------
__QOR_INTERFACE( __CQOR ) int dbm_error( DBM* db )
{
__QCS_FCONTEXT( "dbm_error" );
int iResult = 0;
__QCS_PROTECT
{
iResult = _ndbm.dbm_error( db );
}__QCS_ENDPROTECT
return iResult;
}
//--------------------------------------------------------------------------------
__QOR_INTERFACE( __CQOR ) datum dbm_fetch( DBM* db, datum key )
{
__QCS_FCONTEXT( "dbm_fetch" );
datum Result;
__QCS_PROTECT
{
Result = _ndbm.dbm_fetch( db, key );
}__QCS_ENDPROTECT
return Result;
}
//--------------------------------------------------------------------------------
__QOR_INTERFACE( __CQOR ) datum dbm_firstkey( DBM* db )
{
__QCS_FCONTEXT( "dbm_firstkey" );
datum Result;
__QCS_PROTECT
{
Result = _ndbm.dbm_firstkey( db );
}__QCS_ENDPROTECT
return Result;
}
//--------------------------------------------------------------------------------
__QOR_INTERFACE( __CQOR ) datum dbm_nextkey( DBM* db )
{
__QCS_FCONTEXT( "mq_close" );
datum Result;
__QCS_PROTECT
{
Result = _ndbm.dbm_nextkey( db );
}__QCS_ENDPROTECT
return Result;
}
//--------------------------------------------------------------------------------
__QOR_INTERFACE( __CQOR ) DBM* dbm_open( const char* szFile, int iFlags, mode_t iMode )
{
__QCS_FCONTEXT( "dbm_open" );
DBM* pResult = 0;
__QCS_PROTECT
{
pResult = _ndbm.dbm_open( szFile, iFlags, iMode );
}__QCS_ENDPROTECT
return pResult;
}
//--------------------------------------------------------------------------------
__QOR_INTERFACE( __CQOR ) int dbm_store( DBM* db, datum key, datum content, int iStoreMode )
{
__QCS_FCONTEXT( "dbm_store" );
int iResult = 0;
__QCS_PROTECT
{
iResult = _ndbm.dbm_store( db, key, content, iStoreMode );
}__QCS_ENDPROTECT
return iResult;
}
__QCMP_ENDLINKAGE_C
| 28.746914 | 92 | 0.575048 | [
"object"
] |
440a4373d1e48e3d99bc4f9df955d132a18748b4 | 4,948 | cpp | C++ | Data Structures/Segment Tree/Stree.cpp | arias0723/ACM_Codes | 7846f5cf8bcd824018df0075067b240b401de6ec | [
"MIT"
] | 1 | 2018-03-16T18:41:08.000Z | 2018-03-16T18:41:08.000Z | Data Structures/Segment Tree/Stree.cpp | arias0723/ACM_Codes | 7846f5cf8bcd824018df0075067b240b401de6ec | [
"MIT"
] | null | null | null | Data Structures/Segment Tree/Stree.cpp | arias0723/ACM_Codes | 7846f5cf8bcd824018df0075067b240b401de6ec | [
"MIT"
] | null | null | null | /**
We can all benefit by doing occasional "toy" programs, when artificial
restrictions are set up, so that we are forced to push our abilities to
the limit.The art of tackling miniproblems with all our energy will sharpen
our talents for the real problems.
Donald E. Knuth
**/
#include <bits/stdc++.h>
#include <ext/pb_ds/tree_policy.hpp>
#include <ext/pb_ds/assoc_container.hpp>
using namespace std;
using namespace __gnu_pbds;
typedef long long ll;
typedef unsigned long long llu;
typedef vector<int> vi;
typedef vector<ll> vll;
typedef vector<vi> vvi;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
typedef vector<pii> vii;
// find_by_order(k): iterator to the k-th largest element (counting from zero)
// order_of_key(val): number of items strictly smaller than val
template <class T> using StdTreap = tree<T, null_type, less<T>, rb_tree_tag,tree_order_statistics_node_update>;
// Add defines here ...
#define endl '\n'
#define F0R(i, a) for (int i = 0; i < (a); ++i)
//#define FOR(i, a, b) for (int i = (a); i < (b); ++i)
#define FORR(i, a, b) for (int i = (b)-1; i >= a; --i)
#define F0RR(i, a) for (int i = (a)-1; i >= 0; --i)
#define REP(i,n) for ( int i=0; i<int(n); i++ )
#define REP1(i,a,b) for ( int i=(a); i<=int(b); i++ )
#define REPeste(i,n) for((i)=0;(i)<(int)(n);(i)++)
#define foreach(c,itr) for(__typeof((c).begin()) itr=(c).begin();itr!=(c).end();itr++)
#define FOR(it,c) for ( auto it=(c).begin(); it!=(c).end(); it++ )
#define mp make_pair
#define pback push_back
#define lbound lower_bound
#define ubound upper_bound
#define popcount __builtin_popcount
const int MAXN = 100005 + 5, MAXNLOG = 25;
const ll MOD = 998244353;
const int INF = 1e9;
const int BASE = 31;
const long double EPS = 1e-9;
const double PI = 4*atan(1);
const int boardi[] = {-1, -1, +0, +1, +1, +1, +0, -1};
const int boardj[] = {+0, +1, +1, +1, +0, -1, -1, -1};
// Input
int N, M, Q, P, K;
char A[MAXN];
// Segment Tree
struct data {int opened, closed;};
struct node {
int l, r;
data val;
void apply_update(node& left, node& right) {
val.opened = right.val.opened + left.val.opened - min(left.val.opened, right.val.closed);
val.closed = left.val.closed + right.val.closed - min(left.val.opened, right.val.closed);
}
data get_val() {
return val;
}
};
class STree {
public:
STree(int N) {
nodes.reserve(4 * N);
init(0, N - 1);
}
void update(const int l, const int r, const data val, int root = 1) {
node& rnode = nodes[root];
if(rnode.r < l || rnode.l > r || rnode.l > rnode.r) {
return;
}
if(rnode.l >= l && rnode.r <= r) {
// update node state
rnode.val = val;
return;
}
// split segment
update(l, r, val, 2*root);
update(l, r, val, 2*root + 1);
// update values
rnode.apply_update(nodes[2*root], nodes[2*root + 1]);
}
data query(const int l, const int r, int root = 1) {
node& rnode = nodes[root];
if(rnode.r < l || rnode.l > r || rnode.l > rnode.r) {
return {0, 0};
}
if(rnode.l >= l && rnode.r <= r) {
// calc node value
return rnode.get_val();
}
// split segment
data le = query(l, r, 2*root);
data ri = query(l, r, 2*root + 1);
int opnd = ri.opened + le.opened - min(le.opened, ri.closed);
int clsd = le.closed + ri.closed - min(le.opened, ri.closed);
return {opnd, clsd};
}
private:
vector<node> nodes;
void init(const int l, const int r, int root = 1) {
// init node
node& rnode = nodes[root];
rnode.l = l; rnode.r = r;
rnode.val = {0, 0};
// leaf nodes
if(r == l) {
if(A[l] == '(')
rnode.val = {1, 0};
else
rnode.val = {0, 1};
return;
}
init(l, (l+r)/2, 2*root);
init((l+r)/2 + 1, r, 2*root + 1);
rnode.apply_update(nodes[2*root], nodes[2*root + 1]);
}
};
int main() {
//Input region
#ifdef GHOST
system("subl name.in");
freopen("name.in", "r", stdin);
FILE * FILE_NAME = freopen("name.out", "w", stdout);
int TIME = clock();
#endif
std::ios::sync_with_stdio(false); cin.tie(0);
//Add your code here...
cin >> A;
int openCost, closeCost, op, a, b, len = strlen(A);
cin >> Q >> openCost >> closeCost >> K;
STree stree(len);
while(Q--) {
cin >> op;
if(op == 1) {
cin >> a;
a--;
if(A[a] == '(') {
A[a] = ')';
stree.update(a, a, {0, 1});
}
else {
A[a] = '(';
stree.update(a, a, {1, 0});
}
}
else {
cin >> a >> b;
data ans = stree.query(a-1, b-1);
// cout << "[" << a-1 << ", " << b-1 << "] -> " << ans.opened << ", " << ans.closed << endl;
if( (ans.opened + ans.closed) % 2 == 0 &&
(ans.opened + 1)/2 + (ans.closed + 1)/2 <= K ) {
cout << ((ans.opened + 1)/2)*openCost + ((ans.closed + 1)/2)*closeCost << endl;
}
else {
cout << "Impossible" << endl;
}
}
}
//Output region
#ifdef GHOST
cout << "\n\nTIME: " << (clock() - TIME) << " MS" << endl;
cout.flush();
fclose(FILE_NAME);
system("subl name.out");
#endif
return 0;
} | 24.616915 | 111 | 0.581447 | [
"vector"
] |
440b23fda39425ef0021eb485e266e71b8c28941 | 8,945 | cpp | C++ | src/calculator/lepton/Operation.cpp | ufopleds/DengueME_public | 6bc4af029ba88b645fc9e6d2bb437a65c548a0de | [
"BSD-2-Clause"
] | 5 | 2016-12-17T16:02:38.000Z | 2018-12-12T21:33:04.000Z | src/calculator/lepton/Operation.cpp | ufopleds/DengueME_public | 6bc4af029ba88b645fc9e6d2bb437a65c548a0de | [
"BSD-2-Clause"
] | 44 | 2016-07-15T20:00:27.000Z | 2021-03-02T02:22:53.000Z | src/calculator/lepton/Operation.cpp | ufopleds/DengueME_public | 6bc4af029ba88b645fc9e6d2bb437a65c548a0de | [
"BSD-2-Clause"
] | 5 | 2016-10-16T06:54:43.000Z | 2020-03-21T20:05:38.000Z | /* -------------------------------------------------------------------------- *
* Lepton *
* -------------------------------------------------------------------------- *
* This is part of the Lepton expression parser originating from *
* Simbios, the NIH National Center for Physics-Based Simulation of *
* Biological Structures at Stanford, funded under the NIH Roadmap for *
* Medical Research, grant U54 GM072970. See https://simtk.org. *
* *
* Portions copyright (c) 2009 Stanford University and the Authors. *
* Authors: Peter Eastman *
* Contributors: *
* *
* Permission is hereby granted, free of charge, to any person obtaining a *
* copy of this software and associated documentation files (the "Software"), *
* to deal in the Software without restriction, including without limitation *
* the rights to use, copy, modify, merge, publish, distribute, sublicense, *
* and/or sell copies of the Software, and to permit persons to whom the *
* Software is furnished to do so, subject to the following conditions: *
* *
* The above copyright notice and this permission notice shall be included in *
* all copies or substantial portions of the Software. *
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR *
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *
* THE AUTHORS, CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, *
* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR *
* OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE *
* USE OR OTHER DEALINGS IN THE SOFTWARE. *
* -------------------------------------------------------------------------- */
#include "Operation.h"
#include "ExpressionTreeNode.h"
//#include "MSVC_erfc.h"
using namespace Lepton;
using namespace std;
ExpressionTreeNode Operation::Constant::differentiate(const std::vector<ExpressionTreeNode>& children, const std::vector<ExpressionTreeNode>& childDerivs ) const {
return ExpressionTreeNode(new Operation::Constant(0.0));
}
ExpressionTreeNode Operation::Variable::differentiate(const std::vector<ExpressionTreeNode>& children, const std::vector<ExpressionTreeNode>& childDerivs ) const {
return ExpressionTreeNode(new Operation::Constant(1.0));
}
ExpressionTreeNode Operation::Custom::differentiate(const std::vector<ExpressionTreeNode>& children, const std::vector<ExpressionTreeNode>& childDerivs ) const {
if (function->getNumArguments() == 0)
return ExpressionTreeNode(new Operation::Constant(0.0));
ExpressionTreeNode result = ExpressionTreeNode(new Operation::Multiply(), ExpressionTreeNode(new Operation::Custom(*this, 0), children), childDerivs[0]);
for (int i = 1; i < getNumArguments(); i++) {
result = ExpressionTreeNode(new Operation::Add(),
result,
ExpressionTreeNode(new Operation::Multiply(), ExpressionTreeNode(new Operation::Custom(*this, i), children), childDerivs[i]));
}
return result;
}
ExpressionTreeNode Operation::Add::differentiate(const std::vector<ExpressionTreeNode>& children, const std::vector<ExpressionTreeNode>& childDerivs ) const {
return ExpressionTreeNode(new Operation::Add(), childDerivs[0], childDerivs[1]);
}
ExpressionTreeNode Operation::Subtract::differentiate(const std::vector<ExpressionTreeNode>& children, const std::vector<ExpressionTreeNode>& childDerivs ) const {
return ExpressionTreeNode(new Operation::Subtract(), childDerivs[0], childDerivs[1]);
}
ExpressionTreeNode Operation::Multiply::differentiate(const std::vector<ExpressionTreeNode>& children, const std::vector<ExpressionTreeNode>& childDerivs ) const {
return ExpressionTreeNode(new Operation::Add(),
ExpressionTreeNode(new Operation::Multiply(), children[0], childDerivs[1]),
ExpressionTreeNode(new Operation::Multiply(), children[1], childDerivs[0]));
}
ExpressionTreeNode Operation::Divide::differentiate(const std::vector<ExpressionTreeNode>& children, const std::vector<ExpressionTreeNode>& childDerivs ) const {
return ExpressionTreeNode(new Operation::Divide(),
ExpressionTreeNode(new Operation::Subtract(),
ExpressionTreeNode(new Operation::Multiply(), children[1], childDerivs[0]),
ExpressionTreeNode(new Operation::Multiply(), children[0], childDerivs[1])),
ExpressionTreeNode(new Operation::Square(), children[1]));
}
ExpressionTreeNode Operation::Power::differentiate(const std::vector<ExpressionTreeNode>& children, const std::vector<ExpressionTreeNode>& childDerivs ) const {
return ExpressionTreeNode(new Operation::Add(),
ExpressionTreeNode(new Operation::Multiply(),
ExpressionTreeNode(new Operation::Multiply(),
children[1],
ExpressionTreeNode(new Operation::Power(),
children[0], ExpressionTreeNode(new Operation::AddConstant(-1.0), children[1]))),
childDerivs[0]),
ExpressionTreeNode(new Operation::Multiply(),
ExpressionTreeNode(new Operation::Multiply(),
ExpressionTreeNode(new Operation::Power(), children[0], children[1])),
childDerivs[1]));
}
ExpressionTreeNode Operation::Negate::differentiate(const std::vector<ExpressionTreeNode>& children, const std::vector<ExpressionTreeNode>& childDerivs ) const {
return ExpressionTreeNode(new Operation::Negate(), childDerivs[0]);
}
ExpressionTreeNode Operation::Exp::differentiate(const std::vector<ExpressionTreeNode>& children, const std::vector<ExpressionTreeNode>& childDerivs ) const {
return ExpressionTreeNode(new Operation::Multiply(),
ExpressionTreeNode(new Operation::Exp(), children[0]),
childDerivs[0]);
}
ExpressionTreeNode Operation::Square::differentiate(const std::vector<ExpressionTreeNode>& children, const std::vector<ExpressionTreeNode>& childDerivs ) const {
return ExpressionTreeNode(new Operation::Multiply(),
ExpressionTreeNode(new Operation::MultiplyConstant(2.0),
children[0]),
childDerivs[0]);
}
ExpressionTreeNode Operation::Cube::differentiate(const std::vector<ExpressionTreeNode>& children, const std::vector<ExpressionTreeNode>& childDerivs ) const {
return ExpressionTreeNode(new Operation::Multiply(),
ExpressionTreeNode(new Operation::MultiplyConstant(3.0),
ExpressionTreeNode(new Operation::Square(), children[0])),
childDerivs[0]);
}
ExpressionTreeNode Operation::AddConstant::differentiate(const std::vector<ExpressionTreeNode>& children, const std::vector<ExpressionTreeNode>& childDerivs ) const {
return childDerivs[0];
}
ExpressionTreeNode Operation::MultiplyConstant::differentiate(const std::vector<ExpressionTreeNode>& children, const std::vector<ExpressionTreeNode>& childDerivs ) const {
return ExpressionTreeNode(new Operation::MultiplyConstant(value),
childDerivs[0]);
}
ExpressionTreeNode Operation::PowerConstant::differentiate(const std::vector<ExpressionTreeNode>& children, const std::vector<ExpressionTreeNode>& childDerivs ) const {
return ExpressionTreeNode(new Operation::Multiply(),
ExpressionTreeNode(new Operation::MultiplyConstant(value),
ExpressionTreeNode(new Operation::PowerConstant(value - 1),
children[0])),
childDerivs[0]);
}
| 61.689655 | 172 | 0.592957 | [
"vector"
] |
440c01a006b2071d117185e016f71c0c12efd68c | 3,064 | cpp | C++ | graph/dinic.cpp | ACM-CUBA/Team-Reference | 0ffa66be3ebed7a0c34dfffc19c9189d9435b182 | [
"Apache-2.0"
] | 3 | 2019-04-12T16:24:59.000Z | 2022-03-30T20:21:31.000Z | graph/dinic.cpp | ACM-CUBA/TR | 0ffa66be3ebed7a0c34dfffc19c9189d9435b182 | [
"Apache-2.0"
] | 3 | 2018-04-01T22:41:51.000Z | 2018-04-02T21:20:42.000Z | graph/dinic.cpp | ACM-CUBA/TR | 0ffa66be3ebed7a0c34dfffc19c9189d9435b182 | [
"Apache-2.0"
] | 2 | 2019-04-12T16:25:04.000Z | 2019-09-22T20:28:11.000Z | /*
Algorithm:
Max Flow (Dinic)
Complexity:
O(n^2 * m)
Tested:
https://www.hackerrank.com/contests/w30/challenges/a-graph-problem/problem
http://www.spoj.com/problems/FASTFLOW/
Notes:
+ In practice is faster than O(n^2 * m)
+ For network where each edge has capacity 1 the complexity is O(m * min(m^(1/2), n^(2/3))
Reference: https://people.orie.cornell.edu/dpw/orie633/LectureNotes/lecture9.pdf (Lemma 4)
*/
template<typename F, typename R = F>
struct dinic
{
typedef F flow_type;
typedef R result_type;
struct edge
{
int src, dst, rev;
flow_type flow, cap;
};
dinic(int n) : adj(n), que(n), level(n), iter(n) {}
bool side_of_S(int u) { return level[u] == -1; }
const vector<edge>& operator[](int u) const { return adj[u]; }
vector<edge>& operator[](int u) { return adj[u]; }
int add_edge(int src, int dst, flow_type cap, flow_type rcap = 0)
{
adj[src].push_back({src, dst, (int) adj[dst].size(), 0, cap});
if (src == dst) adj[src].back().rev++;
adj[dst].push_back({dst, src, (int) adj[src].size() - 1, 0, rcap});
return adj[src].size() - 1 - (src == dst);
}
static constexpr flow_type oo = numeric_limits<flow_type>::max();
result_type max_flow(int source, int sink)
{
for (int u = 0; u < adj.size(); ++u)
for (edge &e : adj[u]) e.flow = 0;
result_type flow = 0;
while (bfs(source, sink))
{
std:fill(iter.begin(), iter.end(), 0);
for (flow_type f; (f = dfs(source, sink, oo)) > 0;)
flow += f;
}
return flow;
}
private:
vector<vector<edge>> adj;
vector<int> que;
vector<int> level;
vector<int> iter;
inline edge& rev(const edge &e) { return adj[e.dst][e.rev]; }
bool bfs(int source, int sink)
{
int front = 0, back = 0;
fill(level.begin(), level.end(), -1);
level[sink] = 0;
for (que[back++] = sink; front < back && level[source] == -1; ++front)
{
int u = que[front];
for (const edge &e : adj[u])
if (level[e.dst] == -1 && rev(e).flow < rev(e).cap)
{
level[e.dst] = 1 + level[u];
que[back++] = e.dst;
}
}
return level[source] != -1;
}
flow_type dfs(int source, int sink, flow_type flow)
{
if (source == sink) return flow;
for (int &index = iter[source]; index != adj[source].size(); ++index)
{
edge &e = adj[source][index];
if (e.flow < e.cap && level[source] == 1 + level[e.dst])
{
flow_type delta = dfs(e.dst, sink, min(flow, e.cap - e.flow));
if (delta > 0)
{
e.flow += delta;
rev(e).flow -= delta;
return delta;
}
}
}
return 0;
}
};
| 28.635514 | 102 | 0.490209 | [
"vector"
] |
440fe9d2e9e2b406915d9b9d069fd1f2cd69db39 | 1,296 | cpp | C++ | aws-cpp-sdk-devops-guru/source/model/EndTimeRange.cpp | perfectrecall/aws-sdk-cpp | fb8cbebf2fd62720b65aeff841ad2950e73d8ebd | [
"Apache-2.0"
] | 1 | 2022-02-12T08:09:30.000Z | 2022-02-12T08:09:30.000Z | aws-cpp-sdk-devops-guru/source/model/EndTimeRange.cpp | perfectrecall/aws-sdk-cpp | fb8cbebf2fd62720b65aeff841ad2950e73d8ebd | [
"Apache-2.0"
] | 1 | 2021-10-14T16:57:00.000Z | 2021-10-18T10:47:24.000Z | aws-cpp-sdk-devops-guru/source/model/EndTimeRange.cpp | ravindra-wagh/aws-sdk-cpp | 7d5ff01b3c3b872f31ca98fb4ce868cd01e97696 | [
"Apache-2.0"
] | 1 | 2022-03-23T15:17:18.000Z | 2022-03-23T15:17:18.000Z | /**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/devops-guru/model/EndTimeRange.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <utility>
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
namespace Aws
{
namespace DevOpsGuru
{
namespace Model
{
EndTimeRange::EndTimeRange() :
m_fromTimeHasBeenSet(false),
m_toTimeHasBeenSet(false)
{
}
EndTimeRange::EndTimeRange(JsonView jsonValue) :
m_fromTimeHasBeenSet(false),
m_toTimeHasBeenSet(false)
{
*this = jsonValue;
}
EndTimeRange& EndTimeRange::operator =(JsonView jsonValue)
{
if(jsonValue.ValueExists("FromTime"))
{
m_fromTime = jsonValue.GetDouble("FromTime");
m_fromTimeHasBeenSet = true;
}
if(jsonValue.ValueExists("ToTime"))
{
m_toTime = jsonValue.GetDouble("ToTime");
m_toTimeHasBeenSet = true;
}
return *this;
}
JsonValue EndTimeRange::Jsonize() const
{
JsonValue payload;
if(m_fromTimeHasBeenSet)
{
payload.WithDouble("FromTime", m_fromTime.SecondsWithMSPrecision());
}
if(m_toTimeHasBeenSet)
{
payload.WithDouble("ToTime", m_toTime.SecondsWithMSPrecision());
}
return payload;
}
} // namespace Model
} // namespace DevOpsGuru
} // namespace Aws
| 17.753425 | 71 | 0.716821 | [
"model"
] |
4413755b00e02be9c5eb5d2aeaa386c0e80debb6 | 2,147 | cpp | C++ | examples/google-code-jam/tanmayc25/B.cpp | rbenic-fer/progauthfp | d0fd96c31ab0aab1a9acdcb7c75f2b430f51c675 | [
"MIT"
] | null | null | null | examples/google-code-jam/tanmayc25/B.cpp | rbenic-fer/progauthfp | d0fd96c31ab0aab1a9acdcb7c75f2b430f51c675 | [
"MIT"
] | null | null | null | examples/google-code-jam/tanmayc25/B.cpp | rbenic-fer/progauthfp | d0fd96c31ab0aab1a9acdcb7c75f2b430f51c675 | [
"MIT"
] | null | null | null | //by Tanmay Chaudhari
#ifdef _MSC_VER
#define _CRT_SECURE_NO_WARNINGS
#endif
//#pragma comment(linker, "/STACK:66777216")
#include <bits/stdc++.h>
using namespace std;
#define si(a) scanf("%d",&a)
#define sl(a) scanf("%lld",&a)
#define pi(a) printf("%d\n",a)
#define pl(a) printf("%lld\n",a)
typedef long long ll;
typedef vector<int> vi;
typedef pair<int, int> ii;
typedef vector<vi> vvi;
typedef vector<ii> vii;
#define fast_io ios_base::sync_with_stdio(false);cin.tie(NULL)
#define SET(a,b) memset(a,b,sizeof(a))
#define forall(i,a,b) for(int i=a; i<b; i++)
#define forrev(i,a,b) for(int i=a; i>=b; i--)
#define forr(it,container) for(auto it=container.begin(); it!=container.end(); it++)
#define w(t) int t;si(t);while(t--)
#define TRACE
#ifdef TRACE
#define trace(...) __f(#__VA_ARGS__, __VA_ARGS__)
template <typename Arg1>
void __f(const char* name, Arg1&& arg1) {
cerr << name << " : " << arg1 << std::endl;
}
template <typename Arg1, typename... Args>
void __f(const char* names, Arg1&& arg1, Args&&... args) {
const char* comma = strchr(names + 1, ',');cerr.write(names, comma - names) << " : " << arg1 << " | ";__f(comma + 1, args...);
}
#else
#define trace(...)
#endif
int adj[55][55];
int main()
{
freopen("B-small-attempt2.in","r",stdin);
freopen("output.txt","w",stdout);
int t;
si(t);
forall(tt, 1, t + 1)
{
ll b, m;
cin >> b >> m;
cout << "Case #" << tt << ": ";
ll sum = (1LL << (b - 2));
if (sum < m)
{
cout << "IMPOSSIBLE\n";
continue;
}
cout << "POSSIBLE\n";
ll cnt = 0;
bool done = 0;
if (b == 2)
adj[0][b - 1] = 1;
for (ll i = 1;i < sum;i++)
{
int prev = 0;
for (int j = 0;j <= b - 2;j++)
{
if (i&(1LL << j))
{
adj[prev][j + 1] = 1;
prev = j + 1;
cnt++;
}
if (cnt == m)
{
done = 1;
break;
}
}
adj[prev][b - 1] = 1;
if (done)break;
}
for (int i = 0;i < b;i++)
{
for (int j = 0;j < b;j++)
{
cout << adj[i][j];
}
cout << endl;
}
SET(adj, 0);
}
return 0;
} | 22.134021 | 128 | 0.518398 | [
"vector"
] |
441aad77199336dc93c426c8ae0d994e5d17f587 | 939 | cpp | C++ | out/production/leetcode/io/github/zhengyhn/leetcode/global_and_local_inversions/global-and-local-inversions.cpp | zhengyhn/leetcode | 2e5e618dd7c964c8e983b187c6b1762cbe1764de | [
"MIT"
] | null | null | null | out/production/leetcode/io/github/zhengyhn/leetcode/global_and_local_inversions/global-and-local-inversions.cpp | zhengyhn/leetcode | 2e5e618dd7c964c8e983b187c6b1762cbe1764de | [
"MIT"
] | null | null | null | out/production/leetcode/io/github/zhengyhn/leetcode/global_and_local_inversions/global-and-local-inversions.cpp | zhengyhn/leetcode | 2e5e618dd7c964c8e983b187c6b1762cbe1764de | [
"MIT"
] | null | null | null | #include <iostream>
#include <vector>
#include <unordered_map>
using namespace std;
class Solution {
public:
bool isIdealPermutationOld(vector<int>& A) {
int global = 0;
int local = 0;
for (int i = 0; i < A.size(); ++i) {
int j = i + 1;
if (j < A.size() && A[i] > A[j]) {
++global;
++local;
}
for (++j; j < A.size(); ++j) {
if (A[i] > A[j]) {
++global;
}
}
}
return global == local;
}
bool isIdealPermutation(vector<int>& A) {
for (int i = 0; i < A.size(); ++i) {
if (A[i] - i > 1 || A[i] - i < -1) {
return false;
}
}
return true;
}
};
int main() {
Solution sln;
vector<int> arr;
arr = {1, 0, 2};
std::cout << sln.isIdealPermutation(arr) << std::endl;
arr = {1, 2, 0};
std::cout << sln.isIdealPermutation(arr) << std::endl;
return 0;
}
| 20.413043 | 56 | 0.452609 | [
"vector"
] |
441df84259fdab4293e477698565c38435f48370 | 26,861 | cpp | C++ | src/Value.cpp | mwoehlke-kitware/JsonBox | c5e5c60666f4610bc4d36bb08db44fb170589ec2 | [
"MIT"
] | null | null | null | src/Value.cpp | mwoehlke-kitware/JsonBox | c5e5c60666f4610bc4d36bb08db44fb170589ec2 | [
"MIT"
] | null | null | null | src/Value.cpp | mwoehlke-kitware/JsonBox | c5e5c60666f4610bc4d36bb08db44fb170589ec2 | [
"MIT"
] | null | null | null | #include <JsonBox/Value.h>
#include <cassert>
#include <stack>
#include <sstream>
#include <list>
#include <iomanip>
#include <fstream>
#include <stdexcept>
#include <JsonBox/Grammar.h>
#include <JsonBox/Convert.h>
#include <JsonBox/OutputFilter.h>
#include <JsonBox/IndentCanceller.h>
#include <JsonBox/SolidusEscaper.h>
#include <JsonBox/Array.h>
#include <JsonBox/Object.h>
#include <JsonBox/JsonParsingError.h>
#include <JsonBox/JsonWritingError.h>
namespace JsonBox {
const std::string Value::EMPTY_STRING = std::string();
const double Value::EMPTY_DOUBLE = 0.0;
const Object Value::EMPTY_OBJECT = Object();
const Array Value::EMPTY_ARRAY = Array();
std::string Value::escapeMinimumCharacters(const std::string &str) {
std::stringstream result;
// For each character in the string.
for (std::string::const_iterator i = str.begin(); i != str.end(); ++i) {
if (*i == Strings::Std::QUOTATION_MARK) {
result << Strings::Json::QUOTATION_MARK;
} else if (*i == Strings::Std::REVERSE_SOLIDUS) {
result << Strings::Json::REVERSE_SOLIDUS;
} else if (*i == Strings::Std::BACKSPACE) {
result << Strings::Json::BACKSPACE;
} else if (*i == Strings::Std::FORM_FEED) {
result << Strings::Json::FORM_FEED;
} else if (*i == Strings::Std::LINE_FEED) {
result << Strings::Json::LINE_FEED;
} else if (*i == Strings::Std::CARRIAGE_RETURN) {
result << Strings::Json::CARRIAGE_RETURN;
} else if (*i == Strings::Std::TAB) {
result << Strings::Json::TAB;
} else if (*i >= '\0' && *i <= '\x1f') {
result << Value::escapeToUnicode(*i);
} else {
result << *i;
}
}
return result.str();
}
std::string Value::escapeAllCharacters(const std::string &str) {
std::stringstream result;
// For each character in the string.
for (std::string::const_iterator i = str.begin(); i != str.end(); ++i) {
if (*i == Strings::Std::QUOTATION_MARK) {
result << Strings::Json::QUOTATION_MARK;
} else if (*i == Strings::Std::REVERSE_SOLIDUS) {
result << Strings::Json::REVERSE_SOLIDUS;
} else if (*i == Strings::Std::SOLIDUS) {
result << Strings::Json::SOLIDUS;
} else if (*i == Strings::Std::BACKSPACE) {
result << Strings::Json::BACKSPACE;
} else if (*i == Strings::Std::FORM_FEED) {
result << Strings::Json::FORM_FEED;
} else if (*i == Strings::Std::LINE_FEED) {
result << Strings::Json::LINE_FEED;
} else if (*i == Strings::Std::CARRIAGE_RETURN) {
result << Strings::Json::CARRIAGE_RETURN;
} else if (*i == Strings::Std::TAB) {
result << Strings::Json::TAB;
} else if (*i >= '\0' && *i <= '\x1f') {
result << Value::escapeToUnicode(*i);
} else {
result << *i;
}
}
return result.str();
}
const std::string Value::escapeToUnicode(char charToEscape) {
std::stringstream result;
if (charToEscape >= '\0' && charToEscape <= '\x1f') {
result << "\\u00";
result << std::hex << std::setfill('0') << std::setw(2) << static_cast<int>(charToEscape);
}
return result.str();
}
Value::Value() : type(NULL_VALUE), data() {
}
Value::Value(std::istream &input) : type(NULL_VALUE), data() {
loadFromStream(input);
}
Value::Value(const std::string &newString) : type(STRING),
data(new std::string(newString)) {
}
Value::Value(const char *newCString) : type(STRING),
data(new std::string(newCString)) {
}
Value::Value(int newInt) : type(INTEGER), data(new int(newInt)) {
}
Value::Value(double newDouble) : type(DOUBLE), data(new double(newDouble)) {
}
Value::Value(const Object &newObject) : type(OBJECT),
data(new Object(newObject)) {
}
Value::Value(const Array &newArray) : type(ARRAY),
data(new Array(newArray)) {
}
Value::Value(bool newBoolean) : type(BOOLEAN), data(new bool(newBoolean)) {
}
Value::Value(const Value &src) : type(src.type), data() {
switch (type) {
case STRING:
data.stringValue = new std::string(*src.data.stringValue);
break;
case INTEGER:
data.intValue = new int(*src.data.intValue);
break;
case DOUBLE:
data.doubleValue = new double(*src.data.doubleValue);
break;
case OBJECT:
data.objectValue = new Object(*src.data.objectValue);
break;
case ARRAY:
data.arrayValue = new Array(*src.data.arrayValue);
break;
case BOOLEAN:
data.boolValue = new bool(*src.data.boolValue);
break;
default:
type = NULL_VALUE;
break;
}
}
Value::~Value() {
clear();
}
Value &Value::operator=(const Value &src) {
if (this != &src) {
clear();
type = src.type;
switch (type) {
case STRING:
data.stringValue = new std::string(*src.data.stringValue);
break;
case INTEGER:
data.intValue = new int(*src.data.intValue);
break;
case DOUBLE:
data.doubleValue = new double(*src.data.doubleValue);
break;
case OBJECT:
data.objectValue = new Object(*src.data.objectValue);
break;
case ARRAY:
data.arrayValue = new Array(*src.data.arrayValue);
break;
case BOOLEAN:
data.boolValue = new bool(*src.data.boolValue);
break;
default:
type = NULL_VALUE;
data.stringValue = NULL;
break;
}
}
return *this;
}
Value &Value::operator=(const std::string &src) {
this->setString(src);
return *this;
}
Value &Value::operator=(const char *src) {
this->setString(src);
return *this;
}
Value &Value::operator=(int src) {
this->setInteger(src);
return *this;
}
Value &Value::operator=(double src) {
this->setDouble(src);
return *this;
}
Value &Value::operator=(const Object &src) {
this->setObject(src);
return *this;
}
Value &Value::operator=(const Array &src) {
this->setArray(src);
return *this;
}
Value &Value::operator=(bool src) {
this->setBoolean(src);
return *this;
}
bool Value::operator==(const Value &rhs) const {
bool result = true;
if (this != &rhs) {
if (type == rhs.type) {
switch (type) {
case STRING:
result = (*data.stringValue == rhs.getString());
break;
case INTEGER:
result = (*data.intValue == rhs.getInteger());
break;
case DOUBLE:
result = (*data.doubleValue == rhs.getDouble());
break;
case OBJECT:
result = (*data.objectValue == rhs.getObject());
break;
case ARRAY:
result = (*data.arrayValue == rhs.getArray());
break;
case BOOLEAN:
result = (*data.boolValue == rhs.getBoolean());
break;
default:
break;
}
} else {
result = false;
}
}
return result;
}
bool Value::operator!=(const Value &rhs) const {
return !(*this == rhs);
}
bool Value::operator<(const Value &rhs) const {
bool result = false;
if (this != &rhs) {
if (type == rhs.type) {
switch (type) {
case STRING:
result = (*data.stringValue < rhs.getString());
break;
case INTEGER:
result = (*data.intValue < rhs.getInteger());
break;
case DOUBLE:
result = (*data.doubleValue < rhs.getDouble());
break;
case OBJECT:
result = (*data.objectValue < rhs.getObject());
break;
case ARRAY:
result = (*data.arrayValue < rhs.getArray());
break;
case BOOLEAN:
result = (*data.boolValue < rhs.getBoolean());
break;
default:
break;
}
}
}
return result;
}
bool Value::operator<=(const Value &rhs) const {
return *this < rhs || *this == rhs;
}
bool Value::operator>(const Value &rhs) const {
return !(*this <= rhs);
}
bool Value::operator>=(const Value &rhs) const {
return *this > rhs || *this == rhs;
}
Value &Value::operator[](const Object::key_type &key) {
if (type != OBJECT) {
clear();
type = OBJECT;
data.objectValue = new Object();
}
return (*data.objectValue)[key];
}
Value &Value::operator[](const char *key) {
return operator[](std::string(key));
}
Value &Value::operator[](Array::size_type index) {
// We make sure it's an array.
if (type != ARRAY) {
clear();
type = ARRAY;
data.arrayValue = new Array(index + 1);
} else if (index >= (*data.arrayValue).size()) {
// We make sure the array is big enough.
data.arrayValue->resize(index + 1);
}
return (*data.arrayValue)[index];
}
Value::Type Value::getType() const {
return type;
}
bool Value::isString() const {
return type == STRING;
}
bool Value::isStringable() const {
return type != ARRAY && type != OBJECT;
}
bool Value::isInteger() const {
return type == INTEGER;
}
bool Value::isDouble() const {
return type == DOUBLE;
}
bool Value::isNumeric() const {
return type == INTEGER || type == DOUBLE;
}
bool Value::isObject() const {
return type == OBJECT;
}
bool Value::isArray() const {
return type == ARRAY;
}
bool Value::isBoolean() const {
return type == BOOLEAN;
}
bool Value::isNull() const {
return type == NULL_VALUE;
}
const std::string &Value::getString() const {
return (type == STRING) ? (*data.stringValue) : (EMPTY_STRING);
}
const std::string Value::getToString() const {
if (type == STRING) {
return *data.stringValue;
} else {
switch (type) {
case INTEGER: {
std::stringstream ss;
ss << *data.intValue;
return ss.str();
}
case DOUBLE: {
std::stringstream ss;
ss << *data.doubleValue;
return ss.str();
}
case BOOLEAN:
return (*data.boolValue) ? (Literals::TRUE_STRING) : (Literals::FALSE_STRING);
case NULL_VALUE:
return Literals::NULL_STRING;
default:
return std::string();
}
}
}
void Value::setString(std::string const &newString) {
if (type == STRING) {
*data.stringValue = newString;
} else {
clear();
type = STRING;
data.stringValue = new std::string(newString);
}
}
int Value::getInteger() const {
return (type == INTEGER) ? (*data.intValue) : ((type == DOUBLE) ? (static_cast<int>(*data.doubleValue)) : (EMPTY_INT));
}
void Value::setInteger(int newInteger) {
if (type == INTEGER) {
*data.intValue = newInteger;
} else {
clear();
type = INTEGER;
data.intValue = new int(newInteger);
}
}
double Value::getDouble() const {
return (type == DOUBLE) ? (*data.doubleValue) : ((type == INTEGER) ? (static_cast<double>(*data.intValue)) : (EMPTY_DOUBLE));
}
float Value::getFloat() const {
return static_cast<float>(getDouble());
}
void Value::setDouble(double newDouble) {
if (type == DOUBLE) {
*data.doubleValue = newDouble;
} else {
clear();
type = DOUBLE;
data.doubleValue = new double(newDouble);
}
}
const Object &Value::getObject() const {
return (type == OBJECT) ? (*data.objectValue) : (EMPTY_OBJECT);
}
void Value::setObject(const Object &newObject) {
if (type == OBJECT) {
*data.objectValue = newObject;
} else {
clear();
type = OBJECT;
data.objectValue = new Object(newObject);
}
}
const Array &Value::getArray() const {
return (type == ARRAY) ? (*data.arrayValue) : (EMPTY_ARRAY);
}
void Value::setArray(const Array &newArray) {
if (type == ARRAY) {
*data.arrayValue = newArray;
} else {
clear();
type = ARRAY;
data.arrayValue = new Array(newArray);
}
}
bool Value::getBoolean() const {
return (type == BOOLEAN) ? (*data.boolValue) : (EMPTY_BOOL);
}
void Value::setBoolean(bool newBoolean) {
if (type == BOOLEAN) {
*data.boolValue = newBoolean;
} else {
clear();
type = BOOLEAN;
data.boolValue = new bool(newBoolean);
}
}
void Value::setNull() {
clear();
type = NULL_VALUE;
data.stringValue = NULL;
}
void Value::loadFromString(std::string const &json) {
std::stringstream jsonStream(json);
loadFromStream(jsonStream);
}
void Value::loadFromStream(std::istream &input) {
char currentCharacter;
// We check that the stream is in UTF-8.
char encoding[2];
input.get(encoding[0]);
input.get(encoding[1]);
if (encoding[0] != '\0' && encoding[1] != '\0') {
// We put the characters back.
input.putback(encoding[1]);
input.putback(encoding[0]);
// Boolean value used to stop reading characters after the value
// is done loading.
bool reading = true;
while (reading && input.good()) {
input.get(currentCharacter);
if (input.good()) {
if (currentCharacter == Structural::BEGIN_END_STRING) {
// The value to be parsed is a string.
setString("");
readString(input, *data.stringValue);
reading = false;
} else if (currentCharacter == Structural::BEGIN_OBJECT) {
// The value to be parsed is an object.
setObject(Object());
readObject(input, *data.objectValue);
reading = false;
} else if (currentCharacter == Structural::BEGIN_ARRAY) {
// The value to be parsed is an array.
setArray(Array());
readArray(input, *data.arrayValue);
reading = false;
} else if (currentCharacter == Literals::NULL_STRING[0]) {
// We try to read the literal 'null'.
if (!input.eof()) {
input.get(currentCharacter);
if (currentCharacter == Literals::NULL_STRING[1]) {
if (!input.eof()) {
input.get(currentCharacter);
if (currentCharacter == Literals::NULL_STRING[2]) {
if (!input.eof()) {
input.get(currentCharacter);
if (currentCharacter == Literals::NULL_STRING[3]) {
setNull();
reading = false;
} else {
throw JsonParsingError("Invalid characters found.");
}
} else {
throw JsonParsingError("JSON input ends incorrectly.");
}
} else {
throw JsonParsingError("Invalid characters found.");
}
} else {
throw JsonParsingError("JSON ends incorrectly.");
}
} else {
throw JsonParsingError("Invalid characters found");
}
} else {
throw JsonParsingError("JSON input ends incorrectly.");
}
} else if (currentCharacter == Numbers::MINUS ||
(currentCharacter >= Numbers::DIGITS[0] && currentCharacter <= Numbers::DIGITS[9])) {
// Numbers can't start with zeroes.
input.putback(currentCharacter);
readNumber(input, *this);
reading = false;
} else if (currentCharacter == Literals::TRUE_STRING[0]) {
// We try to read the boolean literal 'true'.
if (!input.eof()) {
input.get(currentCharacter);
if (currentCharacter == Literals::TRUE_STRING[1]) {
if (!input.eof()) {
input.get(currentCharacter);
if (currentCharacter == Literals::TRUE_STRING[2]) {
if (!input.eof()) {
input.get(currentCharacter);
if (currentCharacter == Literals::TRUE_STRING[3]) {
setBoolean(true);
reading = false;
}
}
}
}
}
}
} else if (currentCharacter == Literals::FALSE_STRING[0]) {
// We try to read the boolean literal 'false'.
if (!input.eof()) {
input.get(currentCharacter);
if (currentCharacter == Literals::FALSE_STRING[1]) {
if (!input.eof()) {
input.get(currentCharacter);
if (currentCharacter == Literals::FALSE_STRING[2]) {
if (!input.eof()) {
input.get(currentCharacter);
if (currentCharacter == Literals::FALSE_STRING[3]) {
if (!input.eof()) {
input.get(currentCharacter);
if (currentCharacter == Literals::FALSE_STRING[4]) {
setBoolean(false);
reading = false;
}
}
}
}
}
}
}
}
} else if (!isWhiteSpace(currentCharacter)) {
throw JsonParsingError( std::string("Invalid character found: '").append(std::string(1, currentCharacter)).append("'"));
}
}
}
} else {
throw std::invalid_argument("JSON in input stream is not in UTF-8.");
}
}
void Value::loadFromFile(const std::string &filePath) {
std::ifstream file;
file.open(filePath.c_str(), std::ios::binary | std::ios::in);
if (file.is_open()) {
loadFromStream(file);
file.close();
} else {
throw std::invalid_argument(std::string("Failed to open the following JSON file: ").append(filePath));
}
}
void Value::writeToStream(std::ostream &output, bool indent,
bool escapeAll) const {
this->output(output, indent, escapeAll);
}
void Value::writeToFile(const std::string &filePath, bool indent,
bool escapeAll) const {
std::ofstream file;
file.open(filePath.c_str());
if (file.is_open()) {
writeToStream(file, indent, escapeAll);
file.close();
} else {
throw JsonWritingError(std::string("Failed to open the following file to write the JSON to: ").append(filePath));
}
}
Value::ValueDataPointer::ValueDataPointer(): stringValue(NULL) {
}
Value::ValueDataPointer::ValueDataPointer(std::string *newStringValue) :
stringValue(newStringValue) {
}
Value::ValueDataPointer::ValueDataPointer(int *newIntValue) :
intValue(newIntValue) {
}
Value::ValueDataPointer::ValueDataPointer(double *newDoubleValue) :
doubleValue(newDoubleValue) {
}
Value::ValueDataPointer::ValueDataPointer(Object *newObjectValue) :
objectValue(newObjectValue) {
}
Value::ValueDataPointer::ValueDataPointer(Array *newArrayValue) :
arrayValue(newArrayValue) {
}
Value::ValueDataPointer::ValueDataPointer(bool *newBoolValue) :
boolValue(newBoolValue) {
}
bool Value::isHexDigit(char digit) {
return (digit >= Numbers::DIGITS[0] && digit <= Numbers::DIGITS[9]) || (digit >= Numbers::DIGITS[10] && digit <= Numbers::DIGITS[15]) ||
(digit >= Numbers::DIGITS[16] && digit <= Numbers::DIGITS[21]);
}
bool Value::isWhiteSpace(char whiteSpace) {
return whiteSpace == Whitespace::SPACE ||
whiteSpace == Whitespace::HORIZONTAL_TAB ||
whiteSpace == Whitespace::NEW_LINE ||
whiteSpace == Whitespace::CARRIAGE_RETURN;
}
void Value::readString(std::istream &input, std::string &result) {
bool noErrors = true, noUnicodeError = true;
char currentCharacter, tmpCharacter;
std::stringstream constructing;
std::string tmpStr(4, ' ');
std::stringstream tmpSs;
int32_t tmpInt;
String32 tmpStr32;
unsigned int tmpCounter;
// As long as there aren't any errors and that we haven't reached the
// end of the input stream.
while (noErrors && !input.eof()) {
input.get(currentCharacter);
if (input.good()) {
if (currentCharacter & 0x80) { // 0x80 --> 10000000
// The character is part of an utf8 character.
constructing << currentCharacter;
} else if (currentCharacter == Strings::Json::Escape::BEGIN_ESCAPE) {
if (!input.eof()) {
input.get(tmpCharacter);
switch (tmpCharacter) {
case Strings::Json::Escape::QUOTATION_MARK:
constructing << Strings::Std::QUOTATION_MARK;
break;
case Strings::Json::Escape::REVERSE_SOLIDUS:
constructing << Strings::Std::REVERSE_SOLIDUS;
break;
case Strings::Json::Escape::SOLIDUS:
constructing << Strings::Std::SOLIDUS;
break;
case Strings::Json::Escape::BACKSPACE:
constructing << Strings::Std::BACKSPACE;
break;
case Strings::Json::Escape::FORM_FEED:
constructing << Strings::Std::FORM_FEED;
break;
case Strings::Json::Escape::LINE_FEED:
constructing << Strings::Std::LINE_FEED;
break;
case Strings::Json::Escape::CARRIAGE_RETURN:
constructing << Strings::Std::CARRIAGE_RETURN;
break;
case Strings::Json::Escape::TAB:
constructing << Strings::Std::TAB;
break;
case Strings::Json::Escape::BEGIN_UNICODE:
// TODO: Check for utf16 surrogate pairs.
tmpCounter = 0;
tmpStr.clear();
tmpStr = " ";
noUnicodeError = true;
while (tmpCounter < 4 && !input.eof()) {
input.get(tmpCharacter);
if (isHexDigit(tmpCharacter)) {
tmpStr[tmpCounter] = tmpCharacter;
} else {
// Invalid \u character, skipping it.
noUnicodeError = false;
}
++tmpCounter;
}
if (noUnicodeError) {
tmpSs.clear();
tmpSs.str("");
tmpSs << std::hex << tmpStr;
tmpSs >> tmpInt;
tmpStr32.clear();
tmpStr32.push_back(tmpInt);
tmpStr = Convert::encodeToUTF8(tmpStr32);
constructing << tmpStr;
}
break;
default:
break;
}
}
} else if (currentCharacter == '"') {
result = constructing.str();
noErrors = false;
} else {
constructing << currentCharacter;
}
}
}
}
void Value::readObject(std::istream &input, Object &result) {
bool noErrors = true;
char currentCharacter;
std::string tmpString;
while (noErrors && !input.eof()) {
input.get(currentCharacter);
if (input.good()) {
if (currentCharacter == Structural::BEGIN_END_STRING) {
// We read the object's member's name.
readString(input, tmpString);
currentCharacter = input.peek();
// We read white spaces until the next non white space.
readToNonWhiteSpace(input, currentCharacter);
if (!input.eof()) {
// We make sure it's the right character.
if (currentCharacter == Structural::NAME_SEPARATOR) {
// We read until the value starts.
readToNonWhiteSpace(input, currentCharacter);
if (!input.eof()) {
// We put the character back and we load the value
// from the stream.
input.putback(currentCharacter);
result[tmpString].loadFromStream(input);
while (!input.eof() && currentCharacter != Structural::VALUE_SEPARATOR &&
currentCharacter != Structural::END_OBJECT) {
input.get(currentCharacter);
}
if (currentCharacter == Structural::END_OBJECT) {
// We are done reading the object.
noErrors = false;
}
}
}
}
} else if (currentCharacter == Structural::END_OBJECT) {
noErrors = false;
} else if (!isWhiteSpace(currentCharacter)) {
std::cout << "Expected '\"', got '" << currentCharacter << "', ignoring it." << std::endl;
}
}
}
}
void Value::readArray(std::istream &input, Array &result) {
bool notDone = true;
char currentChar;
while (notDone && !input.eof()) {
input.get(currentChar);
if (input.good()) {
if (currentChar == Structural::END_ARRAY) {
notDone = false;
} else if (!isWhiteSpace(currentChar)) {
input.putback(currentChar);
result.push_back(Value());
result.back().type = UNKNOWN;
result.back().loadFromStream(input);
if (result.back().type == UNKNOWN) {
result.pop_back();
}
while (!input.eof() && currentChar != ',' &&
currentChar != Structural::END_ARRAY) {
input.get(currentChar);
}
if (currentChar == Structural::END_ARRAY) {
notDone = false;
}
}
}
}
}
void Value::readNumber(std::istream &input, JsonBox::Value &result) {
bool notDone = true, inFraction = false, inExponent = false;
char currentCharacter;
std::stringstream constructing;
if (!input.eof() && input.peek() == Numbers::DIGITS[0]) {
// We make sure there isn't more than one zero.
input.get(currentCharacter);
if (input.peek() == '0') {
notDone = false;
} else {
input.putback(currentCharacter);
}
}
while (notDone && !input.eof()) {
input.get(currentCharacter);
if (currentCharacter == '-') {
if (constructing.str().empty()) {
constructing << currentCharacter;
} else {
std::cout << "Expected a digit, '.', 'e' or 'E', got '" << currentCharacter << "' instead, ignoring it." << std::endl;
}
} else if (currentCharacter >= '0' && currentCharacter <= '9') {
constructing << currentCharacter;
} else if (currentCharacter == '.') {
if (!inFraction && !inExponent) {
inFraction = true;
constructing << currentCharacter;
}
} else if (currentCharacter == 'e' || currentCharacter == 'E') {
if (!inExponent) {
inExponent = true;
constructing << currentCharacter;
if (!input.eof() && (input.peek() == '-' || input.peek() == '+')) {
input.get(currentCharacter);
constructing << currentCharacter;
}
}
} else {
input.putback(currentCharacter);
notDone = false;
}
}
if (inFraction || inExponent) {
double doubleResult;
constructing >> doubleResult;
result.setDouble(doubleResult);
} else {
int intResult;
constructing >> intResult;
result.setInteger(intResult);
}
}
void Value::readToNonWhiteSpace(std::istream &input, char ¤tCharacter) {
do {
input.get(currentCharacter);
} while (!input.eof() && isWhiteSpace(currentCharacter));
}
void Value::clear() {
switch (type) {
case STRING:
delete data.stringValue;
break;
case INTEGER:
delete data.intValue;
break;
case DOUBLE:
delete data.doubleValue;
break;
case OBJECT:
delete data.objectValue;
break;
case ARRAY:
delete data.arrayValue;
break;
case BOOLEAN:
delete data.boolValue;
break;
default:
break;
}
}
void Value::output(std::ostream &output, bool indent,
bool escapeAll) const {
if (indent) {
if (escapeAll) {
OutputFilter<SolidusEscaper> solidusEscaper(output.rdbuf());
output.rdbuf(&solidusEscaper);
output << *this;
output.rdbuf(solidusEscaper.getDestination());
} else {
output << *this;
}
} else {
OutputFilter<IndentCanceller> indentCanceller(output.rdbuf());
output.rdbuf(&indentCanceller);
if (escapeAll) {
OutputFilter<SolidusEscaper> solidusEscaper(output.rdbuf());
output.rdbuf(&solidusEscaper);
output << *this;
output.rdbuf(solidusEscaper.getDestination());
} else {
output << *this;
}
output.rdbuf(indentCanceller.getDestination());
}
}
std::ostream &operator<<(std::ostream &output, const Value &v) {
switch (v.type) {
case Value::STRING:
output << Structural::BEGIN_END_STRING << Value::escapeMinimumCharacters(v.getString()) << Structural::BEGIN_END_STRING;
break;
case Value::INTEGER:
output << v.getInteger();
break;
case Value::DOUBLE:
{
std::streamsize precisionBackup = output.precision();
output.precision(17);
output << v.getDouble();
output.precision(precisionBackup);
}
break;
case Value::OBJECT:
output << v.getObject();
break;
case Value::ARRAY:
output << v.getArray();
break;
case Value::BOOLEAN:
output << (v.getBoolean() ? Literals::TRUE_STRING : Literals::FALSE_STRING);
break;
case Value::NULL_VALUE:
output << Literals::NULL_STRING;
break;
default:
break;
}
return output;
}
}
| 23.176014 | 138 | 0.611854 | [
"object"
] |
442198bfd8024dfd8f8e8ddbc19948c3fcff3370 | 4,986 | hpp | C++ | modules/wechat_qrcode/src/zxing/qrcode/detector/finder_pattern_finder.hpp | ptelang/opencv_contrib | dd68e396c76f1db4d82e5aa7a6545580939f9b9d | [
"Apache-2.0"
] | 7,158 | 2016-07-04T22:19:27.000Z | 2022-03-31T07:54:32.000Z | modules/wechat_qrcode/src/zxing/qrcode/detector/finder_pattern_finder.hpp | ptelang/opencv_contrib | dd68e396c76f1db4d82e5aa7a6545580939f9b9d | [
"Apache-2.0"
] | 2,184 | 2016-07-05T12:04:14.000Z | 2022-03-30T19:10:12.000Z | modules/wechat_qrcode/src/zxing/qrcode/detector/finder_pattern_finder.hpp | ptelang/opencv_contrib | dd68e396c76f1db4d82e5aa7a6545580939f9b9d | [
"Apache-2.0"
] | 5,535 | 2016-07-06T12:01:10.000Z | 2022-03-31T03:13:24.000Z | // This file is part of OpenCV project.
// It is subject to the license terms in the LICENSE file found in the top-level directory
// of this distribution and at http://opencv.org/license.html.
//
// Tencent is pleased to support the open source community by making WeChat QRCode available.
// Copyright (C) 2020 THL A29 Limited, a Tencent company. All rights reserved.
//
// Modified from ZXing. Copyright ZXing authors.
// Licensed under the Apache License, Version 2.0 (the "License").
#ifndef __ZXING_QRCODE_DETECTOR_FINDER_PATTERN_FINDER_HPP_
#define __ZXING_QRCODE_DETECTOR_FINDER_PATTERN_FINDER_HPP_
#include "../../common/bitmatrix.hpp"
#include "../../common/counted.hpp"
#include "../../common/unicomblock.hpp"
#include "../../errorhandler.hpp"
#include "finder_pattern.hpp"
#include "finder_pattern_info.hpp"
using zxing::ErrorHandler;
using zxing::ReaderErrorHandler;
namespace zxing {
class DecodeHints;
namespace qrcode {
class FinderPatternFinder {
public:
enum CrossCheckState {
NORMAL = 0,
LEFT_SPILL = 1,
RIHGT_SPILL = 2,
LEFT_RIGHT_SPILL = 3,
NOT_PATTERN = 4,
};
private:
static int CENTER_QUORUM;
static int MIN_SKIP;
static int MAX_MODULES;
static int INTEGER_MATH_SHIFT;
static int FP_INPUT_CNN_MAX_NUM;
static int FP_IS_SELECT_BEST;
static int FP_IS_SELECT_FILE_BEST;
static int FP_INPUT_MAX_NUM;
static int FP_FILTER_SIZE;
static int FPS_CLUSTER_MAX;
static int FPS_RESULT_MAX;
static int K_FACTOR;
static float FPS_MS_VAL;
static float FP_COUNT_MIN;
static float FP_MS_MIN;
static float FP_RIGHT_ANGLE;
static float FP_SMALL_ANGLE1;
static float FP_SMALL_ANGLE2;
static float QR_MIN_FP_AREA_ERR;
static float QR_MIN_FP_MS_ERR;
static int QR_MIN_FP_ACCEPT;
int finder_time;
CrossCheckState CURRENT_CHECK_STATE;
int compared_finder_counts;
struct HorizontalCheckedResult {
size_t centerI;
float centerJ;
};
vector<vector<HorizontalCheckedResult> > _horizontalCheckedResult;
// INI CONFIG
protected:
Ref<BitMatrix> image_;
std::vector<Ref<FinderPattern> > possibleCenters_;
bool hasSkipped_;
Ref<UnicomBlock> block_;
/** stateCount must be int[5] */
float centerFromEnd(int* stateCount, int end);
// check if satisfies finder pattern
bool foundPatternCross(int* stateCount);
// try to insert to possibleCenters_
int getStateCountTotal(int* stateCount, const CrossCheckState& check_state);
bool tryToPushToCenters(float posX, float posY, float estimatedModuleSize,
CrossCheckState horizontalState = FinderPatternFinder::NORMAL,
CrossCheckState verticalState = FinderPatternFinder::NORMAL);
bool crossCheckDiagonal(int startI, int centerJ, int maxCount, int originalStateCountTotal);
float crossCheckVertical(size_t startI, size_t centerJ, int maxCount,
int originalStateCountTota, float& estimatedVerticalModuleSize);
float crossCheckHorizontal(size_t startJ, size_t centerI, int maxCount,
int originalStateCountTotal, float& estimatedHorizontalModuleSize);
float hasHorizontalCheckedResult(size_t startJ, size_t centerI);
int addHorizontalCheckedResult(size_t startJ, size_t centerI, float centerJ);
int getMinModuleSize();
bool isEqualResult(Ref<FinderPatternInfo> src, Ref<FinderPatternInfo> dst);
/** stateCount must be int[5] */
bool handlePossibleCenter(int* stateCount, size_t i, size_t j);
int findRowSkip();
std::vector<Ref<FinderPattern> > selectBestPatterns(ErrorHandler& err_handler);
std::vector<Ref<FinderPattern> > selectFileBestPatterns(ErrorHandler& err_handler);
std::vector<Ref<FinderPattern> > orderBestPatterns(std::vector<Ref<FinderPattern> > patterns);
vector<Ref<FinderPatternInfo> > getPatternInfosFileMode(DecodeHints const& hints,
ErrorHandler& err_handler);
bool IsPossibleFindPatterInfo(Ref<FinderPattern> a, Ref<FinderPattern> b, Ref<FinderPattern> c);
void PushToResult(Ref<FinderPattern> a, Ref<FinderPattern> b, Ref<FinderPattern> c,
vector<Ref<FinderPatternInfo> >& patternInfos);
Ref<BitMatrix> getImage();
std::vector<Ref<FinderPattern> >& getPossibleCenters();
public:
void InitConfig();
float distance(Ref<ResultPoint> p1, Ref<ResultPoint> p2);
FinderPatternFinder(Ref<BitMatrix> image, Ref<UnicomBlock> block);
std::vector<Ref<FinderPatternInfo> > find(DecodeHints const& hints, ErrorHandler& err_handler);
bool checkIsoscelesRightTriangle(Ref<FinderPattern> centerA, Ref<FinderPattern> centerB,
Ref<FinderPattern> centerC, float& longSide);
};
} // namespace qrcode
} // namespace zxing
#endif // __ZXING_QRCODE_DETECTOR_FINDER_PATTERN_FINDER_HPP_
| 36.394161 | 100 | 0.71781 | [
"vector"
] |
4422f45aeaeb7166a419af7540b18ca574e216d9 | 18,395 | cc | C++ | src/modular/tests/basemgr_test.cc | liexusong/fuchsia | 81897680af92a1848a063e3c20ff3a4892ccff07 | [
"BSD-2-Clause"
] | 3 | 2021-09-02T07:21:06.000Z | 2022-03-12T03:20:10.000Z | src/modular/tests/basemgr_test.cc | liexusong/fuchsia | 81897680af92a1848a063e3c20ff3a4892ccff07 | [
"BSD-2-Clause"
] | 56 | 2021-06-03T03:16:25.000Z | 2022-03-20T01:07:44.000Z | src/modular/tests/basemgr_test.cc | liexusong/fuchsia | 81897680af92a1848a063e3c20ff3a4892ccff07 | [
"BSD-2-Clause"
] | 2 | 2022-02-25T12:22:49.000Z | 2022-03-12T03:20:10.000Z | // Copyright 2020 The Fuchsia 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 <fuchsia/testing/modular/cpp/fidl.h>
#include <lib/inspect/contrib/cpp/archive_reader.h>
#include <lib/modular/testing/cpp/fake_component.h>
#include <lib/stdcompat/optional.h>
#include <gmock/gmock.h>
#include <sdk/lib/modular/testing/cpp/fake_agent.h>
#include "src/lib/fsl/vmo/strings.h"
#include "src/modular/lib/fidl/clone.h"
#include "src/modular/lib/modular_config/modular_config.h"
#include "src/modular/lib/modular_config/modular_config_constants.h"
#include "src/modular/lib/modular_test_harness/cpp/fake_session_launcher_component.h"
#include "src/modular/lib/modular_test_harness/cpp/fake_session_shell.h"
#include "src/modular/lib/modular_test_harness/cpp/test_harness_fixture.h"
#include "src/modular/lib/pseudo_dir/pseudo_dir_server.h"
namespace {
using ::testing::HasSubstr;
constexpr char kBasemgrSelector[] = "*_inspect/basemgr.cmx:root";
constexpr char kBasemgrComponentName[] = "basemgr.cmx";
class BasemgrTest : public modular_testing::TestHarnessFixture {
public:
BasemgrTest() : executor_(dispatcher()) {}
fit::result<inspect::contrib::DiagnosticsData> GetInspectDiagnosticsData() {
auto archive = real_services()->Connect<fuchsia::diagnostics::ArchiveAccessor>();
inspect::contrib::ArchiveReader reader(std::move(archive), {kBasemgrSelector});
fit::result<std::vector<inspect::contrib::DiagnosticsData>, std::string> result;
executor_.schedule_task(
reader.SnapshotInspectUntilPresent({kBasemgrComponentName})
.then([&](fit::result<std::vector<inspect::contrib::DiagnosticsData>, std::string>&
snapshot_result) { result = std::move(snapshot_result); }));
RunLoopUntil([&] { return result.is_ok() || result.is_error(); });
if (result.is_error()) {
EXPECT_FALSE(result.is_error()) << "Error was " << result.error();
return fit::error();
}
if (result.value().size() != 1) {
EXPECT_EQ(1u, result.value().size()) << "Expected only one component";
return fit::error();
}
return fit::ok(std::move(result.value()[0]));
}
async::Executor executor_;
};
// Tests that when multiple session shell are provided the first is picked
TEST_F(BasemgrTest, StartFirstShellWhenMultiple) {
fuchsia::modular::testing::TestHarnessSpec spec;
modular_testing::TestHarnessBuilder builder(std::move(spec));
// Session shells used in list
auto session_shell = modular_testing::FakeSessionShell::CreateWithDefaultOptions();
auto session_shell2 = modular_testing::FakeSessionShell::CreateWithDefaultOptions();
// Create session shell list (appended in order)
builder.InterceptSessionShell(session_shell->BuildInterceptOptions());
builder.InterceptSessionShell(session_shell2->BuildInterceptOptions());
builder.BuildAndRun(test_harness());
// Run until one is started
RunLoopUntil([&] { return session_shell->is_running() || session_shell2->is_running(); });
// Assert only first one is started
EXPECT_TRUE(session_shell->is_running());
EXPECT_FALSE(session_shell2->is_running());
}
// Tests that basemgr starts the configured session launcher component when basemgr starts.
TEST_F(BasemgrTest, StartsSessionComponent) {
fuchsia::modular::testing::TestHarnessSpec spec;
modular_testing::TestHarnessBuilder builder(std::move(spec));
auto session_launcher_component =
modular_testing::FakeSessionLauncherComponent::CreateWithDefaultOptions();
builder.InterceptSessionLauncherComponent(session_launcher_component->BuildInterceptOptions());
builder.BuildAndRun(test_harness());
RunLoopUntil([&] { return session_launcher_component->is_running(); });
EXPECT_TRUE(session_launcher_component->is_running());
}
// Tests that basemgr starts the configured session launcher component with the given args.
TEST_F(BasemgrTest, StartsSessionComponentWithArgs) {
static const std::string kTestArg = "--foo";
fuchsia::modular::testing::TestHarnessSpec spec;
modular_testing::TestHarnessBuilder builder(std::move(spec));
fidl::VectorPtr<std::string> startup_args = std::nullopt;
builder.InterceptSessionLauncherComponent(
{.url = modular_testing::TestHarnessBuilder::GenerateFakeUrl(),
.launch_handler = [&startup_args](
fuchsia::sys::StartupInfo startup_info,
fidl::InterfaceHandle<fuchsia::modular::testing::InterceptedComponent>
/* unused */) { startup_args = startup_info.launch_info.arguments; }},
/*args=*/cpp17::make_optional<std::vector<std::string>>({kTestArg}));
builder.BuildAndRun(test_harness());
// Run until the session launcher component is started.
RunLoopUntil([&] { return startup_args.has_value(); });
ASSERT_TRUE(startup_args.has_value());
ASSERT_EQ(1u, startup_args->size());
EXPECT_EQ(kTestArg, startup_args->at(0));
}
// Tests that basemgr starts a session with the given configuration when instructed by
// the session launcher component.
TEST_F(BasemgrTest, StartsSessionWithConfig) {
fuchsia::modular::testing::TestHarnessSpec spec;
modular_testing::TestHarnessBuilder builder(std::move(spec));
auto session_launcher_component =
modular_testing::FakeSessionLauncherComponent::CreateWithDefaultOptions();
auto session_shell = modular_testing::FakeSessionShell::CreateWithDefaultOptions();
builder.InterceptSessionLauncherComponent(session_launcher_component->BuildInterceptOptions());
// The session shell is specified in the configuration generated by the session launcher
// component, so avoid InterceptSessionShell(), which adds it to the configuration in |builder|.
builder.InterceptComponent(session_shell->BuildInterceptOptions());
builder.BuildAndRun(test_harness());
RunLoopUntil([&] { return session_launcher_component->is_running(); });
EXPECT_TRUE(!session_shell->is_running());
// Create the configuration that the session launcher component passes to basemgr.
fuchsia::modular::session::SessionShellMapEntry entry;
entry.mutable_config()->mutable_app_config()->set_url(session_shell->url());
fuchsia::modular::session::ModularConfig config;
config.mutable_basemgr_config()->mutable_session_shell_map()->push_back(std::move(entry));
fuchsia::mem::Buffer config_buf;
ASSERT_TRUE(fsl::VmoFromString(modular::ConfigToJsonString(config), &config_buf));
// Launch the session.
session_launcher_component->launcher()->LaunchSessionmgr(std::move(config_buf));
// The configured session shell should start.
RunLoopUntil([&] { return session_shell->is_running(); });
EXPECT_TRUE(session_shell->is_running());
}
// Tests that the session launcher component can also provide services to sessionmgr's children.
TEST_F(BasemgrTest, SessionLauncherCanOfferServices) {
fuchsia::modular::testing::TestHarnessSpec spec;
modular_testing::TestHarnessBuilder builder(std::move(spec));
auto session_launcher_component =
modular_testing::FakeSessionLauncherComponent::CreateWithDefaultOptions();
auto session_shell = modular_testing::FakeSessionShell::CreateWithDefaultOptions();
auto agent = modular_testing::FakeAgent::CreateWithDefaultOptions();
builder.InterceptSessionLauncherComponent(session_launcher_component->BuildInterceptOptions());
// The following components are specified in the configuration generated by the session launcher.
builder.InterceptComponent(session_shell->BuildInterceptOptions());
auto agent_options = agent->BuildInterceptOptions();
agent_options.sandbox_services.push_back(fuchsia::testing::modular::TestProtocol::Name_);
builder.InterceptComponent(std::move(agent_options));
builder.BuildAndRun(test_harness());
RunLoopUntil([&] { return session_launcher_component->is_running(); });
EXPECT_TRUE(!session_shell->is_running());
// Create the configuration that the session launcher component passes to basemgr.
fuchsia::modular::session::SessionShellMapEntry entry;
entry.mutable_config()->mutable_app_config()->set_url(session_shell->url());
fuchsia::modular::session::ModularConfig config;
config.mutable_basemgr_config()->mutable_session_shell_map()->push_back(std::move(entry));
config.mutable_sessionmgr_config()->mutable_session_agents()->push_back(agent->url());
fuchsia::mem::Buffer config_buf;
ASSERT_TRUE(fsl::VmoFromString(modular::ConfigToJsonString(config), &config_buf));
// Build a directory to serve services from the session launcher component.
int connect_count = 0;
auto dir = std::make_unique<vfs::PseudoDir>();
dir->AddEntry(
fuchsia::testing::modular::TestProtocol::Name_,
std::make_unique<vfs::Service>([&](zx::channel, async_dispatcher_t*) { ++connect_count; }));
auto dir_server = std::make_unique<modular::PseudoDirServer>(std::move(dir));
// Construct a ServiceList with the above dir server.
fuchsia::sys::ServiceList service_list;
service_list.names.push_back(fuchsia::testing::modular::TestProtocol::Name_);
service_list.host_directory = dir_server->Serve().Unbind().TakeChannel();
// Launch the session.
session_launcher_component->launcher()->LaunchSessionmgrWithServices(std::move(config_buf),
std::move(service_list));
// The configured session shell and agent should start.
RunLoopUntil([&] { return session_shell->is_running() && agent->is_running(); });
// Connect to the provided service from the agent.
auto test_ptr =
agent->component_context()->svc()->Connect<fuchsia::testing::modular::TestProtocol>();
RunLoopUntil([&] { return connect_count > 0; });
EXPECT_EQ(1, connect_count);
// Test that the provided services can still be reached if the session is restarted
// (fxbug.dev/61680).
session_shell->Exit(1);
RunLoopUntil([&] { return !session_shell->is_running() && !agent->is_running(); });
RunLoopUntil([&] { return session_shell->is_running() && agent->is_running(); });
auto test_ptr2 =
agent->component_context()->svc()->Connect<fuchsia::testing::modular::TestProtocol>();
RunLoopUntil([&] { return connect_count > 1; });
EXPECT_EQ(2, connect_count);
}
// Tests that basemgr starts a new session with a new configuration, and stops the existing one
// when instructed to launch a new session by the session launcher component.
TEST_F(BasemgrTest, LaunchSessionmgrReplacesExistingSession) {
// Instructs the session launcher component to launches a session with a configuration with the
// given session shell URL, and waits until it's launched.
auto launch_session_with_session_shell =
[](modular_testing::FakeSessionLauncherComponent& session_launcher_component,
std::string session_shell_url) {
fuchsia::modular::session::SessionShellMapEntry entry;
entry.mutable_config()->mutable_app_config()->set_url(std::move(session_shell_url));
fuchsia::modular::session::ModularConfig config;
config.mutable_basemgr_config()->mutable_session_shell_map()->push_back(std::move(entry));
fuchsia::mem::Buffer config_buf;
ASSERT_TRUE(fsl::VmoFromString(modular::ConfigToJsonString(config), &config_buf));
session_launcher_component.launcher()->LaunchSessionmgr(std::move(config_buf));
};
fuchsia::modular::testing::TestHarnessSpec spec;
modular_testing::TestHarnessBuilder builder(std::move(spec));
auto session_launcher_component =
modular_testing::FakeSessionLauncherComponent::CreateWithDefaultOptions();
auto session_shell = modular_testing::FakeSessionShell::CreateWithDefaultOptions();
auto session_shell_2 = modular_testing::FakeSessionShell::CreateWithDefaultOptions();
builder.InterceptSessionLauncherComponent(session_launcher_component->BuildInterceptOptions());
builder.InterceptComponent(session_shell->BuildInterceptOptions());
builder.InterceptComponent(session_shell_2->BuildInterceptOptions());
builder.BuildAndRun(test_harness());
RunLoopUntil([&] { return session_launcher_component->is_running(); });
EXPECT_TRUE(!session_shell->is_running());
// Launch the first session.
launch_session_with_session_shell(*session_launcher_component, session_shell->url());
// The first session shell should start.
RunLoopUntil([&] { return session_shell->is_running(); });
EXPECT_TRUE(session_shell->is_running());
// Launch the second session.
launch_session_with_session_shell(*session_launcher_component, session_shell_2->url());
// The second session shell should start, and the first shell should stop.
RunLoopUntil([&] { return !session_shell->is_running() && session_shell_2->is_running(); });
EXPECT_FALSE(session_shell->is_running());
EXPECT_TRUE(session_shell_2->is_running());
}
// Tests that LaunchSessionmgr closes the channel with an ZX_ERR_INVALID_ARGS epitaph if the
// config buffer is not readable.
TEST_F(BasemgrTest, LaunchSessionmgrFailsGivenUnreadableBuffer) {
fuchsia::modular::testing::TestHarnessSpec spec;
modular_testing::TestHarnessBuilder builder(std::move(spec));
auto session_launcher_component =
modular_testing::FakeSessionLauncherComponent::CreateWithDefaultOptions();
builder.InterceptSessionLauncherComponent(session_launcher_component->BuildInterceptOptions());
builder.BuildAndRun(test_harness());
RunLoopUntil([&] { return session_launcher_component->is_running(); });
// Launch the session with a configuration Buffer that has an incorrect size.
fuchsia::mem::Buffer config_buf;
ASSERT_TRUE(fsl::VmoFromString("", &config_buf));
config_buf.size = 1;
// Connect to Launcher with a handler that lets us capture the error.
fuchsia::modular::session::LauncherPtr launcher;
session_launcher_component->component_context()->svc()->Connect(launcher.NewRequest());
bool error_handler_called{false};
zx_status_t error_status{ZX_OK};
launcher.set_error_handler([&](zx_status_t status) {
error_handler_called = true;
error_status = status;
});
launcher->LaunchSessionmgr(std::move(config_buf));
RunLoopUntil([&] { return error_handler_called; });
EXPECT_EQ(ZX_ERR_INVALID_ARGS, error_status);
}
// Tests that LaunchSessionmgr closes the channel with an ZX_ERR_INVALID_ARGS epitaph if the
// config buffer does not contain valid Modular configuration JSON.
TEST_F(BasemgrTest, LaunchSessionmgrFailsGivenInvalidConfigJson) {
fuchsia::modular::testing::TestHarnessSpec spec;
modular_testing::TestHarnessBuilder builder(std::move(spec));
auto session_launcher_component =
modular_testing::FakeSessionLauncherComponent::CreateWithDefaultOptions();
builder.InterceptSessionLauncherComponent(session_launcher_component->BuildInterceptOptions());
builder.BuildAndRun(test_harness());
RunLoopUntil([&] { return session_launcher_component->is_running(); });
// Launch the session with a configuration that is not valid JSON.
fuchsia::mem::Buffer config_buf;
ASSERT_TRUE(fsl::VmoFromString("this is not valid json", &config_buf));
// Connect to Launcher with a handler that lets us capture the error.
fuchsia::modular::session::LauncherPtr launcher;
session_launcher_component->component_context()->svc()->Connect(launcher.NewRequest());
bool error_handler_called{false};
zx_status_t error_status{ZX_OK};
launcher.set_error_handler([&](zx_status_t status) {
error_handler_called = true;
error_status = status;
});
launcher->LaunchSessionmgr(std::move(config_buf));
RunLoopUntil([&] { return error_handler_called; });
EXPECT_EQ(ZX_ERR_INVALID_ARGS, error_status);
}
// Tests that LaunchSessionmgr closes the channel with an ZX_ERR_INVALID_ARGS epitaph if the
// config includes a session launcher component.
TEST_F(BasemgrTest, LaunchSessionmgrFailsGivenConfigWithSessionLauncher) {
static constexpr auto kTestSessionLauncherUrl =
"fuchsia-pkg://fuchsia.com/test_session_launcher#meta/test_session_launcher.cmx";
fuchsia::modular::testing::TestHarnessSpec spec;
modular_testing::TestHarnessBuilder builder(std::move(spec));
auto session_launcher_component =
modular_testing::FakeSessionLauncherComponent::CreateWithDefaultOptions();
builder.InterceptSessionLauncherComponent(session_launcher_component->BuildInterceptOptions());
builder.BuildAndRun(test_harness());
RunLoopUntil([&] { return session_launcher_component->is_running(); });
// Launch the session with a valid configuration that has `session_launcher` set.
fuchsia::modular::session::ModularConfig config;
config.mutable_basemgr_config()->mutable_session_launcher()->set_url(kTestSessionLauncherUrl);
fuchsia::mem::Buffer config_buf;
ASSERT_TRUE(fsl::VmoFromString(modular::ConfigToJsonString(config), &config_buf));
// Connect to Launcher with a handler that lets us capture the error.
fuchsia::modular::session::LauncherPtr launcher;
session_launcher_component->component_context()->svc()->Connect(launcher.NewRequest());
bool error_handler_called{false};
zx_status_t error_status{ZX_OK};
launcher.set_error_handler([&](zx_status_t status) {
error_handler_called = true;
error_status = status;
});
launcher->LaunchSessionmgr(std::move(config_buf));
RunLoopUntil([&] { return error_handler_called; });
EXPECT_EQ(ZX_ERR_INVALID_ARGS, error_status);
}
// Tests that basemgr exposes its configuration in Inspect.
TEST_F(BasemgrTest, ExposesConfigInInspect) {
auto session_shell = modular_testing::FakeSessionShell::CreateWithDefaultOptions();
fuchsia::modular::testing::TestHarnessSpec spec;
spec.set_environment_suffix("inspect");
modular_testing::TestHarnessBuilder builder(std::move(spec));
builder.InterceptSessionShell(session_shell->BuildInterceptOptions());
builder.BuildAndRun(test_harness());
RunLoopUntil([&] { return session_shell->is_running(); });
auto inspect_result = GetInspectDiagnosticsData();
ASSERT_TRUE(inspect_result.is_ok());
auto inspect_data = inspect_result.take_value();
// The inspect property should contain configuration that uses |session_shell|.
const auto& config_value = inspect_data.GetByPath({"root", modular_config::kInspectConfig});
ASSERT_TRUE(config_value.IsString());
EXPECT_THAT(config_value.GetString(), HasSubstr(session_shell->url()));
}
} // namespace
| 43.693587 | 99 | 0.762001 | [
"vector"
] |
4429aa728802c03dc727cf9d2d39439bcb775aef | 24,514 | tcc | C++ | libraries/nodes/tcc/BinaryOperationNode.tcc | siddu1998/ELL | 993d5370f0f7a274e8dfd8f43220c792be46f314 | [
"MIT"
] | 1 | 2018-11-08T06:19:31.000Z | 2018-11-08T06:19:31.000Z | libraries/nodes/tcc/BinaryOperationNode.tcc | vishnoitanuj/ELL | 993d5370f0f7a274e8dfd8f43220c792be46f314 | [
"MIT"
] | null | null | null | libraries/nodes/tcc/BinaryOperationNode.tcc | vishnoitanuj/ELL | 993d5370f0f7a274e8dfd8f43220c792be46f314 | [
"MIT"
] | 1 | 2019-12-19T10:02:48.000Z | 2019-12-19T10:02:48.000Z | ////////////////////////////////////////////////////////////////////////////////////////////////////
//
// Project: Embedded Learning Library (ELL)
// File: BinaryOperationNode.tcc (nodes)
// Authors: Chuck Jacobs
//
////////////////////////////////////////////////////////////////////////////////////////////////////
#define ADD_TO_STRING_ENTRY(NAMESPACE, OPERATOR) \
case NAMESPACE::OPERATOR: \
return #OPERATOR;
#define BEGIN_FROM_STRING if (false)
#define ADD_FROM_STRING_ENTRY(NAMESPACE, OPERATOR) else if (name == #OPERATOR) return NAMESPACE::OPERATOR
namespace ell
{
namespace nodes
{
namespace BinaryOperations
{
inline std::string to_string(emitters::BinaryOperationType op)
{
switch (op)
{
ADD_TO_STRING_ENTRY(emitters::BinaryOperationType, none);
ADD_TO_STRING_ENTRY(emitters::BinaryOperationType, add);
ADD_TO_STRING_ENTRY(emitters::BinaryOperationType, subtract);
ADD_TO_STRING_ENTRY(emitters::BinaryOperationType, coordinatewiseMultiply);
ADD_TO_STRING_ENTRY(emitters::BinaryOperationType, coordinatewiseDivide);
ADD_TO_STRING_ENTRY(emitters::BinaryOperationType, logicalAnd);
ADD_TO_STRING_ENTRY(emitters::BinaryOperationType, logicalOr);
ADD_TO_STRING_ENTRY(emitters::BinaryOperationType, logicalXor);
default:
throw utilities::InputException(utilities::InputExceptionErrors::indexOutOfRange, "Unknown binary operation");
}
}
inline emitters::BinaryOperationType from_string(std::string name)
{
BEGIN_FROM_STRING;
ADD_FROM_STRING_ENTRY(emitters::BinaryOperationType, none);
ADD_FROM_STRING_ENTRY(emitters::BinaryOperationType, add);
ADD_FROM_STRING_ENTRY(emitters::BinaryOperationType, subtract);
ADD_FROM_STRING_ENTRY(emitters::BinaryOperationType, coordinatewiseMultiply);
ADD_FROM_STRING_ENTRY(emitters::BinaryOperationType, coordinatewiseDivide);
ADD_FROM_STRING_ENTRY(emitters::BinaryOperationType, logicalAnd);
ADD_FROM_STRING_ENTRY(emitters::BinaryOperationType, logicalOr);
ADD_FROM_STRING_ENTRY(emitters::BinaryOperationType, logicalXor);
throw utilities::InputException(utilities::InputExceptionErrors::indexOutOfRange, "Unknown binary operation");
}
template <typename ValueType>
ValueType Add(ValueType a, ValueType b)
{
return a + b;
}
template <>
inline bool Add(bool a, bool b)
{
throw utilities::InputException(utilities::InputExceptionErrors::typeMismatch);
}
template <typename ValueType>
ValueType Subtract(ValueType a, ValueType b)
{
return a - b;
}
template <>
inline bool Subtract(bool a, bool b)
{
throw utilities::InputException(utilities::InputExceptionErrors::typeMismatch);
}
template <typename ValueType>
ValueType Multiply(ValueType a, ValueType b)
{
return a * b;
}
template <>
inline bool Multiply(bool a, bool b)
{
throw utilities::InputException(utilities::InputExceptionErrors::typeMismatch);
}
template <typename ValueType>
ValueType Divide(ValueType a, ValueType b)
{
return a / b;
}
template <>
inline bool Divide(bool a, bool b)
{
throw utilities::InputException(utilities::InputExceptionErrors::typeMismatch);
}
//
// Logical operations
//
template <typename ValueType>
ValueType LogicalAnd(ValueType a, ValueType b)
{
throw utilities::InputException(utilities::InputExceptionErrors::typeMismatch);
}
template <>
inline bool LogicalAnd(bool a, bool b)
{
return a && b;
}
template <typename ValueType>
ValueType LogicalOr(ValueType a, ValueType b)
{
throw utilities::InputException(utilities::InputExceptionErrors::typeMismatch);
}
template <>
inline bool LogicalOr(bool a, bool b)
{
return a || b;
}
template <typename ValueType>
ValueType LogicalXor(ValueType a, ValueType b)
{
throw utilities::InputException(utilities::InputExceptionErrors::typeMismatch);
}
template <>
inline bool LogicalXor(bool a, bool b)
{
return (!a) != (!b);
}
}
template <typename ValueType>
BinaryOperationNode<ValueType>::BinaryOperationNode()
: CompilableNode({ &_input1, &_input2 }, { &_output }), _input1(this, {}, defaultInput1PortName), _input2(this, {}, defaultInput2PortName), _output(this, defaultOutputPortName, 0), _operation(emitters::BinaryOperationType::none)
{
}
template <typename ValueType>
BinaryOperationNode<ValueType>::BinaryOperationNode(const model::OutputPort<ValueType>& input1, const model::OutputPort<ValueType>& input2, emitters::BinaryOperationType operation)
: CompilableNode({ &_input1, &_input2 }, { &_output }),
_input1(this, input1, defaultInput1PortName), _inputLayout1(input1.GetMemoryLayout()),
_input2(this, input2, defaultInput2PortName), _inputLayout2(input2.GetMemoryLayout()),
_output(this, defaultOutputPortName, input1.GetMemoryLayout()),
_operation(operation),
_paddingValue(0)
{
if (_inputLayout1.GetActiveSize() != _inputLayout2.GetActiveSize())
{
throw utilities::InputException(utilities::InputExceptionErrors::invalidArgument, "Active areas must match for both inputs");
}
}
template <typename ValueType>
BinaryOperationNode<ValueType>::BinaryOperationNode(const model::OutputPort<ValueType>& input1,
const model::OutputPort<ValueType>& input2,
const model::PortMemoryLayout& layout,
emitters::BinaryOperationType operation,
ValueType padding)
: CompilableNode({ &_input1, &_input2 }, { &_output }),
_input1(this, input1, defaultInput1PortName), _inputLayout1(layout),
_input2(this, input2, defaultInput2PortName), _inputLayout2(layout),
_output(this, defaultOutputPortName, layout),
_operation(operation),
_paddingValue(padding)
{
}
template <typename ValueType>
BinaryOperationNode<ValueType>::BinaryOperationNode(const model::OutputPort<ValueType>& input1,
const model::PortMemoryLayout& inputLayout1,
const model::OutputPort<ValueType>& input2,
const model::PortMemoryLayout& inputLayout2,
const model::PortMemoryLayout& outputLayout,
emitters::BinaryOperationType operation,
ValueType padding)
: CompilableNode({ &_input1, &_input2 }, { &_output }),
_input1(this, input1, defaultInput1PortName), _inputLayout1(inputLayout1),
_input2(this, input2, defaultInput2PortName), _inputLayout2(inputLayout2),
_output(this, defaultOutputPortName, outputLayout),
_operation(operation),
_paddingValue(padding)
{
if (inputLayout1.GetActiveSize() != inputLayout2.GetActiveSize())
{
throw utilities::InputException(utilities::InputExceptionErrors::invalidArgument, "Active areas must match for both inputs");
}
if (inputLayout1.GetActiveSize() != outputLayout.GetActiveSize())
{
throw utilities::InputException(utilities::InputExceptionErrors::invalidArgument, "Input and output active areas must match");
}
}
template <typename ValueType>
template <typename Operation>
std::vector<ValueType> BinaryOperationNode<ValueType>::ComputeOutput(Operation&& function) const
{
auto outputLayout = _output.GetMemoryLayout();
auto outputSize = outputLayout.GetStride().NumElements();
auto output = std::vector<ValueType>(outputSize);
const size_t prevInput1Offset = 0;
const size_t prevInput2Offset = 0;
const size_t prevOutputOffset = 0;
ComputeDimensionLoop(function, 0, output, prevInput1Offset, prevInput2Offset, prevOutputOffset);
return output;
}
template <typename ValueType>
void BinaryOperationNode<ValueType>::Compute() const
{
std::vector<ValueType> output;
switch (_operation)
{
case emitters::BinaryOperationType::add:
output = ComputeOutput(BinaryOperations::Add<ValueType>);
break;
case emitters::BinaryOperationType::subtract:
output = ComputeOutput(BinaryOperations::Subtract<ValueType>);
break;
case emitters::BinaryOperationType::coordinatewiseMultiply:
output = ComputeOutput(BinaryOperations::Multiply<ValueType>);
break;
case emitters::BinaryOperationType::coordinatewiseDivide:
output = ComputeOutput(BinaryOperations::Divide<ValueType>);
break;
case emitters::BinaryOperationType::logicalAnd:
output = ComputeOutput(BinaryOperations::LogicalAnd<ValueType>);
break;
case emitters::BinaryOperationType::logicalOr:
output = ComputeOutput(BinaryOperations::LogicalOr<ValueType>);
break;
case emitters::BinaryOperationType::logicalXor:
output = ComputeOutput(BinaryOperations::LogicalXor<ValueType>);
break;
default:
throw utilities::LogicException(utilities::LogicExceptionErrors::notImplemented, "Unknown operation type");
}
_output.SetOutput(output);
};
template <typename ValueType>
void BinaryOperationNode<ValueType>::Copy(model::ModelTransformer& transformer) const
{
const auto& PortElements1 = transformer.GetCorrespondingInputs(_input1);
const auto& PortElements2 = transformer.GetCorrespondingInputs(_input2);
auto outputLayout = _output.GetMemoryLayout();
auto newNode = transformer.AddNode<BinaryOperationNode<ValueType>>(PortElements1, _inputLayout1, PortElements2, _inputLayout2, outputLayout, _operation);
transformer.MapNodeOutput(output, newNode->output);
}
template <typename ValueType>
void BinaryOperationNode<ValueType>::Compile(model::IRMapCompiler& compiler, emitters::IRFunctionEmitter& function)
{
if (_inputLayout1.GetMemorySize() == _inputLayout2.GetMemorySize())
{
if (!compiler.GetCompilerOptions().unrollLoops)
{
CompileLoop(compiler, function);
}
else
{
CompileExpanded(compiler, function);
}
}
else
{
emitters::LLVMValue pInput1 = compiler.EnsurePortEmitted(input1);
emitters::LLVMValue pInput2 = compiler.EnsurePortEmitted(input2);
emitters::LLVMValue pResult = compiler.EnsurePortEmitted(output, _paddingValue);
// Call recursive function to emit nested loops
emitters::LLVMValue prevInput1DimensionOffset = nullptr;
emitters::LLVMValue prevInput2DimensionOffset = nullptr;
emitters::LLVMValue prevOutputDimensionOffset = nullptr;
EmitComputeDimensionLoop(compiler, function, 0, pInput1, pInput2, pResult, prevInput1DimensionOffset, prevInput2DimensionOffset, prevOutputDimensionOffset);
}
}
template <typename ValueType>
void BinaryOperationNode<ValueType>::CompileLoop(model::IRMapCompiler& compiler, emitters::IRFunctionEmitter& function)
{
emitters::LLVMValue pInput1 = compiler.EnsurePortEmitted(input1);
emitters::LLVMValue pInput2 = compiler.EnsurePortEmitted(input2);
emitters::LLVMValue pResult = compiler.EnsurePortEmitted(output);
auto count = input1.Size();
function.VectorOperator(emitters::GetOperator<ValueType>(GetOperation()), count, pInput1, pInput2, [&pResult, &function](emitters::LLVMValue i, emitters::LLVMValue pValue) {
function.SetValueAt(pResult, i, pValue);
});
}
template <typename ValueType>
void BinaryOperationNode<ValueType>::CompileExpanded(model::IRMapCompiler& compiler, emitters::IRFunctionEmitter& function)
{
emitters::LLVMValue pResult = compiler.EnsurePortEmitted(output);
auto count = input1.Size();
for (size_t i = 0; i < count; ++i)
{
emitters::LLVMValue inputValue1 = compiler.LoadPortElementVariable(input1.GetInputElement(i));
emitters::LLVMValue inputValue2 = compiler.LoadPortElementVariable(input2.GetInputElement(i));
emitters::LLVMValue pOpResult = function.Operator(emitters::GetOperator<ValueType>(GetOperation()), inputValue1, inputValue2);
function.SetValueAt(pResult, function.Literal<int>(i), pOpResult);
}
}
//
// Arbitrary-depth nested loops are generated recursively. The ComputeDimensionLoop
// function emits `numDimensions` nested loops of the form:
//
// for(iz = 0; iz < sz; ++iz)
// {
// zOffset = (iz+offset[2]) * stride[2];
// for(iy = 0; iy < sy; ++iy)
// {
// yOffset = zOffset + (iy+offset[1]) * stride[1];
// for(ix = 0; ix < sx; ++ix)
// {
// offset = yOffset + (ix+offset[0]) * stride[0];
// x = arr[offset];
// val = f(x);
// output[offset] = val;
// }
// }
// }
//
template <typename ValueType>
template <typename Operation>
void BinaryOperationNode<ValueType>::ComputeDimensionLoop(Operation& function,
size_t dimension,
std::vector<ValueType>& output,
size_t prevInput1DimensionOffset,
size_t prevInput2DimensionOffset,
size_t prevOutputDimensionOffset) const
{
auto outputLayout = _output.GetMemoryLayout();
const auto numDimensions = _inputLayout1.NumDimensions();
auto&& inputStride1 = _inputLayout1.GetStride();
auto&& inputOffset1 = _inputLayout1.GetOffset();
auto&& inputStride2 = _inputLayout2.GetStride();
auto&& inputOffset2 = _inputLayout2.GetOffset();
auto&& inputSize = _inputLayout1.GetActiveSize();
auto&& outputOffset = outputLayout.GetOffset();
auto&& outputStride = outputLayout.GetStride();
for (int loopIndex = 0; loopIndex < inputSize[dimension]; ++loopIndex)
{
// offset within start of this dimension = (loopIndex + offset[dimension])
auto thisInput1DimensionInternalOffset = loopIndex + inputOffset1[dimension];
auto thisInput2DimensionInternalOffset = loopIndex + inputOffset2[dimension];
auto thisOutputDimensionInternalOffset = loopIndex + outputOffset[dimension];
size_t thisInput1DimensionOffset = thisInput1DimensionInternalOffset;
size_t thisInput2DimensionOffset = thisInput2DimensionInternalOffset;
size_t thisOutputDimensionOffset = thisOutputDimensionInternalOffset;
if (dimension != 0)
{
thisInput1DimensionOffset += prevInput1DimensionOffset * inputStride1[dimension];
thisInput2DimensionOffset += prevInput2DimensionOffset * inputStride2[dimension];
thisOutputDimensionOffset += prevOutputDimensionOffset * outputStride[dimension];
}
if (static_cast<int>(dimension) < numDimensions - 1)
{
// Recursive call to emit nested loop
ComputeDimensionLoop(function, dimension + 1, output, thisInput1DimensionOffset, thisInput2DimensionOffset, thisOutputDimensionOffset);
}
else
{
// We're in the innermost loop --- compute the value
auto value1 = _input1[thisInput1DimensionOffset];
auto value2 = _input2[thisInput2DimensionOffset];
auto outputValue = function(value1, value2);
output[thisOutputDimensionOffset] = outputValue;
}
}
}
template <typename ValueType>
void BinaryOperationNode<ValueType>::EmitComputeDimensionLoop(model::IRMapCompiler& compiler,
emitters::IRFunctionEmitter& function,
size_t dimension,
emitters::LLVMValue input1,
emitters::LLVMValue input2,
emitters::LLVMValue output,
emitters::LLVMValue prevInput1DimensionOffset,
emitters::LLVMValue prevInput2DimensionOffset,
emitters::LLVMValue prevOutputDimensionOffset) const
{
auto outputLayout = _output.GetMemoryLayout();
const auto numDimensions = _inputLayout1.NumDimensions();
auto&& inputStride1 = _inputLayout1.GetStride();
auto&& inputOffset1 = _inputLayout1.GetOffset();
auto&& inputStride2 = _inputLayout2.GetStride();
auto&& inputOffset2 = _inputLayout2.GetOffset();
auto&& inputSize = _inputLayout1.GetActiveSize();
auto&& outputStride = outputLayout.GetStride();
auto&& outputOffset = outputLayout.GetOffset();
function.For(inputSize[dimension], [input1, input2, output, inputOffset1, inputOffset2, inputStride1, inputStride2, outputStride, outputOffset, prevInput1DimensionOffset, prevInput2DimensionOffset, prevOutputDimensionOffset, dimension, numDimensions, &compiler, this](emitters::IRFunctionEmitter& function, emitters::LLVMValue loopIndex) {
// Calculate the offset within this dimension = (loopIndex + offset[dimension])
emitters::LLVMValue thisInput1DimensionInternalOffset = function.Operator(emitters::GetAddForValueType<int>(), loopIndex, function.Literal<int>(inputOffset1[dimension]));
emitters::LLVMValue thisInput2DimensionInternalOffset = function.Operator(emitters::GetAddForValueType<int>(), loopIndex, function.Literal<int>(inputOffset2[dimension]));
emitters::LLVMValue thisOutputDimensionInternalOffset = function.Operator(emitters::GetAddForValueType<int>(), loopIndex, function.Literal<int>(outputOffset[dimension]));
// Calculate the total offset from beginning of memory:
// * if in the outermost loop, the offset into this dimension
// * otherwise, the offset into this dimension plus the previous offset scaled by the previous dimension's stride
emitters::LLVMValue thisInput1DimensionOffset = nullptr;
emitters::LLVMValue thisInput2DimensionOffset = nullptr;
emitters::LLVMValue thisOutputDimensionOffset = nullptr;
if (dimension == 0)
{
assert(prevInput1DimensionOffset == nullptr);
assert(prevInput2DimensionOffset == nullptr);
assert(prevOutputDimensionOffset == nullptr);
thisInput1DimensionOffset = thisInput1DimensionInternalOffset;
thisInput2DimensionOffset = thisInput2DimensionInternalOffset;
thisOutputDimensionOffset = thisOutputDimensionInternalOffset;
}
else
{
auto scaledInput1DimensionOffset = function.Operator(emitters::GetMultiplyForValueType<int>(), prevInput1DimensionOffset, function.Literal<int>(inputStride1[dimension]));
auto scaledInput2DimensionOffset = function.Operator(emitters::GetMultiplyForValueType<int>(), prevInput2DimensionOffset, function.Literal<int>(inputStride2[dimension]));
thisInput1DimensionOffset = function.Operator(emitters::GetAddForValueType<int>(), scaledInput1DimensionOffset, thisInput1DimensionInternalOffset);
thisInput2DimensionOffset = function.Operator(emitters::GetAddForValueType<int>(), scaledInput2DimensionOffset, thisInput2DimensionInternalOffset);
auto scaledOutputDimensionOffset = function.Operator(emitters::GetMultiplyForValueType<int>(), prevOutputDimensionOffset, function.Literal<int>(outputStride[dimension]));
thisOutputDimensionOffset = function.Operator(emitters::GetAddForValueType<int>(), scaledOutputDimensionOffset, thisOutputDimensionInternalOffset);
}
if (static_cast<int>(dimension) < numDimensions - 1)
{
// Recursive call to emit nested loop
EmitComputeDimensionLoop(compiler, function, dimension + 1, input1, input2, output, thisInput1DimensionOffset, thisInput2DimensionOffset, thisOutputDimensionOffset);
}
else
{
// We're in the innermost loop --- compute the value
auto value1 = function.ValueAt(input1, thisInput1DimensionOffset);
auto value2 = function.ValueAt(input2, thisInput2DimensionOffset);
auto outputValue = function.Operator(emitters::GetOperator<ValueType>(GetOperation()), value1, value2);
function.SetValueAt(output, thisOutputDimensionOffset, outputValue);
}
});
}
template <typename ValueType>
utilities::ArchiveVersion BinaryOperationNode<ValueType>::GetArchiveVersion() const
{
constexpr utilities::ArchiveVersion archiveVersion = { utilities::ArchiveVersionNumbers::v7_binary_operation_active_regions };
return archiveVersion;
}
template <typename ValueType>
bool BinaryOperationNode<ValueType>::CanReadArchiveVersion(const utilities::ArchiveVersion& version) const
{
constexpr utilities::ArchiveVersion archiveVersion = { utilities::ArchiveVersionNumbers::v7_binary_operation_active_regions };
return version >= archiveVersion;
}
template <typename ValueType>
void BinaryOperationNode<ValueType>::WriteToArchive(utilities::Archiver& archiver) const
{
Node::WriteToArchive(archiver);
archiver[defaultInput1PortName] << _input1;
archiver[defaultInput2PortName] << _input2;
archiver["inputLayout1"] << _inputLayout1;
archiver["inputLayout2"] << _inputLayout2;
archiver["operation"] << BinaryOperations::to_string(_operation);
auto outputLayout = _output.GetMemoryLayout();
archiver["outputLayout"] << outputLayout;
archiver["padding"] << _paddingValue;
}
template <typename ValueType>
void BinaryOperationNode<ValueType>::ReadFromArchive(utilities::Unarchiver& archiver)
{
Node::ReadFromArchive(archiver);
archiver[defaultInput1PortName] >> _input1;
archiver[defaultInput2PortName] >> _input2;
archiver["inputLayout1"] >> _inputLayout1;
archiver["inputLayout2"] >> _inputLayout2;
std::string operation;
archiver["operation"] >> operation;
_operation = BinaryOperations::from_string(operation);
model::PortMemoryLayout outputLayout;
archiver["outputLayout"] >> outputLayout;
_output.SetMemoryLayout(outputLayout);
archiver["padding"] >> _paddingValue;
}
}
}
| 48.351085 | 347 | 0.627845 | [
"vector",
"model"
] |
442a76ccd9cc24e4acdf08f43c24ec35700c45dc | 38,073 | cpp | C++ | wallet/core/common.cpp | fakecoinbase/BeamMWslashbeam | 5ff290e1f0e7b063265fbfdd0e60b5ad4938221e | [
"Apache-2.0"
] | 1 | 2020-11-05T08:03:54.000Z | 2020-11-05T08:03:54.000Z | wallet/core/common.cpp | fakecoinbase/BeamMWslashbeam | 5ff290e1f0e7b063265fbfdd0e60b5ad4938221e | [
"Apache-2.0"
] | null | null | null | wallet/core/common.cpp | fakecoinbase/BeamMWslashbeam | 5ff290e1f0e7b063265fbfdd0e60b5ad4938221e | [
"Apache-2.0"
] | null | null | null | // Copyright 2019 The Beam Team;
//
// 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
//
// 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 "common.h"
#include "utility/logger.h"
#include "core/ecc_native.h"
#include "core/serialization_adapters.h"
#include "base58.h"
#include "utility/string_helpers.h"
#include "strings_resources.h"
#include "core/shielded.h"
#include "3rdparty/nlohmann/json.hpp"
#include "wallet_db.h"
#include <algorithm>
#include <iomanip>
#include <regex>
#include <boost/algorithm/string.hpp>
#include <boost/serialization/nvp.hpp>
#include <boost/multiprecision/cpp_dec_float.hpp>
#ifndef EMSCRIPTEN
#include <boost/multiprecision/cpp_int.hpp>
using boost::multiprecision::cpp_int;
#endif
using namespace std;
using namespace ECC;
using namespace beam;
using boost::multiprecision::cpp_dec_float_50;
namespace
{
string SkipLeadingZeroes(const char* szPtr)
{
while (*szPtr == '0')
szPtr++;
if (!*szPtr)
szPtr--; // leave at least 1 symbol
return szPtr;
}
// skips leading zeroes
template<typename T>
string EncodeToHex(const T& v)
{
char szBuf[sizeof(v) * 2 + 1];
beam::to_hex(szBuf, &v, sizeof(v));
return SkipLeadingZeroes(szBuf);
}
string EncodeToHex(const ByteBuffer& v)
{
if (v.empty())
{
return {};
}
char* szBuf = (char*)alloca(2 * v.size() + 1);
beam::to_hex(szBuf, &v[0], v.size());
return SkipLeadingZeroes(szBuf);
}
}
namespace std
{
string to_string(const beam::wallet::WalletID& id)
{
static_assert(sizeof(id) == sizeof(id.m_Channel) + sizeof(id.m_Pk), "");
return EncodeToHex(id);
}
string to_string(const Merkle::Hash& hash)
{
char sz[Merkle::Hash::nTxtLen + 1];
hash.Print(sz);
return string(sz);
}
#ifndef EMSCRIPTEN
string to_string(const beam::wallet::PrintableAmount& amount)
{
cpp_int intval;
import_bits(intval, amount.m_value.m_pData, amount.m_value.m_pData + decltype(amount.m_value)::nBytes);
if (amount.m_showPoint)
{
const auto maxGroths = std::lround(std::log10(Rules::Coin));
cpp_dec_float_50 floatval(intval);
stringstream ss;
ss << fixed << setprecision(maxGroths) << floatval / Rules::Coin;
auto str = ss.str();
const auto point = std::use_facet< std::numpunct<char>>(ss.getloc()).decimal_point();
boost::algorithm::trim_right_if(str, boost::is_any_of("0"));
boost::algorithm::trim_right_if(str, [point](const char ch) {return ch == point;});
return str;
}
else
{
stringstream ss;
cpp_int coin = intval / Rules::Coin;
cpp_int groth = intval - coin * Rules::Coin;
if (intval >= Rules::Coin)
{
ss << coin << " " << (amount.m_coinName.empty() ? "beams" : amount.m_coinName);
}
if (groth > 0 || intval == 0)
{
ss << (intval >= Rules::Coin ? (" ") : "")
<< groth << " " << (amount.m_grothName.empty() ? "groth" : amount.m_grothName);
}
return ss.str();
}
}
#endif // EMSCRIPTEN
string to_string(const beam::wallet::TxParameters& value)
{
beam::wallet::TxToken token(value);
Serializer s;
s & token;
ByteBuffer buffer;
s.swap_buf(buffer);
return beam::wallet::EncodeToBase58(buffer);
}
string to_string(const beam::Version& v)
{
return v.to_string();
}
string to_string(const beam::wallet::TxID& id)
{
return to_hex(id.data(), id.size());
}
string to_string(const beam::PeerID& id)
{
return EncodeToHex(id);
}
unsigned to_unsigned(const std::string& what, bool throws)
{
try
{
return boost::lexical_cast<unsigned>(what);
}
catch(...)
{
if (throws) throw;
return 0;
}
}
#ifndef EMSCRIPTEN
string to_string(const beam::AmountBig::Type& amount)
{
cpp_int intval;
import_bits(intval, amount.m_pData, amount.m_pData + beam::AmountBig::Type::nBytes);
stringstream ss;
ss << intval;
return ss.str();
}
#endif // EMSCRIPTEN
} // namespace std
namespace beam
{
std::ostream& operator<<(std::ostream& os, const wallet::TxID& uuid)
{
stringstream ss;
ss << "[" << std::to_string(uuid) << "]";
os << ss.str();
return os;
}
std::ostream& operator<<(std::ostream& os, const wallet::PrintableAmount& amount)
{
os << std::to_string(amount);
return os;
}
} // namespace beam
namespace beam::wallet
{
const char kTimeStampFormat3x3[] = "%Y.%m.%d %H:%M:%S";
const char kTimeStampFormatCsv[] = "%d %b %Y | %H:%M";
int WalletID::cmp(const WalletID& x) const
{
int n = m_Channel.cmp(x.m_Channel);
if (n)
return n;
return m_Pk.cmp(x.m_Pk);
}
bool WalletID::FromBuf(const ByteBuffer& x)
{
if (x.size() > sizeof(*this))
return false;
typedef uintBig_t<sizeof(*this)> BigSelf;
static_assert(sizeof(BigSelf) == sizeof(*this), "");
*reinterpret_cast<BigSelf*>(this) = Blob(x);
return true;
}
bool WalletID::FromHex(const std::string& s)
{
bool bValid = true;
ByteBuffer bb = from_hex(s, &bValid);
return bValid && FromBuf(bb);
}
bool WalletID::IsValid() const
{
BbsChannel channel;
m_Channel.Export(channel);
Point::Native p;
return m_Pk.ExportNnz(p) && channel < proto::Bbs::s_MaxWalletChannels;
}
BbsChannel WalletID::get_Channel() const
{
BbsChannel ret;
m_Channel.Export(ret);
return ret;
}
void WalletID::SetChannelFromPk()
{
// derive the channel from the address
BbsChannel ch;
m_Pk.ExportWord<0>(ch);
ch %= proto::Bbs::s_MaxWalletChannels;
m_Channel = ch;
}
boost::optional<PeerID> FromHex(const std::string& s)
{
boost::optional<PeerID> res;
bool isValid = false;
auto buf = from_hex(s, &isValid);
if (!isValid)
{
return res;
}
res.emplace();
*res = Blob(buf);
return res;
}
bool fromByteBuffer(const ByteBuffer& b, ByteBuffer& value)
{
value = b;
return true;
}
ByteBuffer toByteBuffer(const ECC::Point::Native& value)
{
ECC::Point pt;
if (value.Export(pt))
{
return toByteBuffer(pt);
}
return ByteBuffer();
}
ByteBuffer toByteBuffer(const ECC::Scalar::Native& value)
{
ECC::Scalar s;
value.Export(s);
return toByteBuffer(s);
}
ByteBuffer toByteBuffer(const ByteBuffer& value)
{
return value;
}
ErrorType getWalletError(proto::NodeProcessingException::Type exceptionType)
{
switch (exceptionType)
{
case proto::NodeProcessingException::Type::Incompatible:
return ErrorType::NodeProtocolIncompatible;
case proto::NodeProcessingException::Type::TimeOutOfSync:
return ErrorType::TimeOutOfSync;
default:
return ErrorType::NodeProtocolBase;
}
}
ErrorType getWalletError(io::ErrorCode errorCode)
{
switch (errorCode)
{
case io::ErrorCode::EC_ETIMEDOUT:
return ErrorType::ConnectionTimedOut;
case io::ErrorCode::EC_ECONNREFUSED:
return ErrorType::ConnectionRefused;
case io::ErrorCode::EC_EHOSTUNREACH:
return ErrorType::ConnectionHostUnreach;
case io::ErrorCode::EC_EADDRINUSE:
return ErrorType::ConnectionAddrInUse;
case io::ErrorCode::EC_HOST_RESOLVED_ERROR:
return ErrorType::HostResolvedError;
default:
return ErrorType::ConnectionBase;
}
}
bool ConfirmationBase::IsValid(const PeerID& pid) const
{
Point::Native pk;
if (!pid.ExportNnz(pk))
return false;
Hash::Value hv;
get_Hash(hv);
return m_Signature.IsValid(hv, pk);
}
void ConfirmationBase::Sign(const Scalar::Native& sk)
{
Hash::Value hv;
get_Hash(hv);
m_Signature.Sign(hv, sk);
}
void PaymentConfirmation::get_Hash(Hash::Value& hv) const
{
Hash::Processor hp;
hp
<< "PaymentConfirmation"
<< m_KernelID
<< m_Sender
<< m_Value;
if (m_AssetID != Asset::s_InvalidID)
{
hp
<< "asset"
<< m_AssetID;
}
hp >> hv;
}
void SwapOfferConfirmation::get_Hash(Hash::Value& hv) const
{
beam::Blob data(m_offerData);
Hash::Processor()
<< "SwapOfferSignature"
<< data
>> hv;
}
void SignatureHandler::get_Hash(Hash::Value& hv) const
{
beam::Blob data(m_data);
Hash::Processor()
<< "Undersign"
<< data
>> hv;
}
TxParameters::TxParameters(const boost::optional<TxID>& txID)
: m_ID(txID)
{
}
bool TxParameters::operator==(const TxParameters& other)
{
return m_ID == other.m_ID &&
m_Parameters == other.m_Parameters;
}
bool TxParameters::operator!=(const TxParameters& other)
{
return !(*this == other);
}
const boost::optional<TxID>& TxParameters::GetTxID() const
{
return m_ID;
}
boost::optional<ByteBuffer> TxParameters::GetParameter(TxParameterID parameterID, SubTxID subTxID) const
{
auto subTxIt = m_Parameters.find(subTxID);
if (subTxIt == m_Parameters.end())
{
return {};
}
auto it = subTxIt->second.find(parameterID);
if (it == subTxIt->second.end())
{
return {};
}
return boost::optional<ByteBuffer>(it->second);
}
TxParameters& TxParameters::SetParameter(TxParameterID parameterID, const ByteBuffer& parameter, SubTxID subTxID)
{
m_Parameters[subTxID][parameterID] = parameter;
return *this;
}
PackedTxParameters TxParameters::Pack() const
{
PackedTxParameters parameters;
for (const auto& subTx : m_Parameters)
{
if (subTx.first > kDefaultSubTxID)
{
parameters.emplace_back(TxParameterID::SubTxIndex, toByteBuffer(subTx.first));
}
for (const auto& p : subTx.second)
{
parameters.emplace_back(p.first, p.second);
}
}
return parameters;
}
TxToken::TxToken(const TxParameters& parameters)
: m_Flags(TxToken::TokenFlag)
, m_TxID(parameters.GetTxID())
, m_Parameters(parameters.Pack())
{
}
TxParameters TxToken::UnpackParameters() const
{
TxParameters result(m_TxID);
SubTxID subTxID = kDefaultSubTxID;
Deserializer d;
for (const auto& p : m_Parameters)
{
if (p.first == TxParameterID::SubTxIndex)
{
// change subTxID
d.reset(p.second.data(), p.second.size());
d & subTxID;
continue;
}
result.SetParameter(p.first, p.second, subTxID);
}
return result;
}
boost::optional<TxParameters> ParseParameters(const string& text)
{
bool isValid = true;
ByteBuffer buffer = from_hex(text, &isValid);
if (!isValid)
{
buffer = DecodeBase58(text);
if (buffer.empty())
{
return {};
}
}
if (buffer.size() < 2)
{
return {};
}
if (buffer.size() > 33 && buffer[0] & TxToken::TokenFlag) // token
{
try
{
TxToken token;
// simply deserialize for now
Deserializer d;
d.reset(&buffer[0], buffer.size());
d & token;
return boost::make_optional<TxParameters>(token.UnpackParameters());
}
catch (...)
{
// failed to deserialize
}
}
else // plain WalletID
{
WalletID walletID;
if (walletID.FromBuf(buffer) && walletID.IsValid())
{
auto result = boost::make_optional<TxParameters>({});
result->SetParameter(TxParameterID::PeerID, walletID);
return result;
}
}
return {};
}
bool LoadReceiverParams(const TxParameters& receiverParams, TxParameters& params)
{
bool res = false;
const TxParameters& p = receiverParams;
if (auto peerID = p.GetParameter<WalletID>(TxParameterID::PeerID); peerID)
{
params.SetParameter(TxParameterID::PeerID, *peerID);
res = true;
}
if (auto peerID = p.GetParameter<PeerID>(TxParameterID::PeerWalletIdentity); peerID)
{
params.SetParameter(TxParameterID::PeerWalletIdentity, *peerID);
if (auto vouchers = p.GetParameter<ShieldedVoucherList>(TxParameterID::ShieldedVoucherList); vouchers)
{
if (!IsValidVoucherList(*vouchers, *peerID))
{
LOG_ERROR() << "Voucher signature verification failed. Unauthorized voucher was provider.";
return false;
}
params.SetParameter(TxParameterID::ShieldedVoucherList, *vouchers);
}
res &= true;
}
#ifdef BEAM_LIB_VERSION
if (auto libVersion = receiverParams.GetParameter(beam::wallet::TxParameterID::LibraryVersion); libVersion)
{
std::string libVersionStr;
beam::wallet::fromByteBuffer(*libVersion, libVersionStr);
std::string myLibVersionStr = BEAM_LIB_VERSION;
std::regex libVersionRegex("\\d{1,}\\.\\d{1,}\\.\\d{4,}");
if (std::regex_match(libVersionStr, libVersionRegex) &&
std::lexicographical_compare(
myLibVersionStr.begin(),
myLibVersionStr.end(),
libVersionStr.begin(),
libVersionStr.end(),
std::less<char>{}))
{
LOG_WARNING() <<
"This token generated by newer Beam library version(" << libVersionStr << ")\n" <<
"Your version is: " << myLibVersionStr << " Please, check for updates.";
}
}
#endif // BEAM_LIB_VERSION
return res;
}
bool IsValidTimeStamp(Timestamp currentBlockTime_s, Timestamp tolerance_s)
{
Timestamp currentTime_s = getTimestamp();
if (currentTime_s > currentBlockTime_s + tolerance_s)
{
LOG_INFO() << "It seems that last known blockchain tip is not up to date";
return false;
}
return true;
}
TxStatusInterpreter::TxStatusInterpreter(const TxParameters& txParams) : m_txParams(txParams)
{
auto value = txParams.GetParameter(TxParameterID::Status);
if (value) fromByteBuffer(*value, m_status);
value = txParams.GetParameter(TxParameterID::IsSender);
if (value) fromByteBuffer(*value, m_sender);
value = txParams.GetParameter(TxParameterID::IsSelfTx);
if (value) fromByteBuffer(*value, m_selfTx);
value = txParams.GetParameter(TxParameterID::FailureReason);
if (value) fromByteBuffer(*value, m_failureReason);
}
std::string TxStatusInterpreter::getStatus() const
{
switch (m_status)
{
case TxStatus::Pending: return "pending";
case TxStatus::InProgress:
return m_selfTx ? "self sending" : (m_sender ? "waiting for receiver" : "waiting for sender");
case TxStatus::Registering:
return m_selfTx ? "self sending" : (m_sender == false ? "receiving" : "sending");
case TxStatus::Failed:
return TxFailureReason::TransactionExpired == m_failureReason ? "expired" : "failed";
case TxStatus::Canceled: return "cancelled";
case TxStatus::Completed:
return m_selfTx ? "completed" : (m_sender ? "sent" : "received");
default:
BOOST_ASSERT_MSG(false, kErrorUnknownTxStatus);
return "unknown";
}
}
std::string SimpleTxStatusInterpreter::getStatus() const
{
const auto& status = TxStatusInterpreter::getStatus();
if (status == "receiving" || status == "sending")
return "in progress";
else if (status == "completed")
return "sent to own address";
else if (status == "self sending")
return "sending to own address";
return status;
}
AssetTxStatusInterpreter::AssetTxStatusInterpreter(const TxParameters& txParams) : TxStatusInterpreter(txParams)
{
boost::optional<ByteBuffer> value = txParams.GetParameter(TxParameterID::TransactionType);
if (value) fromByteBuffer(*value, m_txType);
}
std::string AssetTxStatusInterpreter::getStatus() const
{
if (m_status == TxStatus::InProgress && m_txType == TxType::AssetInfo) return "getting info";
if (m_status == TxStatus::Completed)
{
switch (m_txType)
{
case TxType::AssetIssue: return "asset issued";
case TxType::AssetConsume: return "asset consumed";
case TxType::AssetReg: return "asset registered";
case TxType::AssetUnreg: return "asset unregistered";
case TxType::AssetInfo: return "asset confirmed";
default: break;
}
}
return TxStatusInterpreter::getStatus();
}
TxDescription::TxDescription(const TxParameters p)
: TxParameters(p)
{
fillFromTxParameters(*this);
}
void TxDescription::fillFromTxParameters(const TxParameters& parameters)
{
boost::optional<TxID> txId = parameters.GetTxID();
if (txId)
{
m_txId = *txId;
}
for (const TxParameterID p : m_initialParameters)
{
boost::optional<ByteBuffer> value = parameters.GetParameter(p);
if (value)
{
switch (p)
{
case TxParameterID::TransactionType:
fromByteBuffer(*value, m_txType);
break;
case TxParameterID::Amount:
fromByteBuffer(*value, m_amount);
break;
case TxParameterID::Fee:
fromByteBuffer(*value, m_fee);
break;
case TxParameterID::MinHeight:
fromByteBuffer(*value, m_minHeight);
break;
case TxParameterID::PeerID:
fromByteBuffer(*value, m_peerId);
break;
case TxParameterID::MyID:
fromByteBuffer(*value, m_myId);
break;
case TxParameterID::CreateTime:
fromByteBuffer(*value, m_createTime);
break;
case TxParameterID::IsSender:
fromByteBuffer(*value, m_sender);
break;
case TxParameterID::Message:
fromByteBuffer(*value, m_message);
break;
case TxParameterID::ChangeBeam:
fromByteBuffer(*value, m_changeBeam);
break;
case TxParameterID::ChangeAsset:
fromByteBuffer(*value, m_changeAsset);
break;
case TxParameterID::ModifyTime:
fromByteBuffer(*value, m_modifyTime);
break;
case TxParameterID::Status:
fromByteBuffer(*value, m_status);
break;
case TxParameterID::KernelID:
fromByteBuffer(*value, m_kernelID);
break;
case TxParameterID::FailureReason:
fromByteBuffer(*value, m_failureReason);
break;
case TxParameterID::IsSelfTx:
fromByteBuffer(*value, m_selfTx);
break;
case TxParameterID::AssetID:
fromByteBuffer(*value, m_assetId);
break;
case TxParameterID::AssetMetadata:
fromByteBuffer(*value, m_assetMeta);
break;
default:
break; // suppress warning
}
}
}
}
bool TxDescription::canResume() const
{
return m_status == TxStatus::Pending
|| m_status == TxStatus::InProgress
|| m_status == TxStatus::Registering;
}
bool TxDescription::canCancel() const
{
return m_status == TxStatus::InProgress
|| m_status == TxStatus::Pending;
}
bool TxDescription::canDelete() const
{
return m_status == TxStatus::Failed
|| m_status == TxStatus::Completed
|| m_status == TxStatus::Canceled;
}
std::string TxDescription::getTxTypeString() const
{
switch(m_txType)
{
case TxType::Simple: return "simple";
case TxType::AssetReg: return "asset register";
case TxType::AssetUnreg: return "asset unregister";
case TxType::AssetIssue: return "asset issue";
case TxType::AssetConsume: return "asset consume";
case TxType::AtomicSwap: return "atomic swap";
case TxType::AssetInfo: return "asset info";
default:
BOOST_ASSERT_MSG(false, kErrorUnknownTxType);
return "unknown";
}
}
/// Return empty string if second currency exchange rate is not presented
std::string TxDescription::getAmountInSecondCurrency(ExchangeRate::Currency secondCurrency) const
{
auto exchangeRatesOptional = GetParameter<std::vector<ExchangeRate>>(TxParameterID::ExchangeRates);
if (exchangeRatesOptional)
{
std::vector<ExchangeRate>& rates = *exchangeRatesOptional;
for (const auto r : rates)
{
if (r.m_currency == ExchangeRate::Currency::Beam &&
r.m_unit == secondCurrency &&
r.m_rate != 0)
{
cpp_dec_float_50 dec_first(m_amount);
dec_first /= Rules::Coin;
cpp_dec_float_50 dec_second(r.m_rate);
dec_second /= Rules::Coin;
cpp_dec_float_50 product = dec_first * dec_second;
std::ostringstream oss;
uint32_t precision = secondCurrency == ExchangeRate::Currency::Usd
? 2
: std::lround(std::log10(Rules::Coin));
oss.precision(precision);
oss << std::fixed << product;
return oss.str();
}
}
}
return "";
}
std::string TxDescription::getToken() const
{
auto token = GetParameter<std::string>(TxParameterID::OriginalToken);
if (token)
{
return *token;
}
return {};
}
std::string TxDescription::getSenderIdentity() const
{
return getIdentity(m_sender);
}
std::string TxDescription::getReceiverIdentity() const
{
return getIdentity(!m_sender);
}
std::string TxDescription::getIdentity(bool isSender) const
{
auto v = isSender ? GetParameter<PeerID>(TxParameterID::MyWalletIdentity)
: GetParameter<PeerID>(TxParameterID::PeerWalletIdentity);
if (v)
{
return std::to_string(*v);
}
return {};
}
uint64_t get_RandomID()
{
uintBigFor<uint64_t>::Type val;
ECC::GenRandom(val);
uint64_t ret;
val.Export(ret);
return ret;
}
std::string GetSendToken(const std::string& sbbsAddress, const std::string& identityStr, Amount amount)
{
WalletID walletID;
if (!walletID.FromHex(sbbsAddress))
{
return "";
}
auto identity = FromHex(identityStr);
if (!identity)
{
return "";
}
TxParameters parameters;
if (amount > 0)
{
parameters.SetParameter(TxParameterID::Amount, amount);
}
parameters.SetParameter(TxParameterID::PeerID, walletID);
parameters.SetParameter(TxParameterID::TransactionType, beam::wallet::TxType::Simple);
parameters.SetParameter(TxParameterID::PeerWalletIdentity, *identity);
return std::to_string(parameters);
}
ShieldedVoucherList GenerateVoucherList(ECC::Key::IKdf::Ptr pKdf, uint64_t ownID, size_t count)
{
ShieldedVoucherList res;
if (!pKdf || count == 0)
return res;
const size_t MAX_VOUCHERS = 20;
if (MAX_VOUCHERS < count)
{
LOG_WARNING() << "You are trying to generate more than " << MAX_VOUCHERS << ". The list of vouchers will be truncated.";
}
res.reserve(std::min(count, MAX_VOUCHERS));
ECC::Scalar::Native sk;
pKdf->DeriveKey(sk, Key::ID(ownID, Key::Type::WalletID));
PeerID pid;
pid.FromSk(sk);
ECC::Hash::Value hv;
ShieldedTxo::Viewer viewer;
viewer.FromOwner(*pKdf, 0);
for (size_t i = 0; i < res.capacity(); ++i)
{
if (res.empty())
ECC::GenRandom(hv);
else
ECC::Hash::Processor() << hv >> hv;
ShieldedTxo::Voucher& voucher = res.emplace_back();
ShieldedTxo::Data::TicketParams tp;
tp.Generate(voucher.m_Ticket, viewer, hv);
voucher.m_SharedSecret = tp.m_SharedSecret;
ECC::Hash::Value hvMsg;
voucher.get_Hash(hvMsg);
voucher.m_Signature.Sign(hvMsg, sk);
}
return res;
}
bool IsValidVoucherList(const ShieldedVoucherList& vouchers, const PeerID& identity)
{
if (vouchers.empty())
return false;
ECC::Point::Native pk;
if (!identity.ExportNnz(pk))
return false;
for (const auto& voucher : vouchers)
{
if (!voucher.IsValid(pk))
{
return false;
}
}
return true;
}
using nlohmann::json;
#define BEAM_IGNORED_JSON_TYPES2(MACRO) \
MACRO(ECC::RangeProof::Confidential::Part2) \
MACRO(ECC::RangeProof::Confidential::Part3)
#define MACRO(type) \
static bool fromByteBuffer(const ByteBuffer&, type&) \
{ \
return false; \
} \
BEAM_IGNORED_JSON_TYPES2(MACRO)
#undef MACRO
#define MACRO(type) \
static ByteBuffer toByteBuffer(const type&) \
{ \
return {}; \
} \
BEAM_IGNORED_JSON_TYPES2(MACRO)
#undef MACRO
namespace
{
using Names = std::array<string, uint8_t(128)>;
Names GetParameterNames()
{
Names names;
#define MACRO(name, index, type) names[index] = #name;
BEAM_TX_PUBLIC_PARAMETERS_MAP(MACRO)
#undef MACRO
return names;
}
using NameIDs = std::map<string, TxParameterID>;
NameIDs GetParameterNameIDs()
{
NameIDs names;
#define MACRO(name, index, type) names[#name] = TxParameterID(index);
BEAM_TX_PUBLIC_PARAMETERS_MAP(MACRO)
#undef MACRO
return names;
}
template<typename T>
string ToJsonValue(const T& v)
{
return std::to_string(v);
}
json ToJsonValue(TxType v)
{
return uint8_t(v);
}
json ToJsonValue(bool v)
{
return v;
}
string ToJsonValue(const ByteBuffer& buf)
{
return EncodeToHex(buf);
}
json ToJsonValue(const AmountList& amountList)
{
json list = json::array();
for (const auto& a : amountList)
{
list.push_back(std::to_string(a));
}
return list;
}
json ToJsonValue(const CoinIDList& coinList)
{
json list = json::array();
for (const auto& c : coinList)
{
list.push_back(toString(c));
}
return list;
}
#define BEAM_IGNORED_JSON_TYPES(MACRO) \
MACRO(ECC::Point) \
MACRO(ECC::Scalar) \
MACRO(ECC::Signature) \
MACRO(std::vector<Input::Ptr>) \
MACRO(std::vector<Output::Ptr>) \
MACRO(std::vector<ExchangeRate>) \
MACRO(ShieldedVoucherList)
#define MACRO(type) \
json ToJsonValue(const type&) \
{ \
return {}; \
} \
BEAM_IGNORED_JSON_TYPES(MACRO)
BEAM_IGNORED_JSON_TYPES2(MACRO)
#undef MACRO
#define MACRO(type) \
bool FromJson(const json&, type&) \
{ \
return false; \
} \
BEAM_IGNORED_JSON_TYPES(MACRO)
BEAM_IGNORED_JSON_TYPES2(MACRO)
#undef MACRO
const string& ToJsonValue(const std::string& s)
{
return s;
}
const string& GetParameterName(TxParameterID id)
{
static auto names = GetParameterNames();
return names[uint8_t(id)];
}
TxParameterID GetParameterID(const std::string& n)
{
static auto names = GetParameterNameIDs();
return names[n];
}
json GetParameterValue(TxParameterID id, const ByteBuffer& buffer)
{
switch (id)
{
#define MACRO(name, index, type) \
case TxParameterID::name: \
{ \
type value; \
if (fromByteBuffer(buffer, value)) \
{ \
return ToJsonValue(value); \
} \
} break;
BEAM_TX_PUBLIC_PARAMETERS_MAP(MACRO)
#undef MACRO
default:
break;
}
return {};
}
bool FromJson(const json& s, WalletID& v)
{
if (!s.is_string())
{
return false;
}
return v.FromHex(s.get<string>());
}
template<typename T>
bool FromJson(const json& s, T& v)
{
if (!s.is_string())
{
return false;
}
v = T(stoll(s.get<string>()));
return true;
}
bool FromJson(const json& s, TxType& v)
{
if (!s.is_number_integer())
{
return false;
}
v = TxType(s.get<uint8_t>());
return true;
}
bool FromJson(const json& s, bool& v)
{
if (!s.is_boolean())
{
return false;
}
v = s.get<bool>();
return true;
}
bool FromJson(const json& s, uintBig& v)
{
if (!s.is_string())
{
return false;
}
bool isValid = false;
auto buf = from_hex(s.get<std::string>(), &isValid);
if (!isValid)
{
return false;
}
v = Blob(buf.data(), static_cast<uint32_t>(buf.size()));
return true;
}
bool FromJson(const json& s, PeerID& p)
{
if (!s.is_string())
{
return false;
}
return FromJson(s, static_cast<uintBig&>(p));
}
bool FromJson(const json& s, CoinID& v)
{
if (!s.is_string())
{
return false;
}
auto t = Coin::FromString(s.get<std::string>());
if (!t)
{
return false;
}
v = *t;
return true;
}
bool FromJson(const json& s, std::string& v)
{
if (!s.is_string())
{
return false;
}
v = s.get<std::string>();
return true;
}
bool FromJson(const json& s, ByteBuffer& v)
{
if (!s.is_string())
{
return false;
}
bool isValid = false;
v = from_hex(s.get<std::string>(), &isValid);
return isValid;
}
template<typename T>
bool VectorFromJson(const json& s, T& v)
{
if (!s.is_array())
{
return false;
}
for (const auto& item : s)
{
typename T::value_type t;
if (FromJson(item, t))
{
v.push_back(t);
}
}
return true;
}
bool FromJson(const json& s, AmountList& v)
{
return VectorFromJson(s, v);
}
bool FromJson(const json& s, CoinIDList& v)
{
return VectorFromJson(s, v);
}
ByteBuffer GetParameterValue(TxParameterID id, const json& jsonValue)
{
switch (id)
{
#define MACRO(name, index, type) \
case TxParameterID::name: \
{ \
type value; \
if (FromJson(jsonValue, value)) \
{ \
return toByteBuffer(value); \
} \
} break;
BEAM_TX_PUBLIC_PARAMETERS_MAP(MACRO)
#undef MACRO
default:
break;
}
return {};
}
const std::string ParamsName = "params";
const std::string TxIDName = "tx_id";
const std::string IdName = "id";
const std::string ValueName = "value";
}
std::string ConvertTokenToJson(const std::string& token)
{
auto p = ParseParameters(token);
if (!p)
{
return {};
}
auto packedParams = p->Pack();
json params = json::object();
for (const auto& pair : packedParams)
{
params.push_back(
{
GetParameterName(pair.first),
GetParameterValue(pair.first, pair.second)
});
}
auto txID = p->GetTxID();
json res = json
{
{ TxIDName, txID.is_initialized() ? json(std::to_string(*txID)) : json{}},
{ ParamsName, params }
};
return res.dump();
}
std::string ConvertJsonToToken(const std::string& jsonParams)
{
try
{
json obj = json::parse(jsonParams.data(), jsonParams.data() + jsonParams.size());
auto paramsIt = obj.find(ParamsName);
if (paramsIt == obj.end())
{
return {};
}
boost::optional<TxID> txID;
auto txIDIt = obj.find(TxIDName);
if (txIDIt != obj.end() && !txIDIt->is_null())
{
auto txIdVec = from_hex(*txIDIt);
if (txIdVec.size() >= 16)
{
txID.emplace();
std::copy_n(txIdVec.begin(), 16, txID->begin());
}
}
TxParameters txParams(txID);
for (const auto& p : paramsIt->items())
{
auto id = GetParameterID(p.key());
ByteBuffer value = GetParameterValue(id, p.value());
txParams.SetParameter(id, value);
}
return std::to_string(txParams);
}
catch (const nlohmann::detail::exception&)
{
}
return {};
}
std::string TimestampFile(const std::string& fileName)
{
size_t dotPos = fileName.find_last_of('.');
stringstream ss;
ss << fileName.substr(0, dotPos);
ss << getTimestamp();
if (dotPos != string::npos)
{
ss << fileName.substr(dotPos);
}
string timestampedPath = ss.str();
return timestampedPath;
}
} // namespace beam::wallet
| 28.307063 | 132 | 0.521341 | [
"object",
"vector"
] |
442c11764d0662e6266917d5cde28977d91eeb9c | 619 | cpp | C++ | cf/Div2/B/Football Kit/main.cpp | wdjpng/soi | dd565587ae30985676f7f374093ec0687436b881 | [
"MIT"
] | null | null | null | cf/Div2/B/Football Kit/main.cpp | wdjpng/soi | dd565587ae30985676f7f374093ec0687436b881 | [
"MIT"
] | null | null | null | cf/Div2/B/Football Kit/main.cpp | wdjpng/soi | dd565587ae30985676f7f374093ec0687436b881 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
#define int long long
#define double long double
using namespace std;
signed main() {
// Turn off synchronization between cin/cout and scanf/printf
ios_base::sync_with_stdio(false);
// Disable automatic flush of cout when reading from cin cin.tie(0);
cin.tie(0);
int n;
cin >> n;
vector<int>home(100001);
vector<int>in;
for (int i = 0; i < n; ++i) {
int x, y;
cin >> x >> y;
home[x]++;
in.push_back(y);
}
for (int i = 0; i < n; ++i) {
cout << n-1+home[in[i]] << " " << n - 1 -home[in[i]] << "\n";
}
} | 22.107143 | 72 | 0.531502 | [
"vector"
] |
442dffab3d06a016344a952419d6b43b3f720710 | 4,468 | hpp | C++ | external/cfmesh/meshLibrary/utilities/helperClasses/parallelHelpers/labelledPoint/labelledPoint.hpp | MrAwesomeRocks/caelus-cml | 55b6dc5ba47d0e95c07412d9446ac72ac11d7fd7 | [
"mpich2"
] | null | null | null | external/cfmesh/meshLibrary/utilities/helperClasses/parallelHelpers/labelledPoint/labelledPoint.hpp | MrAwesomeRocks/caelus-cml | 55b6dc5ba47d0e95c07412d9446ac72ac11d7fd7 | [
"mpich2"
] | null | null | null | external/cfmesh/meshLibrary/utilities/helperClasses/parallelHelpers/labelledPoint/labelledPoint.hpp | MrAwesomeRocks/caelus-cml | 55b6dc5ba47d0e95c07412d9446ac72ac11d7fd7 | [
"mpich2"
] | null | null | null | /*---------------------------------------------------------------------------*\
Copyright (C) Creative Fields, Ltd.
-------------------------------------------------------------------------------
License
This file is part of cfMesh.
cfMesh is free software; you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by the
Free Software Foundation; either version 3 of the License, or (at your
option) any later version.
cfMesh is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
for more details.
You should have received a copy of the GNU General Public License
along with cfMesh. If not, see <http://www.gnu.org/licenses/>.
Class
labelledPoint
Description
A class containing point label and its coordinates. It is used for
exchanging data over processors
Author: Franjo Juretic (franjo.juretic@c-fields.com)
SourceFiles
\*---------------------------------------------------------------------------*/
#ifndef labelledPoint_HPP
#define labelledPoint_HPP
#include "label.hpp"
#include "point.hpp"
#include "contiguous.hpp"
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
namespace CML
{
/*---------------------------------------------------------------------------*\
Class labelledPoint Declaration
\*---------------------------------------------------------------------------*/
class labelledPoint
{
// Private data
//- point label
label pLabel_;
//- point coordinates
point coords_;
public:
// Constructors
//- Null construct
labelledPoint()
:
pLabel_(-1),
coords_(vector::zero)
{}
//- Construct from point and label
labelledPoint(const label pl, const point& p)
:
pLabel_(pl),
coords_(p)
{}
// Destructor
~labelledPoint()
{}
// Member functions
//- return point label
inline label pointLabel() const
{
return pLabel_;
}
inline label& pointLabel()
{
return pLabel_;
}
//- return point coordinates
inline const point& coordinates() const
{
return coords_;
}
inline point& coordinates()
{
return coords_;
}
// Member operators
inline void operator=(const labelledPoint& lp)
{
pLabel_ = lp.pLabel_;
coords_ = lp.coords_;
}
inline bool operator==(const labelledPoint& lp) const
{
if( pLabel_ == lp.pLabel_ )
return true;
return false;
}
inline bool operator!=(const labelledPoint& lp) const
{
return !this->operator==(lp);
}
// Friend operators
friend Ostream& operator<<(Ostream& os, const labelledPoint& lp)
{
os << token::BEGIN_LIST;
os << lp.pLabel_ << token::SPACE;
os << lp.coords_ << token::END_LIST;
// Check state of Ostream
os.check("operator<<(Ostream&, const labelledPoint&");
return os;
}
friend Istream& operator>>(Istream& is, labelledPoint& lp)
{
// Read beginning of labelledPoint
is.readBegin("labelledPoint");
is >> lp.pLabel_;
is >> lp.coords_;
// Read end of labelledPoint
is.readEnd("labelledPoint");
// Check state of Istream
is.check("operator>>(Istream&, labelledPoint");
return is;
}
};
//- Specify data associated with labelledPoint type is contiguous
template<>
inline bool contiguous<labelledPoint>() {return true;}
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
} // End namespace CML
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
#endif
// ************************************************************************* //
| 26.754491 | 79 | 0.460609 | [
"vector"
] |
443535f8247d94422f10d6a9db4d38dc1df6b4b0 | 2,784 | cc | C++ | extensions/renderer/activity_log_converter_strategy.cc | metux/chromium-deb | 3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | extensions/renderer/activity_log_converter_strategy.cc | metux/chromium-deb | 3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | extensions/renderer/activity_log_converter_strategy.cc | metux/chromium-deb | 3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | // Copyright 2014 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 "extensions/renderer/activity_log_converter_strategy.h"
#include <memory>
#include "base/logging.h"
#include "base/values.h"
#include "v8/include/v8.h"
namespace extensions {
namespace {
// Summarize a V8 value. This performs a shallow conversion in all cases, and
// returns only a string with a description of the value (e.g.,
// "[HTMLElement]").
std::unique_ptr<base::Value> SummarizeV8Value(v8::Isolate* isolate,
v8::Local<v8::Object> object) {
v8::TryCatch try_catch(isolate);
v8::Isolate::DisallowJavascriptExecutionScope scope(
isolate, v8::Isolate::DisallowJavascriptExecutionScope::THROW_ON_FAILURE);
v8::Local<v8::String> name = v8::String::NewFromUtf8(isolate, "[");
if (object->IsFunction()) {
name =
v8::String::Concat(name, v8::String::NewFromUtf8(isolate, "Function"));
v8::Local<v8::Value> fname =
v8::Local<v8::Function>::Cast(object)->GetName();
if (fname->IsString() && v8::Local<v8::String>::Cast(fname)->Length()) {
name = v8::String::Concat(name, v8::String::NewFromUtf8(isolate, " "));
name = v8::String::Concat(name, v8::Local<v8::String>::Cast(fname));
name = v8::String::Concat(name, v8::String::NewFromUtf8(isolate, "()"));
}
} else {
name = v8::String::Concat(name, object->GetConstructorName());
}
name = v8::String::Concat(name, v8::String::NewFromUtf8(isolate, "]"));
if (try_catch.HasCaught()) {
return std::unique_ptr<base::Value>(
new base::Value("[JS Execution Exception]"));
}
return std::unique_ptr<base::Value>(
new base::Value(std::string(*v8::String::Utf8Value(name))));
}
} // namespace
ActivityLogConverterStrategy::ActivityLogConverterStrategy() {}
ActivityLogConverterStrategy::~ActivityLogConverterStrategy() {}
bool ActivityLogConverterStrategy::FromV8Object(
v8::Local<v8::Object> value,
std::unique_ptr<base::Value>* out,
v8::Isolate* isolate,
const FromV8ValueCallback& callback) const {
return FromV8Internal(value, out, isolate, callback);
}
bool ActivityLogConverterStrategy::FromV8Array(
v8::Local<v8::Array> value,
std::unique_ptr<base::Value>* out,
v8::Isolate* isolate,
const FromV8ValueCallback& callback) const {
return FromV8Internal(value, out, isolate, callback);
}
bool ActivityLogConverterStrategy::FromV8Internal(
v8::Local<v8::Object> value,
std::unique_ptr<base::Value>* out,
v8::Isolate* isolate,
const FromV8ValueCallback& callback) const {
*out = SummarizeV8Value(isolate, value);
return true;
}
} // namespace extensions
| 33.542169 | 80 | 0.684986 | [
"object"
] |
44375e43233330f5a0dfc80469f461a38bd65c7a | 8,589 | cc | C++ | elements/analysis/aggpktcounter.cc | MacWR/Click-changed-for-ParaGraph | 18285e5da578fbb7285d10380836146e738dee6e | [
"Apache-2.0"
] | 32 | 2017-11-02T12:33:21.000Z | 2022-02-07T22:25:58.000Z | elements/analysis/aggpktcounter.cc | MacWR/Click-changed-for-ParaGraph | 18285e5da578fbb7285d10380836146e738dee6e | [
"Apache-2.0"
] | 2 | 2019-02-18T08:47:16.000Z | 2019-05-24T14:41:23.000Z | elements/analysis/aggpktcounter.cc | MacWR/Click-changed-for-ParaGraph | 18285e5da578fbb7285d10380836146e738dee6e | [
"Apache-2.0"
] | 10 | 2018-06-13T11:54:53.000Z | 2020-09-08T06:52:43.000Z | // -*- c-basic-offset: 4 -*-
/*
* aggpktcounter.{cc,hh} -- element counts packets per packet number and
* aggregate annotation
* Eddie Kohler
*
* Copyright (c) 2002 International Computer Science Institute
* Copyright (c) 2008 Meraki, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, subject to the conditions
* listed in the Click LICENSE file. These conditions include: you must
* preserve this copyright notice, and you cannot mention the copyright
* holders in advertising related to the Software without their permission.
* The Software is provided WITHOUT ANY WARRANTY, EXPRESS OR IMPLIED. This
* notice is a summary of the Click LICENSE file; the license in that file is
* legally binding.
*/
#include <click/config.h>
#include "aggpktcounter.hh"
#include <click/args.hh>
#include <click/error.hh>
#include <click/packet_anno.hh>
#include <click/router.hh>
#include <click/straccum.hh>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <fcntl.h>
CLICK_DECLS
AggregatePacketCounter::Flow::Flow(uint32_t aggregate, int columns)
: _aggregate(aggregate), _next(0), _counts(new Vector<uint32_t>[columns])
{
}
void
AggregatePacketCounter::Flow::add(uint32_t packetno, int column)
{
if (_counts[column].size() <= (int) packetno)
_counts[column].resize(packetno + 1, 0);
_counts[column].unchecked_at(packetno)++;
}
AggregatePacketCounter::packetctr_t
AggregatePacketCounter::Flow::column_count(int column) const
{
packetctr_t count = 0;
for (const uint32_t *v = _counts[column].begin(); v < _counts[column].end(); v++)
count += *v;
return count;
}
void
AggregatePacketCounter::Flow::received(Vector<uint32_t> &v, const AggregatePacketCounter *apc) const
{
int n = 0;
for (int port = 0; port < apc->noutputs(); port++)
if (_counts[port].size() > n)
n = _counts[port].size();
for (int packetno = 0; packetno < n; packetno++)
for (int port = 0; port < apc->noutputs(); port++)
if (packetno < _counts[port].size() && _counts[port].unchecked_at(packetno)) {
v.push_back(packetno);
break;
}
}
void
AggregatePacketCounter::Flow::undelivered(Vector<uint32_t> &undelivered, const AggregatePacketCounter *apc) const
{
assert(apc->noutputs() >= 2);
int packetno;
int min_n = (_counts[0].size() < _counts[1].size() ? _counts[0].size() : _counts[1].size());
for (packetno = 0; packetno < min_n; packetno++)
if (_counts[0].unchecked_at(packetno) > _counts[1].unchecked_at(packetno))
undelivered.push_back(packetno);
for (; packetno < _counts[0].size(); packetno++)
if (_counts[0].unchecked_at(packetno))
undelivered.push_back(packetno);
}
AggregatePacketCounter::AggregatePacketCounter()
{
for (int i = 0; i < NFLOWMAP; i++)
_flowmap[i] = 0;
}
AggregatePacketCounter::~AggregatePacketCounter()
{
}
int
AggregatePacketCounter::configure(Vector<String> &conf, ErrorHandler *errh)
{
Element *e = 0;
String anno = String::make_stable("PACKET_NUMBER");
if (Args(conf, this, errh)
.read("NOTIFIER", e)
.read("ANNO", WordArg(), anno)
.complete() < 0)
return -1;
if (anno == "NONE")
_anno = -1;
else if (!cp_anno(anno, 4, &_anno, this))
return errh->error("bad ANNO");
/*if (e && !(_agg_notifier = (AggregateNotifier *)e->cast("AggregateNotifier")))
return errh->error("%s is not an AggregateNotifier", e->name().c_str()); */
return 0;
}
int
AggregatePacketCounter::initialize(ErrorHandler *)
{
_total_flows = _total_packets = 0;
//if (_agg_notifier)
//_agg_notifier->add_listener(this);
//_gc_timer.initialize(this);
return 0;
}
void
AggregatePacketCounter::end_flow(Flow *f, ErrorHandler *)
{
/* if (f->npackets() >= _mincount) {
f->output(errh);
if (_gzip && f->filename() != "-")
if (add_compressable(f->filename(), errh) < 0)
_gzip = false;
} else
f->unlink(errh);*/
delete f;
}
void
AggregatePacketCounter::cleanup(CleanupStage)
{
ErrorHandler *errh = ErrorHandler::default_handler();
for (int i = 0; i < NFLOWMAP; i++)
while (Flow *f = _flowmap[i]) {
_flowmap[i] = f->next();
end_flow(f, errh);
}
if (_total_packets > 0 && _total_flows == 0)
errh->lwarning(declaration(), "saw no packets with aggregate annotations");
}
AggregatePacketCounter::Flow *
AggregatePacketCounter::find_flow(uint32_t agg)
{
if (agg == 0)
return 0;
int bucket = (agg & (NFLOWMAP - 1));
Flow *prev = 0, *f = _flowmap[bucket];
while (f && f->aggregate() != agg) {
prev = f;
f = f->next();
}
if (f)
/* nada */;
else if ((f = new Flow(agg, ninputs()))) {
prev = f;
_total_flows++;
} else
return 0;
if (prev) {
prev->set_next(f->next());
f->set_next(_flowmap[bucket]);
_flowmap[bucket] = f;
}
return f;
}
inline void
AggregatePacketCounter::smaction(int port, Packet *p)
{
_total_packets++;
if (Flow *f = find_flow(AGGREGATE_ANNO(p))) {
if (_anno >= 0)
f->add(p->anno_u32(_anno), port);
else
f->add(0, port);
}
}
void
AggregatePacketCounter::push(int port, Packet *p)
{
smaction(port, p);
output(port).push(p);
}
Packet *
AggregatePacketCounter::pull(int port)
{
if (Packet *p = input(port).pull()) {
smaction(port, p);
return p;
} else
return 0;
}
/*
void
AggregatePacketCounter::aggregate_notify(uint32_t agg, AggregateEvent event, const Packet *)
{
if (event == DELETE_AGG && find_aggregate(agg, 0)) {
_gc_aggs.push_back(agg);
_gc_aggs.push_back(click_jiffies());
if (!_gc_timer.scheduled())
_gc_timer.schedule_after_msec(250);
}
}
void
AggregatePacketCounter::gc_hook(Timer *t, void *thunk)
{
AggregatePacketCounter *td = static_cast<AggregatePacketCounter *>(thunk);
uint32_t limit_jiff = click_jiffies() - (CLICK_HZ / 4);
int i;
for (i = 0; i < td->_gc_aggs.size() && SEQ_LEQ(td->_gc_aggs[i+1], limit_jiff); i += 2)
if (Flow *f = td->find_aggregate(td->_gc_aggs[i], 0)) {
int bucket = (f->aggregate() & (NFLOWMAP - 1));
assert(td->_flowmap[bucket] == f);
td->_flowmap[bucket] = f->next();
td->end_flow(f, ErrorHandler::default_handler());
}
if (i < td->_gc_aggs.size()) {
td->_gc_aggs.erase(td->_gc_aggs.begin(), td->_gc_aggs.begin() + i);
t->schedule_after_msec(250);
}
}
*/
enum { H_CLEAR, H_COUNT };
String
AggregatePacketCounter::read_handler(Element *e, void *thunk)
{
AggregatePacketCounter *ac = static_cast<AggregatePacketCounter *>(e);
switch ((intptr_t)thunk) {
case H_COUNT: {
packetctr_t count = 0;
for (int i = 0; i < NFLOWMAP; i++)
for (const Flow *f = ac->_flowmap[i]; f; f = f->next())
for (int col = 0; col < ac->ninputs(); col++)
count += f->column_count(col);
return String(count);
}
default:
return "<error>";
}
}
int
AggregatePacketCounter::write_handler(const String &, Element *e, void *thunk, ErrorHandler *errh)
{
AggregatePacketCounter *td = static_cast<AggregatePacketCounter *>(e);
switch ((intptr_t)thunk) {
case H_CLEAR:
for (int i = 0; i < NFLOWMAP; i++)
while (Flow *f = td->_flowmap[i]) {
td->_flowmap[i] = f->next();
td->end_flow(f, errh);
}
return 0;
default:
return -1;
}
}
String
AggregatePacketCounter::flow_handler(uint32_t aggregate, FlowFunc func)
{
Vector<uint32_t> v;
if (Flow *f = find_flow(aggregate))
(f->*func)(v, this);
StringAccum sa;
for (int i = 0; i < v.size(); i++)
sa << v[i] << '\n';
return sa.take_string();
}
int
AggregatePacketCounter::thing_read_handler(int, String& s, Element* e, const Handler* h, ErrorHandler* errh)
{
uint32_t aggregate = 0;
if (s && !IntArg().parse(cp_uncomment(s), aggregate))
return errh->error("argument should be aggregate number");
FlowFunc ff = (h->read_user_data() ? &Flow::undelivered : &Flow::received);
AggregatePacketCounter *apc = static_cast<AggregatePacketCounter *>(e);
s = apc->flow_handler(aggregate, ff);
return 0;
}
void
AggregatePacketCounter::add_handlers()
{
add_write_handler("clear", write_handler, H_CLEAR);
add_read_handler("count", read_handler, H_COUNT);
set_handler("received", Handler::f_read | Handler::f_read_param, thing_read_handler, 0);
set_handler("undelivered", Handler::f_read | Handler::f_read_param, thing_read_handler, (void*) 1);
}
CLICK_ENDDECLS
ELEMENT_REQUIRES(userlevel int64)
EXPORT_ELEMENT(AggregatePacketCounter)
| 26.924765 | 113 | 0.664338 | [
"vector"
] |
4437d134a8a36de74fbc55174582a08373b102e4 | 1,770 | cpp | C++ | platform/android/src/geojson/polygon.cpp | mueschm/mapbox-gl-native | b07db0f8d01f855dcd336aa1baabde94c5c1740d | [
"BSL-1.0",
"Apache-2.0"
] | 316 | 2021-02-05T10:34:35.000Z | 2022-03-23T21:58:39.000Z | platform/android/src/geojson/polygon.cpp | mueschm/mapbox-gl-native | b07db0f8d01f855dcd336aa1baabde94c5c1740d | [
"BSL-1.0",
"Apache-2.0"
] | 187 | 2021-02-11T10:39:30.000Z | 2022-03-31T21:59:47.000Z | platform/android/src/geojson/polygon.cpp | mueschm/mapbox-gl-native | b07db0f8d01f855dcd336aa1baabde94c5c1740d | [
"BSL-1.0",
"Apache-2.0"
] | 93 | 2021-02-04T09:39:14.000Z | 2022-03-31T04:03:56.000Z | #include "polygon.hpp"
#include "multi_line_string.hpp"
#include "util.hpp"
namespace mbgl {
namespace android {
namespace geojson {
jni::Local<jni::Object<Polygon>> Polygon::New(jni::JNIEnv& env, const mbgl::Polygon<double>& polygon) {
static auto& javaClass = jni::Class<Polygon>::Singleton(env);
static auto method = javaClass.GetStaticMethod<jni::Object<Polygon> (jni::Object<java::util::List>)>(env, "fromLngLats");
return javaClass.Call(env, method, asPointsListsList(env, polygon));
}
mapbox::geojson::polygon Polygon::convert(jni::JNIEnv &env, const jni::Object<Polygon>& jPolygon) {
mapbox::geojson::polygon polygon;
if (jPolygon) {
polygon = Polygon::convert(env, Polygon::coordinates(env, jPolygon));
}
return polygon;
}
mapbox::geojson::polygon Polygon::convert(jni::JNIEnv &env, const jni::Object<java::util::List/*<java::util::List<Point>>*/>& jPointListsList) {
mapbox::geojson::polygon polygon;
if (jPointListsList) {
auto multiLine = MultiLineString::convert(env, jPointListsList);
polygon.reserve(multiLine.size());
for (auto&& line : multiLine) {
polygon.emplace_back(convertExplicit<mapbox::geojson::linear_ring>(std::move(line)));
}
}
return polygon;
}
jni::Local<jni::Object<java::util::List>> Polygon::coordinates(jni::JNIEnv &env, const jni::Object<Polygon>& jPolygon) {
static auto& javaClass = jni::Class<Polygon>::Singleton(env);
static auto method = javaClass.GetMethod<jni::Object<java::util::List> ()>(env, "coordinates");
return jPolygon.Call(env, method);
}
void Polygon::registerNative(jni::JNIEnv &env) {
jni::Class<Polygon>::Singleton(env);
}
} // namespace geojson
} // namespace android
} // namespace mbgl | 32.181818 | 144 | 0.687571 | [
"object"
] |
443870f96cc0f57d75e6f975814ea6bc656ddf17 | 19,919 | cc | C++ | src/devices/tee/drivers/optee/test/optee-controller-test.cc | allansrc/fuchsia | a2c235b33fc4305044d496354a08775f30cdcf37 | [
"BSD-2-Clause"
] | 2 | 2022-02-24T16:24:29.000Z | 2022-02-25T22:33:10.000Z | src/devices/tee/drivers/optee/test/optee-controller-test.cc | allansrc/fuchsia | a2c235b33fc4305044d496354a08775f30cdcf37 | [
"BSD-2-Clause"
] | null | null | null | src/devices/tee/drivers/optee/test/optee-controller-test.cc | allansrc/fuchsia | a2c235b33fc4305044d496354a08775f30cdcf37 | [
"BSD-2-Clause"
] | null | null | null | // Copyright 2020 The Fuchsia 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 "../optee-controller.h"
#include <fidl/fuchsia.hardware.rpmb/cpp/wire.h>
#include <fuchsia/hardware/platform/device/cpp/banjo.h>
#include <fuchsia/hardware/sysmem/cpp/banjo.h>
#include <lib/async-loop/cpp/loop.h>
#include <lib/async-loop/default.h>
#include <lib/fake-bti/bti.h>
#include <lib/fake-object/object.h>
#include <lib/fake-resource/resource.h>
#include <lib/fidl/llcpp/client.h>
#include <lib/sync/completion.h>
#include <lib/zx/bti.h>
#include <stdlib.h>
#include <zircon/time.h>
#include <zircon/types.h>
#include <functional>
#include <ddktl/suspend-txn.h>
#include <zxtest/zxtest.h>
#include "../optee-smc.h"
#include "../tee-smc.h"
#include "lib/fidl/llcpp/connect_service.h"
#include "src/devices/testing/mock-ddk/mock-device.h"
struct SharedMemoryInfo {
zx_paddr_t address = 0;
size_t size = 0;
};
// This will be populated once the FakePdev creates the fake contiguous vmo so we can use the
// physical addresses within it.
static SharedMemoryInfo gSharedMemory = {};
constexpr uuid_t kOpteeOsUuid = {
0x486178E0, 0xE7F8, 0x11E3, {0xBC, 0x5E, 0x00, 0x02, 0xA5, 0xD5, 0xC5, 0x1B}};
using SmcCb = std::function<void(const zx_smc_parameters_t*, zx_smc_result_t*)>;
static SmcCb call_with_arg_handler;
static uint32_t call_with_args_count = 0;
static std::mutex handler_mut;
void SetSmcCallWithArgHandler(SmcCb handler) {
std::lock_guard<std::mutex> lock(handler_mut);
call_with_arg_handler = std::move(handler);
}
zx_status_t zx_smc_call(zx_handle_t handle, const zx_smc_parameters_t* parameters,
zx_smc_result_t* out_smc_result) {
EXPECT_TRUE(parameters);
EXPECT_TRUE(out_smc_result);
switch (parameters->func_id) {
case tee_smc::kTrustedOsCallUidFuncId:
out_smc_result->arg0 = optee::kOpteeApiUid_0;
out_smc_result->arg1 = optee::kOpteeApiUid_1;
out_smc_result->arg2 = optee::kOpteeApiUid_2;
out_smc_result->arg3 = optee::kOpteeApiUid_3;
break;
case tee_smc::kTrustedOsCallRevisionFuncId:
out_smc_result->arg0 = optee::kOpteeApiRevisionMajor;
out_smc_result->arg1 = optee::kOpteeApiRevisionMinor;
break;
case optee::kGetOsRevisionFuncId:
out_smc_result->arg0 = 1;
out_smc_result->arg1 = 0;
break;
case optee::kExchangeCapabilitiesFuncId:
out_smc_result->arg0 = optee::kReturnOk;
out_smc_result->arg1 =
optee::kSecureCapHasReservedSharedMem | optee::kSecureCapCanUsePrevUnregisteredSharedMem;
break;
case optee::kGetSharedMemConfigFuncId:
out_smc_result->arg0 = optee::kReturnOk;
out_smc_result->arg1 = gSharedMemory.address;
out_smc_result->arg2 = gSharedMemory.size;
break;
case optee::kCallWithArgFuncId: {
call_with_args_count++;
SmcCb handler;
{
std::lock_guard<std::mutex> lock(handler_mut);
std::swap(handler, call_with_arg_handler);
}
if (handler != nullptr) {
handler(parameters, out_smc_result);
} else {
out_smc_result->arg0 = optee::kReturnOk;
}
} break;
default:
return ZX_ERR_NOT_SUPPORTED;
}
return ZX_OK;
}
namespace optee {
namespace {
class FakePDev : public ddk::PDevProtocol<FakePDev, ddk::base_protocol> {
public:
FakePDev() {}
const pdev_protocol_ops_t* proto_ops() const { return &pdev_protocol_ops_; }
zx_status_t PDevGetMmio(uint32_t index, pdev_mmio_t* out_mmio) {
EXPECT_EQ(index, 0);
constexpr size_t kSecureWorldMemorySize = 0x20000;
EXPECT_OK(zx::vmo::create_contiguous(*fake_bti_, 0x20000, 0, &fake_vmo_));
// Briefly pin the vmo to get the paddr for populating the gSharedMemory object
zx_paddr_t secure_world_paddr;
zx::pmt pmt;
EXPECT_OK(fake_bti_->pin(ZX_BTI_PERM_READ | ZX_BTI_CONTIGUOUS, fake_vmo_, 0,
kSecureWorldMemorySize, &secure_world_paddr, 1, &pmt));
// Use the second half of the secure world range to use as shared memory
gSharedMemory.address = secure_world_paddr + (kSecureWorldMemorySize / 2);
gSharedMemory.size = kSecureWorldMemorySize / 2;
EXPECT_OK(pmt.unpin());
out_mmio->vmo = fake_vmo_.get();
out_mmio->offset = 0;
out_mmio->size = kSecureWorldMemorySize;
return ZX_OK;
}
zx_status_t PDevGetBti(uint32_t index, zx::bti* out_bti) {
zx_status_t status = fake_bti_create(out_bti->reset_and_get_address());
// Stash an unowned copy of it, for the purposes of creating a contiguous vmo to back the secure
// world memory
fake_bti_ = out_bti->borrow();
return status;
}
zx_status_t PDevGetSmc(uint32_t index, zx::resource* out_resource) {
// Just use a fake root resource for now, which is technically eligible for SMC calls. A more
// appropriate object would be to use the root resource to mint an SMC resource type.
return fake_root_resource_create(out_resource->reset_and_get_address());
}
zx_status_t PDevGetInterrupt(uint32_t index, uint32_t flags, zx::interrupt* out_irq) {
return ZX_ERR_NOT_SUPPORTED;
}
zx_status_t PDevGetDeviceInfo(pdev_device_info_t* out_info) { return ZX_ERR_NOT_SUPPORTED; }
zx_status_t PDevGetBoardInfo(pdev_board_info_t* out_info) { return ZX_ERR_NOT_SUPPORTED; }
private:
zx::unowned_bti fake_bti_;
zx::vmo fake_vmo_;
};
class FakeSysmem : public ddk::SysmemProtocol<FakeSysmem> {
public:
FakeSysmem() {}
const sysmem_protocol_ops_t* proto_ops() const { return &sysmem_protocol_ops_; }
zx_status_t SysmemConnect(zx::channel allocator2_request) { return ZX_ERR_NOT_SUPPORTED; }
zx_status_t SysmemRegisterHeap(uint64_t heap, zx::channel heap_connection) {
return ZX_ERR_NOT_SUPPORTED;
}
zx_status_t SysmemRegisterSecureMem(zx::channel tee_connection) { return ZX_ERR_NOT_SUPPORTED; }
zx_status_t SysmemUnregisterSecureMem() { return ZX_ERR_NOT_SUPPORTED; }
};
class FakeDdkOptee : public zxtest::Test {
public:
FakeDdkOptee() : clients_loop_(&kAsyncLoopConfigNoAttachToCurrentThread) {
ASSERT_OK(clients_loop_.StartThread());
ASSERT_OK(clients_loop_.StartThread());
ASSERT_OK(clients_loop_.StartThread());
parent_->AddProtocol(ZX_PROTOCOL_PDEV, pdev_.proto_ops(), &pdev_, "pdev");
parent_->AddProtocol(ZX_PROTOCOL_SYSMEM, sysmem_.proto_ops(), &sysmem_, "sysmem");
parent_->AddFidlProtocol(
fidl::DiscoverableProtocolName<fuchsia_hardware_rpmb::Rpmb>,
[](zx::channel) { return ZX_OK; }, "rpmb");
ASSERT_OK(OpteeController::Create(nullptr, parent_.get()));
optee_ = parent_->GetLatestChild()->GetDeviceContext<OpteeController>();
}
void SetUp() override { call_with_args_count = 0; }
protected:
FakePDev pdev_;
FakeSysmem sysmem_;
std::shared_ptr<MockDevice> parent_ = MockDevice::FakeRootParent();
OpteeController* optee_ = nullptr;
async::Loop clients_loop_;
};
TEST_F(FakeDdkOptee, PmtUnpinned) {
zx_handle_t pmt_handle = optee_->pmt().get();
EXPECT_NE(pmt_handle, ZX_HANDLE_INVALID);
EXPECT_TRUE(fake_object::FakeHandleTable().Get(pmt_handle).is_ok());
EXPECT_EQ(ZX_OBJ_TYPE_PMT, fake_object::FakeHandleTable().Get(pmt_handle)->type());
optee_->zxdev()->SuspendNewOp(DEV_POWER_STATE_D3COLD, false, DEVICE_SUSPEND_REASON_REBOOT);
EXPECT_FALSE(fake_object::FakeHandleTable().Get(pmt_handle).is_ok());
}
TEST_F(FakeDdkOptee, RpmbTest) {
using Rpmb = fuchsia_hardware_rpmb::Rpmb;
EXPECT_EQ(optee_->RpmbConnectServer(fidl::ServerEnd<Rpmb>()), ZX_ERR_INVALID_ARGS);
auto endpoints = fidl::CreateEndpoints<Rpmb>();
ASSERT_TRUE(endpoints.is_ok());
auto [client_end, server_end] = std::move(endpoints.value());
EXPECT_EQ(optee_->RpmbConnectServer(std::move(server_end)), ZX_OK);
}
TEST_F(FakeDdkOptee, MultiThreadTest) {
zx::channel tee_app_client[2];
sync_completion_t completion1;
sync_completion_t completion2;
sync_completion_t smc_completion;
sync_completion_t smc_completion1;
zx_status_t status;
for (auto& i : tee_app_client) {
zx::channel tee_app_server;
ASSERT_OK(zx::channel::create(0, &i, &tee_app_server));
zx::channel provider_server;
zx::channel provider_client;
ASSERT_OK(zx::channel::create(0, &provider_client, &provider_server));
optee_->TeeConnectToApplication(&kOpteeOsUuid, std::move(tee_app_server),
std::move(provider_client));
}
auto client_end1 = fidl::ClientEnd<fuchsia_tee::Application>(std::move(tee_app_client[0]));
fidl::WireSharedClient fidl_client1(std::move(client_end1), clients_loop_.dispatcher());
auto client_end2 = fidl::ClientEnd<fuchsia_tee::Application>(std::move(tee_app_client[1]));
fidl::WireSharedClient fidl_client2(std::move(client_end2), clients_loop_.dispatcher());
{
SetSmcCallWithArgHandler([&](const zx_smc_parameters_t* params, zx_smc_result_t* out) {
sync_completion_signal(&smc_completion1);
sync_completion_wait(&smc_completion, ZX_TIME_INFINITE);
out->arg0 = optee::kReturnOk;
});
}
{
fidl::VectorView<fuchsia_tee::wire::Parameter> parameter_set;
fidl_client1->OpenSession2(
std::move(parameter_set),
[&](::fidl::WireResponse<::fuchsia_tee::Application::OpenSession2>* resp) {
sync_completion_signal(&completion1);
});
}
status = sync_completion_wait(&completion1, ZX_SEC(1));
EXPECT_EQ(status, ZX_ERR_TIMED_OUT);
sync_completion_wait(&smc_completion1, ZX_TIME_INFINITE);
{
SetSmcCallWithArgHandler([&](const zx_smc_parameters_t* params, zx_smc_result_t* out) {
out->arg0 = optee::kReturnOk;
});
}
{
fidl::VectorView<fuchsia_tee::wire::Parameter> parameter_set;
fidl_client2->OpenSession2(
std::move(parameter_set),
[&](::fidl::WireResponse<::fuchsia_tee::Application::OpenSession2>* resp) {
sync_completion_signal(&completion2);
});
}
sync_completion_wait(&completion2, ZX_TIME_INFINITE);
sync_completion_signal(&smc_completion);
sync_completion_wait(&completion1, ZX_TIME_INFINITE);
EXPECT_EQ(call_with_args_count, 2);
}
TEST_F(FakeDdkOptee, TheadLimitCorrectOrder) {
zx::channel tee_app_client[2];
sync_completion_t completion1;
sync_completion_t completion2;
sync_completion_t smc_completion;
zx_status_t status;
for (auto& i : tee_app_client) {
zx::channel tee_app_server;
ASSERT_OK(zx::channel::create(0, &i, &tee_app_server));
zx::channel provider_server;
zx::channel provider_client;
ASSERT_OK(zx::channel::create(0, &provider_client, &provider_server));
optee_->TeeConnectToApplication(&kOpteeOsUuid, std::move(tee_app_server),
std::move(provider_client));
}
auto client_end1 = fidl::ClientEnd<fuchsia_tee::Application>(std::move(tee_app_client[0]));
fidl::WireSharedClient fidl_client1(std::move(client_end1), clients_loop_.dispatcher());
auto client_end2 = fidl::ClientEnd<fuchsia_tee::Application>(std::move(tee_app_client[1]));
fidl::WireSharedClient fidl_client2(std::move(client_end2), clients_loop_.dispatcher());
{
SetSmcCallWithArgHandler([&](const zx_smc_parameters_t* params, zx_smc_result_t* out) {
sync_completion_signal(&smc_completion);
out->arg0 = optee::kReturnEThreadLimit;
});
}
{
fidl::VectorView<fuchsia_tee::wire::Parameter> parameter_set;
fidl_client1->OpenSession2(
std::move(parameter_set),
[&](::fidl::WireResponse<::fuchsia_tee::Application::OpenSession2>* resp) {
sync_completion_signal(&completion1);
});
}
sync_completion_wait(&smc_completion, ZX_TIME_INFINITE);
status = sync_completion_wait(&completion1, ZX_SEC(1));
EXPECT_EQ(status, ZX_ERR_TIMED_OUT);
EXPECT_EQ(call_with_args_count, 1);
EXPECT_EQ(optee_->CommandQueueSize(), 1);
{
SetSmcCallWithArgHandler([&](const zx_smc_parameters_t* params, zx_smc_result_t* out) {
out->arg0 = optee::kReturnOk;
});
}
{
fidl::VectorView<fuchsia_tee::wire::Parameter> parameter_set;
fidl_client2->OpenSession2(
std::move(parameter_set),
[&](::fidl::WireResponse<::fuchsia_tee::Application::OpenSession2>* resp) {
sync_completion_signal(&completion2);
});
}
sync_completion_wait(&completion2, ZX_TIME_INFINITE);
sync_completion_wait(&completion1, ZX_TIME_INFINITE);
EXPECT_EQ(call_with_args_count, 3);
EXPECT_EQ(optee_->CommandQueueSize(), 0);
EXPECT_EQ(optee_->CommandQueueWaitSize(), 0);
}
TEST_F(FakeDdkOptee, TheadLimitWrongOrder) {
zx::channel tee_app_client[3];
sync_completion_t completion1;
sync_completion_t completion2;
sync_completion_t completion3;
sync_completion_t smc_completion;
sync_completion_t smc_sleep_completion;
for (auto& i : tee_app_client) {
zx::channel tee_app_server;
ASSERT_OK(zx::channel::create(0, &i, &tee_app_server));
zx::channel provider_server;
zx::channel provider_client;
ASSERT_OK(zx::channel::create(0, &provider_client, &provider_server));
optee_->TeeConnectToApplication(&kOpteeOsUuid, std::move(tee_app_server),
std::move(provider_client));
}
auto client_end1 = fidl::ClientEnd<fuchsia_tee::Application>(std::move(tee_app_client[0]));
fidl::WireSharedClient fidl_client1(std::move(client_end1), clients_loop_.dispatcher());
auto client_end2 = fidl::ClientEnd<fuchsia_tee::Application>(std::move(tee_app_client[1]));
fidl::WireSharedClient fidl_client2(std::move(client_end2), clients_loop_.dispatcher());
auto client_end3 = fidl::ClientEnd<fuchsia_tee::Application>(std::move(tee_app_client[2]));
fidl::WireSharedClient fidl_client3(std::move(client_end3), clients_loop_.dispatcher());
{
SetSmcCallWithArgHandler([&](const zx_smc_parameters_t* params, zx_smc_result_t* out) {
sync_completion_signal(&smc_completion);
sync_completion_wait(&smc_sleep_completion, ZX_TIME_INFINITE);
out->arg0 = optee::kReturnOk;
});
}
{ // first client is just sleeping for a long time (without ThreadLimit)
fidl::VectorView<fuchsia_tee::wire::Parameter> parameter_set;
fidl_client1->OpenSession2(
std::move(parameter_set),
[&](::fidl::WireResponse<::fuchsia_tee::Application::OpenSession2>* resp) {
sync_completion_signal(&completion1);
});
}
sync_completion_wait(&smc_completion, ZX_TIME_INFINITE);
EXPECT_FALSE(sync_completion_signaled(&completion1));
EXPECT_EQ(call_with_args_count, 1);
sync_completion_reset(&smc_completion);
{
SetSmcCallWithArgHandler([&](const zx_smc_parameters_t* params, zx_smc_result_t* out) {
sync_completion_signal(&smc_completion);
out->arg0 = optee::kReturnEThreadLimit;
});
}
{ // 2nd client got ThreadLimit
fidl::VectorView<fuchsia_tee::wire::Parameter> parameter_set;
fidl_client2->OpenSession2(
std::move(parameter_set),
[&](::fidl::WireResponse<::fuchsia_tee::Application::OpenSession2>* resp) {
sync_completion_signal(&completion2);
});
}
sync_completion_wait(&smc_completion, ZX_TIME_INFINITE);
EXPECT_FALSE(sync_completion_signaled(&completion2));
EXPECT_EQ(call_with_args_count, 2);
EXPECT_EQ(optee_->CommandQueueSize(), 2);
{
SetSmcCallWithArgHandler([&](const zx_smc_parameters_t* params, zx_smc_result_t* out) {
out->arg0 = optee::kReturnOk;
});
}
{
fidl::VectorView<fuchsia_tee::wire::Parameter> parameter_set;
fidl_client3->OpenSession2(
std::move(parameter_set),
[&](::fidl::WireResponse<::fuchsia_tee::Application::OpenSession2>* resp) {
sync_completion_signal(&completion3);
});
}
sync_completion_wait(&completion3, ZX_TIME_INFINITE);
sync_completion_wait(&completion2, ZX_TIME_INFINITE);
EXPECT_EQ(call_with_args_count, 4);
sync_completion_signal(&smc_sleep_completion);
sync_completion_wait(&completion1, ZX_TIME_INFINITE);
EXPECT_EQ(optee_->CommandQueueSize(), 0);
EXPECT_EQ(optee_->CommandQueueWaitSize(), 0);
}
TEST_F(FakeDdkOptee, TheadLimitWrongOrderCascade) {
zx::channel tee_app_client[3];
sync_completion_t completion1;
sync_completion_t completion2;
sync_completion_t completion3;
sync_completion_t smc_completion;
sync_completion_t smc_sleep_completion1;
sync_completion_t smc_sleep_completion2;
for (auto& i : tee_app_client) {
zx::channel tee_app_server;
ASSERT_OK(zx::channel::create(0, &i, &tee_app_server));
zx::channel provider_server;
zx::channel provider_client;
ASSERT_OK(zx::channel::create(0, &provider_client, &provider_server));
optee_->TeeConnectToApplication(&kOpteeOsUuid, std::move(tee_app_server),
std::move(provider_client));
}
auto client_end1 = fidl::ClientEnd<fuchsia_tee::Application>(std::move(tee_app_client[0]));
fidl::WireSharedClient fidl_client1(std::move(client_end1), clients_loop_.dispatcher());
auto client_end2 = fidl::ClientEnd<fuchsia_tee::Application>(std::move(tee_app_client[1]));
fidl::WireSharedClient fidl_client2(std::move(client_end2), clients_loop_.dispatcher());
auto client_end3 = fidl::ClientEnd<fuchsia_tee::Application>(std::move(tee_app_client[2]));
fidl::WireSharedClient fidl_client3(std::move(client_end3), clients_loop_.dispatcher());
{
SetSmcCallWithArgHandler([&](const zx_smc_parameters_t* params, zx_smc_result_t* out) {
sync_completion_signal(&smc_completion);
sync_completion_wait(&smc_sleep_completion1, ZX_TIME_INFINITE);
out->arg0 = optee::kReturnEThreadLimit;
});
}
{ // first client is just sleeping for a long time (without ThreadLimit)
fidl::VectorView<fuchsia_tee::wire::Parameter> parameter_set;
fidl_client1->OpenSession2(
std::move(parameter_set),
[&](::fidl::WireResponse<::fuchsia_tee::Application::OpenSession2>* resp) {
sync_completion_signal(&completion1);
});
}
sync_completion_wait(&smc_completion, ZX_TIME_INFINITE);
EXPECT_FALSE(sync_completion_signaled(&completion1));
EXPECT_EQ(call_with_args_count, 1);
sync_completion_reset(&smc_completion);
{
SetSmcCallWithArgHandler([&](const zx_smc_parameters_t* params, zx_smc_result_t* out) {
sync_completion_signal(&smc_completion);
sync_completion_wait(&smc_sleep_completion2, ZX_TIME_INFINITE);
out->arg0 = optee::kReturnOk;
});
}
{ // 2nd client got ThreadLimit
fidl::VectorView<fuchsia_tee::wire::Parameter> parameter_set;
fidl_client2->OpenSession2(
std::move(parameter_set),
[&](::fidl::WireResponse<::fuchsia_tee::Application::OpenSession2>* resp) {
sync_completion_signal(&completion2);
});
}
sync_completion_wait(&smc_completion, ZX_TIME_INFINITE);
EXPECT_FALSE(sync_completion_signaled(&completion2));
EXPECT_EQ(call_with_args_count, 2);
EXPECT_EQ(optee_->CommandQueueSize(), 2);
{
SetSmcCallWithArgHandler([&](const zx_smc_parameters_t* params, zx_smc_result_t* out) {
out->arg0 = optee::kReturnOk;
});
}
{
fidl::VectorView<fuchsia_tee::wire::Parameter> parameter_set;
fidl_client3->OpenSession2(
std::move(parameter_set),
[&](::fidl::WireResponse<::fuchsia_tee::Application::OpenSession2>* resp) {
sync_completion_signal(&completion3);
});
}
sync_completion_wait(&completion3, ZX_TIME_INFINITE);
EXPECT_EQ(call_with_args_count, 3);
sync_completion_signal(&smc_sleep_completion2);
sync_completion_wait(&completion2, ZX_TIME_INFINITE);
EXPECT_EQ(call_with_args_count, 3);
sync_completion_signal(&smc_sleep_completion1);
sync_completion_wait(&completion1, ZX_TIME_INFINITE);
EXPECT_EQ(call_with_args_count, 4);
EXPECT_EQ(optee_->CommandQueueSize(), 0);
EXPECT_EQ(optee_->CommandQueueWaitSize(), 0);
}
} // namespace
} // namespace optee
| 37.09311 | 100 | 0.726492 | [
"object"
] |
443962b694c6bacf029348c280e4a1e393a3a444 | 29,632 | cpp | C++ | code/pilotfile/csg_convert.cpp | trgswe/fs2open.github.com | a159eba0cebca911ad14a118412fddfe5be8e9f8 | [
"Unlicense"
] | 307 | 2015-04-10T13:27:32.000Z | 2022-03-21T03:30:38.000Z | code/pilotfile/csg_convert.cpp | trgswe/fs2open.github.com | a159eba0cebca911ad14a118412fddfe5be8e9f8 | [
"Unlicense"
] | 2,231 | 2015-04-27T10:47:35.000Z | 2022-03-31T19:22:37.000Z | code/pilotfile/csg_convert.cpp | trgswe/fs2open.github.com | a159eba0cebca911ad14a118412fddfe5be8e9f8 | [
"Unlicense"
] | 282 | 2015-01-05T12:16:57.000Z | 2022-03-28T04:45:11.000Z |
/* WARNING:
* This is magic-number central, but these numbers are set specifically
* to the acceptable defaults or range values that were used when the
* pl2/plr files were created. Standard game defines should not be used in
* place of these major numbers for /any/ reason, *ever*!
*/
#include "cfile/cfilesystem.h"
#include "pilotfile/pilotfile_convert.h"
#include "cutscene/cutscenes.h"
#include "menuui/techmenu.h"
#include "ship/ship.h"
#include "stats/medals.h"
#include "weapon/weapon.h"
#include <iostream>
#include <sstream>
#include <limits>
// copy of old scoring struct * NORMAL PILOTS *
typedef struct scoring_conv_t {
int flags;
int score;
int rank;
int medals[18];
int kills[130];
int assists;
int kill_count;
int kill_count_ok;
unsigned int p_shots_fired;
unsigned int s_shots_fired;
unsigned int p_shots_hit;
unsigned int s_shots_hit;
unsigned int p_bonehead_hits;
unsigned int s_bonehead_hits;
int bonehead_kills;
unsigned int missions_flown;
unsigned int flight_time;
_fs_time_t last_flown;
_fs_time_t last_backup;
// Mission total
int m_medal_earned;
int m_badge_earned;
int m_promotion_earned;
int m_score;
int m_kills[130];
int m_okKills[130];
int m_kill_count;
int m_kill_count_ok;
int m_assists;
unsigned int mp_shots_fired;
unsigned int ms_shots_fired;
unsigned int mp_shots_hit;
unsigned int ms_shots_hit;
unsigned int mp_bonehead_hits;
unsigned int ms_bonehead_hits;
int m_bonehead_kills;
int m_player_deaths;
int m_dogfight_kills[12];
} scoring_conv_t;
static const size_t SCORING_SIZE = 1808;
// copy of old scoring struct * INFERNO PILOTS *
typedef struct scoring_conv_INF_t {
int flags;
int score;
int rank;
int medals[18];
int kills[250];
int assists;
int kill_count;
int kill_count_ok;
unsigned int p_shots_fired;
unsigned int s_shots_fired;
unsigned int p_shots_hit;
unsigned int s_shots_hit;
unsigned int p_bonehead_hits;
unsigned int s_bonehead_hits;
int bonehead_kills;
unsigned int missions_flown;
unsigned int flight_time;
_fs_time_t last_flown;
_fs_time_t last_backup;
// Mission total
int m_medal_earned;
int m_badge_earned;
int m_promotion_earned;
int m_score;
int m_kills[250];
int m_okKills[250];
int m_kill_count;
int m_kill_count_ok;
int m_assists;
unsigned int mp_shots_fired;
unsigned int ms_shots_fired;
unsigned int mp_shots_hit;
unsigned int ms_shots_hit;
unsigned int mp_bonehead_hits;
unsigned int ms_bonehead_hits;
int m_bonehead_kills;
int m_player_deaths;
int m_dogfight_kills[12];
} scoring_conv_INF_t;
static const size_t SCORING_INF_SIZE = 3248;
csg_data::csg_data()
{
sig = 0;
cutscenes = 0;
main_hall = "";
prev_mission = -1;
next_mission = -1;
loop_reentry = 0;
loop_enabled = 0;
num_completed = 0;
last_ship_flown_index = -1;
}
csg_data::~csg_data()
{
}
void pilotfile_convert::csg_import_ships_weapons()
{
index_list_t ilist;
char name[35];
int idx;
int list_size = 0;
int ship_count = cfread_int(cfp);
int weap_count = cfread_int(cfp);
for (idx = 0; idx < ship_count; idx++) {
ubyte allowed = cfread_ubyte(cfp);
csg->ships_allowed.push_back( (allowed != 0) );
cfread_string_len(name, sizeof(name), cfp);
ilist.name = name;
ilist.index = ship_info_lookup(name);
if (ilist.index < 0) {
std::ostringstream error_msg;
error_msg << "Data mismatch (ship lookup: " << ilist.name << ")!";
throw std::runtime_error(error_msg.str().c_str());
}
csg->ship_list.push_back( ilist );
}
for (idx = 0; idx < weap_count; idx++) {
ubyte allowed = cfread_ubyte(cfp);
csg->weapons_allowed.push_back( allowed != 0 );
cfread_string_len(name, sizeof(name), cfp);
ilist.name = name;
ilist.index = weapon_info_lookup(name);
if (ilist.index < 0) {
std::ostringstream error_msg;
error_msg << "Data mismatch (weapon lookup: " << ilist.name << ")!";
throw std::runtime_error(error_msg.str().c_str());
}
csg->weapon_list.push_back( ilist );
}
// get last ship flown index
for (idx = 0; idx < ship_count; idx++) {
if ( csg->ship_list[idx].name == plr->last_ship_flown ) {
csg->last_ship_flown_index = idx;
break;
}
}
if (csg->last_ship_flown_index < 0) {
std::ostringstream error_msg;
error_msg << "Data mismatch (player ship: " << csg->last_ship_flown_index << ")!";
throw std::runtime_error(error_msg.str().c_str());
}
// create list of medals (since it's missing from the old files)
list_size = Num_medals;
for (idx = 0; idx < list_size; idx++) {
ilist.name = Medals[idx].name;
ilist.index = idx;
csg->medals_list.push_back( ilist );
}
// stuff intel list as well (present but buried in old files)
list_size = intel_info_size();
for (idx = 0; idx < list_size; idx++) {
ilist.name = Intel_info[idx].name;
ilist.index = idx;
csg->intel_list.push_back( ilist );
}
}
void pilotfile_convert::csg_import_missions(bool inferno)
{
cmission_conv_t miss;
int idx, j;
int count;
int list_size = 0, k;
scoring_conv_t t_score;
scoring_conv_INF_t t_inf_score;
Assert( sizeof(scoring_conv_t) == SCORING_SIZE );
Assert( sizeof(scoring_conv_INF_t) == SCORING_INF_SIZE );
int ship_list_size = (int)csg->ship_list.size();
int num_missions = cfread_int(cfp);
csg->missions.reserve(num_missions);
for (idx = 0; idx < num_missions; idx++) {
miss.index = cfread_int(cfp);
// goals
count = cfread_int(cfp);
if (count > 0) {
mgoal n_goal;
miss.goals.reserve(count);
for (j = 0; j < count; j++) {
memset(&n_goal, 0, sizeof(mgoal));
cfread_string_len(n_goal.name, sizeof(n_goal.name), cfp);
n_goal.status = cfread_char(cfp);
miss.goals.push_back( n_goal );
}
}
// events
count = cfread_int(cfp);
if (count > 0) {
mevent n_event;
miss.events.reserve(count);
for (j = 0; j < count; j++) {
memset(&n_event, 0, sizeof(mevent));
cfread_string_len(n_event.name, sizeof(n_event.name), cfp);
n_event.status = cfread_char(cfp);
miss.events.push_back( n_event );
}
}
// variables
count = cfread_int(cfp);
if (count > 0) {
sexp_variable n_variable;
miss.variables.reserve(count);
for (j = 0; j < count; j++) {
memset(&n_variable, 0, sizeof(sexp_variable));
n_variable.type = cfread_int(cfp);
cfread_string_len(n_variable.text, sizeof(n_variable.text), cfp);
cfread_string_len(n_variable.variable_name, sizeof(n_variable.variable_name), cfp);
miss.variables.push_back( n_variable );
}
}
// stats
miss.stats.ship_kills = csg->ship_list;
miss.stats.medals_earned = csg->medals_list;
if (inferno) {
cfread(&t_inf_score, sizeof(scoring_conv_INF_t), 1, cfp);
for (j = 0; j < ship_list_size; j++) {
miss.stats.ship_kills[j].val = INTEL_INT(t_inf_score.kills[j]);
}
miss.stats.score = INTEL_INT(t_inf_score.score);
miss.stats.rank = INTEL_INT(t_inf_score.rank);
miss.stats.assists = INTEL_INT(t_inf_score.assists);
miss.stats.kill_count = INTEL_INT(t_inf_score.kill_count);
miss.stats.kill_count_ok = INTEL_INT(t_inf_score.kill_count_ok);
miss.stats.p_shots_fired = INTEL_INT(t_inf_score.p_shots_fired);
miss.stats.s_shots_fired = INTEL_INT(t_inf_score.s_shots_fired);
miss.stats.p_shots_hit = INTEL_INT(t_inf_score.p_shots_hit);
miss.stats.s_shots_hit = INTEL_INT(t_inf_score.s_shots_hit);
miss.stats.p_bonehead_hits = INTEL_INT(t_inf_score.p_bonehead_hits);
miss.stats.s_bonehead_hits = INTEL_INT(t_inf_score.s_bonehead_hits);
miss.stats.bonehead_kills = INTEL_INT(t_inf_score.bonehead_kills);
for (j = 0; j < 18; j++) {
miss.stats.medals_earned[j].val = INTEL_INT(t_inf_score.medals[j]);
}
} else {
cfread(&t_score, sizeof(scoring_conv_t), 1, cfp);
for (j = 0; j < ship_list_size; j++) {
miss.stats.ship_kills[j].val = INTEL_INT(t_score.kills[j]);
}
miss.stats.score = INTEL_INT(t_score.score);
miss.stats.rank = INTEL_INT(t_score.rank);
miss.stats.assists = INTEL_INT(t_score.assists);
miss.stats.kill_count = INTEL_INT(t_score.kill_count);
miss.stats.kill_count_ok = INTEL_INT(t_score.kill_count_ok);
miss.stats.p_shots_fired = INTEL_INT(t_score.p_shots_fired);
miss.stats.s_shots_fired = INTEL_INT(t_score.s_shots_fired);
miss.stats.p_shots_hit = INTEL_INT(t_score.p_shots_hit);
miss.stats.s_shots_hit = INTEL_INT(t_score.s_shots_hit);
miss.stats.p_bonehead_hits = INTEL_INT(t_score.p_bonehead_hits);
miss.stats.s_bonehead_hits = INTEL_INT(t_score.s_bonehead_hits);
miss.stats.bonehead_kills = INTEL_INT(t_score.bonehead_kills);
for (j = 0; j < 18; j++) {
miss.stats.medals_earned[j].val = INTEL_INT(t_score.medals[j]);
}
}
// flags
miss.flags = cfread_int(cfp);
// now add to list
csg->missions.push_back( miss );
}
// finally, convert old mission variables to proper campaign variables
for (idx = 0; idx < num_missions; idx++) {
count = (int)csg->missions[idx].variables.size();
for (j = 0; j < count; j++) {
bool add_it = true;
list_size = (int)csg->variables.size();
for (k = 0; k < list_size; k++) {
if ( !stricmp(csg->variables[k].variable_name, csg->missions[idx].variables[j].variable_name) ) {
csg->variables[k] = csg->missions[idx].variables[j];
add_it = false;
break;
}
}
if (add_it) {
csg->variables.push_back( csg->missions[idx].variables[j] );
}
}
}
}
void pilotfile_convert::csg_import_red_alert()
{
int idx, i, j;
int count;
char t_string[35] = { '\0' };
float val;
wep_t weapons;
count = cfread_int(cfp);
if (count <= 0) {
return;
}
csg->wingman_status.reserve( count );
cfread_string(t_string, sizeof(t_string)-1, cfp);
csg->precursor_mission = t_string;
int ship_list_size = (int)csg->ship_list.size();
int weapon_list_size = (int)csg->weapon_list.size();
for (idx = 0; idx < count; idx++) {
red_alert_ship_status ras;
// ship name
cfread_string(t_string, sizeof(t_string)-1, cfp);
ras.name = t_string;
ras.hull = cfread_float(cfp);
ras.ship_class = cfread_int(cfp);
if (ras.ship_class >= ship_list_size) {
throw std::runtime_error("Data failure (RedAlert-ship)!");
}
// system status
ras.subsys_current_hits.reserve(64);
for (j = 0; j < 64; j++) {
val = cfread_float(cfp);
ras.subsys_current_hits.push_back( val );
}
ras.subsys_aggregate_current_hits.reserve(12);
for (j = 0; j < 12; j++) {
val = cfread_float(cfp);
ras.subsys_aggregate_current_hits.push_back( val );
}
// loadout
ras.primary_weapons.reserve(3);
for (j = 0; j < 3; j++) {
i = cfread_int(cfp);
if (i >= weapon_list_size || i < -1) {
throw std::runtime_error("Data check failure (RedAlert-weapon)!");
} else if (i >= 0) {
weapons.index = csg->weapon_list[i].index;
} else {
weapons.index = -1;
}
weapons.count = cfread_int(cfp);
if (weapons.index >= 0) {
ras.primary_weapons.push_back( weapons );
}
}
ras.secondary_weapons.reserve(4);
for (j = 0; j < 4; j++) {
i = cfread_int(cfp);
if (i >= weapon_list_size || i < -1) {
throw std::runtime_error("Data check failure (RedAlert-weapon)!");
} else if (i >= 0) {
weapons.index = csg->weapon_list[i].index;
} else {
weapons.index = -1;
}
weapons.count = cfread_int(cfp);
if (weapons.index >= 0) {
ras.secondary_weapons.push_back( weapons );
}
}
// add to list
csg->wingman_status.push_back( ras );
}
}
void pilotfile_convert::csg_import_techroom()
{
int idx, list_size = 0;
bool visible;
unsigned char in = 0;
// intel entry count
int intel_count = cfread_int(cfp);
csg->ships_techroom.reserve( csg->ship_list.size() );
csg->weapons_techroom.reserve( csg->weapon_list.size() );
csg->intel_techroom.reserve( intel_count );
// ships
list_size = (int)csg->ship_list.size();
for (idx = 0; idx < list_size; idx++) {
in = cfread_ubyte(cfp);
if (in > 1) {
throw std::runtime_error("Data check failure (techroom-ship)!");
}
visible = (in == 1) ? true : false;
csg->ships_techroom.push_back( visible );
}
// weapons
list_size = (int)csg->weapon_list.size();
for (idx = 0; idx < list_size; idx++) {
in = cfread_ubyte(cfp);
if (in > 1) {
throw std::runtime_error("Data check failure (techroom-weapon)!");
}
visible = (in == 1) ? true : false;
csg->weapons_techroom.push_back( visible );
}
// intel
list_size = intel_count;
for (idx = 0; idx < list_size; idx++) {
in = cfread_ubyte(cfp);
if (in > 1) {
throw std::runtime_error("Data check failure (techroom-intel)!");
}
visible = (in == 1) ? true : false;
csg->intel_techroom.push_back( visible );
}
}
void pilotfile_convert::csg_import_loadout()
{
char t_string[50] = { '\0' };
// mission name/status
cfread_string_len(t_string, sizeof(t_string), cfp);
csg->loadout.filename = t_string;
cfread_string_len(t_string, sizeof(t_string), cfp);
csg->loadout.last_modified = t_string;
// ship pool
size_t list_size = csg->ship_list.size();
csg->loadout.ship_pool.reserve(list_size);
for (size_t idx = 0; idx < list_size; idx++) {
int count = cfread_int(cfp);
csg->loadout.ship_pool.push_back( count );
}
// weapon pool
list_size = csg->weapon_list.size();
csg->loadout.weapon_pool.reserve(list_size);
for (size_t idx = 0; idx < list_size; idx++) {
int count = cfread_int(cfp);
csg->loadout.weapon_pool.push_back( count );
}
// loadout info
for (size_t idx = 0; idx < MAX_WSS_SLOTS_CONV; idx++) {
csg->loadout.slot[idx].ship_index = cfread_int(cfp);
for (size_t j = 0; j < MAX_SHIP_WEAPONS_CONV; j++) {
csg->loadout.slot[idx].wep[j] = cfread_int(cfp);
csg->loadout.slot[idx].wep_count[j] = cfread_int(cfp);
}
}
}
void pilotfile_convert::csg_import_stats()
{
int list_size = 0;
int idx;
csg->stats.score = cfread_int(cfp);
csg->stats.rank = cfread_int(cfp);
csg->stats.assists = cfread_int(cfp);
csg->stats.medals_earned = csg->medals_list;
list_size = (int)csg->stats.medals_earned.size();
for (idx = 0; idx < list_size; idx++) {
csg->stats.medals_earned[idx].val = cfread_int(cfp);
}
csg->stats.ship_kills = csg->ship_list;
list_size = cfread_int(cfp);
// NOTE: could be less, but never greater than
if ( list_size > (int)csg->stats.ship_kills.size() ) {
throw std::runtime_error("Data check failure (kills size)!");
}
for (idx = 0; idx < list_size; idx++) {
csg->stats.ship_kills[idx].val = (int)cfread_ushort(cfp);
}
csg->stats.kill_count = cfread_int(cfp);
csg->stats.kill_count_ok = cfread_int(cfp);
csg->stats.p_shots_fired = cfread_uint(cfp);
csg->stats.s_shots_fired = cfread_uint(cfp);
csg->stats.p_shots_hit = cfread_uint(cfp);
csg->stats.s_shots_hit = cfread_uint(cfp);
csg->stats.p_bonehead_hits = cfread_uint(cfp);
csg->stats.s_bonehead_hits = cfread_uint(cfp);
csg->stats.bonehead_kills = cfread_uint(cfp);
}
void pilotfile_convert::csg_import(bool inferno)
{
Assert( cfp != NULL );
char name[35];
unsigned int csg_id = cfread_uint(cfp);
if (csg_id != 0xbeefcafe) {
throw std::runtime_error("Invalid file signature!");
}
fver = cfread_uint(cfp);
if (fver != 15) {
throw std::runtime_error("Unsupported file version!");
}
// campaign type (single/multi)
csg->sig = cfread_int(cfp);
// trash
cfread_string_len(name, sizeof(name), cfp);
csg->prev_mission = cfread_int(cfp);
csg->next_mission = cfread_int(cfp);
csg->loop_reentry = cfread_int(cfp);
csg->loop_enabled = cfread_int(cfp);
csg_import_ships_weapons();
csg_import_missions(inferno);
csg->main_hall = cfread_ubyte(cfp);
csg_import_red_alert();
csg_import_techroom();
csg_import_loadout();
csg_import_stats();
csg->cutscenes = cfread_int(cfp);
// final data checks
if ( csg->ship_list.size() != csg->ships_allowed.size() ) {
throw std::runtime_error("Data check failure (ship size)!");
} else if ( csg->ship_list.size() != csg->ships_techroom.size() ) {
throw std::runtime_error("Data check failure (ship size)!");
} else if ( csg->weapon_list.size() != csg->weapons_allowed.size() ) {
throw std::runtime_error("Data check failure (weapon size)!");
} else if ( csg->weapon_list.size() != csg->weapons_techroom.size() ) {
throw std::runtime_error("Data check failure (weapon size)!");
} else if ( csg->intel_list.size() != csg->intel_techroom.size() ) {
throw std::runtime_error("Data check failure (intel size)!");
}
// and... we're done!
}
void pilotfile_convert::csg_export_flags()
{
startSection(Section::Flags);
// tips
cfwrite_ubyte((ubyte)plr->tips, cfp);
// special rank
cfwrite_int(csg->stats.rank, cfp);
endSection();
}
void pilotfile_convert::csg_export_info()
{
int list_size = 0;
int idx;
ubyte visible;
startSection(Section::Info);
// ship list
list_size = (int)csg->ship_list.size();
cfwrite_int(list_size, cfp);
for (idx = 0; idx < list_size; idx++) {
cfwrite_string_len(csg->ship_list[idx].name.c_str(), cfp);
}
// weapon list
list_size = (int)csg->weapon_list.size();
cfwrite_int(list_size, cfp);
for (idx = 0; idx < list_size; idx++) {
cfwrite_string_len(csg->weapon_list[idx].name.c_str(), cfp);
}
// intel list
list_size = (int)csg->intel_list.size();
cfwrite_int(list_size, cfp);
for (idx = 0; idx < list_size; idx++) {
cfwrite_string_len(csg->intel_list[idx].name.c_str(), cfp);
}
// medals list
list_size = (int)csg->stats.medals_earned.size();
cfwrite_int(list_size, cfp);
for (idx = 0; idx < list_size; idx++) {
cfwrite_string_len(csg->stats.medals_earned[idx].name.c_str(), cfp);
}
// last ship flown
cfwrite_int(csg->last_ship_flown_index, cfp);
// progression state
cfwrite_int(csg->prev_mission, cfp);
cfwrite_int(csg->next_mission, cfp);
// loop state
cfwrite_int(csg->loop_enabled, cfp);
cfwrite_int(csg->loop_reentry, cfp);
// missions completed
list_size = (int)csg->missions.size();
cfwrite_int(list_size, cfp);
// allowed ships
list_size = (int)csg->ships_allowed.size();
for (idx = 0; idx < list_size; idx++) {
visible = csg->ships_allowed[idx] ? 1 : 0;
cfwrite_ubyte(visible, cfp);
}
// allowed weapons
list_size = (int)csg->weapons_allowed.size();
for (idx = 0; idx < list_size; idx++) {
visible = csg->weapons_allowed[idx] ? 1 : 0;
cfwrite_ubyte(visible, cfp);
}
// single/campaign squad name & image, make it the same as multi
cfwrite_string_len(plr->squad_name, cfp);
cfwrite_string_len(plr->squad_filename, cfp);
endSection();
}
void pilotfile_convert::csg_export_missions()
{
startSection(Section::Missions);
size_t list_size = csg->missions.size();
for (size_t idx = 0; idx < list_size; idx++) {
cfwrite_int(csg->missions[idx].index, cfp);
// flags
cfwrite_int(csg->missions[idx].flags, cfp);
// goals
size_t count = csg->missions[idx].goals.size();
cfwrite_int((int)count, cfp);
for (size_t j = 0; j < count; j++) {
cfwrite_string_len(csg->missions[idx].goals[j].name, cfp);
cfwrite_char(csg->missions[idx].goals[j].status, cfp);
}
// events
count = csg->missions[idx].events.size();
cfwrite_int((int)count, cfp);
for (size_t j = 0; j < count; j++) {
cfwrite_string_len(csg->missions[idx].events[j].name, cfp);
cfwrite_char(csg->missions[idx].events[j].status, cfp);
}
// variables
count = csg->missions[idx].variables.size();
cfwrite_int((int)count, cfp);
for (size_t j = 0; j < count; j++) {
cfwrite_int(csg->missions[idx].variables[j].type, cfp);
cfwrite_string_len(csg->missions[idx].variables[j].text, cfp);
cfwrite_string_len(csg->missions[idx].variables[j].variable_name, cfp);
}
// scoring stats
cfwrite_int(csg->missions[idx].stats.score, cfp);
cfwrite_int(csg->missions[idx].stats.rank, cfp);
cfwrite_int(csg->missions[idx].stats.assists, cfp);
cfwrite_int(csg->missions[idx].stats.kill_count, cfp);
cfwrite_int(csg->missions[idx].stats.kill_count_ok, cfp);
cfwrite_int(csg->missions[idx].stats.bonehead_kills, cfp);
cfwrite_uint(csg->missions[idx].stats.p_shots_fired, cfp);
cfwrite_uint(csg->missions[idx].stats.p_shots_hit, cfp);
cfwrite_uint(csg->missions[idx].stats.p_bonehead_hits, cfp);
cfwrite_uint(csg->missions[idx].stats.s_shots_fired, cfp);
cfwrite_uint(csg->missions[idx].stats.s_shots_hit, cfp);
cfwrite_uint(csg->missions[idx].stats.s_bonehead_hits, cfp);
// ship kills (scoring)
count = csg->missions[idx].stats.ship_kills.size();
for (size_t j = 0; j < count; j++) {
cfwrite_int(csg->missions[idx].stats.ship_kills[j].val, cfp);
}
// medals earned (scoring)
count = csg->missions[idx].stats.medals_earned.size();
for (size_t j = 0; j < count; j++) {
cfwrite_int(csg->missions[idx].stats.medals_earned[j].val, cfp);
}
}
endSection();
}
void pilotfile_convert::csg_export_techroom()
{
int list_size = 0;
int idx;
ubyte visible;
startSection(Section::Techroom);
// visible ships
list_size = (int)csg->ships_techroom.size();
for (idx = 0; idx < list_size; idx++) {
visible = csg->ships_techroom[idx] ? 1 : 0;
cfwrite_ubyte(visible, cfp);
}
// visible weapons
list_size = (int)csg->weapons_techroom.size();
for (idx = 0; idx < list_size; idx++) {
visible = csg->weapons_techroom[idx] ? 1 : 0;
cfwrite_ubyte(visible, cfp);
}
// visible intel entries
list_size = (int)csg->intel_techroom.size();
for (idx = 0; idx < list_size; idx++) {
visible = csg->intel_techroom[idx] ? 1 : 0;
cfwrite_ubyte(visible, cfp);
}
endSection();
}
void pilotfile_convert::csg_export_loadout()
{
startSection(Section::Loadout);
// base info
cfwrite_string_len(csg->loadout.filename.c_str(), cfp);
cfwrite_string_len(csg->loadout.last_modified.c_str(), cfp);
// ship pool
size_t list_size = csg->loadout.ship_pool.size();
for (size_t idx = 0; idx < list_size; idx++) {
cfwrite_int(csg->loadout.ship_pool[idx], cfp);
}
// weapon pool
list_size = csg->loadout.weapon_pool.size();
for (size_t idx = 0; idx < list_size; idx++) {
cfwrite_int(csg->loadout.weapon_pool[idx], cfp);
}
// play ship loadout
cfwrite_ushort(12, cfp);
for (size_t idx = 0; idx < 12; idx++) {
// ship
cfwrite_int(csg->loadout.slot[idx].ship_index, cfp);
// primary weapons
cfwrite_int(3, cfp);
for (size_t j = 0; j < 3; j++) {
cfwrite_int(csg->loadout.slot[idx].wep[j], cfp);
cfwrite_int(csg->loadout.slot[idx].wep_count[j], cfp);
}
// secondary weapons
cfwrite_int(4, cfp);
for (size_t j = 0; j < 4; j++) {
cfwrite_int(csg->loadout.slot[idx].wep[j+3], cfp);
cfwrite_int(csg->loadout.slot[idx].wep_count[j+3], cfp);
}
}
endSection();
}
void pilotfile_convert::csg_export_stats()
{
startSection(Section::Scoring);
// scoring stats
cfwrite_int(csg->stats.score, cfp);
cfwrite_int(csg->stats.rank, cfp);
cfwrite_int(csg->stats.assists, cfp);
cfwrite_int(csg->stats.kill_count, cfp);
cfwrite_int(csg->stats.kill_count_ok, cfp);
cfwrite_int(csg->stats.bonehead_kills, cfp);
cfwrite_uint(csg->stats.p_shots_fired, cfp);
cfwrite_uint(csg->stats.p_shots_hit, cfp);
cfwrite_uint(csg->stats.p_bonehead_hits, cfp);
cfwrite_uint(csg->stats.s_shots_fired, cfp);
cfwrite_uint(csg->stats.s_shots_hit, cfp);
cfwrite_uint(csg->stats.s_bonehead_hits, cfp);
cfwrite_uint(csg->stats.flight_time, cfp);
cfwrite_uint(csg->stats.missions_flown, cfp);
cfwrite_int((int)csg->stats.last_flown, cfp);
cfwrite_int((int)csg->stats.last_backup, cfp);
// ship kills (scoring)
size_t list_size = csg->stats.ship_kills.size();
for (size_t idx = 0; idx < list_size; idx++) {
cfwrite_int(csg->stats.ship_kills[idx].val, cfp);
}
// medals earned (scoring)
list_size = csg->stats.medals_earned.size();
for (size_t idx = 0; idx < list_size; idx++) {
cfwrite_int(csg->stats.medals_earned[idx].val, cfp);
}
endSection();
}
void pilotfile_convert::csg_export_redalert()
{
int idx, j, list_size = 0;
int count;
red_alert_ship_status *ras;
startSection(Section::RedAlert);
list_size = (int)csg->wingman_status.size();
cfwrite_int(list_size, cfp);
if (list_size) {
cfwrite_string_len(csg->precursor_mission.c_str(), cfp);
for (idx = 0; idx < list_size; idx++) {
ras = &csg->wingman_status[idx];
cfwrite_string_len(ras->name.c_str(), cfp);
cfwrite_float(ras->hull, cfp);
// ship class, should be index into ship_list[] on load
cfwrite_int(ras->ship_class, cfp);
// subsystem hits
count = (int)ras->subsys_current_hits.size();
cfwrite_int(count, cfp);
for (j = 0; j < count; j++) {
cfwrite_float(ras->subsys_current_hits[j], cfp);
}
// subsystem aggregate hits
count = (int)ras->subsys_aggregate_current_hits.size();
cfwrite_int(count, cfp);
for (j = 0; j < count; j++) {
cfwrite_float(ras->subsys_aggregate_current_hits[j], cfp);
}
// primary weapon loadout and status
count = (int)ras->primary_weapons.size();
cfwrite_int(count, cfp);
for (j = 0; j < count; j++) {
cfwrite_int(ras->primary_weapons[j].index, cfp);
cfwrite_int(ras->primary_weapons[j].count, cfp);
}
// secondary weapon loadout and status
count = (int)ras->secondary_weapons.size();
cfwrite_int(count, cfp);
for (j = 0; j < count; j++) {
cfwrite_int(ras->secondary_weapons[j].index, cfp);
cfwrite_int(ras->secondary_weapons[j].count, cfp);
}
}
}
endSection();
}
void pilotfile_convert::csg_export_hud()
{
int idx;
startSection(Section::HUD);
// flags
cfwrite_int(plr->hud_show_flags, cfp);
cfwrite_int(plr->hud_show_flags2, cfp);
cfwrite_int(plr->hud_popup_flags, cfp);
cfwrite_int(plr->hud_popup_flags2, cfp);
// settings
cfwrite_ubyte(plr->hud_num_lines, cfp);
cfwrite_int(plr->hud_rp_flags, cfp);
cfwrite_int(plr->hud_rp_dist, cfp);
// basic colors
cfwrite_int(0, cfp); // color
cfwrite_int(8, cfp); // alpha
// gauge-specific colors
cfwrite_int(39, cfp);
for (idx = 0; idx < 39; idx++) {
cfwrite_ubyte(plr->hud_colors[idx][0], cfp);
cfwrite_ubyte(plr->hud_colors[idx][1], cfp);
cfwrite_ubyte(plr->hud_colors[idx][2], cfp);
cfwrite_ubyte(plr->hud_colors[idx][3], cfp);
}
endSection();
}
void pilotfile_convert::csg_export_variables()
{
int list_size = 0;
int idx;
startSection(Section::Variables);
list_size = (int)csg->variables.size();
cfwrite_int(list_size, cfp);
for (idx = 0; idx < list_size; idx++) {
cfwrite_int(csg->variables[idx].type, cfp);
cfwrite_string_len(csg->variables[idx].text, cfp);
cfwrite_string_len(csg->variables[idx].variable_name, cfp);
}
endSection();
}
void pilotfile_convert::csg_export_cutscenes() {
SCP_vector<cutscene_info>::iterator cut;
startSection(Section::Cutscenes);
// convert the old int bitfield to the new vector
// the 32 is the size-in-bits of the old int on all platforms
// supported by FSO prior to 3.7.0
size_t size = Cutscenes.size();
size_t viewableScenes = 0;
for (size_t j=0; j<size && j<32; ++j) {
if ( (j < Cutscenes.size()) && (csg->cutscenes & (1<<j)) ) {
Cutscenes.at(j).flags.set(Cutscene::Cutscene_Flags::Viewable);
viewableScenes++;
}
}
// Check for possible overflow because we can only write 32 bit integers
Assertion(viewableScenes <= std::numeric_limits<uint>::max(), "Too many viewable cutscenes! Maximum is %ud!", std::numeric_limits<uint>::max());
// output cutscene data in new format
cfwrite_uint((uint)viewableScenes, cfp);
for (cut = Cutscenes.begin(); cut != Cutscenes.end(); ++cut) {
if (cut->flags[Cutscene::Cutscene_Flags::Viewable]) {
cfwrite_string_len(cut->filename, cfp);
}
}
endSection();
}
void pilotfile_convert::csg_export()
{
Assert( cfp != NULL );
// header and version
cfwrite_int(CSG_FILE_ID, cfp);
cfwrite_ubyte(CSG_VERSION, cfp);
// flags and info sections go first
csg_export_flags();
csg_export_info();
// everything else is next, not order specific
csg_export_missions();
csg_export_techroom();
csg_export_loadout();
csg_export_stats();
csg_export_redalert();
csg_export_hud();
csg_export_variables();
csg_export_cutscenes();
// and... we're done! :)
}
bool pilotfile_convert::csg_convert(const char *fname, bool inferno)
{
Assert( fname != NULL );
Assert( plr != NULL);
Assert( csg == NULL );
SCP_string filename;
bool rval = true;
csg = new(std::nothrow) csg_data;
if (csg == NULL) {
return false;
}
filename.reserve(200);
cf_create_default_path_string(filename, CF_TYPE_SINGLE_PLAYERS, (inferno) ? "inferno" : nullptr, false,
CF_LOCATION_ROOT_USER | CF_LOCATION_ROOT_GAME | CF_LOCATION_TYPE_ROOT);
if (inferno) {
filename.append(DIR_SEPARATOR_STR);
}
filename.append(fname);
filename.append(".cs2");
mprintf((" CS2 => Converting '%s'...\n", filename.c_str()));
cfp = cfopen(filename.c_str(), "rb", CFILE_NORMAL);
if ( !cfp ) {
mprintf((" CS2 => Unable to open '%s' for import!\n", fname));
delete csg;
csg = NULL;
return false;
}
try {
csg_import(inferno);
} catch (const std::exception& err) {
mprintf((" CS2 => Import ERROR: %s\n", err.what()));
rval = false;
}
cfclose(cfp);
cfp = NULL;
if ( !rval ) {
delete csg;
csg = NULL;
return false;
}
filename.assign(fname);
filename.append(".csg");
cfp = cfopen(filename.c_str(), "wb", CFILE_NORMAL, CF_TYPE_PLAYERS, false,
CF_LOCATION_ROOT_USER | CF_LOCATION_ROOT_GAME | CF_LOCATION_TYPE_ROOT);
if ( !cfp ) {
mprintf((" CSG => Unable to open '%s' for export!\n", fname));
return false;
}
try {
csg_export();
} catch (const char *err) {
mprintf((" CSG => Export ERROR: %s\n", err));
rval = false;
}
cfclose(cfp);
cfp = NULL;
delete csg;
csg = NULL;
if (rval) {
mprintf((" CSG => Conversion complete!\n"));
}
return rval;
}
| 23.93538 | 145 | 0.684058 | [
"vector"
] |
44396bec3903827138e7ddc8d5de32ce66396444 | 5,852 | cpp | C++ | src/align/AffineAlignment.cpp | mr-c/pbcopper | 6226c0adf041db717360cf0066bc91e8f556bf48 | [
"BSD-3-Clause-Clear"
] | null | null | null | src/align/AffineAlignment.cpp | mr-c/pbcopper | 6226c0adf041db717360cf0066bc91e8f556bf48 | [
"BSD-3-Clause-Clear"
] | null | null | null | src/align/AffineAlignment.cpp | mr-c/pbcopper | 6226c0adf041db717360cf0066bc91e8f556bf48 | [
"BSD-3-Clause-Clear"
] | null | null | null | // Authors: David Alexander, Lance Hepler
#include <pbcopper/align/AffineAlignment.h>
#include <cassert>
#include <cfloat>
#include <algorithm>
#include <string>
#include <vector>
#include <boost/numeric/ublas/matrix.hpp>
#include <boost/numeric/ublas/matrix_proxy.hpp>
#include <pbcopper/align/PairwiseAlignment.h>
#include <pbcopper/utility/MinMax.h>
#include <pbcopper/utility/SequenceUtils.h>
namespace PacBio {
namespace Align {
namespace {
class IupacAware;
class Standard;
inline bool IsIupacPartialMatch(char iupacCode, char b)
{
assert(iupacCode != b);
switch (iupacCode) {
case 'R':
return (b == 'A' || b == 'G');
case 'Y':
return (b == 'C' || b == 'T');
case 'S':
return (b == 'G' || b == 'C');
case 'W':
return (b == 'A' || b == 'T');
case 'K':
return (b == 'G' || b == 'T');
case 'M':
return (b == 'A' || b == 'C');
default:
return false;
}
}
template <typename C>
float MatchScore(char t, char q, float matchScore, float mismatchScore, float partialMatchScore);
template <>
float MatchScore<Standard>(char t, char q, float matchScore, float mismatchScore, float /*unused*/)
{
return (t == q ? matchScore : mismatchScore);
}
template <>
float MatchScore<IupacAware>(char t, char q, float matchScore, float mismatchScore,
float partialMatchScore)
{
if (t == q) {
return matchScore;
} else if (IsIupacPartialMatch(t, q) || IsIupacPartialMatch(q, t)) {
return partialMatchScore;
} else {
return mismatchScore;
} // NOLINT
}
template <class C>
PairwiseAlignment* AlignAffineGeneric(const std::string& target, const std::string& query,
AffineAlignmentParams params)
{
// Implementation follows the textbook "two-state" affine gap model
// description from Durbin et. al
using boost::numeric::ublas::matrix;
int I = query.length();
int J = target.length();
matrix<float> M(I + 1, J + 1);
matrix<float> GAP(I + 1, J + 1);
// Initialization
M(0, 0) = 0;
GAP(0, 0) = -FLT_MAX;
for (int i = 1; i <= I; ++i) {
M(i, 0) = -FLT_MAX;
GAP(i, 0) = params.GapOpen + (i - 1) * params.GapExtend;
}
for (int j = 1; j <= J; ++j) {
M(0, j) = -FLT_MAX;
GAP(0, j) = params.GapOpen + (j - 1) * params.GapExtend;
}
// Main part of the recursion
for (int i = 1; i <= I; ++i) {
for (int j = 1; j <= J; ++j) {
float matchScore = MatchScore<C>(target[j - 1], query[i - 1], params.MatchScore,
params.MismatchScore, params.PartialMatchScore);
M(i, j) = std::max(M(i - 1, j - 1), GAP(i - 1, j - 1)) + matchScore;
GAP(i, j) =
Utility::Max(M(i, j - 1) + params.GapOpen, GAP(i, j - 1) + params.GapExtend,
M(i - 1, j) + params.GapOpen, GAP(i - 1, j) + params.GapExtend);
}
}
// Perform the traceback
const int MATCH_MATRIX = 1;
const int GAP_MATRIX = 2;
std::string raQuery;
std::string raTarget;
int i = I;
int j = J;
int mat = (M(I, J) >= GAP(I, J) ? MATCH_MATRIX : GAP_MATRIX);
int iPrev;
int jPrev;
int matPrev;
while (i > 0 || j > 0) {
if (mat == MATCH_MATRIX) {
matPrev = (M(i - 1, j - 1) >= GAP(i - 1, j - 1) ? MATCH_MATRIX : GAP_MATRIX);
iPrev = i - 1;
jPrev = j - 1;
raQuery.push_back(query[iPrev]);
raTarget.push_back(target[jPrev]);
} else {
assert(mat == GAP_MATRIX);
float s[4];
s[0] = (j > 0 ? M(i, j - 1) + params.GapOpen : -FLT_MAX);
s[1] = (j > 0 ? GAP(i, j - 1) + params.GapExtend : -FLT_MAX);
s[2] = (i > 0 ? M(i - 1, j) + params.GapOpen : -FLT_MAX);
s[3] = (i > 0 ? GAP(i - 1, j) + params.GapExtend : -FLT_MAX);
int argMax = std::max_element(s, s + 4) - s;
matPrev = ((argMax == 0 || argMax == 2) ? MATCH_MATRIX : GAP_MATRIX);
if (argMax == 0 || argMax == 1) {
iPrev = i;
jPrev = j - 1;
raQuery.push_back('-');
raTarget.push_back(target[jPrev]);
} else {
iPrev = i - 1;
jPrev = j;
raQuery.push_back(query[iPrev]);
raTarget.push_back('-');
}
}
// Go to previous square
i = iPrev;
j = jPrev;
mat = matPrev;
}
assert(raQuery.length() == raTarget.length());
return new PairwiseAlignment(Utility::Reversed(raTarget), Utility::Reversed(raQuery));
}
} // anonymous namespace
AffineAlignmentParams::AffineAlignmentParams(float matchScore, float mismatchScore, float gapOpen,
float gapExtend, float partialMatchScore)
: MatchScore(matchScore)
, MismatchScore(mismatchScore)
, GapOpen(gapOpen)
, GapExtend(gapExtend)
, PartialMatchScore(partialMatchScore)
{
}
AffineAlignmentParams DefaultAffineAlignmentParams() { return {0, -1.0, -1.0, -0.5, 0}; }
AffineAlignmentParams IupacAwareAffineAlignmentParams() { return {0, -1.0, -1.0, -0.5, -0.25}; }
PairwiseAlignment* AlignAffine(const std::string& target, const std::string& query,
AffineAlignmentParams params)
{
return AlignAffineGeneric<Standard>(target, query, params);
}
PairwiseAlignment* AlignAffineIupac(const std::string& target, const std::string& query,
AffineAlignmentParams params)
{
return AlignAffineGeneric<IupacAware>(target, query, params);
}
} // namespace Align
} // namespace PacBio
| 30.8 | 99 | 0.545284 | [
"vector",
"model"
] |
443e4b04e60551a539f23b82fe7aa75ff7f2fd67 | 6,361 | hpp | C++ | include/libp2p/multi/multiaddress.hpp | vvarma/cpp-libp2p | 4953f30bc087de42637640eef929acfd102ef895 | [
"Apache-2.0",
"MIT"
] | 135 | 2020-06-13T08:57:36.000Z | 2022-03-27T05:26:11.000Z | include/libp2p/multi/multiaddress.hpp | igor-egorov/cpp-libp2p | 7c9d83bf0760a5f653d86ddbb00645414c61d4fc | [
"Apache-2.0",
"MIT"
] | 41 | 2020-06-12T15:45:05.000Z | 2022-03-07T23:10:33.000Z | include/libp2p/multi/multiaddress.hpp | igor-egorov/cpp-libp2p | 7c9d83bf0760a5f653d86ddbb00645414c61d4fc | [
"Apache-2.0",
"MIT"
] | 43 | 2020-06-15T10:12:45.000Z | 2022-03-21T03:04:50.000Z | /**
* Copyright Soramitsu Co., Ltd. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0
*/
#ifndef LIBP2P_MULTIADDRESS_HPP
#define LIBP2P_MULTIADDRESS_HPP
#include <functional>
#include <list>
#include <memory>
#include <string>
#include <string_view>
#include <unordered_map>
#include <gsl/span>
#include <boost/optional.hpp>
#include <libp2p/common/types.hpp>
#include <libp2p/multi/multiaddress_protocol_list.hpp>
#include <libp2p/outcome/outcome.hpp>
namespace libp2p::multi {
/**
* Address format, used by Libp2p
*/
class Multiaddress {
private:
using ByteBuffer = common::ByteArray;
using FactoryResult = outcome::result<Multiaddress>;
public:
Multiaddress() = delete;
enum class Error {
INVALID_INPUT = 1, ///< input contains invalid multiaddress
PROTOCOL_NOT_FOUND, ///< given protocol can not be found
INVALID_PROTOCOL_VALUE ///< protocol value can not be casted to T
};
/**
* Construct a multiaddress instance from the string
* @param address - string to be in that multiaddress
* @return pointer to Multiaddress, if creation is successful, error
* otherwise
*/
static FactoryResult create(std::string_view address);
/**
* Construct a multiaddress instance from the bytes
* @param bytes to be in that multiaddress
* @return pointer to Multiaddress, if creation is successful, error
* otherwise
*/
static FactoryResult create(const ByteBuffer &bytes);
/**
* Construct a multiaddress instance from the bytes
* @param bytes to be in that multiaddress
* @return pointer to Multiaddress, if creation is successful, error
* otherwise
*/
static FactoryResult create(gsl::span<const uint8_t> bytes);
/**
* Encapsulate a multiaddress to this one, such that:
* '/ip4/192.168.0.1' after encapsulation with '/udp/138' becomes
* '/ip4/192.168.0.1/udp/138'
* @param address - another address to be encapsulated into this one
*/
void encapsulate(const Multiaddress &address);
/**
* Decapsulate a multiaddress from this one, such that:
* '/ip4/192.168.0.1/udp/138' after decapsulation with '/udp/' becomes
* '/ip4/192.168.0.1'
* @param address - another address to be decapsulated from this one
* @return true, if such address was found and removed, false otherwise
*/
bool decapsulate(const Multiaddress &address);
/**
* @see decapsulate(Multiaddress)
* @param proto - protocol, the last occurrence of which will be
* decapsulated
* @return true, if such protocol was found and removed, false otherwise
*/
bool decapsulate(Protocol::Code proto);
/**
* Split the Multiaddress by the first protocol, such that:
* '/ip4/192.168.0.1/tcp/228' => <'/ip4/192.168.0.1', '/tcp/228'>
* @return pair of addresses; if there's only one protocol in the provided
* address, the second element will be none
*/
std::pair<Multiaddress, boost::optional<Multiaddress>> splitFirst() const;
/**
* @brief Tests if {@param code} exists in this multiaddr.
* @param code protocol to be tested
* @return true if exists, false otherwise
*/
bool hasProtocol(Protocol::Code code) const;
/**
* Get the textual representation of the address inside
* @return stringified address
*/
std::string_view getStringAddress() const;
/**
* Get the byte representation of the address inside
* @return bytes address
*/
const ByteBuffer &getBytesAddress() const;
/**
* Get peer id of this Multiaddress
* @return peer id if exists
*/
boost::optional<std::string> getPeerId() const;
/**
* Get all values, which are under that protocol in this multiaddress
* @param proto to be searched for
* @return empty vector if no protocols found, or vector with values
* otherwise
*/
std::vector<std::string> getValuesForProtocol(Protocol::Code proto) const;
/**
* Get first value for protocol
* @param proto to be searched for
* @return value (string) if protocol is found, none otherwise
*/
outcome::result<std::string> getFirstValueForProtocol(
Protocol::Code proto) const;
/**
* Get protocols contained in the multiaddress. Repetitions are possible
* @return list of contained protocols
*/
std::list<Protocol> getProtocols() const;
/**
* Get protocols contained in the multiaddress and values assosiated with
* them (usually addresses). Repetitions are possible.
* @return list of pairs with a protocol as the first element and the value
* as the second one
*/
std::vector<std::pair<Protocol, std::string>> getProtocolsWithValues()
const;
bool operator==(const Multiaddress &other) const;
/**
* Lexicographical comparison of string representations of the
* Multiaddresses
*/
bool operator<(const Multiaddress &other) const;
template <typename T>
outcome::result<T> getFirstValueForProtocol(
Protocol::Code protocol,
std::function<T(const std::string &)> caster) const {
OUTCOME_TRY(val, getFirstValueForProtocol(protocol));
try {
return caster(val);
} catch (...) {
return Error::INVALID_PROTOCOL_VALUE;
}
}
private:
/**
* Construct a multiaddress instance from both address and bytes
* @param address to be in the multiaddress
* @param bytes to be in the multiaddress
*/
Multiaddress(std::string &&address, ByteBuffer &&bytes);
/**
* Decapsulate a given string, which represents a protocol, from the address
* @return true, if it was found and removed, false otherwise
*/
bool decapsulateStringFromAddress(std::string_view proto,
const ByteBuffer &bytes);
std::string stringified_address_;
ByteBuffer bytes_;
boost::optional<std::string> peer_id_;
};
} // namespace libp2p::multi
namespace std {
template <>
struct hash<libp2p::multi::Multiaddress> {
size_t operator()(const libp2p::multi::Multiaddress &x) const;
};
} // namespace std
OUTCOME_HPP_DECLARE_ERROR(libp2p::multi, Multiaddress::Error)
#endif // LIBP2P_MULTIADDRESS_HPP
| 30.729469 | 80 | 0.664361 | [
"vector"
] |
4442db1aeb08ffa65a166f4d80d1ae25c878dd00 | 4,590 | cpp | C++ | ds3/3_ds_gui/widget/router/router_transfer_widget.cpp | demonsaw/Code | b036d455e9e034d7fd178e63d5e992242d62989a | [
"MIT"
] | 132 | 2017-03-22T03:46:38.000Z | 2022-03-08T15:08:16.000Z | ds3/3_ds_gui/widget/router/router_transfer_widget.cpp | demonsaw/Code | b036d455e9e034d7fd178e63d5e992242d62989a | [
"MIT"
] | 4 | 2017-04-06T17:46:10.000Z | 2018-08-08T18:27:59.000Z | ds3/3_ds_gui/widget/router/router_transfer_widget.cpp | demonsaw/Code | b036d455e9e034d7fd178e63d5e992242d62989a | [
"MIT"
] | 30 | 2017-03-26T22:38:17.000Z | 2021-11-21T20:50:17.000Z | //
// The MIT License(MIT)
//
// Copyright(c) 2014 Demonsaw LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
#include <QAction>
#include <QHeaderView>
#include <QHBoxLayout>
#include <QLabel>
#include <QMenu>
#include <QPoint>
#include <QTimer>
#include <QToolBar>
#include "component/callback/callback_action.h"
#include "component/callback/callback_type.h"
#include "delegate/row_checkbox_delegate.h"
#include "delegate/endpoint_status_delegate.h"
#include "entity/entity.h"
#include "entity/entity_table_view.h"
#include "font/font_awesome.h"
#include "model/router/router_transfer_model.h"
#include "widget/router/router_transfer_widget.h"
namespace eja
{
// Constructor
router_transfer_widget::router_transfer_widget(const entity::ptr entity, QWidget* parent /*= 0*/) : entity_widget(entity, "Transfer Routers", fa::exchange, callback_type::transfer, parent)
{
assert(thread_info::main());
// Action
m_add_action = make_action("Add", fa::plus);
m_remove_action = make_action("Remove", fa::minus);
m_update_action = make_action("Update", fa::bolt);
// Menu
add_button("Add", fa::plus, [&]() { m_table->add(); });
add_button("Remove", fa::minus, [&]() { m_table->remove(); });
add_button("Update", fa::bolt, [&]() { update(); });
add_button("Popout", fa::clone, [&]() { popout(); });
add_button("Close", fa::close, [&]() { close(); });
// Layout
auto hlayout = new QHBoxLayout;
hlayout->setSpacing(0);
hlayout->setMargin(0);
hlayout->addWidget(m_icon);
hlayout->addWidget(m_title);
hlayout->addStretch(1);
hlayout->addWidget(m_toolbar);
m_titlebar = new QWidget(this);
m_titlebar->installEventFilter(this);
m_titlebar->setObjectName("menubar");
m_titlebar->setLayout(hlayout);
setTitleBarWidget(m_titlebar);
// Table
m_table = new entity_table_view(m_entity, this);
m_model = new router_transfer_model(m_entity, { " #", "Name", "Address", "Port" }, { 44, 128, 256, 64 }, this);
init(m_table, m_model);
// Header
const auto hheader = m_table->horizontalHeader();
hheader->setSectionResizeMode(router_transfer_model::column::row, QHeaderView::Fixed);
// Callback
add_callback(callback_action::clear, [&](const entity::ptr entity){ m_model->clear(); });
// Delegate
m_table->setColumnWidth(router_transfer_model::column::row, 44);
m_table->setItemDelegateForColumn(router_transfer_model::column::row, new row_checkbox_delegate(m_table));
m_table->setItemDelegateForColumn(router_transfer_model::column::name, new endpoint_status_delegate(m_table));
// Signal
connect(m_table, &entity_table_view::customContextMenuRequested, this, &router_transfer_widget::show_menu);
connect(m_add_action, &QAction::triggered, [&]() { m_table->add(); });
connect(m_remove_action, &QAction::triggered, [&]() { m_table->remove(); });
connect(m_update_action, &QAction::triggered, [&]() { update(); });
setWidget(m_table);
}
// Utility
void router_transfer_widget::on_update()
{
assert(thread_info::main());
// Spam
auto button = get_button(fa::bolt);
if (button)
{
button->setEnabled(false);
QTimer::singleShot(ui::refresh, [&]() { set_enabled(fa::bolt); });
}
m_table->update();
}
// Menu
void router_transfer_widget::show_menu(const QPoint& pos)
{
assert(thread_info::main());
const auto index = m_table->indexAt(pos);
if (!index.isValid())
return;
QMenu menu(this);
menu.addAction(m_add_action);
menu.addAction(m_remove_action);
menu.addAction(m_update_action);
menu.exec(m_table->viewport()->mapToGlobal(pos));
}
}
| 33.50365 | 189 | 0.720044 | [
"model"
] |
444654876cd9af3b67f0ff7f12799afc3df6f692 | 26,677 | cpp | C++ | oem/ibm/libpldmresponder/file_io_type_dump.cpp | raviteja-b/pldm | 413866955ff9b3dca362d8f9c7a77cd7670f37dc | [
"Apache-2.0"
] | null | null | null | oem/ibm/libpldmresponder/file_io_type_dump.cpp | raviteja-b/pldm | 413866955ff9b3dca362d8f9c7a77cd7670f37dc | [
"Apache-2.0"
] | null | null | null | oem/ibm/libpldmresponder/file_io_type_dump.cpp | raviteja-b/pldm | 413866955ff9b3dca362d8f9c7a77cd7670f37dc | [
"Apache-2.0"
] | null | null | null | #include "file_io_type_dump.hpp"
#include "libpldm/base.h"
#include "oem/ibm/libpldm/file_io.h"
#include "common/utils.hpp"
#include "utils.hpp"
#include "xyz/openbmc_project/Common/error.hpp"
#include <stdint.h>
#include <systemd/sd-bus.h>
#include <unistd.h>
#include <sdbusplus/server.hpp>
#include <xyz/openbmc_project/Dump/NewDump/server.hpp>
#include <exception>
#include <filesystem>
#include <iostream>
#include <type_traits>
using namespace pldm::responder::utils;
using namespace pldm::utils;
namespace pldm
{
namespace responder
{
static constexpr auto dumpEntry = "xyz.openbmc_project.Dump.Entry";
static constexpr auto dumpObjPath = "/xyz/openbmc_project/dump/system";
static constexpr auto systemDumpEntry = "xyz.openbmc_project.Dump.Entry.System";
static constexpr auto resDumpObjPath = "/xyz/openbmc_project/dump/resource";
static constexpr auto resDumpEntryObjPath =
"/xyz/openbmc_project/dump/resource/entry/";
static constexpr auto resDumpEntry = "com.ibm.Dump.Entry.Resource";
static constexpr auto bmcDumpObjPath = "/xyz/openbmc_project/dump/bmc/entry";
static constexpr auto hostbootDumpObjPath =
"/xyz/openbmc_project/dump/hostboot/entry";
static constexpr auto sbeDumpObjPath = "/xyz/openbmc_project/dump/sbe/entry";
static constexpr auto hardwareDumpObjPath =
"/xyz/openbmc_project/dump/hardware/entry";
int DumpHandler::fd = -1;
namespace fs = std::filesystem;
extern SocketWriteStatus socketWriteStatus;
std::string DumpHandler::findDumpObjPath(uint32_t fileHandle)
{
static constexpr auto DUMP_MANAGER_BUSNAME =
"xyz.openbmc_project.Dump.Manager";
static constexpr auto DUMP_MANAGER_PATH = "/xyz/openbmc_project/dump";
static constexpr auto OBJECT_MANAGER_INTERFACE =
"org.freedesktop.DBus.ObjectManager";
auto& bus = pldm::utils::DBusHandler::getBus();
if (dumpType == PLDM_FILE_TYPE_RESOURCE_DUMP_PARMS)
{
resDumpRequestDirPath =
"/var/lib/pldm/resourcedump/" + std::to_string(fileHandle);
}
// Stores the current resource dump entry path
std::string curResDumpEntryPath{};
if (dumpType == PLDM_FILE_TYPE_BMC_DUMP)
{
curResDumpEntryPath =
(std::string)bmcDumpObjPath + "/" + std::to_string(fileHandle);
}
else if (dumpType == PLDM_FILE_TYPE_SBE_DUMP)
{
curResDumpEntryPath =
(std::string)sbeDumpObjPath + "/" + std::to_string(fileHandle);
}
else if (dumpType == PLDM_FILE_TYPE_HOSTBOOT_DUMP)
{
curResDumpEntryPath =
(std::string)hostbootDumpObjPath + "/" + std::to_string(fileHandle);
}
else if (dumpType == PLDM_FILE_TYPE_HARDWARE_DUMP)
{
curResDumpEntryPath =
(std::string)hardwareDumpObjPath + "/" + std::to_string(fileHandle);
}
std::string dumpEntryIntf{};
if ((dumpType == PLDM_FILE_TYPE_RESOURCE_DUMP) ||
(dumpType == PLDM_FILE_TYPE_RESOURCE_DUMP_PARMS))
{
dumpEntryIntf = resDumpEntry;
}
else if (dumpType == PLDM_FILE_TYPE_DUMP)
{
dumpEntryIntf = systemDumpEntry;
}
else
{
return curResDumpEntryPath;
}
dbus::ObjectValueTree objects;
auto method =
bus.new_method_call(DUMP_MANAGER_BUSNAME, DUMP_MANAGER_PATH,
OBJECT_MANAGER_INTERFACE, "GetManagedObjects");
try
{
auto reply = bus.call(method);
reply.read(objects);
}
catch (const std::exception& e)
{
std::cerr
<< "Failure with GetManagedObjects in findDumpObjPath call, ERROR="
<< e.what() << "\n";
pldm::utils::reportError(
"xyz.openbmc_project.bmc.PLDM.findDumpObjPath.GetManagedObjectsFail",
pldm::PelSeverity::WARNING);
return curResDumpEntryPath;
}
for (const auto& object : objects)
{
for (const auto& interface : object.second)
{
if (interface.first != dumpEntryIntf)
{
continue;
}
for (auto& propertyMap : interface.second)
{
if (propertyMap.first == "SourceDumpId")
{
auto dumpIdPtr = std::get_if<uint32_t>(&propertyMap.second);
if (dumpIdPtr != nullptr)
{
auto dumpId = *dumpIdPtr;
if (fileHandle == dumpId)
{
curResDumpEntryPath = object.first.str;
std::cout << "Hit the object path match for"
<< curResDumpEntryPath << std::endl;
return curResDumpEntryPath;
}
}
else
{
std::cerr
<< "Invalid SourceDumpId in curResDumpEntryPath "
<< curResDumpEntryPath
<< " but continuing with next entry for a match..."
<< std::endl;
}
}
}
}
}
return curResDumpEntryPath;
}
int DumpHandler::newFileAvailable(uint64_t length)
{
static constexpr auto dumpInterface = "xyz.openbmc_project.Dump.NewDump";
auto& bus = pldm::utils::DBusHandler::getBus();
std::cout << "newFileAvailable for NewDump" << std::endl;
auto notifyObjPath = dumpObjPath;
if (dumpType == PLDM_FILE_TYPE_RESOURCE_DUMP)
{
// Setting the Notify path for resource dump
notifyObjPath = resDumpObjPath;
}
try
{
auto service =
pldm::utils::DBusHandler().getService(notifyObjPath, dumpInterface);
using namespace sdbusplus::xyz::openbmc_project::Dump::server;
auto method = bus.new_method_call(service.c_str(), notifyObjPath,
dumpInterface, "Notify");
method.append(fileHandle, length);
bus.call(method);
}
catch (const std::exception& e)
{
std::cerr << "failed to make a d-bus call to notify"
" a new dump request using newFileAvailable, ERROR="
<< e.what() << "\n";
pldm::utils::reportError(
"xyz.openbmc_project.bmc.PLDM.newFileAvailable.NewDumpNotifyFail",
pldm::PelSeverity::ERROR);
return PLDM_ERROR;
}
return PLDM_SUCCESS;
}
void DumpHandler::resetOffloadUri()
{
auto path = findDumpObjPath(fileHandle);
if (path.empty())
{
return;
}
std::cout << "DumpHandler::resetOffloadUri path = " << path.c_str()
<< " fileHandle = " << fileHandle << std::endl;
PropertyValue offloadUriValue{""};
DBusMapping dbusMapping{path, dumpEntry, "OffloadUri", "string"};
try
{
pldm::utils::DBusHandler().setDbusProperty(dbusMapping,
offloadUriValue);
}
catch (const std::exception& e)
{
std::cerr << "Failed to set the OffloadUri dbus property, ERROR="
<< e.what() << "\n";
pldm::utils::reportError(
"xyz.openbmc_project.bmc.PLDM.fileAck.DumpEntryOffloadUriSetFail",
pldm::PelSeverity::ERROR);
}
return;
}
std::string DumpHandler::getOffloadUri(uint32_t fileHandle)
{
auto path = findDumpObjPath(fileHandle);
std::cout << "DumpHandler::getOffloadUri path = " << path.c_str()
<< " fileHandle = " << fileHandle << std::endl;
if (path.empty())
{
return {};
}
std::string socketInterface{};
try
{
socketInterface =
pldm::utils::DBusHandler().getDbusProperty<std::string>(
path.c_str(), "OffloadUri", dumpEntry);
std::cout << "socketInterface=" << socketInterface << std::endl;
}
catch (const std::exception& e)
{
std::cerr << "Failed to get the OffloadUri d-bus property, ERROR="
<< e.what() << "\n";
pldm::utils::reportError(
"xyz.openbmc_project.bmc.PLDM.DumpHandler.getOffloadUriFail",
pldm::PelSeverity::ERROR);
}
return socketInterface;
}
int DumpHandler::writeFromMemory(uint32_t, uint32_t length, uint64_t address,
oem_platform::Handler* /*oemPlatformHandler*/)
{
if (DumpHandler::fd == -1)
{
auto socketInterface = getOffloadUri(fileHandle);
int sock = setupUnixSocket(socketInterface);
if (sock < 0)
{
sock = -errno;
close(DumpHandler::fd);
std::cerr
<< "DumpHandler::writeFromMemory: setupUnixSocket() failed"
<< std::endl;
std::remove(socketInterface.c_str());
resetOffloadUri();
return PLDM_ERROR;
}
DumpHandler::fd = sock;
auto rc = transferFileDataToSocket(DumpHandler::fd, length, address);
if (rc < 0)
{
std::cerr
<< "DumpHandler::writeFromMemory: transferFileDataToSocket failed"
<< std::endl;
if (DumpHandler::fd >= 0)
{
close(DumpHandler::fd);
DumpHandler::fd = -1;
}
std::remove(socketInterface.c_str());
resetOffloadUri();
return PLDM_ERROR;
}
return rc < 0 ? PLDM_ERROR : PLDM_SUCCESS;
}
if (socketWriteStatus == Error)
{
std::cerr
<< "DumpHandler::writeFromMemory: Error while writing to Unix socket"
<< std::endl;
if (DumpHandler::fd >= 0)
{
close(DumpHandler::fd);
DumpHandler::fd = -1;
}
auto socketInterface = getOffloadUri(fileHandle);
std::remove(socketInterface.c_str());
resetOffloadUri();
return PLDM_ERROR;
}
else if (socketWriteStatus == InProgress || socketWriteStatus == NotReady)
{
return PLDM_ERROR_NOT_READY;
}
auto rc = transferFileDataToSocket(DumpHandler::fd, length, address);
if (rc < 0)
{
std::cerr
<< "DumpHandler::writeFromMemory: transferFileDataToSocket failed"
<< std::endl;
if (DumpHandler::fd >= 0)
{
close(DumpHandler::fd);
DumpHandler::fd = -1;
}
auto socketInterface = getOffloadUri(fileHandle);
std::remove(socketInterface.c_str());
resetOffloadUri();
return PLDM_ERROR;
}
return rc < 0 ? PLDM_ERROR : PLDM_SUCCESS;
}
int DumpHandler::write(const char* buffer, uint32_t, uint32_t& length,
oem_platform::Handler* /*oemPlatformHandler*/)
{
std::cout << "Enter DumpHandler::write length = " << length
<< " DumpHandler::fd = " << DumpHandler::fd << std::endl;
if (socketWriteStatus == Error)
{
std::cerr << "DumpHandler::write: Error while writing to Unix socket"
<< std::endl;
close(fd);
auto socketInterface = getOffloadUri(fileHandle);
std::remove(socketInterface.c_str());
resetOffloadUri();
return PLDM_ERROR;
}
else if (socketWriteStatus == InProgress)
{
return PLDM_ERROR_NOT_READY;
}
writeToUnixSocket(DumpHandler::fd, buffer, length);
if (socketWriteStatus == Error)
{
std::cerr << "DumpHandler::write: Error while writing to Unix socket"
<< std::endl;
close(fd);
auto socketInterface = getOffloadUri(fileHandle);
std::remove(socketInterface.c_str());
resetOffloadUri();
return PLDM_ERROR;
}
return PLDM_SUCCESS;
}
int DumpHandler::fileAck(uint8_t fileStatus)
{
auto path = findDumpObjPath(fileHandle);
if (dumpType == PLDM_FILE_TYPE_RESOURCE_DUMP_PARMS)
{
if (fileStatus != PLDM_SUCCESS)
{
std::cerr << "Failue in resource dump file ack" << std::endl;
pldm::utils::reportError(
"xyz.openbmc_project.bmc.PLDM.fileAck.ResourceDumpFileAckFail",
PelSeverity::INFORMATIONAL);
PropertyValue value{
"xyz.openbmc_project.Common.Progress.OperationStatus.Failed"};
DBusMapping dbusMapping{path, "xyz.openbmc_project.Common.Progress",
"Status", "string"};
try
{
pldm::utils::DBusHandler().setDbusProperty(dbusMapping, value);
}
catch (const std::exception& e)
{
std::cerr
<< "Failure in setting Progress as OperationStatus.Failed"
"in fileAck, ERROR="
<< e.what() << "\n";
}
}
if (fs::exists(resDumpRequestDirPath))
{
fs::remove_all(resDumpRequestDirPath);
}
return PLDM_SUCCESS;
}
if (!path.empty())
{
if (fileStatus == PLDM_ERROR_FILE_DISCARDED)
{
if (dumpType == PLDM_FILE_TYPE_DUMP ||
dumpType == PLDM_FILE_TYPE_RESOURCE_DUMP)
{
uint32_t val = 0xFFFFFFFF;
PropertyValue value = static_cast<uint32_t>(val);
auto dumpIntf = resDumpEntry;
if (dumpType == PLDM_FILE_TYPE_DUMP)
{
dumpIntf = systemDumpEntry;
}
DBusMapping dbusMapping{path.c_str(), dumpIntf, "SourceDumpId",
"uint32_t"};
try
{
pldm::utils::DBusHandler().setDbusProperty(dbusMapping,
value);
}
catch (const std::exception& e)
{
std::cerr << "Failed to make a d-bus call to DUMP "
"manager to reset source dump id of "
<< path.c_str() << ", with ERROR=" << e.what()
<< "\n";
pldm::utils::reportError(
"xyz.openbmc_project.bmc.PLDM.fileAck.SourceDumpIdResetFail",
pldm::PelSeverity::ERROR);
return PLDM_ERROR;
}
}
auto& bus = pldm::utils::DBusHandler::getBus();
try
{
auto method = bus.new_method_call(
"xyz.openbmc_project.Dump.Manager", path.c_str(),
"xyz.openbmc_project.Object.Delete", "Delete");
bus.call(method);
}
catch (const std::exception& e)
{
std::cerr
<< "Failed to make a d-bus method to delete the dump entry "
<< path.c_str() << ", with ERROR=" << e.what() << "\n";
pldm::utils::reportError(
"xyz.openbmc_project.bmc.PLDM.fileAck.DumpEntryDeleteFail",
pldm::PelSeverity::ERROR);
return PLDM_ERROR;
}
return PLDM_SUCCESS;
}
if (dumpType == PLDM_FILE_TYPE_DUMP ||
dumpType == PLDM_FILE_TYPE_RESOURCE_DUMP)
{
if (socketWriteStatus == InProgress)
{
return PLDM_ERROR_NOT_READY;
}
PropertyValue value{true};
DBusMapping dbusMapping{path, dumpEntry, "Offloaded", "bool"};
try
{
pldm::utils::DBusHandler().setDbusProperty(dbusMapping, value);
}
catch (const std::exception& e)
{
std::cerr
<< "Failed to set the Offloaded dbus property to true, ERROR="
<< e.what() << "\n";
pldm::utils::reportError(
"xyz.openbmc_project.bmc.PLDM.fileAck.DumpEntryOffloadedSetFail",
pldm::PelSeverity::ERROR);
resetOffloadUri();
return PLDM_ERROR;
}
auto socketInterface = getOffloadUri(fileHandle);
if (DumpHandler::fd >= 0)
{
close(DumpHandler::fd);
DumpHandler::fd = -1;
}
std::remove(socketInterface.c_str());
resetOffloadUri();
}
return PLDM_SUCCESS;
}
return PLDM_ERROR;
}
int DumpHandler::readIntoMemory(uint32_t offset, uint32_t& length,
uint64_t address,
oem_platform::Handler* /*oemPlatformHandler*/)
{
auto path = findDumpObjPath(fileHandle);
static constexpr auto dumpFilepathInterface =
"xyz.openbmc_project.Common.FilePath";
if ((dumpType == PLDM_FILE_TYPE_DUMP) ||
(dumpType == PLDM_FILE_TYPE_RESOURCE_DUMP))
{
return PLDM_ERROR_UNSUPPORTED_PLDM_CMD;
}
else if (dumpType != PLDM_FILE_TYPE_RESOURCE_DUMP_PARMS)
{
try
{
auto filePath =
pldm::utils::DBusHandler().getDbusProperty<std::string>(
path.c_str(), "Path", dumpFilepathInterface);
auto rc = transferFileData(fs::path(filePath), true, offset, length,
address);
return rc;
}
catch (const std::exception& e)
{
std::cerr << "Failed to fetch the filepath of the dump entry"
<< std::hex << fileHandle << ", error = " << e.what()
<< "\n";
pldm::utils::reportError(
"xyz.openbmc_project.bmc.PLDM.readIntoMemory.GetFilepathFail",
pldm::PelSeverity::ERROR);
return PLDM_ERROR;
}
}
return transferFileData(resDumpRequestDirPath, true, offset, length,
address);
}
int DumpHandler::read(uint32_t offset, uint32_t& length, Response& response,
oem_platform::Handler* /*oemPlatformHandler*/)
{
auto path = findDumpObjPath(fileHandle);
static constexpr auto dumpFilepathInterface =
"xyz.openbmc_project.Common.FilePath";
if ((dumpType == PLDM_FILE_TYPE_DUMP) ||
(dumpType == PLDM_FILE_TYPE_RESOURCE_DUMP))
{
return PLDM_ERROR_UNSUPPORTED_PLDM_CMD;
}
else if (dumpType != PLDM_FILE_TYPE_RESOURCE_DUMP_PARMS)
{
try
{
auto filePath =
pldm::utils::DBusHandler().getDbusProperty<std::string>(
path.c_str(), "Path", dumpFilepathInterface);
auto rc = readFile(filePath.c_str(), offset, length, response);
return rc;
}
catch (const std::exception& e)
{
std::cerr << "Failed to fetch the filepath of the dump entry"
<< std::hex << fileHandle << ", error = " << e.what()
<< "\n";
pldm::utils::reportError(
"xyz.openbmc_project.bmc.PLDM.read.GetFilepathFail",
pldm::PelSeverity::ERROR);
return PLDM_ERROR;
}
}
return readFile(resDumpRequestDirPath, offset, length, response);
}
int DumpHandler::fileAckWithMetaData(uint8_t /*fileStatus*/,
uint32_t metaDataValue1,
uint32_t metaDataValue2,
uint32_t /*metaDataValue3*/,
uint32_t /*metaDataValue4*/)
{
auto path = findDumpObjPath(fileHandle);
uint8_t statusCode = (uint8_t)metaDataValue2;
if (dumpType == PLDM_FILE_TYPE_RESOURCE_DUMP_PARMS)
{
DBusMapping dbusMapping;
dbusMapping.objectPath =
resDumpEntryObjPath + std::to_string(fileHandle);
dbusMapping.interface = resDumpEntry;
dbusMapping.propertyName = "DumpRequestStatus";
dbusMapping.propertyType = "string";
pldm::utils::PropertyValue value =
"com.ibm.Dump.Entry.Resource.HostResponse.Success";
std::cout << "fileAckWithMetaData with token: " << metaDataValue1
<< " and status: " << metaDataValue2 << std::endl;
if (statusCode == DumpRequestStatus::ResourceSelectorInvalid)
{
value =
"com.ibm.Dump.Entry.Resource.HostResponse.ResourceSelectorInvalid";
}
else if (statusCode == DumpRequestStatus::AcfFileInvalid)
{
value = "com.ibm.Dump.Entry.Resource.HostResponse.AcfFileInvalid";
}
else if (statusCode == DumpRequestStatus::PasswordInvalid)
{
value = "com.ibm.Dump.Entry.Resource.HostResponse.PasswordInvalid";
}
else if (statusCode == DumpRequestStatus::PermissionDenied)
{
value = "com.ibm.Dump.Entry.Resource.HostResponse.PermissionDenied";
}
else if (statusCode == DumpRequestStatus::Success)
{
// Will be enabled after Dump Manager code for requestToken gets
// merged
/*DBusMapping dbusMapping;
dbusMapping.objectPath =
"/xyz/openbmc_project/dump/resource/entry/" +
std::to_string(fileHandle); dbusMapping.interface =
"com.ibm.Dump.Entry.Resource"; dbusMapping.propertyName =
"requestToken"; dbusMapping.propertyType = "uint32_t";
pldm::utils::PropertyValue value = metaDataValue1;
try
{
pldm::utils::DBusHandler().setDbusProperty(dbusMapping,
value);
}
catch (const std::exception& e)
{
std::cerr << "failed to set token for resource dump, ERROR="
<< e.what() << "\n";
return PLDM_ERROR;
}*/
}
try
{
pldm::utils::DBusHandler().setDbusProperty(dbusMapping, value);
}
catch (const std::exception& e)
{
std::cerr
<< "failed to set DumpRequestStatus property for resource dump entry, "
"ERROR="
<< e.what() << "\n";
return PLDM_ERROR;
}
if (statusCode != DumpRequestStatus::Success)
{
std::cerr << "Failue in resource dump file ack with metadata"
<< std::endl;
pldm::utils::reportError(
"xyz.openbmc_project.bmc.PLDM.fileAck.ResourceDumpFileAckWithMetaDataFail",
pldm::PelSeverity::INFORMATIONAL);
PropertyValue value{
"xyz.openbmc_project.Common.Progress.OperationStatus.Failed"};
DBusMapping dbusMapping{
resDumpEntryObjPath + std::to_string(fileHandle),
"xyz.openbmc_project.Common.Progress", "Status", "string"};
try
{
pldm::utils::DBusHandler().setDbusProperty(dbusMapping, value);
}
catch (const std::exception& e)
{
std::cerr
<< "Failure in setting Progress as OperationStatus.Failed"
"in fileAckWithMetaData, ERROR="
<< e.what() << "\n";
}
}
if (fs::exists(resDumpRequestDirPath))
{
fs::remove_all(resDumpRequestDirPath);
}
return PLDM_SUCCESS;
}
if (DumpHandler::fd >= 0 && !path.empty())
{
if (dumpType == PLDM_FILE_TYPE_DUMP ||
dumpType == PLDM_FILE_TYPE_RESOURCE_DUMP)
{
PropertyValue value{true};
DBusMapping dbusMapping{path, dumpEntry, "Offloaded", "bool"};
try
{
pldm::utils::DBusHandler().setDbusProperty(dbusMapping, value);
}
catch (const std::exception& e)
{
std::cerr
<< "Failed to set the Offloaded dbus property to true, ERROR="
<< e.what() << "\n";
pldm::utils::reportError(
"xyz.openbmc_project.bmc.PLDM.fileAckWithMetaData.DumpEntryOffloadedSetFail",
pldm::PelSeverity::ERROR);
return PLDM_ERROR;
}
close(DumpHandler::fd);
auto socketInterface = getOffloadUri(fileHandle);
std::remove(socketInterface.c_str());
DumpHandler::fd = -1;
resetOffloadUri();
}
return PLDM_SUCCESS;
}
return PLDM_ERROR;
}
int DumpHandler::newFileAvailableWithMetaData(uint64_t length,
uint32_t metaDataValue1,
uint32_t /*metaDataValue2*/,
uint32_t /*metaDataValue3*/,
uint32_t /*metaDataValue4*/)
{
static constexpr auto dumpInterface = "xyz.openbmc_project.Dump.NewDump";
auto& bus = pldm::utils::DBusHandler::getBus();
std::cout << "newFileAvailableWithMetaData for NewDump with token :"
<< metaDataValue1 << std::endl;
auto notifyObjPath = dumpObjPath;
if (dumpType == PLDM_FILE_TYPE_RESOURCE_DUMP)
{
// Setting the Notify path for resource dump
notifyObjPath = resDumpObjPath;
}
try
{
auto service =
pldm::utils::DBusHandler().getService(notifyObjPath, dumpInterface);
using namespace sdbusplus::xyz::openbmc_project::Dump::server;
auto method = bus.new_method_call(
service.c_str(), notifyObjPath, dumpInterface,
"Notify"); // need to change the method to "NotifyWithToken"
// once dump manager changes are merged
method.append(fileHandle, length); // need to append metaDataValue1 once
// dump manager changes are merged
bus.call(method);
}
catch (const std::exception& e)
{
std::cerr
<< "failed to make a d-bus call to notify"
" a new dump request using newFileAvailableWithMetaData, ERROR="
<< e.what() << "\n";
pldm::utils::reportError(
"xyz.openbmc_project.bmc.PLDM.newFileAvailableWithMetaData.NewDumpNotifyFail",
pldm::PelSeverity::ERROR);
return PLDM_ERROR;
}
return PLDM_SUCCESS;
}
} // namespace responder
} // namespace pldm
| 34.555699 | 97 | 0.547363 | [
"object"
] |
444694c9c81ef628d715643a58d9a1204146a817 | 1,955 | cpp | C++ | DrawCallRecorderPluginSource/projects/VisualStudio2015/Renderer.cpp | SquallLiu99/DrawCallRecorder | b93a3f4e570a4b42e7bd8f32fbe43e3f7e6976b7 | [
"MIT"
] | null | null | null | DrawCallRecorderPluginSource/projects/VisualStudio2015/Renderer.cpp | SquallLiu99/DrawCallRecorder | b93a3f4e570a4b42e7bd8f32fbe43e3f7e6976b7 | [
"MIT"
] | null | null | null | DrawCallRecorderPluginSource/projects/VisualStudio2015/Renderer.cpp | SquallLiu99/DrawCallRecorder | b93a3f4e570a4b42e7bd8f32fbe43e3f7e6976b7 | [
"MIT"
] | null | null | null | #include "Renderer.h"
#include "Utility.h"
void Renderer::SetSharedMesh(int _meshId)
{
sharedMesh = _meshId;
}
int Renderer::GetSharedMesh()
{
return sharedMesh;
}
void Renderer::AddMaterial(int _matId)
{
sharedMaterials.push_back(_matId);
}
vector<int>& Renderer::GetSharedMaterials()
{
return sharedMaterials;
}
void Renderer::SetInstanceId(int _id)
{
instanceId = _id;
}
int Renderer::GetInstanceId()
{
return instanceId;
}
void Renderer::SetVisible(bool _isVisible)
{
isVisible = _isVisible;
}
bool Renderer::GetVisible()
{
return isVisible;
}
void Renderer::SetObjectConstant(XMMATRIX _objToWorld, XMFLOAT4 _LightmapST)
{
objectConstantCPU._ObjectToWorld = _objToWorld;
objectConstantCPU._LightmapST = _LightmapST;
isDirty = true;
}
void Renderer::CreateObjectConstant(ID3D11Device * _device)
{
objectConstantGPU = make_shared<UploadBuffer>();
HRESULT hr = objectConstantGPU->CreateConstantBuffer(_device, sizeof(ObjectConstant));
if (FAILED(hr))
{
objectConstantGPU = nullptr;
LOGMESSAGE(L"Object Constant Error");
}
}
ID3D11Buffer * Renderer::GetObjectConstant()
{
if (objectConstantGPU == nullptr)
{
return nullptr;
}
return objectConstantGPU->Get();
}
void Renderer::UpdateObjectConstant(ID3D11DeviceContext *_context)
{
if (!isDirty)
{
return;
}
if (objectConstantGPU == nullptr)
{
return;
}
objectConstantGPU->UploadConstantBuffer(_context, &objectConstantCPU);
isDirty = false;
}
void Renderer::AddLightmap(ID3D11ShaderResourceView * _lightmap, ID3D11ShaderResourceView * _shadowMask)
{
lightmapSrvGroup = new ID3D11ShaderResourceView*[2];
lightmapSrvGroup[0] = _lightmap;
lightmapSrvGroup[1] = _shadowMask;
}
ID3D11ShaderResourceView ** Renderer::GetLightmapSrvGroup()
{
return lightmapSrvGroup;
}
void Renderer::Release()
{
sharedMaterials.clear();
objectConstantGPU.reset();
if (lightmapSrvGroup != nullptr)
{
delete[] lightmapSrvGroup;
lightmapSrvGroup = nullptr;
}
}
| 17.455357 | 104 | 0.756522 | [
"object",
"vector"
] |
444ea7951a357d4da0866810035db53d8731a1bf | 24,607 | cpp | C++ | sources/Framework/Tools/LightmapGenerator/spLightmapGeneratorStructs.cpp | rontrek/softpixel | 73a13a67e044c93f5c3da9066eedbaf3805d6807 | [
"Zlib"
] | 14 | 2015-08-16T21:05:20.000Z | 2019-08-21T17:22:01.000Z | sources/Framework/Tools/LightmapGenerator/spLightmapGeneratorStructs.cpp | rontrek/softpixel | 73a13a67e044c93f5c3da9066eedbaf3805d6807 | [
"Zlib"
] | null | null | null | sources/Framework/Tools/LightmapGenerator/spLightmapGeneratorStructs.cpp | rontrek/softpixel | 73a13a67e044c93f5c3da9066eedbaf3805d6807 | [
"Zlib"
] | 3 | 2016-10-31T06:08:44.000Z | 2019-08-02T16:12:33.000Z | /*
* Lightmap generator structures file
*
* This file is part of the "SoftPixel Engine" (Copyright (c) 2008 by Lukas Hermanns)
* See "SoftPixelEngine.hpp" for license information.
*/
#include "Framework/Tools/LightmapGenerator/spLightmapGeneratorStructs.hpp"
#ifdef SP_COMPILE_WITH_LIGHTMAPGENERATOR
#include "Framework/Tools/LightmapGenerator/spLightmapGenerator.hpp"
#include "Base/spMathCollisionLibrary.hpp"
#include "Base/spMathRasterizer.hpp"
#include "Base/spSharedObjects.hpp"
#include "Platform/spSoftPixelDeviceOS.hpp"
#include "SceneGraph/spSceneManager.hpp"
#include <boost/foreach.hpp>
namespace sp
{
extern video::RenderSystem* GlbRenderSys;
extern scene::SceneGraph* GlbSceneGraph;
namespace tool
{
namespace LightmapGen
{
/*
* SVertex structure
*/
SVertex::SVertex() :
Surface (0),
Index (0)
{
}
SVertex::SVertex(const SModel* Model, const u32 VertexSurface, const u32 VertexIndex) :
Surface (VertexSurface ),
Index (VertexIndex )
{
video::MeshBuffer* Surface = Model->Mesh->getMeshBuffer(VertexSurface);
Position = Model->Matrix * Surface->getVertexCoord(Index);
Normal = Model->NormalMatrix * Surface->getVertexNormal(Index);
Color = Surface->getVertexColor(Index);
Normal.normalize();
for (u32 i = 0; i < MAX_COUNT_OF_TEXTURES && i < Surface->getTextureCount(); ++i)
TexCoord[i] = Surface->getVertexTexCoord(Index, i);
}
SVertex::~SVertex()
{
}
bool SVertex::adjacency(const STriangle &OpTriangle) const
{
return
Position.equal(OpTriangle.Vertices[0].Position) ||
Position.equal(OpTriangle.Vertices[1].Position) ||
Position.equal(OpTriangle.Vertices[2].Position);
}
void SVertex::scaleProj(const dim::size2df &Scale)
{
LMapCoord.X = static_cast<s32>(Scale.Width * LMapCoord.X);
LMapCoord.Y = static_cast<s32>(Scale.Height * LMapCoord.Y);
}
dim::point2df SVertex::getMapCoord(const dim::size2di &MaxLightmapSize) const
{
return dim::point2df(
static_cast<f32>(LMapCoord.X) / MaxLightmapSize.Width,
static_cast<f32>(LMapCoord.Y) / MaxLightmapSize.Height
);
}
dim::vector3df SVertex::getVectorColor(const video::color &Color)
{
return dim::vector3df(Color.Red, Color.Green, Color.Blue) / 255;
}
/*
* STriangle structure
*/
STriangle::STriangle() :
Surface (0),
Index (0),
Face (0)
{
}
STriangle::STriangle(
const SModel* Model, u32 TriangleSurface, u32 TriangleIndex, u32 DefIndices[3]) :
Surface (TriangleSurface),
Index (TriangleIndex ),
Face (0 )
{
for (s32 i = 0; i < 3; ++i)
Vertices[i] = SVertex(Model, TriangleSurface, DefIndices[i]);
Plane = dim::plane3df(Vertices[0].Position, Vertices[1].Position, Vertices[2].Position);
}
STriangle::~STriangle()
{
}
bool STriangle::adjacency(const STriangle &OpTriangle) const
{
if (Surface != OpTriangle.Surface)
return false;
return
Vertices[0].adjacency(OpTriangle) ||
Vertices[1].adjacency(OpTriangle) ||
Vertices[2].adjacency(OpTriangle);
}
f32 STriangle::getDistance(const dim::vector3df &Point) const
{
return math::getDistance(
math::CollisionLibrary::getClosestPoint(
dim::triangle3df(Vertices[0].Position, Vertices[1].Position, Vertices[2].Position), Point
),
Point
);
}
dim::point2df STriangle::getProjection(
const dim::vector3df &Point, const dim::vector3df &Normal, const f32 Density)
{
const dim::vector3df AbsNormal(Normal.getAbs());
if (AbsNormal.X >= AbsNormal.Y && AbsNormal.X >= AbsNormal.Z)
return dim::point2df(Point.Z, -Point.Y) * Density;
else if (AbsNormal.Y >= AbsNormal.X && AbsNormal.Y >= AbsNormal.Z)
return dim::point2df(Point.X, -Point.Z) * Density;
return dim::point2df(Point.X, -Point.Y) * Density;
}
//!TODO! -> replace this with a technique using barycentric coordinates!!!
void STriangle::computeInterpolation(
const scene::SIntersectionContact &Contact, u32 Indices[3], const u8 Layer,
dim::point2df &TexCoord, dim::vector3df &Color, f32 &Alpha)
{
// Get triangle construction
if (!Contact.Face)
return;
const dim::triangle3df Triangle(Contact.Triangle);
scene::Mesh* Mesh = Contact.Face->Mesh;
// Temporary variables
const dim::vector3df u(Triangle.PointB - Triangle.PointA);
const dim::vector3df v(Triangle.PointC - Triangle.PointA);
const f32 lenu = u.getLength();
const f32 lenv = v.getLength();
// Get the texture coordinates & vertex colors
video::MeshBuffer* Surface = Mesh->getMeshBuffer(Mesh->getMeshBufferCount() - 1);
const dim::point2df TexCoordA(Surface->getVertexTexCoord(Indices[0], Layer));
const dim::point2df TexCoordB(Surface->getVertexTexCoord(Indices[1], Layer));
const dim::point2df TexCoordC(Surface->getVertexTexCoord(Indices[2], Layer));
const video::color RealColorA(Surface->getVertexColor(Indices[0]));
const video::color RealColorB(Surface->getVertexColor(Indices[1]));
const video::color RealColorC(Surface->getVertexColor(Indices[2]));
const dim::vector3df ColorA(SVertex::getVectorColor(RealColorA));
const dim::vector3df ColorB(SVertex::getVectorColor(RealColorB));
const dim::vector3df ColorC(SVertex::getVectorColor(RealColorC));
const f32 AlphaA = static_cast<f32>(RealColorA.Alpha) / 255;
const f32 AlphaB = static_cast<f32>(RealColorB.Alpha) / 255;
const f32 AlphaC = static_cast<f32>(RealColorC.Alpha) / 255;
// Compute the first coordinates
dim::vector3df pa, pb;
math::CollisionLibrary::getLineLineIntersection(
dim::line3df(Triangle.PointA, Triangle.PointB), dim::line3df(Contact.Point, Contact.Point - v), pa
);
math::CollisionLibrary::getLineLineIntersection(
dim::line3df(Triangle.PointA, Triangle.PointC), dim::line3df(Contact.Point, Contact.Point - u), pb
);
const dim::point2df map(math::getDistance(Contact.Point, pb), math::getDistance(Contact.Point, pa));
// Get the texture coordinate
TexCoord = TexCoordA + (TexCoordB - TexCoordA ) * map.X / lenu + (TexCoordC - TexCoordA ) * map.Y / lenv;
Color = ColorA + (ColorB - ColorA ) * map.X / lenu + (ColorC - ColorA ) * map.Y / lenv;
Alpha = AlphaA + (AlphaB - AlphaA ) * map.X / lenu + (AlphaC - AlphaA ) * map.Y / lenv;
}
/*
* SFace structure
*/
SFace::SFace(SAxisData* FaceAxis) :
Density (0.1f ),
Surface (0 ),
Lightmap (0 ),
RootLightmap(0 ),
Axis (FaceAxis )
{
}
SFace::~SFace()
{
}
void SFace::computeDensityAverage(f32 DefaultDensity)
{
if (!Triangles.empty())
{
Density = 0.0f;
foreach (const STriangle &Tri, Triangles)
Density += (Axis->Model->TrianglesDensity[Tri.Surface])[Tri.Index];
if (math::equal(Density, 0.0f))
Density = DefaultDensity;
else
Density /= Triangles.size();
}
}
void SFace::updateVertexProjection(const dim::size2di &MaxLightmapSize)
{
dim::point2di TexCoord;
dim::point2di Min = 999999;
dim::point2di Max = -999999;
// Compute the vertices' lightmap-texture-coordinates and the faces' lightmap space's bounding box
foreach (STriangle &Tri, Triangles)
{
for (s32 i = 0; i < 3; ++i)
{
TexCoord = (STriangle::getProjection(Tri.Vertices[i].Position, Tri.Plane.Normal, Density) + 0.5).cast<s32>();
if (TexCoord.X < Min.X) Min.X = TexCoord.X;
if (TexCoord.Y < Min.Y) Min.Y = TexCoord.Y;
if (TexCoord.X > Max.X) Max.X = TexCoord.X;
if (TexCoord.Y > Max.Y) Max.Y = TexCoord.Y;
Tri.Vertices[i].LMapCoord = TexCoord;
}
}
// Fit the lightmap-texture-coordinates to the bounding box
foreach (STriangle &Tri, Triangles)
{
Tri.Vertices[0].LMapCoord -= Min;
Tri.Vertices[1].LMapCoord -= Min;
Tri.Vertices[2].LMapCoord -= Min;
}
Size.Width = Max.X - Min.X;
Size.Height = Max.Y - Min.Y;
// Resize the face if to big for lightmap
if (Size.Width > MaxLightmapSize.Width - 2 || Size.Height > MaxLightmapSize.Height - 2)
resizeVertexProjection(Size.getScaledSize(MaxLightmapSize - 2));
}
void SFace::resizeVertexProjection(const dim::size2di &NewSize)
{
const dim::size2df Scale(
static_cast<f32>(NewSize.Width) / Size.Width,
static_cast<f32>(NewSize.Height) / Size.Height
);
foreach (STriangle &Tri, Triangles)
{
Tri.Vertices[0].scaleProj(Scale);
Tri.Vertices[1].scaleProj(Scale);
Tri.Vertices[2].scaleProj(Scale);
}
Size = NewSize;
}
// !INCOMPLETE AND SLOW!
bool SFace::adjacency(const SFace &OpFace) const
{
foreach (const STriangle &TriA, Triangles)
{
foreach (const STriangle &TriB, OpFace.Triangles)
{
if (TriA.adjacency(TriB))
return true;
}
}
return false;
}
void SFace::build(scene::Mesh* Mesh, const dim::size2di &MaxLightmapSize)
{
u32 i, j, c = 0;
u32 VertexIndex;
scene::Mesh* SourceMesh = Axis->Model->Mesh;
video::MeshBuffer* OldSurface = SourceMesh->getMeshBuffer(Surface);
const u32 TextureCount = math::Min(
static_cast<u32>(OldSurface->getVertexFormat()->getTexCoords().size() - 1),
OldSurface->getTextureCount()
);
// Create the face with its vertices & triangles
video::MeshBuffer* NewSurface = Mesh->createMeshBuffer(
OldSurface->getVertexFormat(), OldSurface->getIndexFormat()->getDataType()
);
foreach (STriangle &Tri, Triangles)
{
for (i = 0; i < 3; ++i)
{
VertexIndex = NewSurface->addVertex(
Tri.Vertices[i].Position,
Tri.Vertices[i].Normal,
Tri.Vertices[i].getMapCoord(MaxLightmapSize),
Tri.Vertices[i].Color
);
for (j = 0; j < TextureCount; ++j)
NewSurface->setVertexTexCoord(VertexIndex, Tri.Vertices[i].TexCoord[j], j);
}
NewSurface->addTriangle(c, c + 1, c + 2);
c += 3;
}
// Add the original textures
for (i = 0; i < TextureCount; ++i)
{
NewSurface->addTexture(OldSurface->getTexture(i));
video::TextureLayer* NewTexLayer = NewSurface->getTextureLayer(i);
video::TextureLayer* OldTexLayer = OldSurface->getTextureLayer(i);
if (NewTexLayer && OldTexLayer)
NewTexLayer->setTexture(OldTexLayer->getTexture());
}
// Add the lightmap texture
NewSurface->addTexture(RootLightmap->Texture);
}
/*
* SAxisData structure
*/
SAxisData::SAxisData() :
Model(0)
{
}
SAxisData::~SAxisData()
{
foreach (SFace &Face, Faces)
MemoryManager::deleteMemory(Face.Lightmap);
}
// !THE NEXT TWO FUNCTIONS (createFaces & optimizeFaces) ARE NOT OPTIMIZED AND VERY SLOW!
void SAxisData::createFaces()
{
// Temporary variables
bool FoundList;
std::list<STriangle>::iterator ita, itb;
std::list<SFace>::iterator itFace;
// Create the faces and insert the triangles
for (ita = Triangles.begin(); ita != Triangles.end() && LightmapGenerator::processRunning(); ++ita)
{
FoundList = false;
// Loop for each face and check if the current triangle is adjacency to the face's triangle list
for (itFace = Faces.begin(); itFace != Faces.end() && !FoundList; ++itFace)
{
for (itb = itFace->Triangles.begin(); itb != itFace->Triangles.end(); ++itb)
{
// If adjacency add the current triangle (ita) to the face's triangle list
if (ita->adjacency(*itb))
{
itFace->Triangles.push_back(*ita);
FoundList = true;
break;
}
}
}
// If the triangle was not adjacency to any of the faces' triangle list create a new face
if (!FoundList)
{
SFace NewFace(this);
NewFace.Triangles.push_back(*ita);
Faces.push_back(NewFace);
}
}
}
void SAxisData::optimizeFaces()
{
// Temporary variables
std::list<SFace>::iterator ita, itb;
std::list<STriangle>::iterator itTri;
// Summarize the faces as far as possible
for (ita = Faces.begin(); ita != Faces.end(); ++ita)
{
for (itb = Faces.begin(); itb != Faces.end();)
{
if (ita != itb && ita->adjacency(*itb))
{
// Add the triangle to the first list
for (itTri = itb->Triangles.begin(); itTri != itb->Triangles.end(); ++itTri)
ita->Triangles.push_back(*itTri);
// Delete the old list
itb = Faces.erase(itb);
}
else
++itb;
}
}
}
void SAxisData::completeFaces(const dim::size2di &MaxLightmapSize, f32 DefaultDensity)
{
// Complete each face in the axis (average vertex projection)
foreach (SFace &Face, Faces)
{
Face.computeDensityAverage(DefaultDensity);
Face.updateVertexProjection(MaxLightmapSize);
if (!Face.Triangles.empty())
Face.Surface = Face.Triangles.begin()->Surface;
// Complete the triangles' face connection
foreach (STriangle &Tri, Face.Triangles)
Tri.Face = &Face;
}
}
/*
* SModel structure
*/
SModel::SModel(
scene::Mesh* ObjMesh, bool DefStayAlone, const std::vector< std::vector<f32> > &InitTrianglesDensity) :
Mesh (ObjMesh ),
DefaultDensity (0.1f ),
Matrix (Mesh->getTransformMatrix(true) ),
MatrixInv (Matrix.getInverse() ),
NormalMatrix (Matrix.getRotationMatrix() ),
StayAlone (DefStayAlone ),
TrianglesDensity(InitTrianglesDensity )
{
for (s32 i = 0; i < 6; ++i)
Axles[i].Model = this;
Triangles.resize(Mesh->getMeshBufferCount());
for (u32 s = 0; s < Mesh->getMeshBufferCount(); ++s)
Triangles[s].resize(Mesh->getMeshBuffer(s)->getTriangleCount());
}
SModel::~SModel()
{
}
void SModel::partitionMesh(const dim::size2di &MaxLightmapSize, f32 DefaultDensity)
{
createAxles();
for (s32 i = 0; i < 6 && LightmapGenerator::processRunning(); ++i)
{
Axles[i].createFaces();
Axles[i].optimizeFaces();
Axles[i].completeFaces(MaxLightmapSize, DefaultDensity);
linkAxisTriangles(i);
}
}
void SModel::createAxles()
{
u32 Indices[3] = { 0 };
STriangle CurTriangle;
video::MeshBuffer* Surface = 0;
dim::EAxisTypes AxisType;
for (u32 s = 0, i; s < Mesh->getMeshBufferCount(); ++s)
{
Surface = Mesh->getMeshBuffer(s);
for (i = 0; i < Surface->getTriangleCount(); ++i)
{
Surface->getTriangleIndices(i, Indices);
CurTriangle = STriangle(this, s, i, Indices);
AxisType = CurTriangle.Plane.Normal.getDominantAxis();
Axles[AxisType].Triangles.push_back(CurTriangle);
}
}
}
void SModel::linkAxisTriangles(const s32 Axis)
{
foreach (SFace &Face, Axles[Axis].Faces)
{
foreach (STriangle &Tri, Face.Triangles)
(Triangles[Tri.Surface])[Tri.Index] = &Tri;
}
}
void SModel::buildFaces(scene::Mesh* Mesh, const dim::size2di &MaxLightmapSize)
{
for (s32 i = 0; i < 6; ++i)
{
foreach (SFace &Face, Axles[i].Faces)
Face.build(Mesh, MaxLightmapSize);
}
}
/*
* SLightmapTexel strucuture
*/
SLightmapTexel::SLightmapTexel() :
Color (0),
OrigColor (0),
Face (0)
{
}
SLightmapTexel::~SLightmapTexel()
{
}
/*
* SLightmapTexelLoc strucuture
*/
SLightmapTexelLoc::SLightmapTexelLoc()
{
}
SLightmapTexelLoc::~SLightmapTexelLoc()
{
}
/*
* SLightmap strucutre
*/
SLightmap::SLightmap(const dim::size2di &ImageSize, bool UseTexelBuffer, bool UseTexelLocBuffer) :
Size (ImageSize ),
TexelBuffer (0 ),
TexelLocBuffer (0 ),
Texture (0 ),
RectNode (0 )
{
if (UseTexelBuffer)
TexelBuffer = MemoryManager::createBuffer<SLightmapTexel>(Size.getArea(), "SLightmap::TexelBuffer");
if (UseTexelLocBuffer)
TexelLocBuffer = MemoryManager::createBuffer<SLightmapTexelLoc>(Size.getArea(), "SLightmap::TexelLocBuffer");
}
SLightmap::~SLightmap()
{
delete [] TexelBuffer;
delete [] TexelLocBuffer;
}
video::Texture* SLightmap::createTexture(const video::color &AmbientColor)
{
if (!TexelBuffer)
return 0;
// Create texture if not already done
if (!Texture)
{
Texture = GlbRenderSys->createTexture(Size, video::PIXELFORMAT_RGB);
Texture->setFilename("Lightmap");
}
else
Texture->setSize(Size);
// Create temporary image buffer
const s32 FormatSize = Texture->getImageBuffer()->getFormatSize();
const s32 ImageBufferSize = Size.Width * Size.Height * FormatSize;
u8* ImageBuffer = MemoryManager::createBuffer<u8>(
ImageBufferSize, "SLightmap -> ImageBuffer"
);
const s32 AmbColor[3] = { AmbientColor.Red, AmbientColor.Green, AmbientColor.Blue };
for (s32 i = 0, j = 0; i < ImageBufferSize; i += FormatSize, ++j)
{
ImageBuffer[i + 0] = math::MinMax(AmbColor[0] + TexelBuffer[j].Color.Red , 0, 255);
ImageBuffer[i + 1] = math::MinMax(AmbColor[1] + TexelBuffer[j].Color.Green, 0, 255);
ImageBuffer[i + 2] = math::MinMax(AmbColor[2] + TexelBuffer[j].Color.Blue , 0, 255);
if (FormatSize == 4)
ImageBuffer[i + 3] = 255;
}
// Update texture's image buffer
Texture->setupImageBuffer(ImageBuffer);
// Delete temporary image buffer
MemoryManager::deleteBuffer(ImageBuffer);
return Texture;
}
void SLightmap::copyImageBuffers()
{
if (TexelBuffer)
{
for (s32 i = 0, n = Size.Width * Size.Height; i < n; ++i)
TexelBuffer[i].OrigColor = TexelBuffer[i].Color;
}
}
void SLightmap::reduceBleeding()
{
if (!TexelBuffer)
return;
s32 x, y;
SLightmapTexel* Texel = TexelBuffer;
for (y = 0; y < Size.Height; ++y)
{
for (x = 0; x < Size.Width; ++x, ++Texel)
{
if (!Texel->Face)
Texel->Color = video::color(getAverageColor(x, y), false);
}
}
}
dim::point2df SLightmap::getTexCoord(const dim::point2di &RealPos) const
{
return dim::point2df(
static_cast<f32>(RealPos.X) / Size.Width,
static_cast<f32>(RealPos.Y) / Size.Height
);
}
dim::vector3df SLightmap::getAverageColor(s32 X, s32 Y) const
{
s32 c = 0;
dim::vector3df Color;
getAverageColorPart(X - 1, Y - 1, Color, c);
getAverageColorPart(X , Y - 1, Color, c);
getAverageColorPart(X + 1, Y - 1, Color, c);
getAverageColorPart(X - 1, Y , Color, c);
getAverageColorPart(X + 1, Y , Color, c);
getAverageColorPart(X - 1, Y + 1, Color, c);
getAverageColorPart(X , Y + 1, Color, c);
getAverageColorPart(X + 1, Y + 1, Color, c);
return c ? Color / static_cast<f32>(c) : 0.0f;
}
void SLightmap::getAverageColorPart(s32 X, s32 Y, dim::vector3df &Color, s32 &Counter) const
{
if (X >= 0 && X < Size.Width && Y >= 0 && Y < Size.Height)
{
const SLightmapTexel* Texel = &getTexel(X, Y);
if (Texel->Face)
{
Color += Texel->Color.getVector();
++Counter;
}
}
}
/*
* SLight structure
*/
SLight::SLight(const SLightmapLight &LightData) :
Type (LightData.Type ),
Matrix (LightData.Matrix ),
Position (Matrix.getPosition() ),
Color (LightData.Color.getVector(true) ),
Attn0 (LightData.Attn0 ),
Attn1 (LightData.Attn1 ),
Attn2 (LightData.Attn2 ),
InnerConeAngle (LightData.InnerConeAngle / math::PI),
OuterConeAngle (LightData.OuterConeAngle / math::PI),
FixedDirection (
(Matrix.getRotationMatrix() * dim::vector3df(0, 0, 1)).normalize()
),
FixedVolumetricRadius (getAttenuationRadius()),
FixedVolumetric (
!math::equal(Attn0, 1.0f) || !math::equal(Attn1, 0.0f) || !math::equal(Attn2, 0.0f)
)
{
}
SLight::~SLight()
{
}
f32 SLight::getIntensity(
const dim::vector3df &Point, const dim::vector3df &Normal) const
{
/* Directional light calculations */
if (Type == scene::LIGHT_DIRECTIONAL)
return math::Max(0.0f, -FixedDirection.dot(Normal));
/* General light calculations */
f32 Intensity = 0.0f;
const dim::vector3df RayDirection((Point - Position).normalize());
Intensity = -RayDirection.dot(Normal);
/* Volumetric light calculations */
if (FixedVolumetric)
{
const f32 Distance = math::getDistance(Position, Point);
Intensity /= ( Attn0 + Attn1*Distance + Attn2*Distance*Distance );
}
/* Spot light calculations */
if (Type == scene::LIGHT_SPOT)
{
const f32 Angle = RayDirection.getAngle(FixedDirection);
if (Angle > OuterConeAngle)
Intensity = 0.0f;
else if (Angle > InnerConeAngle)
{
/* Calculate splot-light cone angle linear-interpolation (lerp) */
const f32 ConeAngleLerp = (Angle - InnerConeAngle) / (OuterConeAngle - InnerConeAngle);
Intensity *= (1.0f - ConeAngleLerp);
}
}
return math::Max(0.0f, Intensity);
}
f32 SLight::getAttenuationRadius() const
{
// Last 5 black texel levels (5, 5, 5) to (0, 0, 0) are not rendered -> for optimization
static const f32 COLOR_PRECISE = 5.0f;
if (!FixedVolumetric || Type == scene::LIGHT_DIRECTIONAL)
return math::OMEGA;
// Attenuation calculation backwards using the pq-formula
return -(Attn1/Attn2)/2 + sqrt(math::pow2((Attn1/Attn2)/2) + (255.0f - COLOR_PRECISE*Attn0)/(COLOR_PRECISE*Attn2));
}
bool SLight::checkVisibility(const STriangle &Triangle) const
{
return (
Type == scene::LIGHT_DIRECTIONAL ?
( FixedDirection.dot(-Triangle.Plane.Normal) > 0.0f ) :
( Triangle.Plane.isPointFrontSide(Position) && ( !FixedVolumetric || Triangle.getDistance(Position) < FixedVolumetricRadius ) )
);
}
/*
* SRasterizerVertex structure
*/
SRasterizerVertex::SRasterizerVertex()
{
}
SRasterizerVertex::SRasterizerVertex(
const dim::vector3df &InitPosition,
const dim::vector3df &InitNormal,
const dim::point2di &InitScreenCoord) :
Position (InitPosition ),
Normal (InitNormal ),
ScreenCoord (InitScreenCoord)
{
}
SRasterizerVertex::~SRasterizerVertex()
{
}
SRasterizerVertex& SRasterizerVertex::operator = (const SRasterizerVertex &Other)
{
Position = Other.Position;
Normal = Other.Normal;
return *this;
}
SRasterizerVertex& SRasterizerVertex::operator += (const SRasterizerVertex &Other)
{
Position += Other.Position;
Normal += Other.Normal;
return *this;
}
SRasterizerVertex& SRasterizerVertex::operator -= (const SRasterizerVertex &Other)
{
Position -= Other.Position;
Normal -= Other.Normal;
return *this;
}
SRasterizerVertex& SRasterizerVertex::operator *= (f32 Factor)
{
Position *= Factor;
Normal *= Factor;
return *this;
}
SRasterizerVertex& SRasterizerVertex::operator /= (f32 Factor)
{
Position /= Factor;
Normal /= Factor;
return *this;
}
s32 SRasterizerVertex::getScreenCoordX() const
{
return ScreenCoord.X;
}
s32 SRasterizerVertex::getScreenCoordY() const
{
return ScreenCoord.Y;
}
} // /namespace LightmapGen
} // /namespace tool
} // /namespace sp
#endif
// ================================================================================
| 28.349078 | 135 | 0.604828 | [
"mesh",
"vector",
"model"
] |
445421373a0d669542f820bd3c599db6a8543ca0 | 17,750 | hpp | C++ | src/sdl2_net/SDL_net.hpp | BadOPCode/Oblivion2-XRM | d65d9aa4b8021fc3b50b2c09edd0b19eb7baa1b9 | [
"Zlib"
] | 78 | 2015-10-08T07:14:37.000Z | 2022-02-10T04:51:21.000Z | src/sdl2_net/SDL_net.hpp | BadOPCode/Oblivion2-XRM | d65d9aa4b8021fc3b50b2c09edd0b19eb7baa1b9 | [
"Zlib"
] | 117 | 2015-12-14T16:51:42.000Z | 2020-02-16T07:00:36.000Z | src/sdl2_net/SDL_net.hpp | BadOPCode/Oblivion2-XRM | d65d9aa4b8021fc3b50b2c09edd0b19eb7baa1b9 | [
"Zlib"
] | 10 | 2015-12-10T16:54:24.000Z | 2022-02-10T04:51:29.000Z | /*
SDL_net: An example cross-platform network library for use with SDL
Copyright (C) 1997-2017 Sam Lantinga <slouken@libsdl.org>
Copyright (C) 2012 Simeon Maxein <smaxein@googlemail.com>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
/* $Id$ */
#ifndef SDL_NET_H_
#define SDL_NET_H_
#ifdef WITHOUT_SDL
#include <stdint.h>
typedef uint8_t Uint8;
typedef uint16_t Uint16;
typedef uint32_t Uint32;
#include <cstddef>
typedef struct SDLNet_version
{
Uint8 major;
Uint8 minor;
Uint8 patch;
} SDLNet_version;
// Michael Griffin 2018-02-17
// Add method alias (this was missed in original implementation)
#define SDL_vsnprintf vsnprintf
#define SDL_malloc malloc
#define SDL_realloc realloc
#define SDL_free free
#define SDL_memcpy memcpy
#define SDL_memset memset
#else /* WITHOUT_SDL */
#include <SDL2/SDL.h>
#include <SDL2/SDL_endian.h>
#include <SDL2/SDL_version.h>
typedef SDL_version SDLNet_version;
#endif /* WITHOUT_SDL */
#include "begin_code.h"
/* Set up for C function definitions, even when using C++ */
#ifdef __cplusplus
extern "C" {
#endif
/* Printable format: "%d.%d.%d", MAJOR, MINOR, PATCHLEVEL
*/
#define SDL_NET_MAJOR_VERSION 2
#define SDL_NET_MINOR_VERSION 0
#define SDL_NET_PATCHLEVEL 1
/* This macro can be used to fill a version structure with the compile-time
* version of the SDL_net library.
*/
#define SDL_NET_VERSION(X) \
{ \
(X)->major = SDL_NET_MAJOR_VERSION; \
(X)->minor = SDL_NET_MINOR_VERSION; \
(X)->patch = SDL_NET_PATCHLEVEL; \
}
/**
* This is the version number macro for the current SDL_net version.
*/
#define SDL_NET_COMPILEDVERSION \
SDL_VERSIONNUM(SDL_NET_MAJOR_VERSION, SDL_NET_MINOR_VERSION, SDL_NET_PATCHLEVEL)
/**
* This macro will evaluate to true if compiled with SDL_net at least X.Y.Z.
*/
#define SDL_NET_VERSION_ATLEAST(X, Y, Z) \
(SDL_NET_COMPILEDVERSION >= SDL_VERSIONNUM(X, Y, Z))
/* This function gets the version of the dynamically linked SDL_net library.
it should NOT be used to fill a version structure, instead you should
use the SDL_NET_VERSION() macro.
*/
const SDLNet_version * SDLCALL SDLNet_Linked_Version(void);
/* Initialize/Cleanup the network API
SDL must be initialized before calls to functions in this library,
because this library uses utility functions from the SDL library.
*/
int SDLCALL SDLNet_Init(void);
void SDLCALL SDLNet_Quit(void);
/***********************************************************************/
/* IPv4 hostname resolution API */
/***********************************************************************/
typedef struct
{
Uint32 host; /* 32-bit IPv4 host address */
Uint16 port; /* 16-bit protocol port */
} IPaddress;
/* Resolve a host name and port to an IP address in network form.
If the function succeeds, it will return 0.
If the host couldn't be resolved, the host portion of the returned
address will be INADDR_NONE, and the function will return -1.
If 'host' is NULL, the resolved host will be set to INADDR_ANY.
*/
#ifndef INADDR_ANY
#define INADDR_ANY 0x00000000
#endif
#ifndef INADDR_NONE
#define INADDR_NONE 0xFFFFFFFF
#endif
#ifndef INADDR_LOOPBACK
#define INADDR_LOOPBACK 0x7f000001
#endif
#ifndef INADDR_BROADCAST
#define INADDR_BROADCAST 0xFFFFFFFF
#endif
int SDLCALL SDLNet_ResolveHost(IPaddress *address, const char *host, Uint16 port);
/* Resolve an ip address to a host name in canonical form.
If the ip couldn't be resolved, this function returns NULL,
otherwise a pointer to a static buffer containing the hostname
is returned. Note that this function is not thread-safe.
*/
const char * SDLCALL SDLNet_ResolveIP(const IPaddress *ip);
/* Get the addresses of network interfaces on this system.
This returns the number of addresses saved in 'addresses'
*/
int SDLCALL SDLNet_GetLocalAddresses(IPaddress *addresses, int maxcount);
/***********************************************************************/
/* TCP network API */
/***********************************************************************/
typedef struct _TCPsocket *TCPsocket;
/* Open a TCP network socket
If ip.host is INADDR_NONE or INADDR_ANY, this creates a local server
socket on the given port, otherwise a TCP connection to the remote
host and port is attempted. The address passed in should already be
swapped to network byte order (addresses returned from
SDLNet_ResolveHost() are already in the correct form).
The newly created socket is returned, or NULL if there was an error.
*/
TCPsocket SDLCALL SDLNet_TCP_Open(IPaddress *ip);
/* Accept an incoming connection on the given server socket.
The newly created socket is returned, or NULL if there was an error.
*/
TCPsocket SDLCALL SDLNet_TCP_Accept(TCPsocket server);
/* Get the IP address of the remote system associated with the socket.
If the socket is a server socket, this function returns NULL.
*/
IPaddress * SDLCALL SDLNet_TCP_GetPeerAddress(TCPsocket sock);
/* Send 'len' bytes of 'data' over the non-server socket 'sock'
This function returns the actual amount of data sent. If the return value
is less than the amount of data sent, then either the remote connection was
closed, or an unknown socket error occurred.
*/
int SDLCALL SDLNet_TCP_Send(TCPsocket sock, const void *data, int len);
/* Receive up to 'maxlen' bytes of data over the non-server socket 'sock',
and store them in the buffer pointed to by 'data'.
This function returns the actual amount of data received. If the return
value is less than or equal to zero, then either the remote connection was
closed, or an unknown socket error occurred.
*/
int SDLCALL SDLNet_TCP_Recv(TCPsocket sock, void *data, int maxlen);
/* Close a TCP network socket */
void SDLCALL SDLNet_TCP_Close(TCPsocket sock);
/***********************************************************************/
/* UDP network API */
/***********************************************************************/
/* The maximum channels on a a UDP socket */
#define SDLNET_MAX_UDPCHANNELS 32
/* The maximum addresses bound to a single UDP socket channel */
#define SDLNET_MAX_UDPADDRESSES 4
typedef struct _UDPsocket *UDPsocket;
typedef struct
{
int channel; /* The src/dst channel of the packet */
Uint8 *data; /* The packet data */
int len; /* The length of the packet data */
int maxlen; /* The size of the data buffer */
int status; /* packet status after sending */
IPaddress address; /* The source/dest address of an incoming/outgoing packet */
} UDPpacket;
/* Allocate/resize/free a single UDP packet 'size' bytes long.
The new packet is returned, or NULL if the function ran out of memory.
*/
UDPpacket * SDLCALL SDLNet_AllocPacket(int size);
int SDLCALL SDLNet_ResizePacket(UDPpacket *packet, int newsize);
void SDLCALL SDLNet_FreePacket(UDPpacket *packet);
/* Allocate/Free a UDP packet vector (array of packets) of 'howmany' packets,
each 'size' bytes long.
A pointer to the first packet in the array is returned, or NULL if the
function ran out of memory.
*/
UDPpacket ** SDLCALL SDLNet_AllocPacketV(int howmany, int size);
void SDLCALL SDLNet_FreePacketV(UDPpacket **packetV);
/* Open a UDP network socket
If 'port' is non-zero, the UDP socket is bound to a local port.
The 'port' should be given in native byte order, but is used
internally in network (big endian) byte order, in addresses, etc.
This allows other systems to send to this socket via a known port.
*/
UDPsocket SDLCALL SDLNet_UDP_Open(Uint16 port);
/* Set the percentage of simulated packet loss for packets sent on the socket.
*/
void SDLCALL SDLNet_UDP_SetPacketLoss(UDPsocket sock, int percent);
/* Bind the address 'address' to the requested channel on the UDP socket.
If the channel is -1, then the first unbound channel that has not yet
been bound to the maximum number of addresses will be bound with
the given address as it's primary address.
If the channel is already bound, this new address will be added to the
list of valid source addresses for packets arriving on the channel.
If the channel is not already bound, then the address becomes the primary
address, to which all outbound packets on the channel are sent.
This function returns the channel which was bound, or -1 on error.
*/
int SDLCALL SDLNet_UDP_Bind(UDPsocket sock, int channel, const IPaddress *address);
/* Unbind all addresses from the given channel */
void SDLCALL SDLNet_UDP_Unbind(UDPsocket sock, int channel);
/* Get the primary IP address of the remote system associated with the
socket and channel. If the channel is -1, then the primary IP port
of the UDP socket is returned -- this is only meaningful for sockets
opened with a specific port.
If the channel is not bound and not -1, this function returns NULL.
*/
IPaddress * SDLCALL SDLNet_UDP_GetPeerAddress(UDPsocket sock, int channel);
/* Send a vector of packets to the the channels specified within the packet.
If the channel specified in the packet is -1, the packet will be sent to
the address in the 'src' member of the packet.
Each packet will be updated with the status of the packet after it has
been sent, -1 if the packet send failed.
This function returns the number of packets sent.
*/
int SDLCALL SDLNet_UDP_SendV(UDPsocket sock, UDPpacket **packets, int npackets);
/* Send a single packet to the specified channel.
If the channel specified in the packet is -1, the packet will be sent to
the address in the 'src' member of the packet.
The packet will be updated with the status of the packet after it has
been sent.
This function returns 1 if the packet was sent, or 0 on error.
NOTE:
The maximum size of the packet is limited by the MTU (Maximum Transfer Unit)
of the transport medium. It can be as low as 250 bytes for some PPP links,
and as high as 1500 bytes for ethernet.
*/
int SDLCALL SDLNet_UDP_Send(UDPsocket sock, int channel, UDPpacket *packet);
/* Receive a vector of pending packets from the UDP socket.
The returned packets contain the source address and the channel they arrived
on. If they did not arrive on a bound channel, the the channel will be set
to -1.
The channels are checked in highest to lowest order, so if an address is
bound to multiple channels, the highest channel with the source address
bound will be returned.
This function returns the number of packets read from the network, or -1
on error. This function does not block, so can return 0 packets pending.
*/
int SDLCALL SDLNet_UDP_RecvV(UDPsocket sock, UDPpacket **packets);
/* Receive a single packet from the UDP socket.
The returned packet contains the source address and the channel it arrived
on. If it did not arrive on a bound channel, the the channel will be set
to -1.
The channels are checked in highest to lowest order, so if an address is
bound to multiple channels, the highest channel with the source address
bound will be returned.
This function returns the number of packets read from the network, or -1
on error. This function does not block, so can return 0 packets pending.
*/
int SDLCALL SDLNet_UDP_Recv(UDPsocket sock, UDPpacket *packet);
/* Close a UDP network socket */
void SDLCALL SDLNet_UDP_Close(UDPsocket sock);
/***********************************************************************/
/* Hooks for checking sockets for available data */
/***********************************************************************/
typedef struct _SDLNet_SocketSet *SDLNet_SocketSet;
/* Any network socket can be safely cast to this socket type */
typedef struct _SDLNet_GenericSocket
{
int ready;
} *SDLNet_GenericSocket;
/* Allocate a socket set for use with SDLNet_CheckSockets()
This returns a socket set for up to 'maxsockets' sockets, or NULL if
the function ran out of memory.
*/
SDLNet_SocketSet SDLCALL SDLNet_AllocSocketSet(int maxsockets);
/* Add a socket to a set of sockets to be checked for available data */
int SDLCALL SDLNet_AddSocket(SDLNet_SocketSet set, SDLNet_GenericSocket sock);
SDL_FORCE_INLINE int SDLNet_TCP_AddSocket(SDLNet_SocketSet set, TCPsocket sock)
{
return SDLNet_AddSocket(set, (SDLNet_GenericSocket)sock);
}
SDL_FORCE_INLINE int SDLNet_UDP_AddSocket(SDLNet_SocketSet set, UDPsocket sock)
{
return SDLNet_AddSocket(set, (SDLNet_GenericSocket)sock);
}
/* Remove a socket from a set of sockets to be checked for available data */
int SDLCALL SDLNet_DelSocket(SDLNet_SocketSet set, SDLNet_GenericSocket sock);
SDL_FORCE_INLINE int SDLNet_TCP_DelSocket(SDLNet_SocketSet set, TCPsocket sock)
{
return SDLNet_DelSocket(set, (SDLNet_GenericSocket)sock);
}
SDL_FORCE_INLINE int SDLNet_UDP_DelSocket(SDLNet_SocketSet set, UDPsocket sock)
{
return SDLNet_DelSocket(set, (SDLNet_GenericSocket)sock);
}
/* This function checks to see if data is available for reading on the
given set of sockets. If 'timeout' is 0, it performs a quick poll,
otherwise the function returns when either data is available for
reading, or the timeout in milliseconds has elapsed, which ever occurs
first. This function returns the number of sockets ready for reading,
or -1 if there was an error with the select() system call.
*/
int SDLCALL SDLNet_CheckSockets(SDLNet_SocketSet set, Uint32 timeout);
/* After calling SDLNet_CheckSockets(), you can use this function on a
socket that was in the socket set, to find out if data is available
for reading.
*/
#define SDLNet_SocketReady(sock) _SDLNet_SocketReady((SDLNet_GenericSocket)(sock))
SDL_FORCE_INLINE int _SDLNet_SocketReady(SDLNet_GenericSocket sock)
{
return (sock != NULL) && (sock->ready);
}
/* Free a set of sockets allocated by SDL_NetAllocSocketSet() */
void SDLCALL SDLNet_FreeSocketSet(SDLNet_SocketSet set);
/***********************************************************************/
/* Error reporting functions */
/***********************************************************************/
void SDLCALL SDLNet_SetError(const char *fmt, ...);
const char * SDLCALL SDLNet_GetError(void);
/***********************************************************************/
/* Inline functions to read/write network data */
/***********************************************************************/
/* Warning, some systems have data access alignment restrictions */
#if defined(sparc) || defined(mips) || defined(__arm__)
#define SDL_DATA_ALIGNED 1
#endif
#ifndef SDL_DATA_ALIGNED
#define SDL_DATA_ALIGNED 0
#endif
/* Write a 16/32-bit value to network packet buffer */
#define SDLNet_Write16(value, areap) _SDLNet_Write16(value, areap)
#define SDLNet_Write32(value, areap) _SDLNet_Write32(value, areap)
/* Read a 16/32-bit value from network packet buffer */
#define SDLNet_Read16(areap) _SDLNet_Read16(areap)
#define SDLNet_Read32(areap) _SDLNet_Read32(areap)
#if !defined(WITHOUT_SDL) && !SDL_DATA_ALIGNED
SDL_FORCE_INLINE void _SDLNet_Write16(Uint16 value, void *areap)
{
*(Uint16 *)areap = SDL_SwapBE16(value);
}
SDL_FORCE_INLINE void _SDLNet_Write32(Uint32 value, void *areap)
{
*(Uint32 *)areap = SDL_SwapBE32(value);
}
SDL_FORCE_INLINE Uint16 _SDLNet_Read16(const void *areap)
{
return SDL_SwapBE16(*(const Uint16 *)areap);
}
SDL_FORCE_INLINE Uint32 _SDLNet_Read32(const void *areap)
{
return SDL_SwapBE32(*(const Uint32 *)areap);
}
#else /* !defined(WITHOUT_SDL) && !SDL_DATA_ALIGNED */
SDL_FORCE_INLINE void _SDLNet_Write16(Uint16 value, void *areap)
{
Uint8 *area = (Uint8*)areap;
area[0] = (value >> 8) & 0xFF;
area[1] = value & 0xFF;
}
SDL_FORCE_INLINE void _SDLNet_Write32(Uint32 value, void *areap)
{
Uint8 *area = (Uint8*)areap;
area[0] = (value >> 24) & 0xFF;
area[1] = (value >> 16) & 0xFF;
area[2] = (value >> 8) & 0xFF;
area[3] = value & 0xFF;
}
SDL_FORCE_INLINE Uint16 _SDLNet_Read16(void *areap)
{
Uint8 *area = (Uint8*)areap;
return ((Uint16)area[0]) << 8 | ((Uint16)area[1]);
}
SDL_FORCE_INLINE Uint32 _SDLNet_Read32(const void *areap)
{
const Uint8 *area = (const Uint8*)areap;
return ((Uint32)area[0]) << 24 | ((Uint32)area[1]) << 16 | ((Uint32)area[2]) << 8 | ((Uint32)area[3]);
}
#endif /* !defined(WITHOUT_SDL) && !SDL_DATA_ALIGNED */
/* Ends C function definitions when using C++ */
#ifdef __cplusplus
}
#endif
#include "close_code.h"
// Handle for posix Implementations
#ifndef _WIN32
#ifndef SOCKET
#define SOCKET int
#endif
#endif
#endif /* SDL_NET_H_ */
| 37.056367 | 106 | 0.69262 | [
"vector"
] |
44563da2022e7c134544cf54f4932fe995840253 | 2,307 | hpp | C++ | sparta/sparta/argos/InformationWriter.hpp | bdutro-sv/map | 90812bf631915958c42a1ba8e1c606973b8e1030 | [
"MIT"
] | null | null | null | sparta/sparta/argos/InformationWriter.hpp | bdutro-sv/map | 90812bf631915958c42a1ba8e1c606973b8e1030 | [
"MIT"
] | null | null | null | sparta/sparta/argos/InformationWriter.hpp | bdutro-sv/map | 90812bf631915958c42a1ba8e1c606973b8e1030 | [
"MIT"
] | null | null | null | // <InformationWriter.hpp> -*- C++ -*-
/**
* \file InformationWriter.hpp
* \brief Define the Pipeline Collection Information outputter.
*/
#ifndef __INFORMATION_WRITER_H__
#define __INFORMATION_WRITER_H__
#include <fstream>
#include "sparta/utils/SpartaException.hpp"
namespace sparta{
/**
* \class InformationWriter
* \brief A class that allows the simulation developer to
* write data to an information file stored near pipeline collection
* output files about the simulation.
*
* Human readible data can be written to file via the << operator or
* public writeLine() methods.
*/
class InformationWriter
{
public:
/**
* \brief construct a InformationWriter stream.
* \param file The name of the file + path to use as the output stream.
*/
InformationWriter(const std::string& file) :
file_(file, std::ios::out)
{
if(!file_.is_open()){
throw sparta::SpartaException("Failed to open InformationWriter file for file: " + file);
}
// Throw on write failure
file_.exceptions(std::ostream::eofbit | std::ostream::badbit | std::ostream::failbit | std::ostream::goodbit);
}
virtual ~InformationWriter()
{
file_.close();
}
/**
* \brief Allow appending to the file via the << operator.
* \param object the data to write to the file
*/
template<typename T>
InformationWriter& operator << (const T& object)
{
file_ << object;
return *this;
}
/**
* \brief Allow the user to write a string line to the file.
* \param str the string to be written as a line in the file.
*/
template<typename T>
void writeLine(const T& str)
{
file_ << str << std::endl;
}
/**
* \brief Allow the user to write some stuff to the file.
* This will not break at the end of the line.
*/
template<typename T>
void write(const T& str)
{
file_ << str;
}
private:
std::ofstream file_; /*!< an outstream to write to file with */
};
}
#endif
| 27.141176 | 122 | 0.564369 | [
"object"
] |
4467030c0ae173037edd1f47e4c34c7d99ee9065 | 6,850 | cpp | C++ | src/libtriton/engines/solver/z3/z3Solver.cpp | werew/Triton | 3f95e54f076308d6885071a21ae71eb2123771d2 | [
"Apache-2.0"
] | 2 | 2021-01-13T12:53:07.000Z | 2021-09-27T23:37:53.000Z | src/libtriton/engines/solver/z3/z3Solver.cpp | igogo-x86/Triton | 3225658a138f0beead593bf17103c0cf34500d68 | [
"Apache-2.0"
] | null | null | null | src/libtriton/engines/solver/z3/z3Solver.cpp | igogo-x86/Triton | 3225658a138f0beead593bf17103c0cf34500d68 | [
"Apache-2.0"
] | null | null | null | //! \file
/*
** Copyright (C) - Triton
**
** This program is under the terms of the BSD License.
*/
#include <z3++.h>
#include <z3_api.h>
#include <string>
#include <triton/astContext.hpp>
#include <triton/exceptions.hpp>
#include <triton/solverModel.hpp>
#include <triton/symbolicVariable.hpp>
#include <triton/tritonToZ3Ast.hpp>
#include <triton/tritonTypes.hpp>
#include <triton/z3Solver.hpp>
#include <triton/z3ToTritonAst.hpp>
namespace triton {
namespace engines {
namespace solver {
//! Wrapper to handle variadict number of arguments or'd togethers
z3::expr mk_or(z3::expr_vector args) {
std::vector<Z3_ast> array;
for (triton::uint32 i = 0; i < args.size(); i++)
array.push_back(args[i]);
return to_expr(args.ctx(), Z3_mk_or(args.ctx(), static_cast<triton::uint32>(array.size()), &(array[0])));
}
Z3Solver::Z3Solver() {
}
std::list<std::map<triton::uint32, SolverModel>> Z3Solver::getModels(const triton::ast::SharedAbstractNode& node, triton::uint32 limit) const {
std::list<std::map<triton::uint32, SolverModel>> ret;
triton::ast::SharedAbstractNode onode = node;
triton::ast::TritonToZ3Ast z3Ast{false};
try {
if (onode == nullptr)
throw triton::exceptions::SolverEngine("Z3Solver::getModels(): node cannot be null.");
/* Z3 does not need an assert() as root node */
if (node->getType() == triton::ast::ASSERT_NODE)
onode = node->getChildren()[0];
if (onode->isLogical() == false)
throw triton::exceptions::SolverEngine("Z3Solver::getModels(): Must be a logical node.");
z3::expr expr = z3Ast.convert(onode);
z3::context& ctx = expr.ctx();
z3::solver solver(ctx);
/* Create a solver and add the expression */
solver.add(expr);
/* Check if it is sat */
while (solver.check() == z3::sat && limit >= 1) {
/* Get model */
z3::model m = solver.get_model();
/* Traversing the model */
std::map<triton::uint32, SolverModel> smodel;
z3::expr_vector args(ctx);
for (triton::uint32 i = 0; i < m.size(); i++) {
/* Get the z3 variable */
z3::func_decl z3Variable = m[i];
/* Get the name as std::string from a z3 variable */
std::string varName = z3Variable.name().str();
/* Get z3 expr */
z3::expr exp = m.get_const_interp(z3Variable);
/* Get the size of a z3 expr */
triton::uint32 bvSize = exp.get_sort().bv_size();
/* Get the value of a z3 expr */
std::string svalue = Z3_get_numeral_string(ctx, exp);
/* Convert a string value to a integer value */
triton::uint512 value = triton::uint512(svalue);
/* Create a triton model */
SolverModel trionModel = SolverModel(z3Ast.variables[varName], value);
/* Map the result */
smodel[trionModel.getId()] = trionModel;
/* Uniq result */
if (exp.get_sort().is_bv())
args.push_back(ctx.bv_const(varName.c_str(), bvSize) != ctx.bv_val(svalue.c_str(), bvSize));
}
/* Escape last models */
solver.add(triton::engines::solver::mk_or(args));
/* If there is model available */
if (smodel.size() > 0)
ret.push_back(smodel);
/* Decrement the limit */
limit--;
}
}
catch (const z3::exception& e) {
throw triton::exceptions::SolverEngine(std::string("Z3Solver::getModels(): ") + e.msg());
}
return ret;
}
bool Z3Solver::isSat(const triton::ast::SharedAbstractNode& node) const {
triton::ast::TritonToZ3Ast z3Ast{false};
if (node == nullptr)
throw triton::exceptions::SolverEngine("Z3Solver::isSat(): node cannot be null.");
if (node->isLogical() == false)
throw triton::exceptions::SolverEngine("Z3Solver::isSat(): Must be a logical node.");
try {
z3::expr expr = z3Ast.convert(node);
z3::context& ctx = expr.ctx();
z3::solver solver(ctx);
/* Create a solver and add the expression */
solver.add(expr);
/* Check if it is sat */
return solver.check() == z3::sat;
}
catch (const z3::exception& e) {
throw triton::exceptions::SolverEngine(std::string("Z3Solver::isSat(): ") + e.msg());
}
}
std::map<triton::uint32, SolverModel> Z3Solver::getModel(const triton::ast::SharedAbstractNode& node) const {
std::map<triton::uint32, SolverModel> ret;
std::list<std::map<triton::uint32, SolverModel>> allModels;
allModels = this->getModels(node, 1);
if (allModels.size() > 0)
ret = allModels.front();
return ret;
}
triton::ast::SharedAbstractNode Z3Solver::simplify(const triton::ast::SharedAbstractNode& node) const {
if (node == nullptr)
throw triton::exceptions::AstTranslations("Z3Solver::simplify(): node cannot be null.");
try {
triton::ast::TritonToZ3Ast z3Ast{false};
triton::ast::Z3ToTritonAst tritonAst{node->getContext()};
/* From Triton to Z3 */
z3::expr expr = z3Ast.convert(node);
/* Simplify and back to Triton's AST */
auto snode = tritonAst.convert(expr.simplify());
return snode;
}
catch (const z3::exception& e) {
throw triton::exceptions::AstTranslations(std::string("Z3Solver::evaluate(): ") + e.msg());
}
}
triton::uint512 Z3Solver::evaluate(const triton::ast::SharedAbstractNode& node) const {
if (node == nullptr)
throw triton::exceptions::AstTranslations("Z3Solver::simplify(): node cannot be null.");
try {
triton::ast::TritonToZ3Ast z3ast{true};
/* From Triton to Z3 */
z3::expr expr = z3ast.convert(node);
/* Simplify the expression to get a constant */
expr = expr.simplify();
triton::uint512 res = 0;
if (expr.get_sort().is_bool())
res = Z3_get_bool_value(expr.ctx(), expr) == Z3_L_TRUE ? true : false;
else
res = triton::uint512{Z3_get_numeral_string(expr.ctx(), expr)};
return res;
}
catch (const z3::exception& e) {
throw triton::exceptions::AstTranslations(std::string("Z3Solver::evaluate(): ") + e.msg());
}
}
std::string Z3Solver::getName(void) const {
return "z3";
}
};
};
};
| 31.278539 | 149 | 0.560292 | [
"vector",
"model"
] |
4467dc3e1c9e8c71bc352e6e4f54ccc930ae03bc | 2,284 | cpp | C++ | slambook2/3rdparty/g2o/unit_test/slam2d/mappings_se2.cpp | zhh2005757/slambook2_in_Docker | f0e71327d196cdad3b3c10d96eacdf95240d528b | [
"MIT"
] | 3 | 2021-10-14T07:40:15.000Z | 2022-02-27T09:20:33.000Z | slambook2/3rdparty/g2o/unit_test/slam2d/mappings_se2.cpp | zhh2005757/slambook2_in_Docker | f0e71327d196cdad3b3c10d96eacdf95240d528b | [
"MIT"
] | null | null | null | slambook2/3rdparty/g2o/unit_test/slam2d/mappings_se2.cpp | zhh2005757/slambook2_in_Docker | f0e71327d196cdad3b3c10d96eacdf95240d528b | [
"MIT"
] | 2 | 2021-10-21T06:12:36.000Z | 2022-03-07T15:52:28.000Z | // g2o - General Graph Optimization
// Copyright (C) 2014 R. Kuemmerle, G. Grisetti, W. Burgard
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
// IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
// TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
// PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
// TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "gtest/gtest.h"
#include "g2o/types/slam2d/se2.h"
using namespace std;
using namespace g2o;
TEST(MappingsSlam2D, SE2)
{
// constructor from 3 values
SE2 s1(cst(0.), cst(1.), cst(2.));
EXPECT_DOUBLE_EQ(0., s1[0]);
EXPECT_DOUBLE_EQ(1., s1[1]);
EXPECT_DOUBLE_EQ(2., s1[2]);
// constructor from vector
Vector3 vec2 = Vector3(cst(0.1), cst(0.2), cst(0.3));
SE2 s2(vec2);
EXPECT_DOUBLE_EQ(0.1, s2[0]);
EXPECT_DOUBLE_EQ(0.2, s2[1]);
EXPECT_DOUBLE_EQ(0.3, s2[2]);
EXPECT_DOUBLE_EQ(0., (vec2.head<2>() - s2.translation()).norm());
// constructor from Isometry
Rotation2D rot3 = Rotation2D(cst(1.));
SE2 s3 = SE2(Isometry2(rot3));
EXPECT_DOUBLE_EQ(0., s3.translation()(0));
EXPECT_DOUBLE_EQ(0., s3.translation()(1));
EXPECT_DOUBLE_EQ(1., s3.rotation().angle());
}
| 40.070175 | 76 | 0.712347 | [
"vector"
] |
446acccf8f3a9db8ba09674b1971a62fc5d6fa88 | 6,977 | cpp | C++ | Source/I3D2/Object_uvshift.cpp | mice777/Insanity3D | 49dc70130f786439fb0e4f91b75b6b686a134760 | [
"Apache-2.0"
] | 2 | 2022-02-11T11:59:44.000Z | 2022-02-16T20:33:25.000Z | Source/I3D2/Object_uvshift.cpp | mice777/Insanity3D | 49dc70130f786439fb0e4f91b75b6b686a134760 | [
"Apache-2.0"
] | null | null | null | Source/I3D2/Object_uvshift.cpp | mice777/Insanity3D | 49dc70130f786439fb0e4f91b75b6b686a134760 | [
"Apache-2.0"
] | null | null | null | #include "all.h"
#include "object.h"
#include "mesh.h"
//----------------------------
//----------------------------
class I3D_object_uv_shift: public I3D_object{
//texture shifting
struct{
float add[2];
float reserved[2];
} curr_vals;
S_vector2 uv_add;
enum E_MODE{
MODE_ANIMATE,
MODE_DELTA,
} mode;
void ComputeShift();
public:
I3D_object_uv_shift(PI3D_driver d1):
I3D_object(d1),
mode(MODE_ANIMATE)
{
visual_type = I3D_VISUAL_UV_SHIFT;
uv_add.Zero();
memset(&curr_vals, 0, sizeof(curr_vals));
}
virtual void AddPrimitives(S_preprocess_context&);
#ifndef GL
virtual void DrawPrimitive(const S_preprocess_context&, const S_render_primitive&);
#endif
virtual void DrawPrimitivePS(const S_preprocess_context&, const S_render_primitive&);
virtual I3D_RESULT I3DAPI SetProperty(dword index, dword value){
switch(index){
case I3DPROP_OUVS_F_SHIFT_U: uv_add.x = I3DIntAsFloat(value); break;
case I3DPROP_OUVS_F_SHIFT_V: uv_add.y = I3DIntAsFloat(value); break;
case I3DPROP_OUVS_E_MODE:
if(value>MODE_DELTA)
return I3DERR_INVALIDPARAMS;
mode = (E_MODE)value;
break;
default:
assert(0);
return I3DERR_INVALIDPARAMS;
}
vis_flags &= ~VISF_DEST_UV0_VALID;
return I3D_OK;
}
virtual dword I3DAPI GetProperty(dword index) const{
switch(index){
case I3DPROP_OUVS_F_SHIFT_U: return I3DFloatAsInt(uv_add.x);
case I3DPROP_OUVS_F_SHIFT_V: return I3DFloatAsInt(uv_add.y);
case I3DPROP_OUVS_E_MODE: return mode;
default: assert(0);
}
return 0xffcecece;
}
};
//----------------------------
void I3D_object_uv_shift::ComputeShift(){
int time_delta = drv->GetRenderTime() - last_render_time;
float tsec = (float)time_delta * .001f;
curr_vals.add[0] += uv_add.x * tsec;
curr_vals.add[1] += uv_add.y * tsec;
//clamp to range -1.0 ... 1.0
curr_vals.add[0] = (float)fmod(curr_vals.add[0], 1.0f);
curr_vals.add[1] = (float)fmod(curr_vals.add[1], 1.0f);
}
//----------------------------
void I3D_object_uv_shift::AddPrimitives(S_preprocess_context &pc){
if(!mesh)
return;
AddPrimitives1(mesh, pc);
if(
#ifndef GL
pc.mode!=RV_SHADOW_CASTER &&
#endif
mode==MODE_ANIMATE)
ComputeShift();
}
//----------------------------
#ifndef GL
void I3D_object_uv_shift::DrawPrimitive(const S_preprocess_context &pc, const S_render_primitive &rp){
PI3D_mesh_base mb = mesh;
HRESULT hr;
{
IDirect3DDevice9 *d3d_dev = drv->GetDevice1();
if(last_auto_lod != rp.curr_auto_lod){
last_auto_lod = rp.curr_auto_lod;
vis_flags &= ~(VISF_DEST_LIGHT_VALID | VISF_DEST_UV0_VALID);
}
dword vertex_count;
const C_auto_lod *auto_lods = mb->GetAutoLODs();
if(rp.curr_auto_lod < 0){
vertex_count = mb->vertex_buffer.NumVertices();
}else{
vertex_count = auto_lods[rp.curr_auto_lod].vertex_count;
}
I3D_driver::S_vs_shader_entry_in se;
dword prep_flags = VSPREP_TRANSFORM | VSPREP_FEED_MATRIX | VSPREP_NO_COPY_UV;
if(pc.mode!=RV_SHADOW_CASTER){
if(drv->IsDirectTransform()){
prep_flags |= VSPREP_MAKELIGHTING;
}else{
if(!(vis_flags&VISF_DEST_LIGHT_VALID)){
prep_flags |= VSPREP_MAKELIGHTING;
vis_flags |= VISF_DEST_LIGHT_VALID;
}
}
se.AddFragment(VSF_SHIFT_UV);
se.AddFragment(VSF_STORE_UV_0);
{
switch(mode){
case MODE_ANIMATE:
break;
case MODE_DELTA:
vis_flags |= VISF_DEST_UV0_VALID;
curr_vals.add[0] = uv_add[0];
curr_vals.add[1] = uv_add[1];
break;
default:
assert(0);
}
}
}
const I3D_driver::S_vs_shader_entry *se_out = PrepareVertexShader(mb->GetFGroups1()[0].GetMaterial1(), 1, se, rp, pc.mode, prep_flags);
if(pc.mode!=RV_SHADOW_CASTER){
//feed UV constants
drv->SetVSConstant(se_out->vscs_uv_shift, &curr_vals);
}
if(!drv->IsDirectTransform()){
drv->DisableTextureStage(1);
drv->SetStreamSource(mb->vertex_buffer.GetD3DVertexBuffer(), mb->vertex_buffer.GetSizeOfVertex());
drv->SetVSDecl(vertex_buffer.vs_decl);
hr = d3d_dev->ProcessVertices(mb->vertex_buffer.D3D_vertex_buffer_index,
vertex_buffer.D3D_vertex_buffer_index, vertex_count,
vertex_buffer.GetD3DVertexBuffer(), NULL, D3DPV_DONOTCOPYDATA);
CHECK_D3D_RESULT("ProcessVertices", hr);
drv->SetVertexShader(NULL);
}
}
DrawPrimitiveVisual(mb, pc, rp);
}
#endif
//----------------------------
void I3D_object_uv_shift::DrawPrimitivePS(const S_preprocess_context &pc, const S_render_primitive &rp){
PI3D_mesh_base mb = mesh;
/*
dword vertex_count;
const C_auto_lod *auto_lods = mb->GetAutoLODs();
if(rp.curr_auto_lod < 0){
vertex_count = mb->vertex_buffer.NumVertices();
}else{
vertex_count = auto_lods[rp.curr_auto_lod].vertex_count;
}
*/
I3D_driver::S_vs_shader_entry_in se;
dword prep_flags = VSPREP_TRANSFORM | VSPREP_FEED_MATRIX | VSPREP_NO_COPY_UV;
#ifndef GL
if(pc.mode!=RV_SHADOW_CASTER)
#endif
{
prep_flags |= VSPREP_MAKELIGHTING;
se.AddFragment(VSF_SHIFT_UV);
se.AddFragment(VSF_STORE_UV_0);
switch(mode){
case MODE_ANIMATE:
break;
case MODE_DELTA:
vis_flags |= VISF_DEST_UV0_VALID;
curr_vals.add[0] = uv_add[0];
curr_vals.add[1] = uv_add[1];
break;
default:
assert(0);
}
}
const I3D_driver::S_vs_shader_entry *se_out = PrepareVertexShader(mb->GetFGroups1()[0].GetMaterial1(), 1, se, rp, pc.mode, prep_flags);
//feed UV constants
#ifndef GL
if(pc.mode!=RV_SHADOW_CASTER)
#endif
drv->SetVSConstant(se_out->vscs_uv_shift, &curr_vals);
DrawPrimitiveVisualPS(mb, pc, rp);
}
//----------------------------
//----------------------------
extern const S_visual_property props_ObjectUVshift[] = {
//I3DPROP_OUVS_F_SHIFT_U
{I3DPROP_FLOAT, "Anim U", "Shift values for U coordinate. The meaning of these values is dependent on mode."},
//I3DPROP_OUVS_F_SHIFT_V
{I3DPROP_FLOAT, "Anim V", "Shift values for V coordinate. The meaning of these values is dependent on mode."},
//I3DPROP_OUVS_E_MODE
{I3DPROP_ENUM, "Mode\0Animate\0Delta\0", "Shifting mode."},
{I3DPROP_NULL}
};
I3D_visual *CreateObjectUVshift(PI3D_driver drv){
return new I3D_object_uv_shift(drv);
}
//----------------------------
//----------------------------
| 29.070833 | 141 | 0.606708 | [
"mesh",
"object"
] |
446d5d3e58c61108ef5d4868a75dfe91ef85cb6d | 3,483 | cpp | C++ | Engine/Source/Actor/Geometry/GRectangle.cpp | MarvinChung/Photon-v2 | a42761797f5364525e5686cd7fe2eff6f5b04ddf | [
"MIT"
] | 1 | 2019-02-23T14:06:56.000Z | 2019-02-23T14:06:56.000Z | Engine/Source/Actor/Geometry/GRectangle.cpp | MarvinChung/Photon-v2 | a42761797f5364525e5686cd7fe2eff6f5b04ddf | [
"MIT"
] | null | null | null | Engine/Source/Actor/Geometry/GRectangle.cpp | MarvinChung/Photon-v2 | a42761797f5364525e5686cd7fe2eff6f5b04ddf | [
"MIT"
] | null | null | null | #include "Actor/Geometry/GRectangle.h"
#include "Core/Intersectable/PTriangle.h"
#include "Actor/Geometry/GTriangleMesh.h"
#include "Actor/Geometry/GTriangle.h"
#include "Math/TVector3.h"
#include "Core/Intersectable/PrimitiveMetadata.h"
#include "FileIO/SDL/InputPacket.h"
#include "Actor/Geometry/PrimitiveBuildingMaterial.h"
#include <iostream>
namespace ph
{
GRectangle::GRectangle() :
GRectangle(1, 1)
{}
GRectangle::GRectangle(const real width, const real height) :
m_width(width), m_height(height),
m_texCoordScale(1)
{}
GRectangle::~GRectangle() = default;
void GRectangle::genPrimitive(const PrimitiveBuildingMaterial& data,
std::vector<std::unique_ptr<Primitive>>& out_primitives) const
{
if(!checkData(data, m_width, m_height))
{
return;
}
genTriangleMesh()->genPrimitive(data, out_primitives);
}
std::shared_ptr<Geometry> GRectangle::genTransformApplied(const StaticAffineTransform& transform) const
{
return genTriangleMesh()->genTransformApplied(transform);
}
void GRectangle::setTexCoordScale(const real scale)
{
m_texCoordScale = scale;
}
std::shared_ptr<GTriangleMesh> GRectangle::genTriangleMesh() const
{
// TODO: check data
const real halfWidth = m_width * 0.5_r;
const real halfHeight = m_height * 0.5_r;
const Vector3R vA(-halfWidth, halfHeight, 0.0_r);// quadrant II
const Vector3R vB(-halfWidth, -halfHeight, 0.0_r);// quadrant III
const Vector3R vC( halfWidth, -halfHeight, 0.0_r);// quadrant IV
const Vector3R vD( halfWidth, halfHeight, 0.0_r);// quadrant I
const Vector3R tA(0.0_r, 1.0_r, 0.0_r);// quadrant II
const Vector3R tB(0.0_r, 0.0_r, 0.0_r);// quadrant III
const Vector3R tC(1.0_r, 0.0_r, 0.0_r);// quadrant IV
const Vector3R tD(1.0_r, 1.0_r, 0.0_r);// quadrant I
// 2 triangles for a rectangle (both CCW)
GTriangle tri1(vA, vB, vD);
tri1.setUVWa(tA.mul(m_texCoordScale));
tri1.setUVWb(tB.mul(m_texCoordScale));
tri1.setUVWc(tD.mul(m_texCoordScale));
GTriangle tri2(vB, vC, vD);
tri2.setUVWa(tB.mul(m_texCoordScale));
tri2.setUVWb(tC.mul(m_texCoordScale));
tri2.setUVWc(tD.mul(m_texCoordScale));
auto triMesh = std::make_shared<GTriangleMesh>();
triMesh->addTriangle(tri1);
triMesh->addTriangle(tri2);
return triMesh;
}
bool GRectangle::checkData(const PrimitiveBuildingMaterial& data, const real width, const real height)
{
if(!data.metadata)
{
std::cerr << "warning: at GRectangle::checkData(), no PrimitiveMetadata" << std::endl;
return false;
}
if(width <= 0.0_r || height <= 0.0_r)
{
std::cerr << "warning: at GRectangle::checkData(), GRectangle's dimension is zero or negative" << std::endl;
return false;
}
return true;
}
// command interface
SdlTypeInfo GRectangle::ciTypeInfo()
{
return SdlTypeInfo(ETypeCategory::REF_GEOMETRY, "rectangle");
}
void GRectangle::ciRegister(CommandRegister& cmdRegister)
{
SdlLoader loader;
loader.setFunc<GRectangle>(ciLoad);
cmdRegister.setLoader(loader);
}
std::unique_ptr<GRectangle> GRectangle::ciLoad(const InputPacket& packet)
{
const DataTreatment requiredData(EDataImportance::REQUIRED,
"GRectangle needs width and height specified");
const real width = packet.getReal("width", 1.0_r, requiredData);
const real height = packet.getReal("height", 1.0_r, requiredData);
auto rectangle = std::make_unique<GRectangle>(width, height);
rectangle->setTexCoordScale(packet.getReal("texcoord-scale", 1.0_r));
return rectangle;
}
}// end namespace ph | 27.425197 | 110 | 0.730692 | [
"geometry",
"vector",
"transform"
] |
446e483b832561d5415cb82e58781e5387f9950e | 6,262 | cxx | C++ | Code/Numerics/FEM/itkFEMElement2DC0LinearQuadrilateral.cxx | dtglidden/ITK | ef0c16fee4fac904d6ab706b8f7d438d4062cd96 | [
"BSD-3-Clause"
] | 1 | 2017-07-31T18:41:02.000Z | 2017-07-31T18:41:02.000Z | Code/Numerics/FEM/itkFEMElement2DC0LinearQuadrilateral.cxx | dtglidden/ITK | ef0c16fee4fac904d6ab706b8f7d438d4062cd96 | [
"BSD-3-Clause"
] | null | null | null | Code/Numerics/FEM/itkFEMElement2DC0LinearQuadrilateral.cxx | dtglidden/ITK | ef0c16fee4fac904d6ab706b8f7d438d4062cd96 | [
"BSD-3-Clause"
] | null | null | null | /*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: itkFEMElement2DC0LinearQuadrilateral.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Insight Software Consortium. All rights reserved.
See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
// disable debug warnings in MS compiler
#ifdef _MSC_VER
#pragma warning(disable: 4786)
#endif
#include "itkFEMElement2DC0LinearQuadrilateral.h"
#include "vnl/vnl_math.h"
namespace itk {
namespace fem {
void
Element2DC0LinearQuadrilateral
::GetIntegrationPointAndWeight(unsigned int i, VectorType& pt, Float& w, unsigned int order) const
{
// FIXME: range checking
// default integration order
if (order==0) { order=DefaultIntegrationOrder; }
pt.set_size(2);
pt[0]=gaussPoint[order][i%order];
pt[1]=gaussPoint[order][i/order];
w=gaussWeight[order][i%order]*gaussWeight[order][i/order];
}
unsigned int
Element2DC0LinearQuadrilateral
::GetNumberOfIntegrationPoints(unsigned int order) const
{
// FIXME: range checking
// default integration order
if (order==0) { order=DefaultIntegrationOrder; }
return order*order;
}
Element2DC0LinearQuadrilateral::VectorType
Element2DC0LinearQuadrilateral
::ShapeFunctions( const VectorType& pt ) const
{
/* Linear quadrilateral element has four shape functions */
VectorType shapeF(4);
/**
* Linear quadrilateral element has local coordinates
* (-1,-1), (1,-1), (1,1), and (-1,1)
*/
/* given local point x=(r,s), where -1 <= r,s <= 1 and */
/* shape function 1: ((1 - r) * (1 - s)) / 4 (node 1) */
shapeF[0] = (1 - pt[0]) * (1 - pt[1]) * .25;
/* shape function 2: ((1 + r) * (1 - s)) / 4 (node 2) */
shapeF[1] = (1 + pt[0]) * (1 - pt[1]) * .25;
/* shape function 3: ((1 + r) * (1 + s)) / 4 (node 3) */
shapeF[2] = (1 + pt[0]) * (1 + pt[1]) * .25;
/* shape function 1: ((1 - r) * (1 + s)) / 4 (node 4) */
shapeF[3] = (1 - pt[0]) * (1 + pt[1]) * .25;
return shapeF;
}
void
Element2DC0LinearQuadrilateral
::ShapeFunctionDerivatives( const VectorType& pt, MatrixType& shapeD ) const
{
/** functions at directions r and s. */
shapeD.set_size(2,4);
/** Derivative w.r.t r for shape function 1 (node 1) */
shapeD[0][0] = -(1 - pt[1]) * .25;
/** Derivative w.r.t s for shape function 1 (node 1) */
shapeD[1][0] = -(1 - pt[0]) * .25;
/** Derivative w.r.t r for shape function 2 (node 2) */
shapeD[0][1] = +(1 - pt[1]) * .25;
/** Derivative w.r.t s for shape function 2 (node 2) */
shapeD[1][1] = -(1 + pt[0]) * .25;
/** Derivative w.r.t r for shape function 3 (node 3) */
shapeD[0][2] = +(1 + pt[1]) * .25;
/** Derivative w.r.t s for shape function 3 (node 3) */
shapeD[1][2] = +(1 + pt[0]) * .25;
/** Derivative w.r.t r for shape function 4 (node 4) */
shapeD[0][3] = -(1 + pt[1]) * .25;
/** Derivative w.r.t s for shape function 4 (node 4) */
shapeD[1][3] = +(1 - pt[0]) * .25;
}
bool
Element2DC0LinearQuadrilateral
::GetLocalFromGlobalCoordinates( const VectorType& globalPt , VectorType& localPt) const
{
Float x1, x2, x3, x4, y1, y2, y3, y4, xce, yce, xb, yb, xcn, ycn,
A, J1, J2, x0, y0, dx, dy, be, bn, ce, cn;
localPt.set_size(2);
localPt.fill(0.0);
x1 = this->m_node[0]->GetCoordinates()[0]; y1 = this->m_node[0]->GetCoordinates()[1];
x2 = this->m_node[1]->GetCoordinates()[0]; y2 = this->m_node[1]->GetCoordinates()[1];
x3 = this->m_node[2]->GetCoordinates()[0]; y3 = this->m_node[2]->GetCoordinates()[1];
x4 = this->m_node[3]->GetCoordinates()[0]; y4 = this->m_node[3]->GetCoordinates()[1];
xb = x1 - x2 + x3 - x4;
yb = y1 - y2 + y3 - y4;
xce = x1 + x2 - x3 - x4;
yce = y1 + y2 - y3 - y4;
xcn = x1 - x2 - x3 + x4;
ycn = y1 - y2 - y3 + y4;
A = 0.5 * (((x3 - x1) * (y4 - y2)) - ((x4 - x2) * (y3 - y1)));
J1 = ((x3 - x4) * (y1 - y2)) - ((x1 - x2) * (y3 - y4));
J2 = ((x2 - x3) * (y1 - y4)) - ((x1 - x4) * (y2 - y3));
x0 = 0.25 * (x1 + x2 + x3 + x4);
y0 = 0.25 * (y1 + y2 + y3 + y4);
dx = globalPt[0] - x0;
dy = globalPt[1] - y0;
be = A - (dx * yb) + (dy * xb);
bn = -A - (dx * yb) + (dy * xb);
ce = (dx * yce) - (dy * xce);
cn = (dx * ycn) - (dy * xcn);
localPt[0] = (2 * ce) / (-vcl_sqrt((be * be) - (2 * J1 * ce)) - be);
localPt[1] = (2 * cn) / ( vcl_sqrt((bn * bn) + (2 * J2 * cn)) - bn);
bool isInside=true;
if (localPt[0] < -1.0 || localPt[0] > 1.0 || localPt[1] < -1.0 || localPt[1] > 1.0 )
{
isInside=false;
}
return isInside;
}
/**
* Draw the element on device context pDC.
*/
#ifdef FEM_BUILD_VISUALIZATION
void
Element2DC0LinearQuadrilateral
::Draw(CDC* pDC, Solution::ConstPointer sol) const
{
int x1=m_node[0]->GetCoordinates()[0]*DC_Scale;
int y1=m_node[0]->GetCoordinates()[1]*DC_Scale;
int x2=m_node[1]->GetCoordinates()[0]*DC_Scale;
int y2=m_node[1]->GetCoordinates()[1]*DC_Scale;
int x3=m_node[2]->GetCoordinates()[0]*DC_Scale;
int y3=m_node[2]->GetCoordinates()[1]*DC_Scale;
int x4=m_node[3]->GetCoordinates()[0]*DC_Scale;
int y4=m_node[3]->GetCoordinates()[1]*DC_Scale;
x1 += sol->GetSolutionValue(this->m_node[0]->GetDegreeOfFreedom(0))*DC_Scale;
y1 += sol->GetSolutionValue(this->m_node[0]->GetDegreeOfFreedom(1))*DC_Scale;
x2 += sol->GetSolutionValue(this->m_node[1]->GetDegreeOfFreedom(0))*DC_Scale;
y2 += sol->GetSolutionValue(this->m_node[1]->GetDegreeOfFreedom(1))*DC_Scale;
x3 += sol->GetSolutionValue(this->m_node[2]->GetDegreeOfFreedom(0))*DC_Scale;
y3 += sol->GetSolutionValue(this->m_node[2]->GetDegreeOfFreedom(1))*DC_Scale;
x4 += sol->GetSolutionValue(this->m_node[3]->GetDegreeOfFreedom(0))*DC_Scale;
y4 += sol->GetSolutionValue(this->m_node[3]->GetDegreeOfFreedom(1))*DC_Scale;
pDC->MoveTo(x1,y1);
pDC->LineTo(x2,y2);
pDC->LineTo(x3,y3);
pDC->LineTo(x4,y4);
pDC->LineTo(x1,y1);
}
#endif
}} // end namespace itk::fem
| 29.261682 | 98 | 0.600128 | [
"shape"
] |
446f1d3dab8e771f7443cf80ba74183ab539fd7b | 16,392 | cpp | C++ | patch/llpcPatchPreparePipelineAbi.cpp | hustwarhd/llpc | ff548ab17c0c5e79c3cfca9fa6d3bc717624ae85 | [
"MIT"
] | null | null | null | patch/llpcPatchPreparePipelineAbi.cpp | hustwarhd/llpc | ff548ab17c0c5e79c3cfca9fa6d3bc717624ae85 | [
"MIT"
] | null | null | null | patch/llpcPatchPreparePipelineAbi.cpp | hustwarhd/llpc | ff548ab17c0c5e79c3cfca9fa6d3bc717624ae85 | [
"MIT"
] | null | null | null | /*
***********************************************************************************************************************
*
* Copyright (c) 2018-2019 Advanced Micro Devices, Inc. All Rights Reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
**********************************************************************************************************************/
/**
***********************************************************************************************************************
* @file llpcPatchPrepareAbi.cpp
* @brief LLPC source file: contains declaration and implementation of class Llpc::PatchPreparePipelineAbi.
***********************************************************************************************************************
*/
#include "llvm/Pass.h"
#include "llvm/Support/Debug.h"
#include "llpcAbiMetadata.h"
#include "llpcCodeGenManager.h"
#include "llpcGfx6ConfigBuilder.h"
#include "llpcGfx9ConfigBuilder.h"
#include "llpcPatch.h"
#include "llpcPipelineShaders.h"
#include "llpcShaderMerger.h"
#define DEBUG_TYPE "llpc-patch-prepare-pipeline-abi"
using namespace llvm;
using namespace Llpc;
namespace Llpc
{
// =====================================================================================================================
// Pass to prepare the pipeline ABI
class PatchPreparePipelineAbi final : public Patch
{
public:
static char ID;
PatchPreparePipelineAbi(
bool onlySetCallingConvs = false)
:
Patch(ID),
m_onlySetCallingConvs(onlySetCallingConvs)
{
initializePipelineShadersPass(*llvm::PassRegistry::getPassRegistry());
initializePatchPreparePipelineAbiPass(*PassRegistry::getPassRegistry());
}
bool runOnModule(Module& module) override;
void getAnalysisUsage(AnalysisUsage& analysisUsage) const override
{
analysisUsage.addRequired<PipelineShaders>();
}
private:
LLPC_DISALLOW_COPY_AND_ASSIGN(PatchPreparePipelineAbi);
void SetCallingConvs(Module& module);
void MergeShaderAndSetCallingConvs(Module& module);
void SetCallingConv(ShaderStage stage,
CallingConv::ID callingConv);
void SetAbiEntryNames(Module& module);
void AddAbiMetadata(Module& module);
Result BuildGraphicsPipelineRegConfig(uint8_t** ppConfig, size_t* pConfigSize);
Result BuildComputePipelineRegConfig(uint8_t** ppConfig, size_t* pConfigSize);
// -----------------------------------------------------------------------------------------------------------------
PipelineShaders* m_pPipelineShaders; // API shaders in the pipeline
bool m_hasVs; // Whether the pipeline has vertex shader
bool m_hasTcs; // Whether the pipeline has tessellation control shader
bool m_hasTes; // Whether the pipeline has tessellation evaluation shader
bool m_hasGs; // Whether the pipeline has geometry shader
GfxIpVersion m_gfxIp; // Graphics IP version info
const bool m_onlySetCallingConvs; // Whether to only set the calling conventions
};
char PatchPreparePipelineAbi::ID = 0;
} // Llpc
// =====================================================================================================================
// Create pass to prepare the pipeline ABI
ModulePass* Llpc::CreatePatchPreparePipelineAbi(
bool onlySetCallingConvs) // Should we only set the calling conventions, or do the full prepare.
{
return new PatchPreparePipelineAbi(onlySetCallingConvs);
}
// =====================================================================================================================
// Run the pass on the specified LLVM module.
bool PatchPreparePipelineAbi::runOnModule(
Module& module) // [in,out] LLVM module to be run on
{
LLVM_DEBUG(dbgs() << "Run the pass Patch-Prepare-Pipeline-Abi\n");
Patch::Init(&module);
m_pPipelineShaders = &getAnalysis<PipelineShaders>();
m_hasVs = ((m_pContext->GetShaderStageMask() & ShaderStageToMask(ShaderStageVertex)) != 0);
m_hasTcs = ((m_pContext->GetShaderStageMask() & ShaderStageToMask(ShaderStageTessControl)) != 0);
m_hasTes = ((m_pContext->GetShaderStageMask() & ShaderStageToMask(ShaderStageTessEval)) != 0);
m_hasGs = ((m_pContext->GetShaderStageMask() & ShaderStageToMask(ShaderStageGeometry)) != 0);
m_gfxIp = m_pContext->GetGfxIpVersion();
// If we've only to set the calling conventions, do that now.
if (m_onlySetCallingConvs)
{
SetCallingConvs(module);
}
else
{
if (m_gfxIp.major >= 9)
{
MergeShaderAndSetCallingConvs(module);
}
SetAbiEntryNames(module);
AddAbiMetadata(module);
}
return true; // Modified the module.
}
// =====================================================================================================================
// Set calling convention for the entry-point of each shader (pre-GFX9)
void PatchPreparePipelineAbi::SetCallingConvs(
Module& module) // [in] LLVM module
{
const bool hasTs = (m_hasTcs || m_hasTes);
// NOTE: For each entry-point, set the calling convention appropriate to the hardware shader stage. The action here
// depends on the pipeline type.
SetCallingConv(ShaderStageCompute, CallingConv::AMDGPU_CS);
SetCallingConv(ShaderStageFragment, CallingConv::AMDGPU_PS);
if (hasTs && m_hasGs)
{
// TS-GS pipeline
SetCallingConv(ShaderStageVertex, CallingConv::AMDGPU_LS);
SetCallingConv(ShaderStageTessControl, CallingConv::AMDGPU_HS);
SetCallingConv(ShaderStageTessEval, CallingConv::AMDGPU_ES);
SetCallingConv(ShaderStageGeometry, CallingConv::AMDGPU_GS);
SetCallingConv(ShaderStageCopyShader, CallingConv::AMDGPU_VS);
}
else if (hasTs)
{
// TS-only pipeline
SetCallingConv(ShaderStageVertex, CallingConv::AMDGPU_LS);
SetCallingConv(ShaderStageTessControl, CallingConv::AMDGPU_HS);
SetCallingConv(ShaderStageTessEval, CallingConv::AMDGPU_VS);
}
else if (m_hasGs)
{
// GS-only pipeline
SetCallingConv(ShaderStageVertex, CallingConv::AMDGPU_ES);
SetCallingConv(ShaderStageGeometry, CallingConv::AMDGPU_GS);
SetCallingConv(ShaderStageCopyShader, CallingConv::AMDGPU_VS);
}
else if (m_hasVs)
{
// VS-FS pipeine
SetCallingConv(ShaderStageVertex, CallingConv::AMDGPU_VS);
}
}
// =====================================================================================================================
// Merge shaders and set calling convention for the entry-point of each each shader (GFX9+)
void PatchPreparePipelineAbi::MergeShaderAndSetCallingConvs(
Module& module) // [in] LLVM module
{
LLPC_ASSERT(m_gfxIp.major >= 9);
const bool hasTs = (m_hasTcs || m_hasTes);
// NOTE: For each entry-point, set the calling convention appropriate to the hardware shader stage. The action here
// depends on the pipeline type, and, for GFX9+, may involve merging shaders.
SetCallingConv(ShaderStageCompute, CallingConv::AMDGPU_CS);
SetCallingConv(ShaderStageFragment, CallingConv::AMDGPU_PS);
if (m_pContext->IsGraphics())
{
ShaderMerger shaderMerger(m_pContext, m_pPipelineShaders);
#if LLPC_BUILD_GFX10
const bool enableNgg = m_pContext->GetNggControl()->enableNgg;
#endif
if (hasTs && m_hasGs)
{
// TS-GS pipeline
if (m_hasTcs)
{
auto pLsEntryPoint = m_pPipelineShaders->GetEntryPoint(ShaderStageVertex);
auto pHsEntryPoint = m_pPipelineShaders->GetEntryPoint(ShaderStageTessControl);
if (pHsEntryPoint != nullptr)
{
auto pLsHsEntryPoint = shaderMerger.GenerateLsHsEntryPoint(pLsEntryPoint, pHsEntryPoint);
pLsHsEntryPoint->setCallingConv(CallingConv::AMDGPU_HS);
}
}
auto pEsEntryPoint = m_pPipelineShaders->GetEntryPoint(ShaderStageTessEval);
auto pGsEntryPoint = m_pPipelineShaders->GetEntryPoint(ShaderStageGeometry);
#if LLPC_BUILD_GFX10
if (enableNgg)
{
if (pGsEntryPoint != nullptr)
{
auto pCopyShaderEntryPoint = m_pPipelineShaders->GetEntryPoint(ShaderStageCopyShader);
auto pPrimShaderEntryPoint =
shaderMerger.BuildPrimShader(pEsEntryPoint, pGsEntryPoint, pCopyShaderEntryPoint);
pPrimShaderEntryPoint->setCallingConv(CallingConv::AMDGPU_GS);
}
}
else
#endif
{
if (pGsEntryPoint != nullptr)
{
auto pEsGsEntryPoint = shaderMerger.GenerateEsGsEntryPoint(pEsEntryPoint, pGsEntryPoint);
pEsGsEntryPoint->setCallingConv(CallingConv::AMDGPU_GS);
}
SetCallingConv(ShaderStageCopyShader, CallingConv::AMDGPU_VS);
}
}
else if (hasTs)
{
// TS-only pipeline
if (m_hasTcs)
{
auto pLsEntryPoint = m_pPipelineShaders->GetEntryPoint(ShaderStageVertex);
auto pHsEntryPoint = m_pPipelineShaders->GetEntryPoint(ShaderStageTessControl);
if (pHsEntryPoint != nullptr)
{
auto pLsHsEntryPoint = shaderMerger.GenerateLsHsEntryPoint(pLsEntryPoint, pHsEntryPoint);
pLsHsEntryPoint->setCallingConv(CallingConv::AMDGPU_HS);
}
}
#if LLPC_BUILD_GFX10
if (enableNgg)
{
// If NGG is enabled, ES-GS merged shader should be present even if GS is absent
auto pEsEntryPoint = m_pPipelineShaders->GetEntryPoint(ShaderStageTessEval);
if (pEsEntryPoint != nullptr)
{
auto pPrimShaderEntryPoint = shaderMerger.BuildPrimShader(pEsEntryPoint, nullptr, nullptr);
pPrimShaderEntryPoint->setCallingConv(CallingConv::AMDGPU_GS);
}
}
else
#endif
{
SetCallingConv(ShaderStageTessEval, CallingConv::AMDGPU_VS);
}
}
else if (m_hasGs)
{
// GS-only pipeline
auto pEsEntryPoint = m_pPipelineShaders->GetEntryPoint(ShaderStageVertex);
auto pGsEntryPoint = m_pPipelineShaders->GetEntryPoint(ShaderStageGeometry);
#if LLPC_BUILD_GFX10
if (enableNgg)
{
if (pGsEntryPoint != nullptr)
{
auto pCopyShaderEntryPoint = m_pPipelineShaders->GetEntryPoint(ShaderStageCopyShader);
auto pPrimShaderEntryPoint =
shaderMerger.BuildPrimShader(pEsEntryPoint, pGsEntryPoint, pCopyShaderEntryPoint);
pPrimShaderEntryPoint->setCallingConv(CallingConv::AMDGPU_GS);
}
}
else
#endif
{
if (pGsEntryPoint != nullptr)
{
auto pEsGsEntryPoint = shaderMerger.GenerateEsGsEntryPoint(pEsEntryPoint, pGsEntryPoint);
pEsGsEntryPoint->setCallingConv(CallingConv::AMDGPU_GS);
}
SetCallingConv(ShaderStageCopyShader, CallingConv::AMDGPU_VS);
}
}
else if (m_hasVs)
{
// VS_FS pipeline
#if LLPC_BUILD_GFX10
if (enableNgg)
{
// If NGG is enabled, ES-GS merged shader should be present even if GS is absent
auto pEsEntryPoint = m_pPipelineShaders->GetEntryPoint(ShaderStageVertex);
if (pEsEntryPoint != nullptr)
{
auto pPrimShaderEntryPoint = shaderMerger.BuildPrimShader(pEsEntryPoint, nullptr, nullptr);
pPrimShaderEntryPoint->setCallingConv(CallingConv::AMDGPU_GS);
}
}
else
#endif
{
SetCallingConv(ShaderStageVertex, CallingConv::AMDGPU_VS);
}
}
}
}
// =====================================================================================================================
// Set calling convention on a particular API shader stage, if that stage has a shader
void PatchPreparePipelineAbi::SetCallingConv(
ShaderStage shaderStage, // Shader stage
CallingConv::ID callingConv) // Calling convention to set it to
{
auto pEntryPoint = m_pPipelineShaders->GetEntryPoint(shaderStage);
if (pEntryPoint != nullptr)
{
pEntryPoint->setCallingConv(callingConv);
}
}
// =====================================================================================================================
// Set ABI-specified entrypoint name for each shader
void PatchPreparePipelineAbi::SetAbiEntryNames(
Module& module) // [in] LLVM module
{
for (auto& func : module)
{
if (func.empty() == false)
{
auto callingConv = func.getCallingConv();
auto entryStage = Util::Abi::PipelineSymbolType::CsMainEntry;
switch (callingConv)
{
case CallingConv::AMDGPU_CS:
entryStage = Util::Abi::PipelineSymbolType::CsMainEntry;
break;
case CallingConv::AMDGPU_PS:
entryStage = Util::Abi::PipelineSymbolType::PsMainEntry;
break;
case CallingConv::AMDGPU_VS:
entryStage = Util::Abi::PipelineSymbolType::VsMainEntry;
break;
case CallingConv::AMDGPU_GS:
entryStage = Util::Abi::PipelineSymbolType::GsMainEntry;
break;
case CallingConv::AMDGPU_ES:
entryStage = Util::Abi::PipelineSymbolType::EsMainEntry;
break;
case CallingConv::AMDGPU_HS:
entryStage = Util::Abi::PipelineSymbolType::HsMainEntry;
break;
case CallingConv::AMDGPU_LS:
entryStage = Util::Abi::PipelineSymbolType::LsMainEntry;
break;
default:
continue;
}
const char* pEntryName = Util::Abi::PipelineAbiSymbolNameStrings[static_cast<uint32_t>(entryStage)];
func.setName(pEntryName);
}
}
}
// =====================================================================================================================
// Add ABI metadata
void PatchPreparePipelineAbi::AddAbiMetadata(
Module& module) // [in] LLVM module
{
if (m_gfxIp.major <= 8)
{
Gfx6::ConfigBuilder configBuilder(&module);
configBuilder.BuildPalMetadata();
}
else
{
Gfx9::ConfigBuilder configBuilder(&module);
configBuilder.BuildPalMetadata();
}
}
// =====================================================================================================================
// Initializes the pass
INITIALIZE_PASS(PatchPreparePipelineAbi, DEBUG_TYPE, "Patch LLVM for preparing pipeline ABI", false, false)
| 38.843602 | 120 | 0.576135 | [
"geometry"
] |
446fa4311f6ca706be61ef6aa7d9f5a3a352e503 | 5,393 | cc | C++ | tools/cildissector/cildissector/cil_parser.cc | sodium24/CIL | 8b65d39ff6e9ca56e73708a4051ba37fbcb3c8ab | [
"MIT"
] | null | null | null | tools/cildissector/cildissector/cil_parser.cc | sodium24/CIL | 8b65d39ff6e9ca56e73708a4051ba37fbcb3c8ab | [
"MIT"
] | null | null | null | tools/cildissector/cildissector/cil_parser.cc | sodium24/CIL | 8b65d39ff6e9ca56e73708a4051ba37fbcb3c8ab | [
"MIT"
] | null | null | null | /*
* MIT License
*
* Copyright (c) 2019 Malcolm Stagg
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
* This file is a part of the CIRN Interaction Language.
*/
#include "cil_parser.h"
#include <sstream>
#include <google/protobuf/text_format.h>
using namespace std;
using namespace google::protobuf;
void GetFieldInfo(const Message& m, vector<FieldInfo>& field_info, const string& prefix)
{
const Descriptor * desc = m.GetDescriptor();
const Reflection * refl = m.GetReflection();
MessageFactory * factory = refl->GetMessageFactory();
int field_count = desc->field_count();
for(int i=0; i<field_count; i++)
{
const FieldDescriptor * field = desc->field(i);
FieldInfo info;
info.name = field->name();
info.path = prefix + field->name();
info.type = field->cpp_type_name();
info.repeated = field->is_repeated();
field_info.push_back(info);
if (field->type() == FieldDescriptor::TYPE_MESSAGE)
{
std::string new_prefix = info.path + ".";
if (!field->is_repeated()) {
string new_prefix = info.path + ".";
const Message &message_field = refl->GetMessage(m, field);
GetFieldInfo(message_field, field_info, new_prefix);
}
else
{
string new_prefix = info.path + ".";
const Descriptor * child_desc = field->message_type();
const Message * message_field = factory->GetPrototype(child_desc);
GetFieldInfo(*message_field, field_info, new_prefix);
}
}
}
}
void GetFieldValues(const Message& m, vector<FieldTreeNode>& field_values, const string& prefix, int& id, int parent_id)
{
const Descriptor * desc = m.GetDescriptor();
const Reflection * refl = m.GetReflection();
FieldTreeNode info;
info.parent_id = parent_id;
// Start off the tree with a JSON representation of the entire message
if (parent_id < 0)
{
info.name = "";
info.path = prefix;
info.type = "message";
info.repeated = false;
info.id = id++;
info.value = GetJSON(m);
field_values.push_back(info);
}
TextFormat::Printer printer;
printer.SetSingleLineMode(true);
printer.SetHideUnknownFields(false);
std::vector<const FieldDescriptor *> field_list;
refl->ListFields(m, &field_list);
int field_count = field_list.size();
for(int i=0; i<field_count; i++)
{
const FieldDescriptor * field = field_list[i];
FieldTreeNode info;
info.parent_id = parent_id;
info.name = field->name();
info.path = prefix + field->name();
info.type = field->cpp_type_name();
info.repeated = field->is_repeated();
if (field->is_repeated())
{
int field_size = refl->FieldSize(m, field);
for (int index=0; index<field_size; index++)
{
info.id = id++;
printer.PrintFieldValueToString(m, field, index, &info.value);
field_values.push_back(info);
if (field->type() == FieldDescriptor::TYPE_MESSAGE)
{
string new_prefix = info.path + ".";
const Message &message_field = refl->GetRepeatedMessage(m, field, index);
GetFieldValues(message_field, field_values, new_prefix, id, info.id);
}
}
}
else
{
info.id = id++;
printer.PrintFieldValueToString(m, field, -1, &info.value);
field_values.push_back(info);
if (field->type() == FieldDescriptor::TYPE_MESSAGE)
{
string new_prefix = info.path + ".";
const Message &message_field = refl->GetMessage(m, field);
GetFieldValues(message_field, field_values, new_prefix, id, info.id);
}
}
}
}
std::string GetJSON(const google::protobuf::Message& m)
{
string json_string;
util::JsonOptions opts;
opts.preserve_proto_field_names = true;
util::MessageToJsonString(m, &json_string, opts);
return json_string;
}
| 34.793548 | 121 | 0.606712 | [
"vector"
] |
4475db5ac3f2b8fa91d214a62a741b1ff81ca587 | 30,091 | cpp | C++ | src/test/rpc/KeyGeneration_test.cpp | MUSOChain/MUSO | 6301be50a570e3f49cf941d9e4979110b5a08351 | [
"BSL-1.0"
] | 2 | 2021-03-19T06:33:52.000Z | 2021-03-24T08:16:38.000Z | src/test/rpc/KeyGeneration_test.cpp | MUSOChain/MUSO | 6301be50a570e3f49cf941d9e4979110b5a08351 | [
"BSL-1.0"
] | null | null | null | src/test/rpc/KeyGeneration_test.cpp | MUSOChain/MUSO | 6301be50a570e3f49cf941d9e4979110b5a08351 | [
"BSL-1.0"
] | null | null | null | //------------------------------------------------------------------------------
/*
This file is part of MUSO: https://github.com/MUSO/MUSO
Copyright (c) 2015 MUSO Labs Inc.
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
//==============================================================================
#include <MUSO/basics/StringUtilities.h>
#include <MUSO/json/json_value.h>
#include <MUSO/json/json_writer.h>
#include <MUSO/protocol/ErrorCodes.h>
#include <MUSO/protocol/jss.h>
#include <MUSO/rpc/handlers/WalletPropose.h>
#include <MUSO/rpc/impl/RPCHelpers.h>
#include <test/jtx/TestSuite.h>
namespace MUSO {
namespace RPC {
struct key_strings
{
char const* account_id;
char const* master_key;
char const* master_seed;
char const* master_seed_hex;
char const* public_key;
char const* public_key_hex;
char const* secret_key_hex;
char const* passphrase;
char const* passphrase_warning;
};
namespace common {
static char const* passphrase = "REINDEER FLOTILLA";
static char const* master_key =
"SCAT BERN ISLE FOR ROIL BUS SOAK AQUA FREE FOR DRAM BRIG";
static char const* master_seed = "snMwVWs2hZzfDUF3p2tHZ3EgmyhFs";
static char const* master_seed_hex = "BE6A670A19B209E112146D0A7ED2AAD7";
} // namespace common
static key_strings const secp256k1_strings = {
"r4Vtj2jrfmTVZGfSP3gH9hQPMqFPQFin8f",
common::master_key,
common::master_seed,
common::master_seed_hex,
"aBQxK2YFNqzmAaXNczYcjqDjfiKkLsJUizsr1UBf44RCF8FHdrmX",
"038AAE247B2344B1837FBED8F57389C8C11774510A3F7D784F2A09F0CB6843236C",
"1949ECD889EA71324BC7A30C8E81F4E93CB73EE19D59E9082111E78CC3DDABC2",
common::passphrase,
"This wallet was generated using a user-supplied "
"passphrase that has low entropy and is vulnerable "
"to brute-force attacks.",
};
static key_strings const ed25519_strings = {
"r4qV6xTXerqaZav3MJfSY79ynmc1BSBev1",
common::master_key,
common::master_seed,
common::master_seed_hex,
"aKEQmgLMyZPMruJFejUuedp169LgW6DbJt1rej1DJ5hWUMH4pHJ7",
"ED54C3F5BEDA8BD588B203D23A27398FAD9D20F88A974007D6994659CD7273FE1D",
"77AAED2698D56D6676323629160F4EEF21CFD9EE3D0745CC78FA291461F98278",
common::passphrase,
"This wallet was generated using a user-supplied "
"passphrase that has low entropy and is vulnerable "
"to brute-force attacks.",
};
static key_strings const strong_brain_strings = {
"rBcvXmNb7KPkNdMkpckdWPpbvkWgcV3nir",
"TED AVON CAVE HOUR BRAG JEFF RIFT NEAL TOLD FAT SEW SAN",
"shKdhWka8hS7Es3bpctCZXBiAwfUN",
"74BA8389B44F98CF41E795CD91F9C93F",
"aBRL2sqVuzrsM6zikPB4v8UBHGn1aKkrsxhYEffhcQxB2LKyywE5",
"03BD334FB9E06C58D69603E9922686528B18A754BC2F2E1ADA095FFE67DE952C64",
"84262FB16AA25BE407174C7EDAB531220C30FA4D8A28AA9D564673FB3D34502C",
"A4yKIRGdzrw0YQ$2%TFKYG9HP*&ok^!sy7E@RwICs",
"This wallet was generated using a user-supplied "
"passphrase. It may be vulnerable to brute-force "
"attacks.",
};
class WalletPropose_test : public MUSO::TestSuite
{
public:
void
testRandomWallet(boost::optional<std::string> const& keyType)
{
Json::Value params;
if (keyType)
params[jss::key_type] = *keyType;
Json::Value result = walletPropose(params);
BEAST_EXPECT(!contains_error(result));
BEAST_EXPECT(result.isMember(jss::account_id));
BEAST_EXPECT(result.isMember(jss::master_seed));
BEAST_EXPECT(result.isMember(jss::master_seed_hex));
BEAST_EXPECT(result.isMember(jss::public_key));
BEAST_EXPECT(result.isMember(jss::public_key_hex));
BEAST_EXPECT(result.isMember(jss::key_type));
expectEquals(
result[jss::key_type],
params.isMember(jss::key_type) ? params[jss::key_type]
: "secp256k1");
BEAST_EXPECT(!result.isMember(jss::warning));
std::string seed = result[jss::master_seed].asString();
result = walletPropose(params);
// We asked for two random seeds, so they shouldn't match.
BEAST_EXPECT(result[jss::master_seed].asString() != seed);
}
Json::Value
testSecretWallet(Json::Value const& params, key_strings const& s)
{
Json::Value result = walletPropose(params);
BEAST_EXPECT(!contains_error(result));
expectEquals(result[jss::account_id], s.account_id);
expectEquals(result[jss::master_seed], s.master_seed);
expectEquals(result[jss::master_seed_hex], s.master_seed_hex);
expectEquals(result[jss::public_key], s.public_key);
expectEquals(result[jss::public_key_hex], s.public_key_hex);
expectEquals(
result[jss::key_type],
params.isMember(jss::key_type) ? params[jss::key_type]
: "secp256k1");
return result;
}
void
testSeed(
boost::optional<std::string> const& keyType,
key_strings const& strings)
{
testcase("seed");
Json::Value params;
if (keyType)
params[jss::key_type] = *keyType;
params[jss::seed] = strings.master_seed;
auto const wallet = testSecretWallet(params, strings);
BEAST_EXPECT(!wallet.isMember(jss::warning));
}
void
testSeedHex(
boost::optional<std::string> const& keyType,
key_strings const& strings)
{
testcase("seed_hex");
Json::Value params;
if (keyType)
params[jss::key_type] = *keyType;
params[jss::seed_hex] = strings.master_seed_hex;
auto const wallet = testSecretWallet(params, strings);
BEAST_EXPECT(!wallet.isMember(jss::warning));
}
void
testLegacyPassphrase(
char const* value,
boost::optional<std::string> const& keyType,
key_strings const& strings)
{
Json::Value params;
if (keyType)
params[jss::key_type] = *keyType;
params[jss::passphrase] = value;
auto const wallet = testSecretWallet(params, strings);
if (value == strings.passphrase)
BEAST_EXPECT(wallet[jss::warning] == strings.passphrase_warning);
else
BEAST_EXPECT(!wallet.isMember(jss::warning));
}
void
testLegacyPassphrase(
boost::optional<std::string> const& keyType,
key_strings const& strings)
{
testcase("passphrase");
testLegacyPassphrase(strings.passphrase, keyType, strings);
testLegacyPassphrase(strings.master_key, keyType, strings);
testLegacyPassphrase(strings.master_seed, keyType, strings);
testLegacyPassphrase(strings.master_seed_hex, keyType, strings);
}
void
testKeyType(
boost::optional<std::string> const& keyType,
key_strings const& strings)
{
testcase(keyType ? *keyType : "no key_type");
testRandomWallet(keyType);
testSeed(keyType, strings);
testSeedHex(keyType, strings);
testLegacyPassphrase(keyType, strings);
Json::Value params;
if (keyType)
params[jss::key_type] = *keyType;
params[jss::seed] = strings.master_seed;
params[jss::seed_hex] = strings.master_seed_hex;
// Secret fields are mutually exclusive.
BEAST_EXPECT(contains_error(walletPropose(params)));
}
void
testBadInput()
{
testcase("Bad inputs");
// Passing non-strings where strings are required
{
Json::Value params;
params[jss::key_type] = "secp256k1";
params[jss::passphrase] = 20160506;
auto result = walletPropose(params);
BEAST_EXPECT(contains_error(result));
BEAST_EXPECT(
result[jss::error_message] ==
"Invalid field 'passphrase', not string.");
}
{
Json::Value params;
params[jss::key_type] = "secp256k1";
params[jss::seed] = Json::objectValue;
auto result = walletPropose(params);
BEAST_EXPECT(contains_error(result));
BEAST_EXPECT(
result[jss::error_message] ==
"Invalid field 'seed', not string.");
}
{
Json::Value params;
params[jss::key_type] = "ed25519";
params[jss::seed_hex] = Json::arrayValue;
auto result = walletPropose(params);
BEAST_EXPECT(contains_error(result));
BEAST_EXPECT(
result[jss::error_message] ==
"Invalid field 'seed_hex', not string.");
}
// Specifying multiple items at once
{
Json::Value params;
params[jss::key_type] = "secp256k1";
params[jss::passphrase] = common::master_key;
params[jss::seed_hex] = common::master_seed_hex;
params[jss::seed] = common::master_seed;
auto result = walletPropose(params);
BEAST_EXPECT(contains_error(result));
BEAST_EXPECT(
result[jss::error_message] ==
"Exactly one of the following must be specified: passphrase, "
"seed or seed_hex");
}
// Specifying bad key types:
{
Json::Value params;
params[jss::key_type] = "prime256v1";
params[jss::passphrase] = common::master_key;
auto result = walletPropose(params);
BEAST_EXPECT(contains_error(result));
BEAST_EXPECT(result[jss::error_message] == "Invalid parameters.");
}
{
Json::Value params;
params[jss::key_type] = Json::objectValue;
params[jss::seed_hex] = common::master_seed_hex;
auto result = walletPropose(params);
BEAST_EXPECT(contains_error(result));
BEAST_EXPECT(
result[jss::error_message] ==
"Invalid field 'key_type', not string.");
}
{
Json::Value params;
params[jss::key_type] = Json::arrayValue;
params[jss::seed] = common::master_seed;
auto result = walletPropose(params);
BEAST_EXPECT(contains_error(result));
BEAST_EXPECT(
result[jss::error_message] ==
"Invalid field 'key_type', not string.");
}
}
void
testKeypairForSignature(
boost::optional<std::string> keyType,
key_strings const& strings)
{
testcase(
"keypairForSignature - " + (keyType ? *keyType : "no key_type"));
auto const publicKey = parseBase58<PublicKey>(
TokenType::AccountPublic, strings.public_key);
BEAST_EXPECT(publicKey);
if (!keyType)
{
{
Json::Value params;
Json::Value error;
params[jss::secret] = strings.master_seed;
auto ret = keypairForSignature(params, error);
BEAST_EXPECT(!contains_error(error));
BEAST_EXPECT(ret.first.size() != 0);
BEAST_EXPECT(ret.first == publicKey);
}
{
Json::Value params;
Json::Value error;
params[jss::secret] = strings.master_seed_hex;
auto ret = keypairForSignature(params, error);
BEAST_EXPECT(!contains_error(error));
BEAST_EXPECT(ret.first.size() != 0);
BEAST_EXPECT(ret.first == publicKey);
}
{
Json::Value params;
Json::Value error;
params[jss::secret] = strings.master_key;
auto ret = keypairForSignature(params, error);
BEAST_EXPECT(!contains_error(error));
BEAST_EXPECT(ret.first.size() != 0);
BEAST_EXPECT(ret.first == publicKey);
}
keyType.emplace("secp256k1");
}
{
Json::Value params;
Json::Value error;
params[jss::key_type] = *keyType;
params[jss::seed] = strings.master_seed;
auto ret = keypairForSignature(params, error);
BEAST_EXPECT(!contains_error(error));
BEAST_EXPECT(ret.first.size() != 0);
BEAST_EXPECT(ret.first == publicKey);
}
{
Json::Value params;
Json::Value error;
params[jss::key_type] = *keyType;
params[jss::seed_hex] = strings.master_seed_hex;
auto ret = keypairForSignature(params, error);
BEAST_EXPECT(!contains_error(error));
BEAST_EXPECT(ret.first.size() != 0);
BEAST_EXPECT(ret.first == publicKey);
}
{
Json::Value params;
Json::Value error;
params[jss::key_type] = *keyType;
params[jss::passphrase] = strings.master_key;
auto ret = keypairForSignature(params, error);
BEAST_EXPECT(!contains_error(error));
BEAST_EXPECT(ret.first.size() != 0);
BEAST_EXPECT(ret.first == publicKey);
}
}
void
testKeypairForSignatureErrors()
{
// Specify invalid "secret"
{
Json::Value params;
Json::Value error;
params[jss::secret] = 314159265;
auto ret = keypairForSignature(params, error);
BEAST_EXPECT(contains_error(error));
BEAST_EXPECT(
error[jss::error_message] ==
"Invalid field 'secret', not string.");
BEAST_EXPECT(ret.first.size() == 0);
}
{
Json::Value params;
Json::Value error;
params[jss::secret] = Json::arrayValue;
params[jss::secret].append("array:0");
auto ret = keypairForSignature(params, error);
BEAST_EXPECT(contains_error(error));
BEAST_EXPECT(
error[jss::error_message] ==
"Invalid field 'secret', not string.");
BEAST_EXPECT(ret.first.size() == 0);
}
{
Json::Value params;
Json::Value error;
params[jss::secret] = Json::objectValue;
params[jss::secret]["string"] = "string";
params[jss::secret]["number"] = 702;
auto ret = keypairForSignature(params, error);
BEAST_EXPECT(contains_error(error));
BEAST_EXPECT(ret.first.size() == 0);
BEAST_EXPECT(
error[jss::error_message] ==
"Invalid field 'secret', not string.");
}
// Specify "secret" and "key_type"
{
Json::Value params;
Json::Value error;
params[jss::key_type] = "ed25519";
params[jss::secret] = common::master_seed;
auto ret = keypairForSignature(params, error);
BEAST_EXPECT(contains_error(error));
BEAST_EXPECT(
error[jss::error_message] ==
"The secret field is not allowed if key_type is used.");
BEAST_EXPECT(ret.first.size() == 0);
}
// Specify unknown or bad "key_type"
{
Json::Value params;
Json::Value error;
params[jss::key_type] = "prime256v1";
params[jss::passphrase] = common::master_key;
auto ret = keypairForSignature(params, error);
BEAST_EXPECT(contains_error(error));
BEAST_EXPECT(
error[jss::error_message] == "Invalid field 'key_type'.");
BEAST_EXPECT(ret.first.size() == 0);
}
{
Json::Value params;
Json::Value error;
params[jss::key_type] = Json::objectValue;
params[jss::seed_hex] = common::master_seed_hex;
auto ret = keypairForSignature(params, error);
BEAST_EXPECT(contains_error(error));
BEAST_EXPECT(
error[jss::error_message] ==
"Invalid field 'key_type', not string.");
BEAST_EXPECT(ret.first.size() == 0);
}
{
Json::Value params;
Json::Value error;
params[jss::key_type] = Json::arrayValue;
params[jss::seed] = common::master_seed;
auto ret = keypairForSignature(params, error);
BEAST_EXPECT(contains_error(error));
BEAST_EXPECT(
error[jss::error_message] ==
"Invalid field 'key_type', not string.");
BEAST_EXPECT(ret.first.size() == 0);
}
// Specify non-string passphrase
{ // not a passphrase: number
Json::Value params;
Json::Value error;
params[jss::key_type] = "secp256k1";
params[jss::passphrase] = 1234567890;
auto ret = keypairForSignature(params, error);
BEAST_EXPECT(contains_error(error));
BEAST_EXPECT(
error[jss::error_message] ==
"Invalid field 'passphrase', not string.");
BEAST_EXPECT(ret.first.size() == 0);
}
{ // not a passphrase: object
Json::Value params;
Json::Value error;
params[jss::key_type] = "secp256k1";
params[jss::passphrase] = Json::objectValue;
auto ret = keypairForSignature(params, error);
BEAST_EXPECT(contains_error(error));
BEAST_EXPECT(
error[jss::error_message] ==
"Invalid field 'passphrase', not string.");
BEAST_EXPECT(ret.first.size() == 0);
}
{ // not a passphrase: array
Json::Value params;
Json::Value error;
params[jss::key_type] = "secp256k1";
params[jss::passphrase] = Json::arrayValue;
auto ret = keypairForSignature(params, error);
BEAST_EXPECT(contains_error(error));
BEAST_EXPECT(
error[jss::error_message] ==
"Invalid field 'passphrase', not string.");
BEAST_EXPECT(ret.first.size() == 0);
}
{ // not a passphrase: empty string
Json::Value params;
Json::Value error;
params[jss::key_type] = "secp256k1";
params[jss::passphrase] = "";
auto ret = keypairForSignature(params, error);
BEAST_EXPECT(contains_error(error));
BEAST_EXPECT(error[jss::error_message] == "Disallowed seed.");
BEAST_EXPECT(ret.first.size() == 0);
}
// Specify non-string or invalid seed
{ // not a seed: number
Json::Value params;
Json::Value error;
params[jss::key_type] = "secp256k1";
params[jss::seed] = 443556;
auto ret = keypairForSignature(params, error);
BEAST_EXPECT(contains_error(error));
BEAST_EXPECT(
error[jss::error_message] ==
"Invalid field 'seed', not string.");
BEAST_EXPECT(ret.first.size() == 0);
}
{ // not a string: object
Json::Value params;
Json::Value error;
params[jss::key_type] = "secp256k1";
params[jss::seed] = Json::objectValue;
auto ret = keypairForSignature(params, error);
BEAST_EXPECT(contains_error(error));
BEAST_EXPECT(
error[jss::error_message] ==
"Invalid field 'seed', not string.");
BEAST_EXPECT(ret.first.size() == 0);
}
{ // not a string: array
Json::Value params;
Json::Value error;
params[jss::key_type] = "secp256k1";
params[jss::seed] = Json::arrayValue;
auto ret = keypairForSignature(params, error);
BEAST_EXPECT(contains_error(error));
BEAST_EXPECT(
error[jss::error_message] ==
"Invalid field 'seed', not string.");
BEAST_EXPECT(ret.first.size() == 0);
}
{ // not a seed: empty
Json::Value params;
Json::Value error;
params[jss::key_type] = "secp256k1";
params[jss::seed] = "";
auto ret = keypairForSignature(params, error);
BEAST_EXPECT(contains_error(error));
BEAST_EXPECT(error[jss::error_message] == "Disallowed seed.");
BEAST_EXPECT(ret.first.size() == 0);
}
{ // not a seed: invalid characters
Json::Value params;
Json::Value error;
params[jss::key_type] = "secp256k1";
params[jss::seed] = "s M V s h z D F p t Z E m h s";
auto ret = keypairForSignature(params, error);
BEAST_EXPECT(contains_error(error));
BEAST_EXPECT(error[jss::error_message] == "Disallowed seed.");
BEAST_EXPECT(ret.first.size() == 0);
}
{ // not a seed: random string
Json::Value params;
Json::Value error;
params[jss::key_type] = "secp256k1";
params[jss::seed] = "pnnjkbnobnml43679nbvjdsklnbjs";
auto ret = keypairForSignature(params, error);
BEAST_EXPECT(contains_error(error));
BEAST_EXPECT(error[jss::error_message] == "Disallowed seed.");
BEAST_EXPECT(ret.first.size() == 0);
}
// Specify non-string or invalid seed_hex
{ // not a string: number
Json::Value params;
Json::Value error;
params[jss::key_type] = "secp256k1";
params[jss::seed_hex] = 443556;
auto ret = keypairForSignature(params, error);
BEAST_EXPECT(contains_error(error));
BEAST_EXPECT(
error[jss::error_message] ==
"Invalid field 'seed_hex', not string.");
BEAST_EXPECT(ret.first.size() == 0);
}
{ // not a string: object
Json::Value params;
Json::Value error;
params[jss::key_type] = "secp256k1";
params[jss::seed_hex] = Json::objectValue;
auto ret = keypairForSignature(params, error);
BEAST_EXPECT(contains_error(error));
BEAST_EXPECT(
error[jss::error_message] ==
"Invalid field 'seed_hex', not string.");
BEAST_EXPECT(ret.first.size() == 0);
}
{ // not a string: array
Json::Value params;
Json::Value error;
params[jss::key_type] = "secp256k1";
params[jss::seed_hex] = Json::arrayValue;
auto ret = keypairForSignature(params, error);
BEAST_EXPECT(contains_error(error));
BEAST_EXPECT(
error[jss::error_message] ==
"Invalid field 'seed_hex', not string.");
BEAST_EXPECT(ret.first.size() == 0);
}
{ // empty
Json::Value params;
Json::Value error;
params[jss::key_type] = "secp256k1";
params[jss::seed_hex] = "";
auto ret = keypairForSignature(params, error);
BEAST_EXPECT(contains_error(error));
BEAST_EXPECT(error[jss::error_message] == "Disallowed seed.");
BEAST_EXPECT(ret.first.size() == 0);
}
{ // short
Json::Value params;
Json::Value error;
params[jss::key_type] = "secp256k1";
params[jss::seed_hex] = "A670A19B";
auto ret = keypairForSignature(params, error);
BEAST_EXPECT(contains_error(error));
BEAST_EXPECT(error[jss::error_message] == "Disallowed seed.");
BEAST_EXPECT(ret.first.size() == 0);
}
{ // not hex
Json::Value params;
Json::Value error;
params[jss::key_type] = "secp256k1";
params[jss::seed_hex] = common::passphrase;
auto ret = keypairForSignature(params, error);
BEAST_EXPECT(contains_error(error));
BEAST_EXPECT(error[jss::error_message] == "Disallowed seed.");
BEAST_EXPECT(ret.first.size() == 0);
}
{ // overlong
Json::Value params;
Json::Value error;
params[jss::key_type] = "secp256k1";
params[jss::seed_hex] =
"BE6A670A19B209E112146D0A7ED2AAD72567D0FC913";
auto ret = keypairForSignature(params, error);
BEAST_EXPECT(contains_error(error));
BEAST_EXPECT(error[jss::error_message] == "Disallowed seed.");
BEAST_EXPECT(ret.first.size() == 0);
}
}
void
testMUSOLibEd25519()
{
testcase("MUSO-lib encoded Ed25519 keys");
auto test = [this](char const* seed, char const* addr) {
{
Json::Value params;
Json::Value error;
params[jss::passphrase] = seed;
auto ret = keypairForSignature(params, error);
BEAST_EXPECT(!contains_error(error));
BEAST_EXPECT(ret.first.size() != 0);
BEAST_EXPECT(toBase58(calcAccountID(ret.first)) == addr);
}
{
Json::Value params;
Json::Value error;
params[jss::key_type] = "secp256k1";
params[jss::passphrase] = seed;
auto ret = keypairForSignature(params, error);
BEAST_EXPECT(contains_error(error));
BEAST_EXPECT(
error[jss::error_message] ==
"Specified seed is for an Ed25519 wallet.");
}
{
Json::Value params;
Json::Value error;
params[jss::key_type] = "ed25519";
params[jss::seed] = seed;
auto ret = keypairForSignature(params, error);
BEAST_EXPECT(!contains_error(error));
BEAST_EXPECT(ret.first.size() != 0);
BEAST_EXPECT(toBase58(calcAccountID(ret.first)) == addr);
}
{
Json::Value params;
Json::Value error;
params[jss::key_type] = "secp256k1";
params[jss::seed] = seed;
auto ret = keypairForSignature(params, error);
BEAST_EXPECT(contains_error(error));
BEAST_EXPECT(
error[jss::error_message] ==
"Specified seed is for an Ed25519 wallet.");
}
};
test(
"sEdVWZmeUDgQdMEFKTK9kYVX71FKB7o",
"r34XnDB2zS11NZ1wKJzpU1mjWExGVugTaQ");
test(
"sEd7zJoVnqg1FxB9EuaHC1AB5UPfHWz",
"rDw51qRrBEeMw7Na1Nh79LN7HYZDo7nZFE");
test(
"sEdSxVntbihdLyabbfttMCqsaaucVR9",
"rwiyBDfAYegXZyaQcN2L1vAbKRYn2wNFMq");
test(
"sEdSVwJjEXTYCztqDK4JD9WByH3otDX",
"rQJ4hZzNGkLQhLtKPCmu1ywEw1ai2vgUJN");
test(
"sEdV3jXjKuUoQTSr1Rb4yw8Kyn9r46U",
"rERRw2Pxbau4tevE61V5vZUwD7Rus5Y6vW");
test(
"sEdVeUZjuYT47Uy51FQCnzivsuWyiwB",
"rszewT5gRjUgWNEmnfMjvVYzJCkhvWY32i");
test(
"sEd7MHTewdw4tFYeS7rk7XT4qHiA9jH",
"rBB2rvnf4ztwjgNhinFXQJ91nAZjkFgR3p");
test(
"sEd7A5jFBSdWbNeKGriQvLr1thBScJh",
"rLAXz8Nz7aDivz7PwThsLFqaKrizepNCdA");
test(
"sEdVPU9M2uyzVNT4Yb5Dn4tUtYjbFAw",
"rHbHRFPCxD5fnn98TBzsQHJ7SsRq7eHkRj");
test(
"sEdVfF2zhAmS8gfMYzJ4yWBMeR4BZKc",
"r9PsneKHcAE7kUfiTixomM5Mnwi28tCc7h");
test(
"sEdTjRtcsQkwthDXUSLi9DHNyJcR8GW",
"rM4soF4XS3wZrmLurvE6ZmudG16Lk5Dur5");
test(
"sEdVNKeu1Lhpfh7Nf6tRDbxnmMyZ4Dv",
"r4ZwJxq6FDtWjapDtCGhjG6mtNm1nWdJcD");
test(
"sEd7bK4gf5BHJ1WbaEWx8pKMA9MLHpC",
"rD6tnn51m4o1uXeEK9CFrZ3HR7DcFhiYnp");
test(
"sEd7jCh3ppnQMsLdGcZ6TZayZaHhBLg",
"rTcBkiRQ1EfFQ4FCCwqXNHpn1yUTAACkj");
test(
"sEdTFJezurQwSJAbkLygj2gQXBut2wh",
"rnXaMacNbRwcJddbbPbqdcpSUQcfzFmrR8");
test(
"sEdSWajfQAAWFuDvVZF3AiGucReByLt",
"rBJtow6V3GTdsWMamrxetRDwWs6wwTxcKa");
}
void
run() override
{
testKeyType(boost::none, secp256k1_strings);
testKeyType(std::string("secp256k1"), secp256k1_strings);
testKeyType(std::string("ed25519"), ed25519_strings);
testKeyType(std::string("secp256k1"), strong_brain_strings);
testBadInput();
testKeypairForSignature(boost::none, secp256k1_strings);
testKeypairForSignature(std::string("secp256k1"), secp256k1_strings);
testKeypairForSignature(std::string("ed25519"), ed25519_strings);
testKeypairForSignature(std::string("secp256k1"), strong_brain_strings);
testMUSOLibEd25519();
testKeypairForSignatureErrors();
}
};
BEAST_DEFINE_TESTSUITE(WalletPropose, MUSO_basics, MUSO);
} // namespace RPC
} // namespace MUSO
| 34.350457 | 80 | 0.567844 | [
"object"
] |
447ac716aa7a347ad6ee942e4e6f9cd1d4adc726 | 16,171 | cpp | C++ | Tools/crunch/crunch/main.cpp | fountainment/cherry-soda | 3dd0eb7d0b5503ba572ff2104990856ef7a87495 | [
"MIT"
] | 27 | 2020-01-16T08:20:54.000Z | 2022-03-29T20:40:15.000Z | Tools/crunch/crunch/main.cpp | fountainment/cherry-soda | 3dd0eb7d0b5503ba572ff2104990856ef7a87495 | [
"MIT"
] | 10 | 2022-01-07T14:07:27.000Z | 2022-03-19T18:13:44.000Z | Tools/crunch/crunch/main.cpp | fountainment/cherry-soda | 3dd0eb7d0b5503ba572ff2104990856ef7a87495 | [
"MIT"
] | 6 | 2019-12-27T10:04:07.000Z | 2021-12-15T17:29:24.000Z | /*
MIT License
Copyright (c) 2017 Chevy Ray Johnston
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
crunch - command line texture packer
====================================
usage:
crunch [OUTPUT] [INPUT1,INPUT2,INPUT3...] [OPTIONS...]
example:
crunch bin/atlases/atlas assets/characters,assets/tiles -p -t -v -u -r
options:
-d --default use default settings (-x -p -t -u)
-x --xml saves the atlas data as a .xml file
-b --binary saves the atlas data as a .bin file
-j --json saves the atlas data as a .json file
-p --premultiply premultiplies the pixels of the bitmaps by their alpha channel
-t --trim trims excess transparency off the bitmaps
-v --verbose print to the debug console as the packer works
-f --force ignore the hash, forcing the packer to repack
-u --unique remove duplicate bitmaps from the atlas
-r --rotate enabled rotating bitmaps 90 degrees clockwise when packing
-s# --size# max atlas size (# can be 4096, 2048, 1024, 512, 256, 128, or 64)
-p# --pad# padding between images (# can be from 0 to 16)
binary format:
[int16] num_textures (below block is repeated this many times)
[string] name
[int16] num_images (below block is repeated this many times)
[string] img_name
[int16] img_x
[int16] img_y
[int16] img_width
[int16] img_height
[int16] img_frame_x (if --trim enabled)
[int16] img_frame_y (if --trim enabled)
[int16] img_frame_width (if --trim enabled)
[int16] img_frame_height (if --trim enabled)
[byte] img_rotated (if --rotate enabled)
*/
#include <iostream>
#include <fstream>
#include <streambuf>
#include <sstream>
#include <string>
#include <vector>
#include <algorithm>
#include "tinydir.h"
#include "bitmap.hpp"
#include "packer.hpp"
#include "binary.hpp"
#include "hash.hpp"
#include "str.hpp"
using namespace std;
static int optSize;
static int optPadding;
static bool optXml;
static bool optBinary;
static bool optJson;
static bool optPremultiply;
static bool optTrim;
static bool optVerbose;
static bool optForce;
static bool optUnique;
static bool optRotate;
static vector<Bitmap*> bitmaps;
static vector<Packer*> packers;
static const char* helpMessage =
"usage:\n"
" crunch [OUTPUT] [INPUT1,INPUT2,INPUT3...] [OPTIONS...]\n"
"\n"
"example:\n"
" crunch bin/atlases/atlas assets/characters,assets/tiles -p -t -v -u -r\n"
"\n"
"options:\n"
" -d --default use default settings (-x -p -t -u)\n"
" -x --xml saves the atlas data as a .xml file\n"
" -b --binary saves the atlas data as a .bin file\n"
" -j --json saves the atlas data as a .json file\n"
" -p --premultiply premultiplies the pixels of the bitmaps by their alpha channel\n"
" -t --trim trims excess transparency off the bitmaps\n"
" -v --verbose print to the debug console as the packer works\n"
" -f --force ignore the hash, forcing the packer to repack\n"
" -u --unique remove duplicate bitmaps from the atlas\n"
" -r --rotate enabled rotating bitmaps 90 degrees clockwise when packing\n"
" -s# --size# max atlas size (# can be 4096, 2048, 1024, 512, 256, 128, or 64)\n"
" -p# --pad# padding between images (# can be from 0 to 16)\n"
"\n"
"binary format:\n"
" [int16] num_textures (below block is repeated this many times)\n"
" [string] name\n"
" [int16] num_images (below block is repeated this many times)\n"
" [string] img_name\n"
" [int16] img_x\n"
" [int16] img_y\n"
" [int16] img_width\n"
" [int16] img_height\n"
" [int16] img_frame_x (if --trim enabled)\n"
" [int16] img_frame_y (if --trim enabled)\n"
" [int16] img_frame_width (if --trim enabled)\n"
" [int16] img_frame_height (if --trim enabled)\n"
" [byte] img_rotated (if --rotate enabled)";
static void SplitFileName(const string& path, string* dir, string* name, string* ext)
{
size_t si = path.rfind('/') + 1;
if (si == string::npos)
si = 0;
size_t di = path.rfind('.');
if (dir != nullptr)
{
if (si > 0)
*dir = path.substr(0, si);
else
*dir = "";
}
if (name != nullptr)
{
if (di != string::npos)
*name = path.substr(si, di - si);
else
*name = path.substr(si);
}
if (ext != nullptr)
{
if (di != string::npos)
*ext = path.substr(di);
else
*ext = "";
}
}
static string GetFileName(const string& path)
{
string name;
SplitFileName(path, nullptr, &name, nullptr);
return name;
}
static void LoadBitmap(const string& prefix, const string& path)
{
if (optVerbose)
cout << '\t' << path << endl;
bitmaps.push_back(new Bitmap(path, prefix + GetFileName(path), optPremultiply, optTrim));
}
static void LoadBitmaps(const string& root, const string& prefix)
{
static string dot1 = ".";
static string dot2 = "..";
tinydir_dir dir;
tinydir_open_sorted(&dir, StrToPath(root).data());
for (int i = 0; i < static_cast<int>(dir.n_files); ++i)
{
tinydir_file file;
tinydir_readfile_n(&dir, &file, i);
if (file.is_dir)
{
if (dot1 != PathToStr(file.name) && dot2 != PathToStr(file.name))
LoadBitmaps(PathToStr(file.path), prefix + PathToStr(file.name) + "/");
}
else if (PathToStr(file.extension) == "png")
LoadBitmap(prefix, PathToStr(file.path));
}
tinydir_close(&dir);
}
static void RemoveFile(string file)
{
remove(file.data());
}
static int GetPackSize(const string& str)
{
if (str == "4096")
return 4096;
if (str == "2048")
return 2048;
if (str == "1024")
return 1024;
if (str == "512")
return 512;
if (str == "256")
return 256;
if (str == "128")
return 128;
if (str == "64")
return 64;
cerr << "invalid size: " << str << endl;
exit(EXIT_FAILURE);
return 0;
}
static int GetPadding(const string& str)
{
for (int i = 0; i <= 16; ++i)
if (str == to_string(i))
return i;
cerr << "invalid padding value: " << str << endl;
exit(EXIT_FAILURE);
return 1;
}
int main(int argc, const char* argv[])
{
//Print out passed arguments
for (int i = 0; i < argc; ++i)
cout << argv[i] << ' ';
cout << endl;
if (argc < 3)
{
if (argc == 2) {
string arg = argv[1];
if (arg == "-h") {
cout << helpMessage << endl;
}
}
else {
cerr << "invalid input, expected: \"crunch [OUTPUT] [INPUT1,INPUT2,INPUT3...] [OPTIONS...]\"" << endl;
}
return EXIT_FAILURE;
}
//Get the output directory and name
string outputDir, name;
SplitFileName(argv[1], &outputDir, &name, nullptr);
//Get all the input files and directories
vector<string> inputs;
stringstream ss(argv[2]);
while (ss.good())
{
string inputStr;
getline(ss, inputStr, ',');
inputs.push_back(inputStr);
}
//Get the options
optSize = 4096;
optPadding = 1;
optXml = false;
optBinary = false;
optJson = false;
optPremultiply = false;
optTrim = false;
optVerbose = false;
optForce = false;
optUnique = false;
for (int i = 3; i < argc; ++i)
{
string arg = argv[i];
if (arg == "-d" || arg == "--default")
optXml = optPremultiply = optTrim = optUnique = true;
else if (arg == "-x" || arg == "--xml")
optXml = true;
else if (arg == "-b" || arg == "--binary")
optBinary = true;
else if (arg == "-j" || arg == "--json")
optJson = true;
else if (arg == "-p" || arg == "--premultiply")
optPremultiply = true;
else if (arg == "-t" || arg == "--trim")
optTrim = true;
else if (arg == "-v" || arg == "--verbose")
optVerbose = true;
else if (arg == "-f" || arg == "--force")
optForce = true;
else if (arg == "-u" || arg == "--unique")
optUnique = true;
else if (arg == "-r" || arg == "--rotate")
optRotate = true;
else if (arg.find("--size") == 0)
optSize = GetPackSize(arg.substr(6));
else if (arg.find("-s") == 0)
optSize = GetPackSize(arg.substr(2));
else if (arg.find("--pad") == 0)
optPadding = GetPadding(arg.substr(5));
else if (arg.find("-p") == 0)
optPadding = GetPadding(arg.substr(2));
else
{
cerr << "unexpected argument: " << arg << endl;
return EXIT_FAILURE;
}
}
//Hash the arguments and input directories
size_t newHash = 0;
for (int i = 1; i < argc; ++i)
HashString(newHash, argv[i]);
for (size_t i = 0; i < inputs.size(); ++i)
{
if (inputs[i].rfind('.') == string::npos)
HashFiles(newHash, inputs[i]);
else
HashFile(newHash, inputs[i]);
}
//Load the old hash
size_t oldHash;
if (LoadHash(oldHash, outputDir + name + ".hash"))
{
if (!optForce && newHash == oldHash)
{
cout << "atlas is unchanged: " << name << endl;
return EXIT_SUCCESS;
}
}
/*-d --default use default settings (-x -p -t -u)
-x --xml saves the atlas data as a .xml file
-b --binary saves the atlas data as a .bin file
-j --json saves the atlas data as a .json file
-p --premultiply premultiplies the pixels of the bitmaps by their alpha channel
-t --trim trims excess transparency off the bitmaps
-v --verbose print to the debug console as the packer works
-f --force ignore the hash, forcing the packer to repack
-u --unique remove duplicate bitmaps from the atlas
-r --rotate enabled rotating bitmaps 90 degrees clockwise when packing
-s# --size# max atlas size (# can be 4096, 2048, 1024, 512, or 256)
-p# --pad# padding between images (# can be from 0 to 16)*/
if (optVerbose)
{
cout << "options..." << endl;
cout << "\t--xml: " << (optXml ? "true" : "false") << endl;
cout << "\t--binary: " << (optBinary ? "true" : "false") << endl;
cout << "\t--json: " << (optJson ? "true" : "false") << endl;
cout << "\t--premultiply: " << (optPremultiply ? "true" : "false") << endl;
cout << "\t--trim: " << (optTrim ? "true" : "false") << endl;
cout << "\t--verbose: " << (optVerbose ? "true" : "false") << endl;
cout << "\t--force: " << (optForce ? "true" : "false") << endl;
cout << "\t--unique: " << (optUnique ? "true" : "false") << endl;
cout << "\t--rotate: " << (optRotate ? "true" : "false") << endl;
cout << "\t--size: " << optSize << endl;
cout << "\t--pad: " << optPadding << endl;
}
//Remove old files
RemoveFile(outputDir + name + ".hash");
RemoveFile(outputDir + name + ".bin");
RemoveFile(outputDir + name + ".xml");
RemoveFile(outputDir + name + ".json");
for (size_t i = 0; i < 16; ++i)
RemoveFile(outputDir + name + to_string(i) + ".png");
//Load the bitmaps from all the input files and directories
if (optVerbose)
cout << "loading images..." << endl;
for (size_t i = 0; i < inputs.size(); ++i)
{
if (inputs[i].rfind('.') != string::npos)
LoadBitmap("", inputs[i]);
else
LoadBitmaps(inputs[i], "");
}
//Sort the bitmaps by area
stable_sort(bitmaps.begin(), bitmaps.end(), [](const Bitmap* a, const Bitmap* b) {
return (a->width * a->height) < (b->width * b->height);
});
//Pack the bitmaps
while (!bitmaps.empty())
{
if (optVerbose)
cout << "packing " << bitmaps.size() << " images..." << endl;
auto packer = new Packer(optSize, optSize, optPadding);
packer->Pack(bitmaps, optVerbose, optUnique, optRotate);
packers.push_back(packer);
if (optVerbose)
cout << "finished packing: " << name << to_string(packers.size() - 1) << " (" << packer->width << " x " << packer->height << ')' << endl;
if (packer->bitmaps.empty())
{
cerr << "packing failed, could not fit bitmap: " << (bitmaps.back())->name << endl;
return EXIT_FAILURE;
}
}
//Save the atlas image
for (size_t i = 0; i < packers.size(); ++i)
{
if (optVerbose)
cout << "writing png: " << outputDir << name << to_string(i) << ".png" << endl;
packers[i]->SavePng(outputDir + name + to_string(i) + ".png");
}
//Save the atlas binary
if (optBinary)
{
if (optVerbose)
cout << "writing bin: " << outputDir << name << ".bin" << endl;
ofstream bin(outputDir + name + ".bin", ios::binary);
WriteShort(bin, (int16_t)packers.size());
for (size_t i = 0; i < packers.size(); ++i)
packers[i]->SaveBin(name + to_string(i), bin, optTrim, optRotate);
bin.close();
}
//Save the atlas xml
if (optXml)
{
if (optVerbose)
cout << "writing xml: " << outputDir << name << ".xml" << endl;
ofstream xml(outputDir + name + ".xml");
xml << "<atlas>" << endl;
for (size_t i = 0; i < packers.size(); ++i)
packers[i]->SaveXml(name + to_string(i), xml, optTrim, optRotate);
xml << "</atlas>";
}
//Save the atlas json
if (optJson)
{
if (optVerbose)
cout << "writing json: " << outputDir << name << ".json" << endl;
ofstream json(outputDir + name + ".json");
json << '{' << endl;
json << "\t\"textures\":[" << endl;
for (size_t i = 0; i < packers.size(); ++i)
{
json << "\t\t{" << endl;
packers[i]->SaveJson(name + to_string(i), json, optTrim, optRotate);
json << "\t\t}";
if (i + 1 < packers.size())
json << ',';
json << endl;
}
json << "\t]" << endl;
json << '}';
}
//Save the new hash
SaveHash(newHash, outputDir + name + ".hash");
return EXIT_SUCCESS;
}
| 34.116034 | 149 | 0.534537 | [
"vector"
] |
447bf6385e7cc2d70bcf0dcaa130cff4d3d3969a | 1,577 | cc | C++ | winmods2/Source/TagSet.cc | xtuml/iuml-dumper | a5cd1f8f825b922262a503d86239ce67258a4205 | [
"Apache-2.0"
] | null | null | null | winmods2/Source/TagSet.cc | xtuml/iuml-dumper | a5cd1f8f825b922262a503d86239ce67258a4205 | [
"Apache-2.0"
] | null | null | null | winmods2/Source/TagSet.cc | xtuml/iuml-dumper | a5cd1f8f825b922262a503d86239ce67258a4205 | [
"Apache-2.0"
] | 4 | 2019-03-20T15:13:23.000Z | 2020-09-03T20:46:04.000Z | //
// Filename : TagSet.cc
//
// UK Crown Copyright (c) 2005. All Rights Reserved
//
#include "TagSet.hh"
#include <vector>
#include <algorithm>
#include <functional>
#include <cctype>
#include "iumlapi/TAGS_TagAttachment.hh"
#include "iumlapi/TAGS_TagEnumeration.hh"
#include "iumlapi/TAGS_Tag.hh"
char toLower(char c) { return std::tolower(c); }
MaslGen::TagSet::TagSet( const iUMLAPI::TAGS::TaggedItem& taggedItem )
{
for ( iUMLAPI::TAGS::TagAttachment_Set::const_iterator it = taggedItem.getIsAttachedWithTagAttachmentR2().begin();
it != taggedItem.getIsAttachedWithTagAttachmentR2().end();
++it )
{
std::string name = it->getIsAttachedWithTagR2().getName();
std::transform(name.begin(),name.end(),name.begin(),toLower);
iUMLAPI::TAGS::TagEnumeration enumerate = it->getHasEnumerationDefinedByTagEnumerationR7();
if ( !enumerate.isValid() )
{
tags.insert(std::pair<std::string,std::string>(name,it->getTagValue()));
tagvec.push_back(std::pair<std::string,std::string>(name,it->getTagValue()));
}
else
{
tags.insert(std::pair<std::string,std::string>(name,enumerate.getName()));
tagvec.push_back(std::pair<std::string,std::string>(name,enumerate.getName()));
}
}
}
bool MaslGen::TagSet::hasTag ( const std::string& name ) const
{
return tags.count(name);
}
const std::string& MaslGen::TagSet::getTag ( const std::string& name ) const
{
return tags.find(name)->second;
}
const std::vector<std::pair<std::string,std::string> >& MaslGen::TagSet::getTags() const
{
return tagvec;
}
| 28.672727 | 116 | 0.688015 | [
"vector",
"transform"
] |
447c520415df9820d64483026d60526c46fa21aa | 500 | cpp | C++ | dsalgo/string/lcp.cpp | kagemeka/cpp-algorithms | fdb43a39aa3e8abb90f7058d09cd0951fe198c4e | [
"MIT"
] | null | null | null | dsalgo/string/lcp.cpp | kagemeka/cpp-algorithms | fdb43a39aa3e8abb90f7058d09cd0951fe198c4e | [
"MIT"
] | 2 | 2022-01-07T10:43:26.000Z | 2022-01-07T10:54:34.000Z | dsalgo/string/lcp.cpp | kagemeka/cpp-algorithms | fdb43a39aa3e8abb90f7058d09cd0951fe198c4e | [
"MIT"
] | null | null | null | #include <vector>
#include <cassert>
std::vector<int> lcp_array_kasai(std::vector<int> a, std::vector<int> sa) {
int n = a.size();
assert(n > 0 && (int)sa.size() == n);
std::vector<int> rank(n), lcp(n - 1);
for (int i = 0; i < n; i++) rank[sa[i]] = i;
int h = 0;
for (int i = 0; i < n; i++) {
if (h > 0) --h;
int r = rank[i];
if (r == n - 1) continue;
int j = sa[r + 1];
while (i + h < n && j + h < n && a[i + h] == a[j + h]) ++h;
lcp[r] = h;
}
return lcp;
} | 25 | 75 | 0.464 | [
"vector"
] |
447d046e0608d4433b810bc7f3ec0720cdc36ddc | 988 | cpp | C++ | syncd/PortMap.cpp | vmittal-msft/sonic-sairedis | 6baff35880005aee2854fdcde105c4322c28d04f | [
"Apache-2.0"
] | 50 | 2016-03-23T08:04:44.000Z | 2022-03-25T05:06:16.000Z | syncd/PortMap.cpp | vmittal-msft/sonic-sairedis | 6baff35880005aee2854fdcde105c4322c28d04f | [
"Apache-2.0"
] | 589 | 2016-04-01T04:09:09.000Z | 2022-03-31T00:38:10.000Z | syncd/PortMap.cpp | vmittal-msft/sonic-sairedis | 6baff35880005aee2854fdcde105c4322c28d04f | [
"Apache-2.0"
] | 234 | 2016-03-28T20:59:21.000Z | 2022-03-23T09:26:22.000Z | #include "PortMap.h"
#include "swss/logger.h"
using namespace syncd;
/**
* @brief Port map global map.
*
* WARNING: This object must have global declaration and this exact name since
* external RPC server is linking against this object when in use.
*/
std::map<std::set<int>, std::string> gPortMap;
void PortMap::insert(
_In_ const std::set<int>& laneSet,
_In_ const std::string& name)
{
SWSS_LOG_ENTER();
m_portMap.insert(std::make_pair(laneSet, name));
}
void PortMap::clear()
{
SWSS_LOG_ENTER();
m_portMap.clear();
}
size_t PortMap::size() const
{
SWSS_LOG_ENTER();
return m_portMap.size();
}
const std::map<std::set<int>, std::string>& PortMap::getRawPortMap() const
{
SWSS_LOG_ENTER();
return m_portMap;
};
void PortMap::setGlobalPortMap(
_In_ std::shared_ptr<PortMap> portMap)
{
SWSS_LOG_ENTER();
SWSS_LOG_NOTICE("setting global gPortMap for rpc server");
gPortMap = portMap->getRawPortMap();
}
| 18.296296 | 78 | 0.674089 | [
"object"
] |
44824ca9dd9dc716a8960cb9058d2352cf29cd1c | 9,195 | cc | C++ | tensorflow/core/kernels/data/tf_record_dataset_op_test.cc | yage99/tensorflow | c7fa71b32a3635eb25596ae80d007b41007769c4 | [
"Apache-2.0"
] | 78 | 2020-08-04T12:36:25.000Z | 2022-03-25T04:23:40.000Z | tensorflow/core/kernels/data/tf_record_dataset_op_test.cc | sseung0703/tensorflow | be084bd7a4dd241eb781fc704f57bcacc5c9b6dd | [
"Apache-2.0"
] | 203 | 2019-06-14T23:53:10.000Z | 2022-02-10T02:27:23.000Z | tensorflow/core/kernels/data/tf_record_dataset_op_test.cc | sseung0703/tensorflow | be084bd7a4dd241eb781fc704f57bcacc5c9b6dd | [
"Apache-2.0"
] | 66 | 2020-05-15T10:05:12.000Z | 2022-02-14T07:28:18.000Z | /* Copyright 2019 The TensorFlow Authors. All Rights Reserved.
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
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 "tensorflow/core/kernels/data/tf_record_dataset_op.h"
#include "tensorflow/core/kernels/data/dataset_test_base.h"
namespace tensorflow {
namespace data {
namespace {
constexpr char kNodeName[] = "tf_record_dataset";
class TFRecordDatasetParams : public DatasetParams {
public:
TFRecordDatasetParams(std::vector<tstring> filenames,
CompressionType compression_type, int64 buffer_size,
string node_name)
: DatasetParams({DT_STRING}, {PartialTensorShape({})},
std::move(node_name)),
filenames_(std::move(filenames)),
compression_type_(compression_type),
buffer_size_(buffer_size) {}
std::vector<Tensor> GetInputTensors() const override {
int num_files = filenames_.size();
return {
CreateTensor<tstring>(TensorShape({num_files}), filenames_),
CreateTensor<tstring>(TensorShape({}), {ToString(compression_type_)}),
CreateTensor<int64>(TensorShape({}), {buffer_size_})};
}
Status GetInputNames(std::vector<string>* input_names) const override {
input_names->clear();
*input_names = {
TFRecordDatasetOp::kFileNames,
TFRecordDatasetOp::kCompressionType,
TFRecordDatasetOp::kBufferSize,
};
return Status::OK();
}
Status GetAttributes(AttributeVector* attr_vector) const override {
*attr_vector = {};
return Status::OK();
}
string dataset_type() const override {
return TFRecordDatasetOp::kDatasetType;
}
private:
std::vector<tstring> filenames_;
CompressionType compression_type_;
int64 buffer_size_;
};
class TFRecordDatasetOpTest : public DatasetOpsTestBase {};
Status CreateTestFiles(const std::vector<tstring>& filenames,
const std::vector<std::vector<string>>& contents,
CompressionType compression_type) {
if (filenames.size() != contents.size()) {
return tensorflow::errors::InvalidArgument(
"The number of files does not match with the contents");
}
for (int i = 0; i < filenames.size(); ++i) {
CompressionParams params;
params.output_buffer_size = 10;
params.compression_type = compression_type;
std::vector<absl::string_view> records(contents[i].begin(),
contents[i].end());
TF_RETURN_IF_ERROR(WriteDataToTFRecordFile(filenames[i], records, params));
}
return Status::OK();
}
// Test case 1: multiple text files with ZLIB compression.
TFRecordDatasetParams TFRecordDatasetParams1() {
std::vector<tstring> filenames = {
absl::StrCat(testing::TmpDir(), "/tf_record_ZLIB_1"),
absl::StrCat(testing::TmpDir(), "/tf_record_ZLIB_2")};
std::vector<std::vector<string>> contents = {{"1", "22", "333"},
{"a", "bb", "ccc"}};
CompressionType compression_type = CompressionType::ZLIB;
if (!CreateTestFiles(filenames, contents, compression_type).ok()) {
VLOG(WARNING) << "Failed to create the test files: "
<< absl::StrJoin(filenames, ", ");
}
return TFRecordDatasetParams(filenames,
/*compression_type=*/compression_type,
/*buffer_size=*/10,
/*node_name=*/kNodeName);
}
// Test case 2: multiple text files with GZIP compression.
TFRecordDatasetParams TFRecordDatasetParams2() {
std::vector<tstring> filenames = {
absl::StrCat(testing::TmpDir(), "/tf_record_GZIP_1"),
absl::StrCat(testing::TmpDir(), "/tf_record_GZIP_2")};
std::vector<std::vector<string>> contents = {{"1", "22", "333"},
{"a", "bb", "ccc"}};
CompressionType compression_type = CompressionType::GZIP;
if (!CreateTestFiles(filenames, contents, compression_type).ok()) {
VLOG(WARNING) << "Failed to create the test files: "
<< absl::StrJoin(filenames, ", ");
}
return TFRecordDatasetParams(filenames,
/*compression_type=*/compression_type,
/*buffer_size=*/10,
/*node_name=*/kNodeName);
}
// Test case 3: multiple text files without compression.
TFRecordDatasetParams TFRecordDatasetParams3() {
std::vector<tstring> filenames = {
absl::StrCat(testing::TmpDir(), "/tf_record_UNCOMPRESSED_1"),
absl::StrCat(testing::TmpDir(), "/tf_record_UNCOMPRESSED_2")};
std::vector<std::vector<string>> contents = {{"1", "22", "333"},
{"a", "bb", "ccc"}};
CompressionType compression_type = CompressionType::GZIP;
if (!CreateTestFiles(filenames, contents, compression_type).ok()) {
VLOG(WARNING) << "Failed to create the test files: "
<< absl::StrJoin(filenames, ", ");
}
return TFRecordDatasetParams(filenames,
/*compression_type=*/compression_type,
/*buffer_size=*/10,
/*node_name=*/kNodeName);
}
std::vector<GetNextTestCase<TFRecordDatasetParams>> GetNextTestCases() {
return {
{/*dataset_params=*/TFRecordDatasetParams1(),
/*expected_outputs=*/
CreateTensors<tstring>(
TensorShape({}), {{"1"}, {"22"}, {"333"}, {"a"}, {"bb"}, {"ccc"}})},
{/*dataset_params=*/TFRecordDatasetParams2(),
CreateTensors<tstring>(
TensorShape({}), {{"1"}, {"22"}, {"333"}, {"a"}, {"bb"}, {"ccc"}})},
{/*dataset_params=*/TFRecordDatasetParams3(),
CreateTensors<tstring>(
TensorShape({}), {{"1"}, {"22"}, {"333"}, {"a"}, {"bb"}, {"ccc"}})}};
}
ITERATOR_GET_NEXT_TEST_P(TFRecordDatasetOpTest, TFRecordDatasetParams,
GetNextTestCases())
TEST_F(TFRecordDatasetOpTest, DatasetNodeName) {
auto dataset_params = TFRecordDatasetParams1();
TF_ASSERT_OK(Initialize(dataset_params));
TF_ASSERT_OK(CheckDatasetNodeName(dataset_params.node_name()));
}
TEST_F(TFRecordDatasetOpTest, DatasetTypeString) {
auto dataset_params = TFRecordDatasetParams1();
TF_ASSERT_OK(Initialize(dataset_params));
TF_ASSERT_OK(CheckDatasetTypeString(
name_utils::OpName(TFRecordDatasetOp::kDatasetType)));
}
TEST_F(TFRecordDatasetOpTest, DatasetOutputDtypes) {
auto dataset_params = TFRecordDatasetParams1();
TF_ASSERT_OK(Initialize(dataset_params));
TF_ASSERT_OK(CheckDatasetOutputDtypes({DT_STRING}));
}
TEST_F(TFRecordDatasetOpTest, DatasetOutputShapes) {
auto dataset_params = TFRecordDatasetParams1();
TF_ASSERT_OK(Initialize(dataset_params));
TF_ASSERT_OK(CheckDatasetOutputShapes({PartialTensorShape({})}));
}
TEST_F(TFRecordDatasetOpTest, Cardinality) {
auto dataset_params = TFRecordDatasetParams1();
TF_ASSERT_OK(Initialize(dataset_params));
TF_ASSERT_OK(CheckDatasetCardinality(kUnknownCardinality));
}
TEST_F(TFRecordDatasetOpTest, IteratorOutputDtypes) {
auto dataset_params = TFRecordDatasetParams1();
TF_ASSERT_OK(Initialize(dataset_params));
TF_ASSERT_OK(CheckIteratorOutputDtypes({DT_STRING}));
}
TEST_F(TFRecordDatasetOpTest, IteratorOutputShapes) {
auto dataset_params = TFRecordDatasetParams1();
TF_ASSERT_OK(Initialize(dataset_params));
TF_ASSERT_OK(CheckIteratorOutputShapes({PartialTensorShape({})}));
}
TEST_F(TFRecordDatasetOpTest, IteratorPrefix) {
auto dataset_params = TFRecordDatasetParams1();
TF_ASSERT_OK(Initialize(dataset_params));
TF_ASSERT_OK(CheckIteratorPrefix(name_utils::IteratorPrefix(
TFRecordDatasetOp::kDatasetType, dataset_params.iterator_prefix())));
}
std::vector<IteratorSaveAndRestoreTestCase<TFRecordDatasetParams>>
IteratorSaveAndRestoreTestCases() {
return {
{/*dataset_params=*/TFRecordDatasetParams1(),
/*breakpoints=*/{0, 2, 7},
/*expected_outputs=*/
CreateTensors<tstring>(
TensorShape({}), {{"1"}, {"22"}, {"333"}, {"a"}, {"bb"}, {"ccc"}})},
{/*dataset_params=*/TFRecordDatasetParams2(),
/*breakpoints=*/{0, 2, 7},
CreateTensors<tstring>(
TensorShape({}), {{"1"}, {"22"}, {"333"}, {"a"}, {"bb"}, {"ccc"}})},
{/*dataset_params=*/TFRecordDatasetParams3(),
/*breakpoints=*/{0, 2, 7},
CreateTensors<tstring>(
TensorShape({}), {{"1"}, {"22"}, {"333"}, {"a"}, {"bb"}, {"ccc"}})}};
}
ITERATOR_SAVE_AND_RESTORE_TEST_P(TFRecordDatasetOpTest, TFRecordDatasetParams,
IteratorSaveAndRestoreTestCases())
} // namespace
} // namespace data
} // namespace tensorflow
| 39.805195 | 80 | 0.652311 | [
"vector"
] |
4483e5026c9b8c72e073daebabbdc9adb2def52e | 4,691 | cpp | C++ | Ex1/Tile.cpp | MaximV88/Artificial-Intelligence-Ex1 | 903881e4e035bd473e903db347d99e718f9d149f | [
"MIT"
] | 1 | 2018-07-05T00:33:19.000Z | 2018-07-05T00:33:19.000Z | Ex1/Tile.cpp | MaximV88/Artificial-Intelligence-Ex1 | 903881e4e035bd473e903db347d99e718f9d149f | [
"MIT"
] | null | null | null | Ex1/Tile.cpp | MaximV88/Artificial-Intelligence-Ex1 | 903881e4e035bd473e903db347d99e718f9d149f | [
"MIT"
] | null | null | null | //
// Tile.cpp
// Ex1
//
// Created by Maxim Vainshtein on 14/11/2015.
// Copyright © 2015 Bar-Ilan. All rights reserved.
//
#include "Tile.hpp"
#include <string>
#include <stdexcept>
Tile::Tile(Types eTileType, size_t uiPositionX, size_t uiPositionY) :
eType(eTileType), m_uiPositionX(uiPositionX), m_uiPositionY(uiPositionY) { }
Tile::Tile(const Tile& cTile) :
eType(cTile.eType), m_uiPositionX(cTile.m_uiPositionX), m_uiPositionY(cTile.m_uiPositionY), m_vcNeighbors(cTile.m_vcNeighbors) { }
void Tile::setNeighbors(const std::vector<const Tile *> &vcNeighbors) {
//Copy
m_vcNeighbors = vcNeighbors;
}
std::vector<const Tile*> Tile::getNeighbors() const {
//Returns a copy
return m_vcNeighbors;
}
Directions Tile::getDirection(const Tile& cDestination) const {
//Important to remember that highest is 0 and lowest is N-1, sideways is normal
//Get the horizontal direction
Directions eHorizontal;
if (cDestination.m_uiPositionX == m_uiPositionX) eHorizontal = kCenter;
else if (cDestination.m_uiPositionX > m_uiPositionX) eHorizontal = kRight;
else eHorizontal = kLeft;
//Get the vertical direction
Directions eVertical;
if (cDestination.m_uiPositionY == m_uiPositionY) eVertical = kCenter;
else if (cDestination.m_uiPositionY > m_uiPositionY) eVertical = kDown;
else eVertical = kUp;
//Compare both horizontal and vertical to get the final heading
switch (eHorizontal) {
case kCenter:
switch (eVertical) {
case kCenter: return kCenter;
case kUp: return kUp;
case kDown: return kDown;
default: break; //Shouldnt reach
}
break;
case kRight:
switch (eVertical) {
case kCenter: return kRight;
case kUp: return kRightUp;
case kDown: return kRightDown;
default: break; //Shouldnt reach
}
case kLeft:
switch (eVertical) {
case kCenter: return kLeft;
case kUp: return kLeftUp;
case kDown: return kLeftDown;
default: break; //Shouldnt reach
}
//Shouldnt reach
default: break;
}
throw std::runtime_error("incorrect implementation of direction between tiles");
}
bool Tile::operator==(const Tile &cTile) const {
return ((m_uiPositionX == cTile.m_uiPositionX) && (m_uiPositionY == cTile.m_uiPositionY));
}
bool Tile::operator!=(const Tile &cTile) const {
return ((m_uiPositionX != cTile.m_uiPositionX) || (m_uiPositionY != cTile.m_uiPositionY));
}
bool Tile::operator<(const Tile &cTile) const {
return ((m_uiPositionX < cTile.m_uiPositionX) || ((m_uiPositionX == cTile.m_uiPositionX) && m_uiPositionY < cTile.m_uiPositionY));
}
bool Tile::operator>(const Tile &cTile) const {
return ((m_uiPositionX > cTile.m_uiPositionX) || ((m_uiPositionX == cTile.m_uiPositionX) && m_uiPositionY > cTile.m_uiPositionY));
}
std::string Tile::kind() const {
switch (eType) {
case kStart : return "Start";
case kEnd : return "End";
case kHill : return "Hill";
case kRoad : return "Road";
case kDirt : return "Dirt";
case kWater : return "Water";
}
}
char Tile::type() const {
switch (eType) {
case kStart: return 'S';
case kEnd: return 'G';
case kDirt: return 'D';
case kHill: return 'H';
case kWater: return 'W';
case kRoad: return 'R';
}
}
std::ostream& operator<< (std::ostream &out, const Tile &cTile) {
out << "Type: \t" << cTile.type() << ", Neighbors: \t" << cTile.m_vcNeighbors.size() << ", \tLocation: (" << cTile.m_uiPositionX << ", " << cTile.m_uiPositionY << ")" << "\n";
if (cTile.m_vcNeighbors.size()) out << "List of neighbors: \n" << std::endl;
for (std::vector<const Tile*>::const_iterator iterator = cTile.m_vcNeighbors.begin() ; iterator != cTile.m_vcNeighbors.end() ; iterator++) {
const Tile* cNeighbor = *iterator;
out << "Type: \t" << cNeighbor->type() << ", \tLocation: (" << cNeighbor->m_uiPositionX << ", " << cNeighbor->m_uiPositionY << ")" << "\n";
}
return out;
} | 30.461039 | 179 | 0.566404 | [
"vector"
] |
4487465e4e3f927c7dbaa78b047346d925fcc509 | 990 | cpp | C++ | inference-engine/tests/functional/plugin/cpu/shared_tests_instances/low_precision_transformations/multiply_with_one_parent_transformation.cpp | aisnote/openvino | d901bbfce3d195469339cfcdfd8fbdc619ef7050 | [
"Apache-2.0"
] | 1 | 2020-09-19T18:48:23.000Z | 2020-09-19T18:48:23.000Z | inference-engine/tests/functional/plugin/cpu/shared_tests_instances/low_precision_transformations/multiply_with_one_parent_transformation.cpp | aisnote/openvino | d901bbfce3d195469339cfcdfd8fbdc619ef7050 | [
"Apache-2.0"
] | null | null | null | inference-engine/tests/functional/plugin/cpu/shared_tests_instances/low_precision_transformations/multiply_with_one_parent_transformation.cpp | aisnote/openvino | d901bbfce3d195469339cfcdfd8fbdc619ef7050 | [
"Apache-2.0"
] | null | null | null | // Copyright (C) 2020 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
//
#include <vector>
#include "low_precision_transformations/multiply_with_one_parent_transformation.hpp"
#include "common_test_utils/test_constants.hpp"
using namespace LayerTestsDefinitions;
namespace {
const std::vector<InferenceEngine::Precision> netPrecisions = {
InferenceEngine::Precision::FP32,
InferenceEngine::Precision::FP16
};
const std::vector<MultiplyWithOneParentTransformationValues> values = {
{
{ 256ul, ngraph::Shape { 1, 1, 1, 1 }, { 0.f }, { 255.f }, { 0.f }, { 255.f } }
}
};
INSTANTIATE_TEST_CASE_P(smoke_LPT, MultiplyWithOneParentTransformation,
::testing::Combine(
::testing::ValuesIn(netPrecisions),
::testing::Values(InferenceEngine::SizeVector({ 1, 3, 16, 16 })),
::testing::Values(CommonTestUtils::DEVICE_CPU),
::testing::ValuesIn(values)),
MultiplyWithOneParentTransformation::getTestCaseName);
} // namespace
| 30.9375 | 87 | 0.713131 | [
"shape",
"vector"
] |
448c2c58c4f27989f189ccd67e9c1e90b6583a3b | 2,282 | cpp | C++ | src/Engine/Classes/Instance/Instance.cpp | MasonLeeBack/RSEngine | 9ac4a0380898cb59a48d29dc7250dfb70430932f | [
"MIT"
] | 1 | 2019-01-03T13:42:10.000Z | 2019-01-03T13:42:10.000Z | src/Engine/Classes/Instance/Instance.cpp | MasonLeeBack/RSEngine | 9ac4a0380898cb59a48d29dc7250dfb70430932f | [
"MIT"
] | 2 | 2019-01-03T19:00:42.000Z | 2019-01-03T19:02:16.000Z | src/Engine/Classes/Instance/Instance.cpp | MasonLeeBack/RSEngine | 9ac4a0380898cb59a48d29dc7250dfb70430932f | [
"MIT"
] | null | null | null | /*
RSEngine
Copyright (c) 2020 Mason Lee Back
File name: Instance.cpp
*/
#include <Classes/Instance.h>
namespace rs {
Instance::Instance() {
ClassName = "Instance";
Name = getClassName();
}
Instance::~Instance() {
/* should we do something here? */
}
std::string Instance::GetName() {
return Name;
}
void Instance::SetName(std::string name) {
Name = name;
}
void Instance::Remove() {
SetParent(NULL);
for (auto kid : children) {
if (kid) {
kid->Remove();
}
}
//delete this;
}
std::shared_ptr<Instance> Instance::CopyInstance(std::shared_ptr<Instance> Parent) {
return std::shared_ptr<Instance>();
}
std::string Instance::GetPath() {
std::string temp = Name;
if (Parent != NULL) {
temp = Parent->GetPath() + "/" + temp; /* keep adding the directories until we reach the end */
}
return temp;
}
std::string Instance::GetClassHierarchy() {
std::string temp = getClassName();
if (Parent != NULL) {
temp = Parent->GetClassHierarchy() + "/" + temp;
}
return temp;
}
std::shared_ptr<Instance> Instance::GetParent() {
return Parent;
}
void Instance::SetParent(std::shared_ptr<Instance> parent) {
/* No need to try setting the parent */
if (Parent == parent)
return;
if (parent == shared_from_this())
return;
/* clear the previous child, and add the new one */
if (Parent) {
for (auto i = Parent->children.begin(); i != Parent->children.end(); ) {
if (*i == shared_from_this()) i = Parent->children.erase(i); else ++i;
}
}
Parent = parent;
if (Parent)
Parent->children.push_back(shared_from_this());
}
std::vector<std::shared_ptr<Instance>> Instance::GetChildren() {
return children;
}
void Instance::ClearAllChildren() {
for (auto kid : children) {
if (kid) {
kid->Remove();
}
}
}
void Instance::render() {
renderChildren();
}
void Instance::renderChildren() {
for (auto kid : children) {
if (kid) {
kid->render();
}
}
}
void Instance::tick() {
tickChildren();
}
void Instance::tickChildren() {
for (auto kid : children) {
if (kid) {
kid->tick();
}
}
}
std::string Instance::getClassName() {
return ClassName;
}
} // namespace rs
| 17.968504 | 98 | 0.601665 | [
"render",
"vector"
] |
44904a68ace943d4c1e578f71ab101c1ecfff15e | 12,261 | cpp | C++ | src/game/shared/env_wind_shared.cpp | TF2V/Tf2Vintage | 983d652c338dc017dca51f5bc4eee1a3d4b7ac2e | [
"Unlicense"
] | null | null | null | src/game/shared/env_wind_shared.cpp | TF2V/Tf2Vintage | 983d652c338dc017dca51f5bc4eee1a3d4b7ac2e | [
"Unlicense"
] | null | null | null | src/game/shared/env_wind_shared.cpp | TF2V/Tf2Vintage | 983d652c338dc017dca51f5bc4eee1a3d4b7ac2e | [
"Unlicense"
] | null | null | null | //========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
// Information about algorithmic stuff that can occur on both client + server
//
// In order to reduce network traffic, it's possible to create a algorithms
// that will work on both the client and the server and be totally repeatable.
// All we need do is to send down initial conditions and let the algorithm
// compute the values at various times. Note that this algorithm will be called
// at different times with different frequencies on the client and server.
//
// The trick here is that in order for it to be repeatable, the algorithm either
// cannot depend on random numbers, or, if it does, we need to make sure that
// the random numbers generated are effectively done at the beginning of time,
// so that differences in frame rate on client and server won't matter. It also
// is important that the initial state sent across the network is identical
// bitwise so that we produce the exact same results. Therefore no compression
// should be used in the datatables.
//
// Note also that each algorithm must have its own random number stream so that
// it cannot possibly interact with other code using random numbers that will
// be called at various different intervals on the client + server. Use the
// CUniformRandomStream class for this.
//
// There are two types of client-server neutral code: Code that doesn't interact
// with player prediction, and code that does. The code that doesn't interact
// with player prediction simply has to be able to produce the result f(time)
// where time is monotonically increasing. For prediction, we have to produce
// the result f(time) where time does *not* monotonically increase (time can be
// anywhere between the "current" time and the prior 10 seconds).
//
// Code that is not used by player prediction can maintain state because later
// calls will always compute the value at some future time. This computation can
// use random number generation, but with the following restriction: Your code
// must generate exactly the same number of random numbers regardless of how
// frequently the code is called.
//
// In specific, this means that all random numbers used must either be computed
// at init time, or must be used in an 'event-based form'. Namely, use random
// numbers to compute the time at which events occur and the random inputs for
// those events. When simulating forward, you must simulate all intervening
// time and generate the same number of random numbers.
//
// For functions planned to be used by player prediction, one method is to use
// some sort of stateless computation (where the only states are the initial
// state and time). Note that random number generators have state implicit in
// the number of calls made to that random number generator, and therefore you
// cannot call a random number generator unless you are able to
//
// 1) Use a random number generator that can return the ith random number, namely:
//
// float r = random( i ); // i == the ith number in the random sequence
//
// 2) Be able to accurately know at any given time t how many random numbers
// have already been generated (namely, compute the i in part 1 above).
//
// There is another alternative for code meant to be used by player prediction:
// you could just store a history of 'events' from which you could completely
// determine the value of f(time). That history would need to be at least 10
// seconds long, which is guaranteed to be longer than the amount of time that
// prediction would need. I've written a class which I haven't tested yet (but
// will be using soon) called CTimedEventQueue (currently located in
// env_wind_shared.h) which I plan to use to solve my problem (getting wind to
// blow players).
//
//=============================================================================//
#include "cbase.h"
#include "env_wind_shared.h"
#include "soundenvelope.h"
#include "IEffects.h"
#include "engine/IEngineSound.h"
#include "sharedInterface.h"
#include "renderparm.h"
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
//-----------------------------------------------------------------------------
// globals
//-----------------------------------------------------------------------------
static Vector s_vecWindVelocity( 0, 0, 0 );
CEnvWindShared::CEnvWindShared() : m_WindAveQueue(10), m_WindVariationQueue(10)
{
m_pWindSound = NULL;
}
CEnvWindShared::~CEnvWindShared()
{
if (m_pWindSound)
{
CSoundEnvelopeController::GetController().Shutdown( m_pWindSound );
}
}
void CEnvWindShared::Init( int nEntIndex, int iRandomSeed, float flTime,
int iInitialWindYaw, float flInitialWindSpeed )
{
m_iEntIndex = nEntIndex;
m_flWindAngleVariation = m_flWindSpeedVariation = 1.0f;
m_flStartTime = m_flSimTime = m_flSwitchTime = m_flVariationTime = flTime;
m_iWindSeed = iRandomSeed;
m_Stream.SetSeed( iRandomSeed );
m_WindVariationStream.SetSeed( iRandomSeed );
m_iWindDir = m_iInitialWindDir = iInitialWindYaw;
m_flAveWindSpeed = m_flWindSpeed = m_flInitialWindSpeed = flInitialWindSpeed;
/*
// Cache in the wind sound...
if (!g_pEffects->IsServer())
{
CSoundEnvelopeController &controller = CSoundEnvelopeController::GetController();
m_pWindSound = controller.SoundCreate( -1, CHAN_STATIC,
"EnvWind.Loop", ATTN_NONE );
controller.Play( m_pWindSound, 0.0f, 100 );
}
*/
// Next time a change happens (which will happen immediately), it'll stop gusting
m_bGusting = true;
}
//-----------------------------------------------------------------------------
// Computes wind variation
//-----------------------------------------------------------------------------
#define WIND_VARIATION_UPDATE_TIME 0.1f
void CEnvWindShared::ComputeWindVariation( float flTime )
{
// The wind variation is updated every 10th of a second..
while( flTime >= m_flVariationTime )
{
m_flWindAngleVariation = m_WindVariationStream.RandomFloat( -10, 10 );
m_flWindSpeedVariation = 1.0 + m_WindVariationStream.RandomFloat( -0.2, 0.2 );
m_flVariationTime += WIND_VARIATION_UPDATE_TIME;
}
}
//-----------------------------------------------------------------------------
// Updates the wind sound
//-----------------------------------------------------------------------------
void CEnvWindShared::UpdateWindSound( float flTotalWindSpeed )
{
if (!g_pEffects->IsServer())
{
float flDuration = random->RandomFloat( 1.0f, 2.0f );
CSoundEnvelopeController &controller = CSoundEnvelopeController::GetController();
// FIXME: Tweak with these numbers
float flNormalizedWindSpeed = flTotalWindSpeed / 150.0f;
if (flNormalizedWindSpeed > 1.0f)
flNormalizedWindSpeed = 1.0f;
float flPitch = 120 * Bias( flNormalizedWindSpeed, 0.3f ) + 100;
float flVolume = 0.3f * Bias( flNormalizedWindSpeed, 0.3f ) + 0.7f;
controller.SoundChangePitch( m_pWindSound, flPitch, flDuration );
controller.SoundChangeVolume( m_pWindSound, flVolume, flDuration );
}
}
//-----------------------------------------------------------------------------
// Updates the swaying of trees
//-----------------------------------------------------------------------------
#define TREE_SWAY_UPDATE_TIME 2.0f
void CEnvWindShared::UpdateTreeSway( float flTime )
{
#ifdef CLIENT_DLL
while( flTime >= m_flSwayTime )
{
// Since the wind is constantly changing, but we need smooth values, we cache them off here.
m_PrevSwayVector = m_CurrentSwayVector;
m_CurrentSwayVector = m_currentWindVector;
m_flSwayTime += TREE_SWAY_UPDATE_TIME;
}
// Update vertex shader
float flPercentage = ( 1 - ( ( m_flSwayTime - flTime ) / TREE_SWAY_UPDATE_TIME ) );
CMatRenderContextPtr pRenderContext( g_pMaterialSystem );
// Dividing by 2 helps the numbers the shader is expecting stay in line with other expected game values.
Vector vecWind = Lerp( flPercentage, m_PrevSwayVector, m_CurrentSwayVector ) / 2;
pRenderContext->SetVectorRenderingParameter( VECTOR_RENDERPARM_WIND_DIRECTION, vecWind );
#endif
}
//-----------------------------------------------------------------------------
// Updates the wind speed
//-----------------------------------------------------------------------------
#define WIND_ACCELERATION 150.0f // wind speed can accelerate this many units per second
#define WIND_DECELERATION 15.0f // wind speed can decelerate this many units per second
float CEnvWindShared::WindThink( float flTime )
{
// NOTE: This algorithm can be client-server neutal because we're using
// the random number generator to generate *time* at which the wind changes.
// We therefore need to structure the algorithm so that no matter the
// frequency of calls to this function we produce the same wind speeds...
ComputeWindVariation( flTime );
// Update Tree Sway
UpdateTreeSway( flTime );
while (true)
{
// First, simulate up to the next switch time...
float flTimeToSwitch = m_flSwitchTime - m_flSimTime;
float flMaxDeltaTime = flTime - m_flSimTime;
bool bGotToSwitchTime = (flMaxDeltaTime > flTimeToSwitch);
float flSimDeltaTime = bGotToSwitchTime ? flTimeToSwitch : flMaxDeltaTime;
// Now that we've chosen
// either ramp up, or sleep till change
bool bReachedSteadyState = true;
if ( m_flAveWindSpeed > m_flWindSpeed )
{
m_flWindSpeed += WIND_ACCELERATION * flSimDeltaTime;
if (m_flWindSpeed > m_flAveWindSpeed)
m_flWindSpeed = m_flAveWindSpeed;
else
bReachedSteadyState = false;
}
else if ( m_flAveWindSpeed < m_flWindSpeed )
{
m_flWindSpeed -= WIND_DECELERATION * flSimDeltaTime;
if (m_flWindSpeed < m_flAveWindSpeed)
m_flWindSpeed = m_flAveWindSpeed;
else
bReachedSteadyState = false;
}
// Update the sim time
// If we didn't get to a switch point, then we're done simulating for now
if (!bGotToSwitchTime)
{
m_flSimTime = flTime;
// We're about to exit, let's set the wind velocity...
QAngle vecWindAngle( 0, m_iWindDir + m_flWindAngleVariation, 0 );
AngleVectors( vecWindAngle, &s_vecWindVelocity );
float flTotalWindSpeed = m_flWindSpeed * m_flWindSpeedVariation;
s_vecWindVelocity *= flTotalWindSpeed;
// If we reached a steady state, we don't need to be called until the switch time
// Otherwise, we should be called immediately
// FIXME: If we ever call this from prediction, we'll need
// to only update the sound if it's a new time
// Or, we'll need to update the sound elsewhere.
// Update the sound....
// UpdateWindSound( flTotalWindSpeed );
// Always immediately call, the wind is forever varying
return ( flTime + 0.01f );
}
m_flSimTime = m_flSwitchTime;
// Switch gusting state..
if( m_bGusting )
{
// wind is gusting, so return to normal wind
m_flAveWindSpeed = m_Stream.RandomInt( m_iMinWind, m_iMaxWind );
// set up for another gust later
m_bGusting = false;
m_flSwitchTime += m_flMinGustDelay + m_Stream.RandomFloat( 0, m_flMaxGustDelay );
#ifndef CLIENT_DLL
m_OnGustEnd.FireOutput( NULL, NULL );
#endif
}
else
{
// time for a gust.
m_flAveWindSpeed = m_Stream.RandomInt( m_iMinGust, m_iMaxGust );
// change wind direction, maybe a lot
m_iWindDir = anglemod( m_iWindDir + m_Stream.RandomInt(-m_iGustDirChange, m_iGustDirChange) );
// set up to stop the gust in a short while
m_bGusting = true;
#ifndef CLIENT_DLL
m_OnGustStart.FireOutput( NULL, NULL );
#endif
// !!!HACKHACK - gust duration tied to the length of a particular wave file
m_flSwitchTime += m_flGustDuration;
}
}
}
//-----------------------------------------------------------------------------
// Method to reset windspeed..
//-----------------------------------------------------------------------------
void ResetWindspeed()
{
s_vecWindVelocity.Init( 0, 0, 0 );
}
//-----------------------------------------------------------------------------
// Method to sample the windspeed at a particular time
//-----------------------------------------------------------------------------
void GetWindspeedAtTime( float flTime, Vector &vecVelocity )
{
// For now, ignore history and time.. fix later when we use wind to affect
// client-side prediction
VectorCopy( s_vecWindVelocity, vecVelocity );
}
| 38.196262 | 105 | 0.671234 | [
"vector"
] |
449712345a8e542699e3c122ef0e65269bf7de59 | 11,799 | cc | C++ | src/profiler/tick-sample.cc | patil215/v8 | bb941b58df9ee1e4048b69a555a2ce819fb819ed | [
"BSD-3-Clause"
] | null | null | null | src/profiler/tick-sample.cc | patil215/v8 | bb941b58df9ee1e4048b69a555a2ce819fb819ed | [
"BSD-3-Clause"
] | null | null | null | src/profiler/tick-sample.cc | patil215/v8 | bb941b58df9ee1e4048b69a555a2ce819fb819ed | [
"BSD-3-Clause"
] | null | null | null | // Copyright 2013 the V8 project 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 "src/profiler/tick-sample.h"
#include "include/v8-profiler.h"
#include "src/asan.h"
#include "src/counters.h"
#include "src/frames-inl.h"
#include "src/heap/heap-inl.h" // For MemoryAllocator::code_range.
#include "src/msan.h"
#include "src/simulator.h"
#include "src/vm-state-inl.h"
namespace v8 {
namespace {
bool IsSamePage(i::Address ptr1, i::Address ptr2) {
const uint32_t kPageSize = 4096;
i::Address mask = ~static_cast<i::Address>(kPageSize - 1);
return (ptr1 & mask) == (ptr2 & mask);
}
// Check if the code at specified address could potentially be a
// frame setup code.
bool IsNoFrameRegion(i::Address address) {
struct Pattern {
int bytes_count;
i::byte bytes[8];
int offsets[4];
};
static Pattern patterns[] = {
#if V8_HOST_ARCH_IA32
// push %ebp
// mov %esp,%ebp
{3, {0x55, 0x89, 0xE5}, {0, 1, -1}},
// pop %ebp
// ret N
{2, {0x5D, 0xC2}, {0, 1, -1}},
// pop %ebp
// ret
{2, {0x5D, 0xC3}, {0, 1, -1}},
#elif V8_HOST_ARCH_X64
// pushq %rbp
// movq %rsp,%rbp
{4, {0x55, 0x48, 0x89, 0xE5}, {0, 1, -1}},
// popq %rbp
// ret N
{2, {0x5D, 0xC2}, {0, 1, -1}},
// popq %rbp
// ret
{2, {0x5D, 0xC3}, {0, 1, -1}},
#endif
{0, {}, {}}
};
i::byte* pc = reinterpret_cast<i::byte*>(address);
for (Pattern* pattern = patterns; pattern->bytes_count; ++pattern) {
for (int* offset_ptr = pattern->offsets; *offset_ptr != -1; ++offset_ptr) {
int offset = *offset_ptr;
if (!offset || IsSamePage(address, address - offset)) {
MSAN_MEMORY_IS_INITIALIZED(pc - offset, pattern->bytes_count);
if (!memcmp(pc - offset, pattern->bytes, pattern->bytes_count))
return true;
} else {
// It is not safe to examine bytes on another page as it might not be
// allocated thus causing a SEGFAULT.
// Check the pattern part that's on the same page and
// pessimistically assume it could be the entire pattern match.
MSAN_MEMORY_IS_INITIALIZED(pc, pattern->bytes_count - offset);
if (!memcmp(pc, pattern->bytes + offset, pattern->bytes_count - offset))
return true;
}
}
}
return false;
}
} // namespace
namespace internal {
namespace {
#if defined(USE_SIMULATOR)
class SimulatorHelper {
public:
// Returns true if register values were successfully retrieved
// from the simulator, otherwise returns false.
static bool FillRegisters(Isolate* isolate, v8::RegisterState* state);
};
bool SimulatorHelper::FillRegisters(Isolate* isolate,
v8::RegisterState* state) {
Simulator* simulator = isolate->thread_local_top()->simulator_;
// Check if there is active simulator.
if (simulator == nullptr) return false;
#if V8_TARGET_ARCH_ARM
if (!simulator->has_bad_pc()) {
state->pc = reinterpret_cast<void*>(simulator->get_pc());
}
state->sp = reinterpret_cast<void*>(simulator->get_register(Simulator::sp));
state->fp = reinterpret_cast<void*>(simulator->get_register(Simulator::r11));
#elif V8_TARGET_ARCH_ARM64
state->pc = reinterpret_cast<void*>(simulator->pc());
state->sp = reinterpret_cast<void*>(simulator->sp());
state->fp = reinterpret_cast<void*>(simulator->fp());
#elif V8_TARGET_ARCH_MIPS || V8_TARGET_ARCH_MIPS64
if (!simulator->has_bad_pc()) {
state->pc = reinterpret_cast<void*>(simulator->get_pc());
}
state->sp = reinterpret_cast<void*>(simulator->get_register(Simulator::sp));
state->fp = reinterpret_cast<void*>(simulator->get_register(Simulator::fp));
#elif V8_TARGET_ARCH_PPC
if (!simulator->has_bad_pc()) {
state->pc = reinterpret_cast<void*>(simulator->get_pc());
}
state->sp = reinterpret_cast<void*>(simulator->get_register(Simulator::sp));
state->fp = reinterpret_cast<void*>(simulator->get_register(Simulator::fp));
#elif V8_TARGET_ARCH_S390
if (!simulator->has_bad_pc()) {
state->pc = reinterpret_cast<void*>(simulator->get_pc());
}
state->sp = reinterpret_cast<void*>(simulator->get_register(Simulator::sp));
state->fp = reinterpret_cast<void*>(simulator->get_register(Simulator::fp));
#endif
if (state->sp == 0 || state->fp == 0) {
// It possible that the simulator is interrupted while it is updating
// the sp or fp register. ARM64 simulator does this in two steps:
// first setting it to zero and then setting it to the new value.
// Bailout if sp/fp doesn't contain the new value.
//
// FIXME: The above doesn't really solve the issue.
// If a 64-bit target is executed on a 32-bit host even the final
// write is non-atomic, so it might obtain a half of the result.
// Moreover as long as the register set code uses memcpy (as of now),
// it is not guaranteed to be atomic even when both host and target
// are of same bitness.
return false;
}
return true;
}
#endif // USE_SIMULATOR
} // namespace
} // namespace internal
//
// StackTracer implementation
//
DISABLE_ASAN void TickSample::Init(Isolate* v8_isolate,
const RegisterState& reg_state,
RecordCEntryFrame record_c_entry_frame,
bool update_stats,
bool use_simulator_reg_state) {
this->update_stats = update_stats;
SampleInfo info;
RegisterState regs = reg_state;
if (!GetStackSample(v8_isolate, ®s, record_c_entry_frame, stack,
kMaxFramesCount, &info, use_simulator_reg_state)) {
// It is executing JS but failed to collect a stack trace.
// Mark the sample as spoiled.
pc = nullptr;
return;
}
state = info.vm_state;
pc = regs.pc;
frames_count = static_cast<unsigned>(info.frames_count);
has_external_callback = info.external_callback_entry != nullptr;
if (has_external_callback) {
external_callback_entry = info.external_callback_entry;
} else if (frames_count) {
// sp register may point at an arbitrary place in memory, make
// sure sanitizers don't complain about it.
ASAN_UNPOISON_MEMORY_REGION(regs.sp, sizeof(void*));
MSAN_MEMORY_IS_INITIALIZED(regs.sp, sizeof(void*));
// Sample potential return address value for frameless invocation of
// stubs (we'll figure out later, if this value makes sense).
tos = i::ReadUnalignedValue<void*>(reinterpret_cast<i::Address>(regs.sp));
} else {
tos = nullptr;
}
}
bool TickSample::GetStackSample(Isolate* v8_isolate, RegisterState* regs,
RecordCEntryFrame record_c_entry_frame,
void** frames, size_t frames_limit,
v8::SampleInfo* sample_info,
bool use_simulator_reg_state) {
i::Isolate* isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
sample_info->frames_count = 0;
sample_info->vm_state = isolate->current_vm_state();
sample_info->external_callback_entry = nullptr;
if (sample_info->vm_state == GC) return true;
i::Address js_entry_sp = isolate->js_entry_sp();
if (js_entry_sp == 0) return true; // Not executing JS now.
#if defined(USE_SIMULATOR)
if (use_simulator_reg_state) {
if (!i::SimulatorHelper::FillRegisters(isolate, regs)) return false;
}
#else
USE(use_simulator_reg_state);
#endif
DCHECK(regs->sp);
// Check whether we interrupted setup/teardown of a stack frame in JS code.
// Avoid this check for C++ code, as that would trigger false positives.
if (regs->pc &&
isolate->heap()->memory_allocator()->code_range().contains(
reinterpret_cast<i::Address>(regs->pc)) &&
IsNoFrameRegion(reinterpret_cast<i::Address>(regs->pc))) {
// The frame is not setup, so it'd be hard to iterate the stack. Bailout.
return false;
}
i::ExternalCallbackScope* scope = isolate->external_callback_scope();
i::Address handler = i::Isolate::handler(isolate->thread_local_top());
// If there is a handler on top of the external callback scope then
// we have already entrered JavaScript again and the external callback
// is not the top function.
if (scope && scope->scope_address() < handler) {
i::Address* external_callback_entry_ptr =
scope->callback_entrypoint_address();
sample_info->external_callback_entry =
external_callback_entry_ptr == nullptr
? nullptr
: reinterpret_cast<void*>(*external_callback_entry_ptr);
}
i::SafeStackFrameIterator it(isolate, reinterpret_cast<i::Address>(regs->fp),
reinterpret_cast<i::Address>(regs->sp),
js_entry_sp);
if (it.done()) return true;
size_t i = 0;
if (record_c_entry_frame == kIncludeCEntryFrame &&
(it.top_frame_type() == internal::StackFrame::EXIT ||
it.top_frame_type() == internal::StackFrame::BUILTIN_EXIT)) {
frames[i++] = reinterpret_cast<void*>(isolate->c_function());
}
i::RuntimeCallTimer* timer =
isolate->counters()->runtime_call_stats()->current_timer();
for (; !it.done() && i < frames_limit; it.Advance()) {
while (timer && reinterpret_cast<i::Address>(timer) < it.frame()->fp() &&
i < frames_limit) {
frames[i++] = reinterpret_cast<void*>(timer->counter());
timer = timer->parent();
}
if (i == frames_limit) break;
if (it.frame()->is_interpreted()) {
// For interpreted frames use the bytecode array pointer as the pc.
i::InterpretedFrame* frame =
static_cast<i::InterpretedFrame*>(it.frame());
// Since the sampler can interrupt execution at any point the
// bytecode_array might be garbage, so don't actually dereference it. We
// avoid the frame->GetXXX functions since they call BytecodeArray::cast,
// which has a heap access in its DCHECK.
i::Address bytecode_array = i::Memory<i::Address>(
frame->fp() + i::InterpreterFrameConstants::kBytecodeArrayFromFp);
i::Address bytecode_offset = i::Memory<i::Address>(
frame->fp() + i::InterpreterFrameConstants::kBytecodeOffsetFromFp);
// If the bytecode array is a heap object and the bytecode offset is a
// Smi, use those, otherwise fall back to using the frame's pc.
if (HAS_HEAP_OBJECT_TAG(bytecode_array) && HAS_SMI_TAG(bytecode_offset)) {
frames[i++] = reinterpret_cast<void*>(
bytecode_array + i::Internals::SmiValue(bytecode_offset));
continue;
}
}
frames[i++] = reinterpret_cast<void*>(it.frame()->pc());
}
sample_info->frames_count = i;
return true;
}
namespace internal {
void TickSample::Init(Isolate* isolate, const v8::RegisterState& state,
RecordCEntryFrame record_c_entry_frame, bool update_stats,
bool use_simulator_reg_state) {
v8::TickSample::Init(reinterpret_cast<v8::Isolate*>(isolate), state,
record_c_entry_frame, update_stats,
use_simulator_reg_state);
if (pc == nullptr) return;
timestamp = base::TimeTicks::HighResolutionNow();
}
void TickSample::print() const {
PrintF("TickSample: at %p\n", this);
PrintF(" - state: %s\n", StateToString(state));
PrintF(" - pc: %p\n", pc);
PrintF(" - stack: (%u frames)\n", frames_count);
for (unsigned i = 0; i < frames_count; i++) {
PrintF(" %p\n", stack[i]);
}
PrintF(" - has_external_callback: %d\n", has_external_callback);
PrintF(" - %s: %p\n",
has_external_callback ? "external_callback_entry" : "tos", tos);
PrintF(" - update_stats: %d\n", update_stats);
PrintF("\n");
}
} // namespace internal
} // namespace v8
| 38.308442 | 80 | 0.653954 | [
"object"
] |
4497c6ad6e53e4495d4faff202cf7c1b57a4c08b | 2,953 | cpp | C++ | Source/GL/GLElementBuffer.cpp | zero-radiance/GIGL | 1917c51c883bbe0bbd457abcf95aecf89ab05010 | [
"MIT"
] | 14 | 2018-12-29T07:50:09.000Z | 2022-02-11T09:22:52.000Z | Source/GL/GLElementBuffer.cpp | zero-radiance/GIGL | 1917c51c883bbe0bbd457abcf95aecf89ab05010 | [
"MIT"
] | 2 | 2015-08-23T14:53:50.000Z | 2016-01-18T15:05:20.000Z | Source/GL/GLElementBuffer.cpp | zero-radiance/GIGL | 1917c51c883bbe0bbd457abcf95aecf89ab05010 | [
"MIT"
] | 2 | 2021-01-24T02:48:11.000Z | 2022-01-17T02:09:22.000Z | #include "GLElementBuffer.h"
#include <cassert>
#include <OpenGL\gl_core_4_4.hpp>
#include <GLM\detail\func_common.hpp>
#include "GLVertArray.h"
using glm::min;
using glm::max;
GLElementBuffer::GLElementBuffer(): m_min_idx{UINT_MAX}, m_max_idx{0}, m_is_buffered{false} {
gl::GenBuffers(1, &m_handle);
}
GLElementBuffer::GLElementBuffer(const GLElementBuffer& ebo): m_min_idx{ebo.m_min_idx},
m_max_idx{ebo.m_max_idx}, m_is_buffered{ebo.m_is_buffered},
m_data_vec(ebo.m_data_vec) {
gl::GenBuffers(1, &m_handle);
if (ebo.m_is_buffered) { buffer(); }
}
GLElementBuffer& GLElementBuffer::operator=(const GLElementBuffer& ebo) {
if (this != &ebo) {
// Free memory
gl::DeleteBuffers(1, &m_handle);
// Generate a new buffer
gl::GenBuffers(1, &m_handle);
// Copy the data
m_min_idx = ebo.m_min_idx;
m_max_idx = ebo.m_max_idx;
m_is_buffered = ebo.m_is_buffered;
m_data_vec = ebo.m_data_vec;
if (ebo.m_is_buffered) { buffer(); }
}
return *this;
}
GLElementBuffer::GLElementBuffer(GLElementBuffer&& ebo): m_handle{ebo.m_handle},
m_min_idx{ebo.m_min_idx}, m_max_idx{ebo.m_max_idx},
m_is_buffered{ebo.m_is_buffered}, m_data_vec(std::move(ebo.m_data_vec)) {
// Mark as moved
ebo.m_handle = 0;
}
GLElementBuffer& GLElementBuffer::operator=(GLElementBuffer&& ebo) {
assert(this != &ebo);
// Free memory
gl::DeleteBuffers(1, &m_handle);
// Now copy the data
memcpy(this, &ebo, sizeof(*this));
// Mark as moved
ebo.m_handle = 0;
return *this;
}
GLElementBuffer::~GLElementBuffer() {
// Check if it was moved
if (m_handle) {
gl::DeleteBuffers(1, &m_handle);
}
}
void GLElementBuffer::buffer() {
gl::BindBuffer(gl::ELEMENT_ARRAY_BUFFER, m_handle);
const auto byte_sz = m_data_vec.size() * sizeof(GLuint);
gl::BufferData(gl::ELEMENT_ARRAY_BUFFER, byte_sz, m_data_vec.data(), gl::STATIC_DRAW);
m_is_buffered = true;
}
void GLElementBuffer::loadData(const std::vector<GLuint>& data_vec, const GLuint offset) {
loadData(data_vec.size(), data_vec.data(), offset);
}
void GLElementBuffer::loadData(const size_t n_elems, const GLuint* const data,
const GLuint offset) {
m_data_vec.reserve(m_data_vec.size() + n_elems);
for (auto i = 0; i < n_elems; ++i) {
const GLuint idx{offset + data[i]};
m_min_idx = min(m_min_idx, idx);
m_max_idx = max(m_max_idx, idx);
m_data_vec.push_back(idx);
}
m_is_buffered = false;
}
void GLElementBuffer::draw(const GLVertArray& va) const {
gl::BindVertexArray(va.id());
gl::BindBuffer(gl::ELEMENT_ARRAY_BUFFER, m_handle);
const auto n_elems = static_cast<GLsizei>(m_data_vec.size());
gl::DrawRangeElements(gl::TRIANGLES, m_min_idx, m_max_idx, n_elems, gl::UNSIGNED_INT, nullptr);
}
| 32.450549 | 99 | 0.656282 | [
"vector"
] |
449fe693a5d54285fb82ce0b6c97dcd45864194b | 10,468 | hpp | C++ | include/lsMesh.hpp | yozoon/ViennaLS | ead51a51b11e357697b7200b68b3d16a242c7a4e | [
"MIT"
] | null | null | null | include/lsMesh.hpp | yozoon/ViennaLS | ead51a51b11e357697b7200b68b3d16a242c7a4e | [
"MIT"
] | null | null | null | include/lsMesh.hpp | yozoon/ViennaLS | ead51a51b11e357697b7200b68b3d16a242c7a4e | [
"MIT"
] | null | null | null | #ifndef LS_MESH_HPP
#define LS_MESH_HPP
#include <lsPreCompileMacros.hpp>
#include <array>
#include <iostream>
#include <vector>
#include <lsPointData.hpp>
/// This class holds an explicit mesh, which is always given in 3 dimensions.
/// If it describes a 2D mesh, the third dimension is set to 0.
/// Vertices, Lines, Triangles, Tetras & Hexas are supported as geometric
/// elements.
template <class T = double> class lsMesh {
public:
std::vector<std::array<T, 3>> nodes;
std::vector<std::array<unsigned, 1>> vertices;
std::vector<std::array<unsigned, 2>> lines;
std::vector<std::array<unsigned, 3>> triangles;
std::vector<std::array<unsigned, 4>> tetras;
std::vector<std::array<unsigned, 8>> hexas;
lsPointData<T> pointData;
lsPointData<T> cellData;
std::array<T, 3> minimumExtent;
std::array<T, 3> maximumExtent;
private:
// iterator typedef
using VectorIt = typename lsPointData<T>::VectorDataType::iterator;
// find function to avoid including the whole algorithm header
VectorIt find(VectorIt first, VectorIt last, const std::array<T, 3> &value) {
for (; first != last; ++first) {
if (*first == value) {
return first;
}
}
return last;
}
// helper function for duplicate removal
template <class ElementType>
void replaceNode(ElementType &elements, std::pair<unsigned, unsigned> node) {
for (unsigned i = 0; i < elements.size(); ++i) {
for (unsigned j = 0; j < elements[i].size(); ++j) {
if (elements[i][j] == node.first) {
elements[i][j] = node.second;
}
}
}
};
public:
const std::vector<std::array<T, 3>> &getNodes() const { return nodes; }
std::vector<std::array<T, 3>> &getNodes() { return nodes; }
template <int D, typename std::enable_if<D == 1, int>::type = 0>
std::vector<std::array<unsigned, D>> &getElements() {
return vertices;
}
template <int D, typename std::enable_if<D == 2, int>::type = 0>
std::vector<std::array<unsigned, D>> &getElements() {
return lines;
}
template <int D, typename std::enable_if<D == 3, int>::type = 0>
std::vector<std::array<unsigned, D>> &getElements() {
return triangles;
}
template <int D, typename std::enable_if<D == 4, int>::type = 0>
std::vector<std::array<unsigned, D>> &getElements() {
return tetras;
}
template <int D, typename std::enable_if<D == 8, int>::type = 0>
std::vector<std::array<unsigned, D>> &getElements() {
return hexas;
}
lsPointData<T> &getPointData() { return pointData; }
const lsPointData<T> &getPointData() const { return pointData; }
lsPointData<T> &getCellData() { return cellData; }
const lsPointData<T> &getCellData() const { return cellData; }
unsigned insertNextNode(const std::array<T, 3> &node) {
nodes.push_back(node);
return nodes.size() - 1;
}
unsigned insertNextVertex(const std::array<unsigned, 1> &vertex) {
vertices.push_back(vertex);
return vertices.size() - 1;
}
unsigned insertNextLine(const std::array<unsigned, 2> &line) {
lines.push_back(line);
return lines.size() - 1;
}
unsigned insertNextTriangle(const std::array<unsigned, 3> &triangle) {
triangles.push_back(triangle);
return triangles.size() - 1;
}
unsigned insertNextTetra(const std::array<unsigned, 4> &tetra) {
tetras.push_back(tetra);
return tetras.size() - 1;
}
unsigned insertNextHexa(const std::array<unsigned, 8> &hexa) {
hexas.push_back(hexa);
return hexas.size() - 1;
}
unsigned insertNextElement(const std::array<unsigned, 1> &vertex) {
vertices.push_back(vertex);
return vertices.size() - 1;
}
unsigned insertNextElement(const std::array<unsigned, 2> &line) {
lines.push_back(line);
return lines.size() - 1;
}
unsigned insertNextElement(const std::array<unsigned, 3> &triangle) {
triangles.push_back(triangle);
return triangles.size() - 1;
}
unsigned insertNextElement(const std::array<unsigned, 4> &tetra) {
tetras.push_back(tetra);
return tetras.size() - 1;
}
unsigned insertNextElement(const std::array<unsigned, 8> &hexa) {
hexas.push_back(hexa);
return hexas.size() - 1;
}
void removeDuplicateNodes() {
std::vector<std::array<T, 3>> newNodes;
// can just push first point since it cannot be duplicate
newNodes.push_back(nodes[0]);
// now check for duplicates
// pair of oldId <-> newId
std::vector<std::pair<unsigned, unsigned>> duplicates;
bool adjusted = false;
for (unsigned i = 1; i < nodes.size(); ++i) {
auto it = find(newNodes.begin(), newNodes.end(), nodes[i]);
if (it != newNodes.end()) {
adjusted = true;
// if duplicate point, save it to be replaced
unsigned nodeId = std::distance(newNodes.begin(), it);
duplicates.push_back(std::make_pair(i, nodeId));
} else {
if (adjusted)
duplicates.push_back(std::make_pair(i, newNodes.size()));
newNodes.push_back(nodes[i]);
}
}
nodes = newNodes;
// now replace in vertices
// TODO also need to shift down all other nodes
for (unsigned i = 0; i < duplicates.size(); ++i) {
replaceNode(vertices, duplicates[i]);
replaceNode(lines, duplicates[i]);
replaceNode(triangles, duplicates[i]);
replaceNode(tetras, duplicates[i]);
replaceNode(hexas, duplicates[i]);
}
}
void append(const lsMesh<T> &passedMesh) {
const unsigned numberOfOldNodes = nodes.size();
// append new nodes
nodes.insert(nodes.end(), passedMesh.nodes.begin(), passedMesh.nodes.end());
// go through all elements and increase node IDs to match new IDS
const unsigned numberOfVertices = vertices.size();
vertices.insert(vertices.end(), passedMesh.vertices.begin(),
passedMesh.vertices.end());
for (unsigned i = numberOfVertices;
i < passedMesh.vertices.size() + numberOfVertices; ++i) {
vertices[i][0] += numberOfOldNodes;
}
const unsigned numberOfLines = lines.size();
lines.insert(lines.end(), passedMesh.lines.begin(), passedMesh.lines.end());
for (unsigned i = numberOfLines;
i < passedMesh.lines.size() + numberOfLines; ++i) {
for (unsigned d = 0; d < 2; ++d) {
lines[i][d] += numberOfOldNodes;
}
}
const unsigned numberOfTriangles = triangles.size();
triangles.insert(triangles.end(), passedMesh.triangles.begin(),
passedMesh.triangles.end());
for (unsigned i = numberOfTriangles;
i < passedMesh.triangles.size() + numberOfTriangles; ++i) {
for (unsigned d = 0; d < 3; ++d) {
triangles[i][d] += numberOfOldNodes;
}
}
const unsigned numberOfTetras = tetras.size();
tetras.insert(tetras.end(), passedMesh.tetras.begin(),
passedMesh.tetras.end());
for (unsigned i = numberOfTetras;
i < passedMesh.tetras.size() + numberOfTetras; ++i) {
for (unsigned d = 0; d < 4; ++d) {
tetras[i][d] += numberOfOldNodes;
}
}
const unsigned numberOfHexas = hexas.size();
hexas.insert(hexas.end(), passedMesh.hexas.begin(), passedMesh.hexas.end());
for (unsigned i = numberOfHexas;
i < passedMesh.hexas.size() + numberOfHexas; ++i) {
for (unsigned d = 0; d < 8; ++d) {
hexas[i][d] += numberOfOldNodes;
}
}
// Append data
// TODO need to adjust lsVTKWriter to deal with different data correctly
// currently this only works for vertex only meshes
pointData.append(passedMesh.pointData);
cellData.append(passedMesh.cellData);
// if(lsPointData<T>::scalarData.size() < nodes.size())
for (unsigned i = 0; i < pointData.getScalarDataSize(); ++i) {
pointData.getScalarData(i)->resize(vertices.size());
}
for (unsigned i = 0; i < pointData.getVectorDataSize(); ++i) {
pointData.getVectorData(i)->resize(vertices.size());
}
for (unsigned i = 0; i < cellData.getScalarDataSize(); ++i) {
cellData.getScalarData(i)->resize(vertices.size());
}
for (unsigned i = 0; i < cellData.getVectorDataSize(); ++i) {
cellData.getVectorData(i)->resize(vertices.size());
}
}
void clear() {
nodes.clear();
vertices.clear();
lines.clear();
triangles.clear();
tetras.clear();
hexas.clear();
pointData.clear();
cellData.clear();
}
void print() {
std::cout << "lsMesh:" << std::endl;
std::cout << "Number of Nodes: " << nodes.size() << std::endl;
if (vertices.size() > 0)
std::cout << "Number of Vertices: " << vertices.size() << std::endl;
if (lines.size() > 0)
std::cout << "Number of Lines: " << lines.size() << std::endl;
if (triangles.size() > 0)
std::cout << "Number of Triangles: " << triangles.size() << std::endl;
if (tetras.size() > 0)
std::cout << "Number of Tetrahedrons: " << tetras.size() << std::endl;
if (hexas.size() > 0)
std::cout << "Number of Hexas: " << hexas.size() << std::endl;
// pointData
if (pointData.getScalarDataSize() > 0) {
std::cout << "Scalar data:" << std::endl;
for (unsigned i = 0; i < pointData.getScalarDataSize(); ++i) {
std::cout << " \"" << pointData.getScalarDataLabel(i) << "\" of size "
<< pointData.getScalarData(i)->size() << std::endl;
}
}
if (pointData.getVectorDataSize() > 0) {
std::cout << "Vector data:" << std::endl;
for (unsigned i = 0; i < pointData.getVectorDataSize(); ++i) {
std::cout << " \"" << pointData.getVectorDataLabel(i) << "\" of size "
<< pointData.getVectorData(i)->size() << std::endl;
}
}
// cellData
if (cellData.getScalarDataSize() > 0) {
std::cout << "Scalar data:" << std::endl;
for (unsigned i = 0; i < cellData.getScalarDataSize(); ++i) {
std::cout << " \"" << cellData.getScalarDataLabel(i) << "\" of size "
<< cellData.getScalarData(i)->size() << std::endl;
}
}
if (cellData.getVectorDataSize() > 0) {
std::cout << "Vector data:" << std::endl;
for (unsigned i = 0; i < cellData.getVectorDataSize(); ++i) {
std::cout << " \"" << cellData.getVectorDataLabel(i) << "\" of size "
<< cellData.getVectorData(i)->size() << std::endl;
}
}
}
};
#endif // LS_MESH_HPP
// add all template specialisations for this class
PRECOMPILE_PRECISION(lsMesh); | 33.022082 | 80 | 0.615208 | [
"mesh",
"vector"
] |
44a11ec5c61d524f910f147042f796f470bea780 | 1,903 | hpp | C++ | include/hxhim/float.hpp | hpc/hxhim | 1a2224a200cb5a9fae33da13720e68beb5bee746 | [
"BSD-3-Clause"
] | 2 | 2020-11-25T17:45:58.000Z | 2021-12-21T02:01:16.000Z | include/hxhim/float.hpp | hpc/hxhim | 1a2224a200cb5a9fae33da13720e68beb5bee746 | [
"BSD-3-Clause"
] | null | null | null | include/hxhim/float.hpp | hpc/hxhim | 1a2224a200cb5a9fae33da13720e68beb5bee746 | [
"BSD-3-Clause"
] | 1 | 2021-10-11T19:54:05.000Z | 2021-10-11T19:54:05.000Z | #ifndef HXHIM_FLOAT_FUNCTIONS_HPP
#define HXHIM_FLOAT_FUNCTIONS_HPP
#include <cstddef>
#include "hxhim/constants.h"
#include "hxhim/float.h"
#include "hxhim/struct.h"
namespace hxhim {
int PutFloat(hxhim_t *hx,
void *subject, std::size_t subject_len, enum hxhim_data_t subject_type,
void *predicate, std::size_t predicate_len, enum hxhim_data_t predicate_type,
float *object,
const hxhim_put_permutation_t permutations);
int GetFloat(hxhim_t *hx,
void *subject, std::size_t subject_len, enum hxhim_data_t subject_type,
void *predicate, std::size_t predicate_len, enum hxhim_data_t predicate_type);
int GetOpFloat(hxhim_t *hx,
void *subject, std::size_t subject_len, enum hxhim_data_t subject_type,
void *predicate, std::size_t predicate_len, enum hxhim_data_t predicate_type,
std::size_t num_records, enum hxhim_getop_t op);
int BPutFloat(hxhim_t *hx,
void **subjects, std::size_t *subject_lens, enum hxhim_data_t *subject_types,
void **predicates, std::size_t *predicate_lens, enum hxhim_data_t *predicate_types,
float **objects,
const hxhim_put_permutation_t *permutations,
const std::size_t count);
int BGetFloat(hxhim_t *hx,
void **subjects, std::size_t *subject_lens, enum hxhim_data_t *subject_types,
void **predicates, std::size_t *predicate_lens, enum hxhim_data_t *predicate_types,
const std::size_t count);
int BGetOpFloat(hxhim_t *hx,
void **subjects, std::size_t *subject_lens, enum hxhim_data_t *subject_types,
void **predicates, std::size_t *predicate_lens, enum hxhim_data_t *predicate_types,
std::size_t *num_records, enum hxhim_getop_t *ops,
const std::size_t count);
}
#endif
| 40.489362 | 99 | 0.673673 | [
"object"
] |
44a3e105e8df558e7f84989d0bdd6b213d825670 | 671 | cpp | C++ | context/dynamic/src/proxy_logger.cpp | ArcticNature/core | bb63529a6deadc83e5adc3b772738ab6ca6ba18a | [
"BSD-3-Clause"
] | null | null | null | context/dynamic/src/proxy_logger.cpp | ArcticNature/core | bb63529a6deadc83e5adc3b772738ab6ca6ba18a | [
"BSD-3-Clause"
] | null | null | null | context/dynamic/src/proxy_logger.cpp | ArcticNature/core | bb63529a6deadc83e5adc3b772738ab6ca6ba18a | [
"BSD-3-Clause"
] | null | null | null | // Copyright 2017 Stefano Pogliani <stefano@spogliani.net>
#include <string>
#include "core/context/context.h"
#include "core/model/logger.h"
using sf::core::context::Context;
using sf::core::context::ProxyLogger;
using sf::core::model::LogInfo;
using sf::core::model::LogLevel;
using sf::core::model::Logger;
ProxyLogger::ProxyLogger(std::string component) : Logger("") {
this->component_ = component;
}
ProxyLogger* ProxyLogger::operator->() {
return this;
}
void ProxyLogger::log(
LogLevel level, const std::string message,
LogInfo variables
) {
variables["<component>"] = this->component_;
Context::Logger()->log(level, message, variables);
}
| 21.645161 | 62 | 0.71237 | [
"model"
] |
44a41f6851b6311739c11cbba704f8548c33897d | 3,448 | cpp | C++ | test/c_api.cpp | Coloquinte/umo | 1f39c316d6584bbed22913aabaa4bfb5ee02d72b | [
"MIT"
] | 1 | 2021-04-24T20:56:25.000Z | 2021-04-24T20:56:25.000Z | test/c_api.cpp | Coloquinte/umo | 1f39c316d6584bbed22913aabaa4bfb5ee02d72b | [
"MIT"
] | null | null | null | test/c_api.cpp | Coloquinte/umo | 1f39c316d6584bbed22913aabaa4bfb5ee02d72b | [
"MIT"
] | null | null | null | #define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE C_API
#include <boost/test/unit_test.hpp>
#include "api/umo.h"
#include <cmath>
#include <string>
BOOST_AUTO_TEST_CASE(Creation) {
const char *err = NULL;
umo_model *model = umo_create_model(&err);
BOOST_CHECK(model);
BOOST_CHECK(!err);
umo_check(model, &err);
BOOST_CHECK(!err);
umo_destroy_model(model, &err);
BOOST_CHECK(!err);
}
BOOST_AUTO_TEST_CASE(Constant) {
const char *err = NULL;
umo_model *model = umo_create_model(&err);
BOOST_CHECK(!err);
long long a1 = umo_create_constant(model, 0.0, &err);
long long a2 = umo_create_constant(model, 0.0, &err);
// Check that constants are deduplicated
BOOST_CHECK_EQUAL(a1, a2);
long long b = umo_create_constant(model, 1.0, &err);
BOOST_CHECK(a1 != b);
// Check that different constants are Ok
double va = umo_get_float_value(model, a1, &err);
BOOST_CHECK(!err);
BOOST_CHECK_EQUAL(0.0, va);
double vb = umo_get_float_value(model, b, &err);
BOOST_CHECK(!err);
umo_check(model, &err);
BOOST_CHECK(!err);
BOOST_CHECK_EQUAL(1.0, vb);
umo_destroy_model(model, &err);
BOOST_CHECK(!err);
}
BOOST_AUTO_TEST_CASE(Decision) {
const char *err = NULL;
umo_model *model = umo_create_model(&err);
// Create a boolean decision variable
long long bool_dec =
umo_create_expression(model, UMO_OP_DEC_BOOL, 0, NULL, &err);
umo_set_float_value(model, bool_dec, 1.0, &err);
BOOST_CHECK(!err);
// Create an integer decision variable
long long int_lb = umo_create_constant(model, -1.0, &err);
long long int_ub = umo_create_constant(model, 3.0, &err);
long long int_ops[2] = {int_lb, int_ub};
long long int_dec =
umo_create_expression(model, UMO_OP_DEC_INT, 2, int_ops, &err);
umo_set_float_value(model, int_dec, 2.0, &err);
BOOST_CHECK(!err);
// Create a floar decision variable
long long float_lb = umo_create_constant(model, -1.5, &err);
long long float_ub = umo_create_constant(model, 3.5, &err);
long long float_ops[2] = {float_lb, float_ub};
long long float_dec =
umo_create_expression(model, UMO_OP_DEC_FLOAT, 2, float_ops, &err);
umo_set_float_value(model, float_dec, -0.5, &err);
BOOST_CHECK(!err);
umo_check(model, &err);
BOOST_CHECK(!err);
umo_destroy_model(model, &err);
BOOST_CHECK(!err);
}
BOOST_AUTO_TEST_CASE(Params) {
const char *err = NULL;
umo_model *model = umo_create_model(&err);
umo_set_float_parameter(model, "testFloatParam", 1.0, &err);
double resFloat = umo_get_float_parameter(model, "testFloatParam", &err);
BOOST_CHECK_EQUAL(resFloat, 1.0);
umo_set_string_parameter(model, "testStringParam", "testValue", &err);
const char *resString =
umo_get_string_parameter(model, "testStringParam", &err);
BOOST_CHECK_EQUAL(std::string(resString), "testValue");
umo_check(model, &err);
BOOST_CHECK(!err);
umo_destroy_model(model, &err);
BOOST_CHECK(!err);
}
BOOST_AUTO_TEST_CASE(Error) {
const char *err = NULL;
umo_model *model = umo_create_model(&err);
BOOST_CHECK(!err);
long long c = umo_create_constant(model, NAN, &err);
BOOST_CHECK(err != NULL);
BOOST_CHECK_EQUAL(c, -1);
free((char *)err);
err = NULL;
umo_check(model, &err);
BOOST_CHECK(!err);
umo_destroy_model(model, &err);
BOOST_CHECK(!err);
}
| 32.838095 | 77 | 0.679234 | [
"model"
] |
44a6ca8012eca41bd3e47cd966554a08c7a754e5 | 19,993 | cc | C++ | src/CCA/Components/LoadBalancers/ProfileDriver.cc | damu1000/Uintah | 0c768664c1fe0a80eff2bbbd9b837e27f281f0a5 | [
"MIT"
] | 2 | 2021-12-17T05:50:44.000Z | 2021-12-22T21:37:32.000Z | src/CCA/Components/LoadBalancers/ProfileDriver.cc | damu1000/Uintah | 0c768664c1fe0a80eff2bbbd9b837e27f281f0a5 | [
"MIT"
] | null | null | null | src/CCA/Components/LoadBalancers/ProfileDriver.cc | damu1000/Uintah | 0c768664c1fe0a80eff2bbbd9b837e27f281f0a5 | [
"MIT"
] | 1 | 2020-11-30T04:46:05.000Z | 2020-11-30T04:46:05.000Z | /*
* The MIT License
*
* Copyright (c) 1997-2020 The University of Utah
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*/
#include <CCA/Components/LoadBalancers/ProfileDriver.h>
#include <Core/Util/DebugStream.h>
#include <sstream>
#include <iomanip>
using namespace Uintah;
namespace Uintah {
extern DebugStream g_profile_stats;
extern DebugStream g_profile_stats2;
}
//______________________________________________________________________
//
void
ProfileDriver::setMinPatchSize( const std::vector<IntVector> & min_patch_size )
{
d_minPatchSize=min_patch_size;
costs.resize(d_minPatchSize.size());
d_minPatchSizeVolume.resize(d_minPatchSize.size());
for( int l = 0; l < (int)d_minPatchSize.size(); l++ ) {
d_minPatchSizeVolume[l]=d_minPatchSize[l][0]*d_minPatchSize[l][1]*d_minPatchSize[l][2];
}
}
//______________________________________________________________________
//
void
ProfileDriver::addContribution( const PatchSubset* patches, double cost )
{
if( patches ) {
//compute number of datapoints
int num_points=0;
for( int p = 0; p < patches->size(); p++ ) {
const Patch* patch=patches->get(p);
int l=patch->getLevel()->getIndex();
num_points+=patch->getNumCells()/d_minPatchSizeVolume[l];
}
double average_cost=cost/num_points;
//loop through patches
for( int p = 0; p < patches->size(); p++ ) {
const Patch* patch=patches->get(p);
int l = patch->getLevel()->getIndex();
//coarsen region by minimum patch size
IntVector low = patch->getCellLowIndex()/d_minPatchSize[l];
IntVector high = patch->getCellHighIndex()/d_minPatchSize[l];
//loop through datapoints
for( CellIterator iter(low,high); !iter.done(); iter++ ) {
//add cost to current contribution
costs[l][*iter].current+=average_cost;
//if(d_myworld->myRank()==0)
// std::cout << "level:" << l << " adding: " << average_cost << " to: " << *iter << " new total:" << costs[l][*iter].current << std::endl;
}
}
}
}
//______________________________________________________________________
//
void
ProfileDriver::outputError( const GridP currentGrid )
{
static int iter=0;
iter++;
std::vector<double> proc_costsm(d_myworld->nRanks(),0);
std::vector<double> proc_costsp(d_myworld->nRanks(),0);
std::vector<std::vector<double> > predicted_sum(currentGrid->numLevels()), measured_sum(currentGrid->numLevels());
double smape=0,max_error=0, smpe=0;
int num_patches=0;
//__________________________________
// each level
for (int l=0; l<currentGrid->numLevels();l++)
{
LevelP level=currentGrid->getLevel(l);
num_patches+=level->numPatches();
std::vector<Region> regions(level->numPatches());
predicted_sum[l].assign(level->numPatches(),0);
measured_sum[l].assign(level->numPatches(),0);
for(int p=0; p<level->numPatches();p++){
const Patch *patch = level->getPatch(p);
regions[p] = Region(patch->getCellLowIndex(),patch->getCellHighIndex());
}
std::vector<double> predicted(regions.size(),0), measured(regions.size(),0);
for(int r=0;r<(int)regions.size();r++)
{
//coarsen region by minimum patch size
IntVector low=regions[r].getLow()/d_minPatchSize[l];
IntVector high=regions[r].getHigh()/d_minPatchSize[l];
//loop through datapoints
for(CellIterator iter(low,high); !iter.done(); iter++)
{
//search for point in the map
std::map<IntVector,Contribution>::iterator it=costs[l].find(*iter);
//if in the map
if(it!=costs[l].end())
{
//add predicted and measured costs to respective arrays
predicted[r]+=it->second.weight;
measured[r]+=it->second.current;
}
}
}
//__________________________________
//allreduce sum weights
if(d_myworld->nRanks()>1)
{
Uintah::MPI::Allreduce(&predicted[0],&predicted_sum[l][0],predicted.size(),MPI_DOUBLE,MPI_SUM,d_myworld->getComm());
Uintah::MPI::Allreduce(&measured[0],&measured_sum[l][0],measured.size(),MPI_DOUBLE,MPI_SUM,d_myworld->getComm());
}
//__________________________________
//
for( int p=0;p<level->numPatches();p++)
{
const Patch *patch=level->getPatch(p);
int proc=d_lb->getPatchwiseProcessorAssignment(patch);
proc_costsm[proc] += measured_sum[l][p];
proc_costsp[proc] += predicted_sum[l][p];
double error = (measured_sum[l][p] - predicted_sum[l][p])/(measured_sum[l][p] + predicted_sum[l][p]);
if(fabs(error)>max_error){
max_error=fabs(error);
}
smape += fabs(error);
smpe += error;
if(d_myworld->myRank()==0 && g_profile_stats2.active())
{
IntVector low(patch->getCellLowIndex()), high(patch->getCellHighIndex());
g_profile_stats2 << iter << " " << patch->getID() << " " << (measured_sum[l][p]-predicted_sum[l][p])/(measured_sum[l][p]+predicted_sum[l][p]) << " "
<< measured_sum[l][p] << " " << predicted_sum[l][p] << " " << l << " "
<< low[0] << " " << low[1] << " " << low[2] << " " << high[0] << " " << high[1] << " " << high[2] << std::endl;
}
}
//__________________________________
// debugging output
if(d_myworld->myRank()==0)
{
//calculate total cost for normalization
double total_measured = 0;
double total_predicted = 0;
double total_measured_error = 0;
double total_measured_percent_error = 0;
double total_volume=0;
for(int r=0;r<(int)regions.size();r++)
{
total_measured += measured_sum[l][r];
total_predicted += predicted_sum[l][r];
total_measured_error += fabs(measured_sum[l][r]-predicted_sum[l][r]);
total_measured_percent_error += fabs(measured_sum[l][r]-predicted_sum[l][r])/measured_sum[l][r];
total_volume+=regions[r].getVolume();
}
if(d_myworld->myRank()==0 && g_profile_stats.active())
{
g_profile_stats << "Profile Error: " << l << " " << total_measured_error/regions.size() << " " << total_measured_percent_error/regions.size() << " " << total_measured << " " << total_predicted << std::endl;
}
}
}
smpe/=num_patches;
smape/=num_patches;
if(d_myworld->myRank()==0 && g_profile_stats.active())
{
std::cout << "SMPE: " << smpe << " sMAPE: " << smape << " MAXsPE: " << max_error << std::endl;
}
double meanCostm = 0;
double meanCostp = 0;
double maxCostm = proc_costsm[0];
double maxCostp = proc_costsp[0];
int maxLocm = 0;
int maxLocp = 0;
for(int p=0;p<d_myworld->nRanks();p++)
{
meanCostm+=proc_costsm[p];
meanCostp+=proc_costsp[p];
if(maxCostm<proc_costsm[p])
{
maxCostm=proc_costsm[p];
maxLocm=p;
}
if(maxCostp<proc_costsp[p])
{
maxCostp=proc_costsp[p];
maxLocp=p;
}
}
if(d_myworld->myRank()==0 && g_profile_stats.active())
{
g_profile_stats << "LoadBalance Measured: Mean:" << meanCostm/d_myworld->nRanks() << " Max:" << maxCostm << " on processor " << maxLocm << std::endl;
g_profile_stats << "LoadBalance Predicted: Mean:" << meanCostp/d_myworld->nRanks() << " Max:" << maxCostp << " on processor " << maxLocp << std::endl;
}
#if 0
if(maxCostm/maxCostp>1.1)
{
stringstream str;
if(d_myworld->myRank()==0 && g_profile_stats.active())
{
g_profile_stats << d_myworld->myRank() << " Error measured/predicted do not line up, patch cost processor " << maxLocm << " patches:\n";
}
//for each level
for (int l=0; l<currentGrid->numLevels();l++)
{
LevelP level=currentGrid->getLevel(l);
std::vector<Region> regions(level->numPatches());
for(int p=0; p<level->numPatches();p++)
{
const Patch *patch=level->getPatch(p);
regions[p]=Region(patch->getCellLowIndex(),patch->getCellHighIndex());
}
double maxError=0;
int maxLoc=0;
for(unsigned int r=0; r<regions.size();r++)
{
const Patch *patch=level->getPatch(r);
int proc=d_lb->getPatchwiseProcessorAssignment(patch);
if(proc==maxLocm)
{
if(d_myworld->myRank()==0 && g_profile_stats.active())
{
g_profile_stats << " level: " << l << " region: " << regions[r] << " measured:" << measured_sum[l][r] << " predicted:" << predicted_sum[l][r] << std::endl;
}
//find max error region
double error=measured_sum[l][r]-predicted_sum[l][r];
if(error>maxError)
{
maxError=error;
maxLoc=r;
}
}
}
IntVector low=regions[maxLoc].getLow()/d_minPatchSize[l];
IntVector high=regions[maxLoc].getHigh()/d_minPatchSize[l];
if(d_myworld->myRank()==0)
str << " map entries for region:" << regions[maxLoc] << std::endl;
//loop through datapoints
for(CellIterator iter(low,high); !iter.done(); iter++)
{
//search for point in the map
std::map<IntVector,Contribution>::iterator it=costs[l].find(*iter);
//if in the map
if(it!=costs[l].end())
{
str << " " << d_myworld->myRank() << " level: " << l << " key: " << it->first << " measured: " << it->second.current << " predicted: " << it->second.weight << std::endl;
}
}
}
for(int p=0;p<d_myworld->nRanks();p++)
{
Uintah::MPI::Barrier(d_myworld->getComm());
if(d_myworld->myRank()==0 && g_profile_stats.active())
{
g_profile_stats << str.str();
}
}
}
#endif
}
//______________________________________________________________________
//
void ProfileDriver::finalizeContributions(const GridP currentGrid)
{
//if(d_myworld->myRank()==0)
// std::cout << "Finalizing Contributions in cost profiler on timestep: " << d_timesteps << "\n";
if(g_profile_stats.active())
{
outputError(currentGrid);
}
d_timesteps++;
//for each level
for(int l=0;l<(int)costs.size();l++)
{
//for each datapoint
for(std::map<IntVector,Contribution>::iterator iter=costs[l].begin();iter!=costs[l].end();)
{
//copy the iterator (so it can be deleted if we need to)
std::map<IntVector,Contribution>::iterator it=iter;
//create a reference to the data
Contribution &data=it->second;
//update timestep
if(data.current>0) {
data.timestep=0;
}else{
data.timestep++; //this keeps track of how long it has been since the data has been updated on this processor
}
if( d_timesteps <= 2 )
{
//first couple timesteps should be set to last timestep to initialize the system
//the first couple timesteps are not representative of the actual cost as extra things
//are occuring.
//if(data.current==0)
// std::cout << d_myworld->myRank() << "WARNING current is equal to 0 at " << it->first << " weight: " << data.weight << " current: " << data.current << std::endl;
data.weight=data.current;
data.timestep=0;
}
else
{
if(d_type==MEMORY)
{
//update exponential average See Equation 5.4 of Justin's Dissertation
data.weight = d_alpha * data.current + (1-d_alpha) * data.weight;
}
else //TYPE IS KALMAN See Eqs. 5.6 to 5.9
{
double m = data.p + d_phi;
double k = m / ( m + d_r );
data.p = (1-k) * m; //computing covariance
//std::cout << setprecision(12);
//std::cout << "m: " << m << " k:" << k << " p:" << data.p << std::endl;
data.weight = data.weight + k * (data.current - data.weight);
}
}
//reset current
data.current=0;
//increment the iterator (doing it here because erasing might invalidate the iterator)
iter++;
//if the data is empty or old
if ( data.weight==0 || data.timestep>log(.001*d_alpha)/log(1-d_alpha))
{
//std::cout << d_myworld->myRank() << " erasing data on level " << l << " at index: " << it->first << " data.timestep: " << data.timestep << " threshold: " << log(.001*d_alpha)/log(1-d_alpha) << std::endl;
//erase saved iterator in order to save space and time
costs[l].erase(it);
}
}
}
}
//______________________________________________________________________
//
void ProfileDriver::getWeights(int l, const std::vector<Region> ®ions, std::vector<double> &weights)
{
if(regions.size()==0){
return;
}
weights.resize(regions.size());
std::vector<double> partial_weights(regions.size(),0);
for(int r=0;r<(int)regions.size();r++)
{
//coarsen region by minimum patch size
IntVector low = regions[r].getLow()/d_minPatchSize[l];
IntVector high = regions[r].getHigh()/d_minPatchSize[l];
//loop through datapoints
for(CellIterator iter(low,high); !iter.done(); iter++)
{
//search for point in the map so we don't inadvertantly add it to the map. If it doesn't exist on this processor
//it should exist on another processor
std::map<IntVector,Contribution>::iterator it=costs[l].find(*iter);
//if in the map
if(it!=costs[l].end())
{
//add cost to weight
partial_weights[r]+=it->second.weight;
}
}
}
//allreduce sum weights
if(d_myworld->nRanks()>1){
Uintah::MPI::Allreduce(&partial_weights[0],&weights[0],weights.size(),MPI_DOUBLE,MPI_SUM,d_myworld->getComm());
}
}
//______________________________________________________________________
//
void ProfileDriver::initializeWeights(const Grid* oldgrid, const Grid* newgrid)
{
if( d_timesteps == 0 ){
return;
}
//__________________________________
////for each level
for(int l=1;l<newgrid->numLevels();l++)
{
std::vector<Region> old_level;
if(oldgrid && oldgrid->numLevels()>l)
{
//create old_level vector
for(int p=0; p<oldgrid->getLevel(l)->numPatches(); p++)
{
const Patch* patch = oldgrid->getLevel(l)->getPatch(p);
old_level.push_back(Region(patch->getCellLowIndex(), patch->getCellHighIndex()));
}
}
//get weights on old_level
std::vector<double> weights;
getWeights(l,old_level,weights);
#if 1
double volume=0;
double weight=0;
//compute average cost per datapoint
for(int r=0;r<(int)old_level.size();r++)
{
volume += old_level[r].getVolume();
weight += weights[r];
}
double initial_cost=weight/volume*d_minPatchSizeVolume[l];
#elif 1
double weight = DBL_MAX;
//compute minimum cost per datapoint
for(int r=0;r<(int)old_level.size();r++)
{
if(weights[r]/old_level[r].getVolume()<weight)
weight=weights[r]/old_level[r].getVolume();
}
double initial_cost=weight*d_minPatchSizeVolume[l]*2;
#else
double weight=0;
//compute maximum cost per datapoint
for(int r=0;r<(int)old_level.size();r++)
{
if(weights[r]/old_level[r].getVolume()>weight)
weight=weights[r]/old_level[r].getVolume();
}
double initial_cost=weight*d_minPatchSizeVolume[l];
#endif
//if there is no cost data
if(initial_cost==0)
{
//set each datapoint to the same small value
initial_cost=1;
}
//compute regions in new level that are not in old
std::vector<Region> new_regions_partial, new_regions, dnew, dold(old_level.begin(),old_level.end());
//create dnew to contain a subset of the new patches
for(int p=0; p<newgrid->getLevel(l)->numPatches(); p++)
{
const Patch* patch = newgrid->getLevel(l)->getPatch(p);
//distribute regions accross processors in order to parallelize the differencing operation
if(p%d_myworld->nRanks()==d_myworld->myRank())
dnew.push_back(Region(patch->getCellLowIndex(), patch->getCellHighIndex()));
}
//compute difference
new_regions_partial=Region::difference(dnew, dold);
//gather new regions onto each processor (needed to erase old data)
int mysize=new_regions_partial.size();
std::vector<int> recvs(d_myworld->nRanks(),0), displs(d_myworld->nRanks(),0);
//gather new regions counts
if(d_myworld->nRanks()>1)
Uintah::MPI::Allgather(&mysize,1,MPI_INT,&recvs[0],1,MPI_INT,d_myworld->getComm());
else
recvs[0]=mysize;
int size=recvs[0];
recvs[0]*=sizeof(Region);
for(int p=1;p<d_myworld->nRanks();p++)
{
//compute displacements
displs[p]=displs[p-1]+recvs[p-1];
//compute number of regions
size+=recvs[p];
//convert to bytes
recvs[p]*=sizeof(Region);
}
new_regions.resize(size);
//gather the regions
if(d_myworld->nRanks()>1)
{
Uintah::MPI::Allgatherv(&new_regions_partial[0], recvs[d_myworld->myRank()], MPI_BYTE,
&new_regions[0], &recvs[0], &displs[0], MPI_BYTE, d_myworld->getComm());
}
else
new_regions.swap(new_regions_partial);
#if 0
if(d_myworld->myRank()==0)
{
std::cout << " Old Regions: ";
for(std::vector<Region>::iterator it=old_level.begin();it!=old_level.end();it++)
{
IntVector low=it->getLow()/d_minPatchSize[l];
IntVector high=it->getHigh()/d_minPatchSize[l];
for(CellIterator iter(low,high); !iter.done(); iter++)
std::cout << *iter << " ";
}
std::cout << std::endl;
std::cout << " New Regions: ";
for(std::vector<Region>::iterator it=new_regions.begin();it!=new_regions.end();it++)
{
IntVector low=it->getLow()/d_minPatchSize[l];
IntVector high=it->getHigh()/d_minPatchSize[l];
for(CellIterator iter(low,high); !iter.done(); iter++)
std::cout << *iter << " ";
}
std::cout << std::endl;
}
#endif
int p=0;
//initialize weights
for(std::vector<Region>::iterator it=new_regions.begin();it!=new_regions.end();it++)
{
//add regions to my map
IntVector low = it->getLow()/d_minPatchSize[l];
IntVector high = it->getHigh()/d_minPatchSize[l];
//loop through datapoints
for(CellIterator iter(low,high); !iter.done(); iter++)
{
std::map<IntVector,Contribution>::iterator it=costs[l].find(*iter);
//erase any old data in map
if(it!=costs[l].end()){
costs[l].erase(it);
}
if(p++%d_myworld->nRanks()==d_myworld->myRank()) //distribute new regions accross processors
{
//add cost to current contribution
costs[l][*iter].weight=initial_cost;
// if(l==2)
// std::cout << " initializing " << *iter*d_minPatchSize[l] << " to " << initial_cost << std::endl;
}
} //end cell iteration
} //end region iteration
}// end levels iteration
}
void
ProfileDriver::reset()
{
for( int i=0;i<(int)costs.size();i++ ) {
costs[i].clear();
}
d_timesteps = 0;
}
| 32.615008 | 213 | 0.619517 | [
"vector"
] |
44a951e684f66469555348d8626a97feae0ffbaa | 901 | cpp | C++ | wavesim/tests/src/test_obj_import.cpp | TheComet/wavesim | 90125d5273b96633e5f74666ddb707cedfa2fbf1 | [
"Apache-2.0"
] | 7 | 2018-01-25T10:58:39.000Z | 2021-05-08T08:08:37.000Z | wavesim/tests/src/test_obj_import.cpp | TheComet/wavesim | 90125d5273b96633e5f74666ddb707cedfa2fbf1 | [
"Apache-2.0"
] | 4 | 2018-03-06T15:47:13.000Z | 2018-03-07T19:07:45.000Z | wavesim/tests/src/test_obj_import.cpp | TheComet/wavesim | 90125d5273b96633e5f74666ddb707cedfa2fbf1 | [
"Apache-2.0"
] | 2 | 2018-02-18T02:02:31.000Z | 2020-02-16T09:49:12.000Z | #include "gmock/gmock.h"
#include "wavesim/mesh/mesh.h"
#include "wavesim/mesh/obj.h"
#define NAME obj_import
using namespace ::testing;
TEST(NAME, try_import_cube)
{
mesh_t* m;
ASSERT_THAT(mesh_create(&m, "test"), Eq(WS_OK));
ASSERT_THAT(obj_import_mesh("../wavesim/models/cube.obj", m), Eq(WS_OK));
/* This particular cube spans from [-5, 0, -5] to [5, 10, 5] */
EXPECT_THAT(AABB_AX(m->aabb), DoubleEq(-5));
EXPECT_THAT(AABB_AY(m->aabb), DoubleEq(0));
EXPECT_THAT(AABB_AZ(m->aabb), DoubleEq(-5));
EXPECT_THAT(AABB_BX(m->aabb), DoubleEq(5));
EXPECT_THAT(AABB_BY(m->aabb), DoubleEq(10));
EXPECT_THAT(AABB_BZ(m->aabb), DoubleEq(5));
/* There should be 8 vertices, 12 faces, and 36 indices */
EXPECT_THAT(mesh_vertex_count(m), Eq(8));
EXPECT_THAT(mesh_face_count(m), Eq(12));
EXPECT_THAT(mesh_index_count(m), Eq(36));
mesh_destroy(m);
}
| 30.033333 | 77 | 0.665927 | [
"mesh"
] |
44aa802563ab732dd57e2ee3c7bcea90c31e83e9 | 6,226 | hxx | C++ | src/Installers/Windows/AspNetCoreModule-Setup/IIS-Setup/IIS-Common/Include/multisza.hxx | legistek/AspNetCore | f8368097a909ba2618efbec5efa5e7e036d3a2e8 | [
"Apache-2.0"
] | 13,846 | 2020-01-07T21:33:57.000Z | 2022-03-31T20:28:11.000Z | src/Installers/Windows/AspNetCoreModule-Setup/IIS-Setup/IIS-Common/Include/multisza.hxx | legistek/AspNetCore | f8368097a909ba2618efbec5efa5e7e036d3a2e8 | [
"Apache-2.0"
] | 20,858 | 2020-01-07T21:28:23.000Z | 2022-03-31T23:51:40.000Z | src/Installers/Windows/AspNetCoreModule-Setup/IIS-Setup/IIS-Common/Include/multisza.hxx | legistek/AspNetCore | f8368097a909ba2618efbec5efa5e7e036d3a2e8 | [
"Apache-2.0"
] | 4,871 | 2020-01-07T21:27:37.000Z | 2022-03-31T21:22:44.000Z | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
#ifndef _MULTISZA_HXX_
#define _MULTISZA_HXX_
# include <stringa.h>
/*++
class MULTISZ:
Intention:
A light-weight multi-string class supporting encapsulated string class.
This object is derived from BUFFER class.
It maintains following state:
m_fValid - whether this object is valid -
used only by MULTISZ() init functions
* NYI: I need to kill this someday *
m_cchLen - string length cached when we update the string.
m_cStrings - number of strings.
Member Functions:
There are two categories of functions:
1) Safe Functions - which do integrity checking of state
2) UnSafe Functions - which do not do integrity checking, but
enable writing to the data stream freely.
(someday this will be enabled as Safe versions without
problem for users)
--*/
class MULTISZA : public BUFFER
{
public:
MULTISZA()
: BUFFER (),
m_cchLen ( 0),
m_cStrings(0)
{ Reset(); }
// creates a stack version of the MULTISZA object - uses passed in stack buffer
// MULTISZA does not free this pbInit on its own.
MULTISZA( __in_bcount(cbInit) CHAR * pbInit, DWORD cbInit)
: BUFFER( (BYTE *) pbInit, cbInit),
m_cchLen (0),
m_cStrings(0)
{}
MULTISZA( const CHAR * pchInit )
: BUFFER (),
m_cchLen ( 0),
m_cStrings(0)
{ AuxInit(pchInit); }
MULTISZA( const MULTISZA & str )
: BUFFER (),
m_cchLen ( 0),
m_cStrings(0)
{ AuxInit( str.QueryStr()); }
// BOOL IsValid(VOID) const { return ( BUFFER::IsValid()) ; }
//
// Checks and returns TRUE if this string has no valid data else FALSE
//
BOOL IsEmpty( VOID) const { return ( *QueryStr() == L'\0'); }
BOOL Append( const CHAR * pchInit ) {
return ((pchInit != NULL) ? (AuxAppend( pchInit,
(DWORD) (::strlen(pchInit)) * sizeof(CHAR)
)) :
TRUE);
}
BOOL Append( const CHAR * pchInit, DWORD cchLen ) {
return ((pchInit != NULL) ? (AuxAppend( pchInit,
cchLen * sizeof(CHAR))) :
TRUE);
}
BOOL Append( STRA & str )
{ return AuxAppend( str.QueryStr(),
(str.QueryCCH()) * sizeof(CHAR)); }
// Resets the internal string to be NULL string. Buffer remains cached.
VOID Reset( VOID)
{ DBG_ASSERT( QueryPtr() != NULL);
QueryStr()[0] = L'\0';
QueryStr()[1] = L'\0';
m_cchLen = 2;
m_cStrings = 0;
}
BOOL Copy( const CHAR * pchInit, IN DWORD cbLen ) {
if ( QueryPtr() ) { Reset(); }
return ( (pchInit != NULL) ?
AuxAppend( pchInit, cbLen, FALSE ):
TRUE);
}
BOOL Copy( const MULTISZA & str )
{ return ( Copy(str.QueryStr(), str.QueryCB())); }
//
// Returns the number of bytes in the string including the terminating
// NULLs
//
UINT QueryCB( VOID ) const
{ return ( m_cchLen * sizeof(CHAR)); }
//
// Returns # of characters in the string including the terminating NULLs
//
UINT QueryCCH( VOID ) const { return (m_cchLen); }
//
// Returns # of strings in the MULTISZA.
//
DWORD QueryStringCount( VOID ) const { return m_cStrings; }
//
// Makes a copy of the stored string in given buffer
//
BOOL CopyToBuffer( __out_ecount_opt(*lpcch) CHAR * lpszBuffer, LPDWORD lpcch) const;
//
// Return the string buffer
//
CHAR * QueryStrA( VOID ) const { return ( QueryStr()); }
CHAR * QueryStr( VOID ) const { return ((CHAR *) QueryPtr()); }
//
// Makes a clone of the current string in the string pointer passed in.
//
BOOL
Clone( OUT MULTISZA * pstrClone) const
{
return ((pstrClone == NULL) ?
(SetLastError(ERROR_INVALID_PARAMETER), FALSE) :
(pstrClone->Copy( *this))
);
} // MULTISZA::Clone()
//
// Recalculates the length of *this because we've modified the buffers
// directly
//
VOID RecalcLen( VOID )
{ m_cchLen = MULTISZA::CalcLength( QueryStr(), &m_cStrings ); }
//
// Calculate total character length of a MULTI_SZ, including the
// terminating NULLs.
//
static DWORD CalcLength( const CHAR * str,
LPDWORD pcStrings = NULL );
//
// Determine if the MULTISZA contains a specific string.
//
BOOL FindString( const CHAR * str );
BOOL FindString( STRA & str )
{ return FindString( str.QueryStr() ); }
//
// Determine if the MULTISZA contains a specific string - case-insensitive
//
BOOL FindStringNoCase( const CHAR * str );
BOOL FindStringNoCase( STRA & str )
{ return FindStringNoCase( str.QueryStr() ); }
//
// Used for scanning a MULTISZA.
//
const CHAR * First( VOID ) const
{ return *QueryStr() == L'\0' ? NULL : QueryStr(); }
const CHAR * Next( const CHAR * Current ) const
{ Current += ::strlen( Current ) + 1;
return *Current == L'\0' ? NULL : Current; }
BOOL
Equals(
MULTISZA* pmszRhs
);
private:
DWORD m_cchLen;
DWORD m_cStrings;
VOID AuxInit( const CHAR * pInit );
BOOL AuxAppend( const CHAR * pInit,
UINT cbStr, BOOL fAddSlop = TRUE );
};
//
// Quick macro for declaring a MULTISZA that will use stack memory of <size>
// bytes. If the buffer overflows then a heap buffer will be allocated
//
#define STACK_MULTISZA( name, size ) CHAR __ach##name[size]; \
MULTISZA name( __ach##name, sizeof( __ach##name ))
HRESULT
SplitCommaDelimitedString(
PCSTR pszList,
BOOL fTrimEntries,
BOOL fRemoveEmptyEntries,
MULTISZA * pmszList
);
#endif // !_MULTISZA_HXX_
| 27.548673 | 89 | 0.560713 | [
"object"
] |
44b0916ba5a076e6bc46d7b7d878e4f5d7a0a33e | 1,802 | cpp | C++ | display/display.cpp | DawidPi/gameForTMS | 0ba50dc12417a5cb07dfc5be0ecf4c144bd39c41 | [
"BSD-3-Clause"
] | null | null | null | display/display.cpp | DawidPi/gameForTMS | 0ba50dc12417a5cb07dfc5be0ecf4c144bd39c41 | [
"BSD-3-Clause"
] | null | null | null | display/display.cpp | DawidPi/gameForTMS | 0ba50dc12417a5cb07dfc5be0ecf4c144bd39c41 | [
"BSD-3-Clause"
] | null | null | null | #include "display.hpp"
#include "../Logger/Logger.h"
#define SetPixel(Pointer, x, y) \
Pointer[(x >> 5) + (y << 3)] |= (unsigned long)0x80000000 >> (x & 0x1f)
extern unsigned short int *textEkran;
extern unsigned long *ekran;
Display::Display(unsigned long *bufferLocation, size_t height, size_t width)
: m_bufferLocation(bufferLocation), m_height(height), m_width(width) {
LOG_INFO("");
drawFrame();
}
bool Display::setPixel(size_t x, size_t y) {
LOG_INFO("");
if (pixelInRange(x, m_height - y - 1)) {
SetPixel(m_bufferLocation, x, (m_height - y - 1));
return true;
}
return false;
}
bool Display::pixelInRange(size_t x, size_t y) {
if (x < m_width && y < m_height)
return true;
LOG_ERROR("Pixel out of range: x=" << x << " y=" << y);
return false;
}
void Display::drawFrame() {
for (size_t currentWidth = 0; currentWidth < m_width; ++currentWidth) {
for (size_t currentHeight = 0; currentHeight < m_height; ++currentHeight) {
if (currentWidth == 0 || currentWidth == m_width - 1 ||
currentHeight == 0 || currentHeight == m_height - 1) {
setPixel(currentWidth, currentHeight);
}
}
}
}
void Display::clear(){
LOG_INFO("");
size_t a;
for (a = 0; a < (40 * 16); a++)
textEkran[a] = ' ';
for (a = 0; a < (128 * 8); a++)
ekran[a] = 0;
}
void Display::draw(const Graphics::Drawable& object, const Graphics::Point2D<size_t>& origin){
LOG_INFO("");
for(size_t currentX =0; currentX < object.width(); ++currentX){
for(size_t currentY=0; currentY < object.height(); ++currentY){
Graphics::Point2D<size_t> currentPoint(currentX, currentY);
if(object.at(currentPoint)){
setPixel(currentX+origin.width(), currentY + origin.height());
}
}
}
}
| 28.15625 | 94 | 0.615982 | [
"object"
] |
44b4a176fd3473087ebd1a16b7d99d064138f827 | 471 | hpp | C++ | src/Client/GUI/GUIButton.hpp | fqhd/BuildBattle | f85ec857aa232313f4678514aa317af73c37de10 | [
"MIT"
] | 10 | 2021-08-17T20:55:52.000Z | 2022-03-28T00:45:14.000Z | src/Client/GUI/GUIButton.hpp | fqhd/BuildBattle | f85ec857aa232313f4678514aa317af73c37de10 | [
"MIT"
] | null | null | null | src/Client/GUI/GUIButton.hpp | fqhd/BuildBattle | f85ec857aa232313f4678514aa317af73c37de10 | [
"MIT"
] | 2 | 2021-07-05T18:49:56.000Z | 2021-07-10T22:03:17.000Z | #pragma once
#include "GUIRenderer.hpp"
#include "GUIAssets.hpp"
#include "InputManager.hpp"
#include "Math.hpp"
class GUIButton {
public:
void init(const math::vec4& destRect);
void update(float deltaTime);
void render();
bool isPressed();
private:
bool m_isPressed = false;
ColorRGBA8 m_baseColor;
ColorRGBA8 m_currentColor;
std::string m_string;
math::vec4 m_originalRect;
math::vec4 m_targetRect;
math::vec4 m_shadowRect;
math::vec4 m_destRect;
};
| 16.241379 | 39 | 0.745223 | [
"render"
] |
44b53c54a8f4b6702e246a481c1c97aec5142d5b | 1,402 | hpp | C++ | drape_frontend/animation/scale_animation.hpp | Dushistov/omim | e366dd2f7508dea305922d7bd91deea076fc4a58 | [
"Apache-2.0"
] | null | null | null | drape_frontend/animation/scale_animation.hpp | Dushistov/omim | e366dd2f7508dea305922d7bd91deea076fc4a58 | [
"Apache-2.0"
] | null | null | null | drape_frontend/animation/scale_animation.hpp | Dushistov/omim | e366dd2f7508dea305922d7bd91deea076fc4a58 | [
"Apache-2.0"
] | null | null | null | #pragma once
#include "animation.hpp"
#include "interpolators.hpp"
namespace df
{
class MapScaleAnimation : public Animation
{
public:
MapScaleAnimation(double startScale, double endScale,
m2::PointD const & globalScaleCenter, m2::PointD const & pxScaleCenter);
Animation::Type GetType() const override { return Animation::MapScale; }
TAnimObjects const & GetObjects() const override
{
return m_objects;
}
bool HasObject(TObject object) const override
{
return object == Animation::MapPlane;
}
TObjectProperties const & GetProperties(TObject object) const override;
bool HasProperty(TObject object, TProperty property) const override;
void Advance(double elapsedSeconds) override;
void Finish() override;
void SetMaxDuration(double maxDuration) override;
double GetDuration() const override;
bool IsFinished() const override;
bool GetProperty(TObject object, TProperty property, PropertyValue & value) const override;
bool GetTargetProperty(TObject object, TProperty property, PropertyValue & value) const override;
private:
bool GetProperty(TObject object, TProperty property, bool targetValue, PropertyValue & value) const;
ScaleInterpolator m_scaleInterpolator;
m2::PointD const m_pxScaleCenter;
m2::PointD const m_globalScaleCenter;
TObjectProperties m_properties;
TAnimObjects m_objects;
};
} // namespace df
| 26.961538 | 102 | 0.762482 | [
"object"
] |
44b934d109537755fdcd43f95a121ee949718228 | 4,847 | cpp | C++ | Userland/Libraries/LibGfx/FontDatabase.cpp | holdengreen/serenity | 0fccada6e9f714f76b2fbe0d189dcf4f26de38d4 | [
"BSD-2-Clause"
] | 1 | 2021-06-11T13:40:55.000Z | 2021-06-11T13:40:55.000Z | Userland/Libraries/LibGfx/FontDatabase.cpp | holdengreen/serenity | 0fccada6e9f714f76b2fbe0d189dcf4f26de38d4 | [
"BSD-2-Clause"
] | null | null | null | Userland/Libraries/LibGfx/FontDatabase.cpp | holdengreen/serenity | 0fccada6e9f714f76b2fbe0d189dcf4f26de38d4 | [
"BSD-2-Clause"
] | null | null | null | /*
* Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
*
* SPDX-License-Identifier: BSD-2-Clause
*/
#include <AK/NonnullRefPtrVector.h>
#include <AK/QuickSort.h>
#include <LibCore/DirIterator.h>
#include <LibGfx/Font.h>
#include <LibGfx/FontDatabase.h>
#include <LibGfx/Typeface.h>
#include <LibTTF/Font.h>
#include <stdlib.h>
namespace Gfx {
static FontDatabase* s_the;
FontDatabase& FontDatabase::the()
{
if (!s_the)
s_the = new FontDatabase;
return *s_the;
}
Font& FontDatabase::default_font()
{
static Font* font;
if (!font) {
font = FontDatabase::the().get_by_name("Katica 10 400");
VERIFY(font);
}
return *font;
}
Font& FontDatabase::default_fixed_width_font()
{
static Font* font;
if (!font) {
font = FontDatabase::the().get_by_name("Csilla 10 400");
VERIFY(font);
}
return *font;
}
Font& FontDatabase::default_bold_fixed_width_font()
{
static Font* font;
if (!font) {
font = FontDatabase::the().get_by_name("Csilla 10 700");
VERIFY(font);
}
return *font;
}
Font& FontDatabase::default_bold_font()
{
static Font* font;
if (!font) {
font = FontDatabase::the().get_by_name("Katica 10 700");
VERIFY(font);
}
return *font;
}
struct FontDatabase::Private {
HashMap<String, RefPtr<Gfx::Font>> full_name_to_font_map;
Vector<RefPtr<Typeface>> typefaces;
};
FontDatabase::FontDatabase()
: m_private(make<Private>())
{
Core::DirIterator dir_iterator("/res/fonts", Core::DirIterator::SkipDots);
if (dir_iterator.has_error()) {
warnln("DirIterator: {}", dir_iterator.error_string());
exit(1);
}
while (dir_iterator.has_next()) {
auto path = dir_iterator.next_full_path();
if (path.ends_with(".font"sv)) {
if (auto font = Gfx::BitmapFont::load_from_file(path)) {
m_private->full_name_to_font_map.set(font->qualified_name(), font);
auto typeface = get_or_create_typeface(font->family(), font->variant());
typeface->add_bitmap_font(font);
}
} else if (path.ends_with(".ttf"sv)) {
// FIXME: What about .otf and .woff
if (auto font = TTF::Font::load_from_file(path)) {
auto typeface = get_or_create_typeface(font->family(), font->variant());
typeface->set_ttf_font(font);
}
}
}
}
FontDatabase::~FontDatabase()
{
}
void FontDatabase::for_each_font(Function<void(const Gfx::Font&)> callback)
{
Vector<RefPtr<Gfx::Font>> fonts;
fonts.ensure_capacity(m_private->full_name_to_font_map.size());
for (auto& it : m_private->full_name_to_font_map)
fonts.append(it.value);
quick_sort(fonts, [](auto& a, auto& b) { return a->qualified_name() < b->qualified_name(); });
for (auto& font : fonts)
callback(*font);
}
void FontDatabase::for_each_fixed_width_font(Function<void(const Gfx::Font&)> callback)
{
Vector<RefPtr<Gfx::Font>> fonts;
fonts.ensure_capacity(m_private->full_name_to_font_map.size());
for (auto& it : m_private->full_name_to_font_map) {
if (it.value->is_fixed_width())
fonts.append(it.value);
}
quick_sort(fonts, [](auto& a, auto& b) { return a->qualified_name() < b->qualified_name(); });
for (auto& font : fonts)
callback(*font);
}
RefPtr<Gfx::Font> FontDatabase::get_by_name(const StringView& name)
{
auto it = m_private->full_name_to_font_map.find(name);
if (it == m_private->full_name_to_font_map.end()) {
dbgln("Font lookup failed: '{}'", name);
return nullptr;
}
return it->value;
}
RefPtr<Gfx::Font> FontDatabase::get(const String& family, unsigned size, unsigned weight)
{
for (auto typeface : m_private->typefaces) {
if (typeface->family() == family && typeface->weight() == weight)
return typeface->get_font(size);
}
return nullptr;
}
RefPtr<Gfx::Font> FontDatabase::get(const String& family, const String& variant, unsigned size)
{
for (auto typeface : m_private->typefaces) {
if (typeface->family() == family && typeface->variant() == variant)
return typeface->get_font(size);
}
return nullptr;
}
RefPtr<Typeface> FontDatabase::get_or_create_typeface(const String& family, const String& variant)
{
for (auto typeface : m_private->typefaces) {
if (typeface->family() == family && typeface->variant() == variant)
return typeface;
}
auto typeface = adopt_ref(*new Typeface(family, variant));
m_private->typefaces.append(typeface);
return typeface;
}
void FontDatabase::for_each_typeface(Function<void(const Typeface&)> callback)
{
for (auto typeface : m_private->typefaces) {
callback(*typeface);
}
}
}
| 27.856322 | 98 | 0.636476 | [
"vector"
] |
44b9af4f04dc763aed86757580a89d651863a4e0 | 10,386 | cpp | C++ | platform/default/src/mbgl/text/bidi.cpp | roblabs/maplibre-gl-native | d62ff400c6f75750d71b563344b1ca1e07b9b576 | [
"BSD-2-Clause",
"BSD-3-Clause"
] | 4,234 | 2015-01-09T08:10:16.000Z | 2022-03-30T14:13:55.000Z | platform/default/src/mbgl/text/bidi.cpp | roblabs/maplibre-gl-native | d62ff400c6f75750d71b563344b1ca1e07b9b576 | [
"BSD-2-Clause",
"BSD-3-Clause"
] | 12,771 | 2015-01-01T20:27:42.000Z | 2022-03-24T18:14:44.000Z | platform/default/src/mbgl/text/bidi.cpp | roblabs/maplibre-gl-native | d62ff400c6f75750d71b563344b1ca1e07b9b576 | [
"BSD-2-Clause",
"BSD-3-Clause"
] | 1,571 | 2015-01-08T08:24:53.000Z | 2022-03-28T06:30:53.000Z | #include <mbgl/text/bidi.hpp>
#include <mbgl/util/traits.hpp>
#include <unicode/ubidi.h>
#include <unicode/ushape.h>
#include <memory>
#include <stdexcept>
#include <utility>
namespace mbgl {
class BiDiImpl {
public:
BiDiImpl() : bidiText(ubidi_open()), bidiLine(ubidi_open()) {
}
~BiDiImpl() {
ubidi_close(bidiText);
ubidi_close(bidiLine);
}
UBiDi* bidiText = nullptr;
UBiDi* bidiLine = nullptr;
};
BiDi::BiDi() : impl(std::make_unique<BiDiImpl>()) {}
BiDi::~BiDi() = default;
// Takes UTF16 input in logical order and applies Arabic shaping to the input while maintaining
// logical order. Output won't be intelligible until the bidirectional algorithm is applied
std::u16string applyArabicShaping(const std::u16string& input) {
UErrorCode errorCode = U_ZERO_ERROR;
const int32_t outputLength =
u_shapeArabic(mbgl::utf16char_cast<const UChar*>(input.c_str()), static_cast<int32_t>(input.size()), nullptr, 0,
(U_SHAPE_LETTERS_SHAPE & U_SHAPE_LETTERS_MASK) |
(U_SHAPE_TEXT_DIRECTION_LOGICAL & U_SHAPE_TEXT_DIRECTION_MASK),
&errorCode);
// Pre-flighting will always set U_BUFFER_OVERFLOW_ERROR
errorCode = U_ZERO_ERROR;
std::u16string outputText(outputLength, 0);
u_shapeArabic(mbgl::utf16char_cast<const UChar*>(input.c_str()), static_cast<int32_t>(input.size()), mbgl::utf16char_cast<UChar*>(&outputText[0]), outputLength,
(U_SHAPE_LETTERS_SHAPE & U_SHAPE_LETTERS_MASK) |
(U_SHAPE_TEXT_DIRECTION_LOGICAL & U_SHAPE_TEXT_DIRECTION_MASK),
&errorCode);
// If the algorithm fails for any reason, fall back to non-transformed text
if (U_FAILURE(errorCode))
return input;
return outputText;
}
void BiDi::mergeParagraphLineBreaks(std::set<size_t>& lineBreakPoints) {
int32_t paragraphCount = ubidi_countParagraphs(impl->bidiText);
for (int32_t i = 0; i < paragraphCount; i++) {
UErrorCode errorCode = U_ZERO_ERROR;
int32_t paragraphEndIndex;
ubidi_getParagraphByIndex(impl->bidiText, i, nullptr, ¶graphEndIndex, nullptr, &errorCode);
if (U_FAILURE(errorCode)) {
throw std::runtime_error(std::string("ProcessedBiDiText::mergeParagraphLineBreaks: ") +
u_errorName(errorCode));
}
lineBreakPoints.insert(static_cast<std::size_t>(paragraphEndIndex));
}
}
std::vector<std::u16string> BiDi::applyLineBreaking(std::set<std::size_t> lineBreakPoints) {
// BiDi::getLine will error if called across a paragraph boundary, so we need to ensure that all
// paragraph boundaries are included in the set of line break points. The calling code might not
// include the line break because it didn't need to wrap at that point, or because the text was
// separated with a more exotic code point such as (U+001C)
mergeParagraphLineBreaks(lineBreakPoints);
std::vector<std::u16string> transformedLines;
transformedLines.reserve(lineBreakPoints.size());
std::size_t start = 0;
for (std::size_t lineBreakPoint : lineBreakPoints) {
transformedLines.push_back(getLine(start, lineBreakPoint));
start = lineBreakPoint;
}
return transformedLines;
}
std::vector<std::u16string> BiDi::processText(const std::u16string& input,
std::set<std::size_t> lineBreakPoints) {
UErrorCode errorCode = U_ZERO_ERROR;
ubidi_setPara(impl->bidiText, mbgl::utf16char_cast<const UChar*>(input.c_str()), static_cast<int32_t>(input.size()),
UBIDI_DEFAULT_LTR, nullptr, &errorCode);
if (U_FAILURE(errorCode)) {
throw std::runtime_error(std::string("BiDi::processText: ") + u_errorName(errorCode));
}
return applyLineBreaking(std::move(lineBreakPoints));
}
std::vector<StyledText> BiDi::processStyledText(const StyledText& input, std::set<std::size_t> lineBreakPoints) {
std::vector<StyledText> lines;
const auto& inputText = input.first;
const auto& styleIndices = input.second;
UErrorCode errorCode = U_ZERO_ERROR;
ubidi_setPara(impl->bidiText, mbgl::utf16char_cast<const UChar*>(inputText.c_str()), static_cast<int32_t>(inputText.size()),
UBIDI_DEFAULT_LTR, nullptr, &errorCode);
if (U_FAILURE(errorCode)) {
throw std::runtime_error(std::string("BiDi::processStyledText: ") + u_errorName(errorCode));
}
mergeParagraphLineBreaks(lineBreakPoints);
std::size_t lineStartIndex = 0;
for (std::size_t lineBreakPoint : lineBreakPoints) {
StyledText line;
line.second.reserve(lineBreakPoint - lineStartIndex);
errorCode = U_ZERO_ERROR;
ubidi_setLine(impl->bidiText, static_cast<int32_t>(lineStartIndex), static_cast<int32_t>(lineBreakPoint), impl->bidiLine, &errorCode);
if (U_FAILURE(errorCode)) {
throw std::runtime_error(std::string("BiDi::processStyledText (setLine): ") + u_errorName(errorCode));
}
errorCode = U_ZERO_ERROR;
uint32_t runCount = ubidi_countRuns(impl->bidiLine, &errorCode);
if (U_FAILURE(errorCode)) {
throw std::runtime_error(std::string("BiDi::processStyledText (countRuns): ") + u_errorName(errorCode));
}
for (uint32_t runIndex = 0; runIndex < runCount; runIndex++) {
int32_t runLogicalStart;
int32_t runLength;
UBiDiDirection direction = ubidi_getVisualRun(impl->bidiLine, runIndex, &runLogicalStart, &runLength);
const bool isReversed = direction == UBIDI_RTL;
std::size_t logicalStart = lineStartIndex + runLogicalStart;
std::size_t logicalEnd = logicalStart + runLength;
if (isReversed) {
// Within this reversed section, iterate logically backwards
// Each time we see a change in style, render a reversed chunk
// of everything since the last change
std::size_t styleRunStart = logicalEnd;
uint8_t currentStyleIndex = styleIndices.at(styleRunStart - 1);
for (std::size_t i = logicalEnd - 1; i >= logicalStart; i--) {
if (currentStyleIndex != styleIndices.at(i) || i == logicalStart) {
std::size_t styleRunEnd = i == logicalStart ? i : i + 1;
std::u16string reversed = writeReverse(inputText, styleRunEnd, styleRunStart);
line.first += reversed;
for (std::size_t j = 0; j < reversed.size(); j++) {
line.second.push_back(currentStyleIndex);
}
currentStyleIndex = styleIndices.at(i);
styleRunStart = styleRunEnd;
}
if (i == 0) {
break;
}
}
} else {
line.first += input.first.substr(logicalStart, runLength);
line.second.insert(line.second.end(), styleIndices.begin() + logicalStart, styleIndices.begin() + logicalStart + runLength);
}
}
lines.push_back(line);
lineStartIndex = lineBreakPoint;
}
return lines;
}
std::u16string BiDi::writeReverse(const std::u16string& input, std::size_t logicalStart, std::size_t logicalEnd) {
UErrorCode errorCode = U_ZERO_ERROR;
auto logicalLength = static_cast<int32_t>(logicalEnd - logicalStart);
std::u16string outputText(logicalLength + 1, 0);
// UBIDI_DO_MIRRORING: Apply unicode mirroring of characters like parentheses
// UBIDI_REMOVE_BIDI_CONTROLS: Now that all the lines are set, remove control characters so that
// they don't show up on screen (some fonts have glyphs representing them)
int32_t outputLength =
ubidi_writeReverse(mbgl::utf16char_cast<const UChar*>(&input[logicalStart]),
logicalLength,
mbgl::utf16char_cast<UChar*>(&outputText[0]),
logicalLength + 1, // Extra room for null terminator, although we don't really need to have ICU write it for us
UBIDI_DO_MIRRORING | UBIDI_REMOVE_BIDI_CONTROLS,
&errorCode);
if (U_FAILURE(errorCode)) {
throw std::runtime_error(std::string("BiDi::writeReverse: ") + u_errorName(errorCode));
}
outputText.resize(outputLength); // REMOVE_BIDI_CONTROLS may have shrunk the string
return outputText;
}
std::u16string BiDi::getLine(std::size_t start, std::size_t end) {
UErrorCode errorCode = U_ZERO_ERROR;
ubidi_setLine(impl->bidiText, static_cast<int32_t>(start), static_cast<int32_t>(end), impl->bidiLine, &errorCode);
if (U_FAILURE(errorCode)) {
throw std::runtime_error(std::string("BiDi::getLine (setLine): ") + u_errorName(errorCode));
}
// Because we set UBIDI_REMOVE_BIDI_CONTROLS, the output may be smaller than what we reserve
// Setting UBIDI_INSERT_LRM_FOR_NUMERIC would require
// ubidi_getLength(pBiDi)+2*ubidi_countRuns(pBiDi)
const int32_t outputLength = ubidi_getProcessedLength(impl->bidiLine);
std::u16string outputText(outputLength, 0);
// UBIDI_DO_MIRRORING: Apply unicode mirroring of characters like parentheses
// UBIDI_REMOVE_BIDI_CONTROLS: Now that all the lines are set, remove control characters so that
// they don't show up on screen (some fonts have glyphs representing them)
int32_t finalLength = ubidi_writeReordered(impl->bidiLine,
mbgl::utf16char_cast<UChar*>(&outputText[0]),
outputLength,
UBIDI_DO_MIRRORING | UBIDI_REMOVE_BIDI_CONTROLS,
&errorCode);
outputText.resize(finalLength); // REMOVE_BIDI_CONTROLS may have shrunk the string
if (U_FAILURE(errorCode)) {
throw std::runtime_error(std::string("BiDi::getLine (writeReordered): ") +
u_errorName(errorCode));
}
return outputText;
}
} // end namespace mbgl
| 42.917355 | 164 | 0.637493 | [
"render",
"vector"
] |
44b9f4971bbd5cc69e1f663ae71e27e69c31a04b | 2,963 | cpp | C++ | mobile/test/fpga/test_concat_op.cpp | jameswu2014/Paddle-Lite | 827e349ac8eb769a873fe9b3aa961af8b8b20a96 | [
"Apache-2.0"
] | 3 | 2018-08-01T09:45:48.000Z | 2021-01-06T14:55:10.000Z | mobile/test/fpga/test_concat_op.cpp | tao8687/Paddle-Lite | ebc0e39c7e8c09ad2d1b6a2923a420b2c1727635 | [
"Apache-2.0"
] | null | null | null | mobile/test/fpga/test_concat_op.cpp | tao8687/Paddle-Lite | ebc0e39c7e8c09ad2d1b6a2923a420b2c1727635 | [
"Apache-2.0"
] | 5 | 2020-10-13T09:30:16.000Z | 2021-06-08T02:46:17.000Z | /* Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.
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
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 "../test_include.h"
#include "operators/concat_op.h"
int main() {
paddle_mobile::framework::Loader<paddle_mobile::FPGA> loader;
auto program = loader.Load(g_googlenet);
PADDLE_MOBILE_ENFORCE(program.originProgram != nullptr,
"program file read fail");
Executor4Test<paddle_mobile::FPGA,
paddle_mobile::operators::ConcatOp<paddle_mobile::FPGA, float>>
executor(program, "concat");
// 1. input_tensors;
vector<Tensor> input_tensors;
Tensor input1;
auto input1_data = CreateInput<float>(&input1, {4, 10, 2, 2}, 0, 1);
input_tensors.push_back(input1);
Tensor input2;
auto input2_data = CreateInput<float>(&input2, {4, 20, 2, 2}, 0, 1);
input_tensors.push_back(input2);
Tensor input3;
auto input3_data = CreateInput<float>(&input3, {4, 30, 2, 2}, 0, 1);
input_tensors.push_back(input3);
Tensor input4;
auto input4_data = CreateInput<float>(&input4, {4, 40, 2, 2}, 0, 1);
input_tensors.push_back(input4);
// 2. input_names
vector<string> input_names({
"conv2d_3.tmp_1",
"conv2d_5.tmp_1",
"conv2d_7.tmp_1",
"conv2d_8.tmp_1",
});
// 3. output_names
vector<string> output_names({"concat_0.tmp_0"});
// 4. out_dims;
vector<DDim> out_ddims;
auto out_ddim = paddle_mobile::framework::make_ddim({3, 100, 2, 2});
out_ddims.push_back(out_ddim);
auto output = executor.Predict<LoDTensor>(input_tensors, input_names,
output_names, out_ddims);
auto output0_data = output[0]->data<float>();
// 5. test one example.
int input_n = 1;
int input_c = 2;
int input_h = 0;
int input_w = 1;
int stride0 = input3.numel() / input3.dims()[0];
int stride1 = input3.numel() / input3.dims()[0] / input3.dims()[1];
int stride2 = input3.dims()[3];
/// inputx1 (4,10,2,2),
/// inputx2 (4,20,2,2),
/// inputx3 (4,30,2,2),
/// inputx4 (4,40,2,2),
/// axis = 1
/// output (4,100,2,2)
int input_index =
input_n * stride0 + input_c * stride1 + input_h * stride2 + input_w;
int output_index = input_n * 100 * 2 * 2 +
(input_c + input1.dims()[1] + input2.dims()[1]) * 2 * 2 +
input_h * 2 + input_w;
DLOG << " input3 [1, 2,0,1] = " << input3_data[input_index];
DLOG << " output [1,32,0,1] = " << output0_data[output_index];
return 0;
}
| 33.670455 | 79 | 0.653392 | [
"vector"
] |
44bf586eff5aa03249361112c503979b2d731640 | 48,052 | cxx | C++ | svc_kube_vision_opencvplus/dependencies/cmake-3.4.1/Source/cmExtraEclipseCDT4Generator.cxx | lucmichalski/kube-vproxy | c7cc0edbcbcd07a48f0fc48b9457eae693b76688 | [
"Apache-2.0"
] | 3 | 2018-06-22T07:55:51.000Z | 2021-06-21T19:18:16.000Z | svc_kube_vision_opencvplus/dependencies/cmake-3.4.1/Source/cmExtraEclipseCDT4Generator.cxx | lucmichalski/kube-vproxy | c7cc0edbcbcd07a48f0fc48b9457eae693b76688 | [
"Apache-2.0"
] | null | null | null | svc_kube_vision_opencvplus/dependencies/cmake-3.4.1/Source/cmExtraEclipseCDT4Generator.cxx | lucmichalski/kube-vproxy | c7cc0edbcbcd07a48f0fc48b9457eae693b76688 | [
"Apache-2.0"
] | 1 | 2020-11-04T04:56:50.000Z | 2020-11-04T04:56:50.000Z | /*============================================================================
CMake - Cross Platform Makefile Generator
Copyright 2004-2009 Kitware, Inc.
Copyright 2004 Alexander Neundorf (neundorf@kde.org)
Copyright 2007 Miguel A. Figueroa-Villanueva
Distributed under the OSI-approved BSD License (the "License");
see accompanying file Copyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even the
implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the License for more information.
============================================================================*/
#include "cmExtraEclipseCDT4Generator.h"
#include "cmGlobalUnixMakefileGenerator3.h"
#include "cmLocalUnixMakefileGenerator3.h"
#include "cmMakefile.h"
#include "cmGeneratedFileStream.h"
#include "cmState.h"
#include "cmTarget.h"
#include "cmSourceFile.h"
#include "cmSystemTools.h"
#include <stdlib.h>
#include <assert.h>
//----------------------------------------------------------------------------
cmExtraEclipseCDT4Generator
::cmExtraEclipseCDT4Generator() : cmExternalMakefileProjectGenerator()
{
// TODO: Verify if __CYGWIN__ should be checked.
//#if defined(_WIN32) && !defined(__CYGWIN__)
#if defined(_WIN32)
this->SupportedGlobalGenerators.push_back("NMake Makefiles");
this->SupportedGlobalGenerators.push_back("MinGW Makefiles");
// this->SupportedGlobalGenerators.push_back("MSYS Makefiles");
#endif
this->SupportedGlobalGenerators.push_back("Ninja");
this->SupportedGlobalGenerators.push_back("Unix Makefiles");
this->SupportsVirtualFolders = true;
this->GenerateLinkedResources = true;
this->SupportsGmakeErrorParser = true;
this->SupportsMachO64Parser = true;
}
//----------------------------------------------------------------------------
void cmExtraEclipseCDT4Generator
::GetDocumentation(cmDocumentationEntry& entry, const std::string&) const
{
entry.Name = this->GetName();
entry.Brief = "Generates Eclipse CDT 4.0 project files.";
}
//----------------------------------------------------------------------------
void cmExtraEclipseCDT4Generator
::EnableLanguage(std::vector<std::string> const& languages,
cmMakefile *, bool)
{
for (std::vector<std::string>::const_iterator lit = languages.begin();
lit != languages.end(); ++lit)
{
if (*lit == "CXX")
{
this->Natures.insert("org.eclipse.cdt.core.ccnature");
this->Natures.insert("org.eclipse.cdt.core.cnature");
}
else if (*lit == "C")
{
this->Natures.insert("org.eclipse.cdt.core.cnature");
}
else if (*lit == "Java")
{
this->Natures.insert("org.eclipse.jdt.core.javanature");
}
}
}
//----------------------------------------------------------------------------
void cmExtraEclipseCDT4Generator::Generate()
{
const cmMakefile* mf
= this->GlobalGenerator->GetLocalGenerators()[0]->GetMakefile();
std::string eclipseVersion = mf->GetSafeDefinition("CMAKE_ECLIPSE_VERSION");
cmsys::RegularExpression regex(".*([0-9]+\\.[0-9]+).*");
if (regex.find(eclipseVersion.c_str()))
{
unsigned int majorVersion = 0;
unsigned int minorVersion = 0;
int res=sscanf(regex.match(1).c_str(), "%u.%u", &majorVersion,
&minorVersion);
if (res == 2)
{
int version = majorVersion * 1000 + minorVersion;
if (version < 3006) // 3.6 is Helios
{
this->SupportsVirtualFolders = false;
this->SupportsMachO64Parser = false;
}
if (version < 3007) // 3.7 is Indigo
{
this->SupportsGmakeErrorParser = false;
}
}
}
// TODO: Decide if these are local or member variables
this->HomeDirectory = mf->GetHomeDirectory();
this->HomeOutputDirectory = mf->GetHomeOutputDirectory();
this->GenerateLinkedResources = mf->IsOn(
"CMAKE_ECLIPSE_GENERATE_LINKED_RESOURCES");
this->IsOutOfSourceBuild = (this->HomeDirectory!=this->HomeOutputDirectory);
this->GenerateSourceProject = (this->IsOutOfSourceBuild &&
mf->IsOn("CMAKE_ECLIPSE_GENERATE_SOURCE_PROJECT"));
if ((this->GenerateSourceProject == false)
&& (mf->IsOn("ECLIPSE_CDT4_GENERATE_SOURCE_PROJECT")))
{
mf->IssueMessage(cmake::WARNING,
"ECLIPSE_CDT4_GENERATE_SOURCE_PROJECT is set to TRUE, "
"but this variable is not supported anymore since CMake 2.8.7.\n"
"Enable CMAKE_ECLIPSE_GENERATE_SOURCE_PROJECT instead.");
}
if (cmSystemTools::IsSubDirectory(this->HomeOutputDirectory,
this->HomeDirectory))
{
mf->IssueMessage(cmake::WARNING, "The build directory is a subdirectory "
"of the source directory.\n"
"This is not supported well by Eclipse. It is strongly "
"recommended to use a build directory which is a "
"sibling of the source directory.");
}
// NOTE: This is not good, since it pollutes the source tree. However,
// Eclipse doesn't allow CVS/SVN to work when the .project is not in
// the cvs/svn root directory. Hence, this is provided as an option.
if (this->GenerateSourceProject)
{
// create .project file in the source tree
this->CreateSourceProjectFile();
}
// create a .project file
this->CreateProjectFile();
// create a .cproject file
this->CreateCProjectFile();
}
void cmExtraEclipseCDT4Generator::CreateSourceProjectFile()
{
assert(this->HomeDirectory != this->HomeOutputDirectory);
// set up the project name: <project>-Source@<baseSourcePathName>
const cmMakefile* mf
= this->GlobalGenerator->GetLocalGenerators()[0]->GetMakefile();
std::string name = this->GenerateProjectName(mf->GetProjectName(), "Source",
this->GetPathBasename(this->HomeDirectory));
const std::string filename = this->HomeDirectory + "/.project";
cmGeneratedFileStream fout(filename.c_str());
if (!fout)
{
return;
}
fout <<
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
"<projectDescription>\n"
"\t<name>" << this->EscapeForXML(name) << "</name>\n"
"\t<comment></comment>\n"
"\t<projects>\n"
"\t</projects>\n"
"\t<buildSpec>\n"
"\t</buildSpec>\n"
"\t<natures>\n"
"\t</natures>\n"
"\t<linkedResources>\n";
if (this->SupportsVirtualFolders)
{
this->CreateLinksToSubprojects(fout, this->HomeDirectory);
this->SrcLinkedResources.clear();
}
fout <<
"\t</linkedResources>\n"
"</projectDescription>\n"
;
}
//----------------------------------------------------------------------------
void cmExtraEclipseCDT4Generator::AddEnvVar(cmGeneratedFileStream& fout,
const char* envVar, cmMakefile* mf)
{
// get the variables from the environment and from the cache and then
// figure out which one to use:
const char* envVarValue = getenv(envVar);
std::string cacheEntryName = "CMAKE_ECLIPSE_ENVVAR_";
cacheEntryName += envVar;
const char* cacheValue = mf->GetState()->GetInitializedCacheValue(
cacheEntryName);
// now we have both, decide which one to use
std::string valueToUse;
if (envVarValue==0 && cacheValue==0)
{
// nothing known, do nothing
valueToUse = "";
}
else if (envVarValue!=0 && cacheValue==0)
{
// The variable is in the env, but not in the cache. Use it and put it
// in the cache
valueToUse = envVarValue;
mf->AddCacheDefinition(cacheEntryName, valueToUse.c_str(),
cacheEntryName.c_str(), cmState::STRING,
true);
mf->GetCMakeInstance()->SaveCache(mf->GetHomeOutputDirectory());
}
else if (envVarValue==0 && cacheValue!=0)
{
// It is already in the cache, but not in the env, so use it from the cache
valueToUse = cacheValue;
}
else
{
// It is both in the cache and in the env.
// Use the version from the env. except if the value from the env is
// completely contained in the value from the cache (for the case that we
// now have a PATH without MSVC dirs in the env. but had the full PATH with
// all MSVC dirs during the cmake run which stored the var in the cache:
valueToUse = cacheValue;
if (valueToUse.find(envVarValue) == std::string::npos)
{
valueToUse = envVarValue;
mf->AddCacheDefinition(cacheEntryName, valueToUse.c_str(),
cacheEntryName.c_str(), cmState::STRING,
true);
mf->GetCMakeInstance()->SaveCache(mf->GetHomeOutputDirectory());
}
}
if (!valueToUse.empty())
{
fout << envVar << "=" << valueToUse << "|";
}
}
//----------------------------------------------------------------------------
void cmExtraEclipseCDT4Generator::CreateProjectFile()
{
cmMakefile* mf
= this->GlobalGenerator->GetLocalGenerators()[0]->GetMakefile();
const std::string filename = this->HomeOutputDirectory + "/.project";
cmGeneratedFileStream fout(filename.c_str());
if (!fout)
{
return;
}
std::string compilerId = mf->GetSafeDefinition("CMAKE_C_COMPILER_ID");
if (compilerId.empty()) // no C compiler, try the C++ compiler:
{
compilerId = mf->GetSafeDefinition("CMAKE_CXX_COMPILER_ID");
}
fout <<
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
"<projectDescription>\n"
"\t<name>" <<
this->GenerateProjectName(mf->GetProjectName(),
mf->GetSafeDefinition("CMAKE_BUILD_TYPE"),
this->GetPathBasename(this->HomeOutputDirectory))
<< "</name>\n"
"\t<comment></comment>\n"
"\t<projects>\n"
"\t</projects>\n"
"\t<buildSpec>\n"
"\t\t<buildCommand>\n"
"\t\t\t<name>org.eclipse.cdt.make.core.makeBuilder</name>\n"
"\t\t\t<triggers>clean,full,incremental,</triggers>\n"
"\t\t\t<arguments>\n"
;
// use clean target
fout <<
"\t\t\t\t<dictionary>\n"
"\t\t\t\t\t<key>org.eclipse.cdt.make.core.cleanBuildTarget</key>\n"
"\t\t\t\t\t<value>clean</value>\n"
"\t\t\t\t</dictionary>\n"
"\t\t\t\t<dictionary>\n"
"\t\t\t\t\t<key>org.eclipse.cdt.make.core.enableCleanBuild</key>\n"
"\t\t\t\t\t<value>true</value>\n"
"\t\t\t\t</dictionary>\n"
"\t\t\t\t<dictionary>\n"
"\t\t\t\t\t<key>org.eclipse.cdt.make.core.append_environment</key>\n"
"\t\t\t\t\t<value>true</value>\n"
"\t\t\t\t</dictionary>\n"
"\t\t\t\t<dictionary>\n"
"\t\t\t\t\t<key>org.eclipse.cdt.make.core.stopOnError</key>\n"
"\t\t\t\t\t<value>true</value>\n"
"\t\t\t\t</dictionary>\n"
;
// set the make command
std::string make = mf->GetRequiredDefinition("CMAKE_MAKE_PROGRAM");
const std::string makeArgs = mf->GetSafeDefinition(
"CMAKE_ECLIPSE_MAKE_ARGUMENTS");
fout <<
"\t\t\t\t<dictionary>\n"
"\t\t\t\t\t<key>org.eclipse.cdt.make.core.enabledIncrementalBuild</key>\n"
"\t\t\t\t\t<value>true</value>\n"
"\t\t\t\t</dictionary>\n"
"\t\t\t\t<dictionary>\n"
"\t\t\t\t\t<key>org.eclipse.cdt.make.core.build.command</key>\n"
"\t\t\t\t\t<value>" << this->GetEclipsePath(make) << "</value>\n"
"\t\t\t\t</dictionary>\n"
"\t\t\t\t<dictionary>\n"
"\t\t\t\t\t<key>org.eclipse.cdt.make.core.contents</key>\n"
"\t\t\t\t\t<value>org.eclipse.cdt.make.core.activeConfigSettings</value>\n"
"\t\t\t\t</dictionary>\n"
"\t\t\t\t<dictionary>\n"
"\t\t\t\t\t<key>org.eclipse.cdt.make.core.build.target.inc</key>\n"
"\t\t\t\t\t<value>all</value>\n"
"\t\t\t\t</dictionary>\n"
"\t\t\t\t<dictionary>\n"
"\t\t\t\t\t<key>org.eclipse.cdt.make.core.build.arguments</key>\n"
"\t\t\t\t\t<value>" << makeArgs << "</value>\n"
"\t\t\t\t</dictionary>\n"
"\t\t\t\t<dictionary>\n"
"\t\t\t\t\t<key>org.eclipse.cdt.make.core.buildLocation</key>\n"
"\t\t\t\t\t<value>"
<< this->GetEclipsePath(this->HomeOutputDirectory) << "</value>\n"
"\t\t\t\t</dictionary>\n"
"\t\t\t\t<dictionary>\n"
"\t\t\t\t\t<key>org.eclipse.cdt.make.core.useDefaultBuildCmd</key>\n"
"\t\t\t\t\t<value>false</value>\n"
"\t\t\t\t</dictionary>\n"
;
// set project specific environment
fout <<
"\t\t\t\t<dictionary>\n"
"\t\t\t\t\t<key>org.eclipse.cdt.make.core.environment</key>\n"
"\t\t\t\t\t<value>VERBOSE=1|CMAKE_NO_VERBOSE=1|" //verbose Makefile output
;
// set vsvars32.bat environment available at CMake time,
// but not necessarily when eclipse is open
if (compilerId == "MSVC")
{
AddEnvVar(fout, "PATH", mf);
AddEnvVar(fout, "INCLUDE", mf);
AddEnvVar(fout, "LIB", mf);
AddEnvVar(fout, "LIBPATH", mf);
}
else if (compilerId == "Intel")
{
// if the env.var is set, use this one and put it in the cache
// if the env.var is not set, but the value is in the cache,
// use it from the cache:
AddEnvVar(fout, "INTEL_LICENSE_FILE", mf);
}
fout <<
"</value>\n"
"\t\t\t\t</dictionary>\n"
;
fout <<
"\t\t\t\t<dictionary>\n"
"\t\t\t\t\t<key>org.eclipse.cdt.make.core.enableFullBuild</key>\n"
"\t\t\t\t\t<value>true</value>\n"
"\t\t\t\t</dictionary>\n"
"\t\t\t\t<dictionary>\n"
"\t\t\t\t\t<key>org.eclipse.cdt.make.core.build.target.auto</key>\n"
"\t\t\t\t\t<value>all</value>\n"
"\t\t\t\t</dictionary>\n"
"\t\t\t\t<dictionary>\n"
"\t\t\t\t\t<key>org.eclipse.cdt.make.core.enableAutoBuild</key>\n"
"\t\t\t\t\t<value>false</value>\n"
"\t\t\t\t</dictionary>\n"
"\t\t\t\t<dictionary>\n"
"\t\t\t\t\t<key>org.eclipse.cdt.make.core.build.target.clean</key>\n"
"\t\t\t\t\t<value>clean</value>\n"
"\t\t\t\t</dictionary>\n"
"\t\t\t\t<dictionary>\n"
"\t\t\t\t\t<key>org.eclipse.cdt.make.core.fullBuildTarget</key>\n"
"\t\t\t\t\t<value>all</value>\n"
"\t\t\t\t</dictionary>\n"
"\t\t\t\t<dictionary>\n"
"\t\t\t\t\t<key>org.eclipse.cdt.make.core.buildArguments</key>\n"
"\t\t\t\t\t<value></value>\n"
"\t\t\t\t</dictionary>\n"
"\t\t\t\t<dictionary>\n"
"\t\t\t\t\t<key>org.eclipse.cdt.make.core.build.location</key>\n"
"\t\t\t\t\t<value>"
<< this->GetEclipsePath(this->HomeOutputDirectory) << "</value>\n"
"\t\t\t\t</dictionary>\n"
"\t\t\t\t<dictionary>\n"
"\t\t\t\t\t<key>org.eclipse.cdt.make.core.autoBuildTarget</key>\n"
"\t\t\t\t\t<value>all</value>\n"
"\t\t\t\t</dictionary>\n"
;
// set error parsers
fout <<
"\t\t\t\t<dictionary>\n"
"\t\t\t\t\t<key>org.eclipse.cdt.core.errorOutputParser</key>\n"
"\t\t\t\t\t<value>"
;
if (compilerId == "MSVC")
{
fout << "org.eclipse.cdt.core.VCErrorParser;";
}
else if (compilerId == "Intel")
{
fout << "org.eclipse.cdt.core.ICCErrorParser;";
}
if (this->SupportsGmakeErrorParser)
{
fout << "org.eclipse.cdt.core.GmakeErrorParser;";
}
else
{
fout << "org.eclipse.cdt.core.MakeErrorParser;";
}
fout <<
"org.eclipse.cdt.core.GCCErrorParser;"
"org.eclipse.cdt.core.GASErrorParser;"
"org.eclipse.cdt.core.GLDErrorParser;"
"</value>\n"
"\t\t\t\t</dictionary>\n"
;
fout <<
"\t\t\t</arguments>\n"
"\t\t</buildCommand>\n"
"\t\t<buildCommand>\n"
"\t\t\t<name>org.eclipse.cdt.make.core.ScannerConfigBuilder</name>\n"
"\t\t\t<arguments>\n"
"\t\t\t</arguments>\n"
"\t\t</buildCommand>\n"
"\t</buildSpec>\n"
;
// set natures for c/c++ projects
fout <<
"\t<natures>\n"
"\t\t<nature>org.eclipse.cdt.make.core.makeNature</nature>\n"
"\t\t<nature>org.eclipse.cdt.make.core.ScannerConfigNature</nature>\n";
for (std::set<std::string>::const_iterator nit=this->Natures.begin();
nit != this->Natures.end(); ++nit)
{
fout << "\t\t<nature>" << *nit << "</nature>\n";
}
if (const char *extraNaturesProp = mf->GetState()
->GetGlobalProperty("ECLIPSE_EXTRA_NATURES"))
{
std::vector<std::string> extraNatures;
cmSystemTools::ExpandListArgument(extraNaturesProp, extraNatures);
for (std::vector<std::string>::const_iterator nit = extraNatures.begin();
nit != extraNatures.end(); ++nit)
{
fout << "\t\t<nature>" << *nit << "</nature>\n";
}
}
fout << "\t</natures>\n";
fout << "\t<linkedResources>\n";
// create linked resources
if (this->IsOutOfSourceBuild)
{
// create a linked resource to CMAKE_SOURCE_DIR
// (this is not done anymore for each project because of
// http://public.kitware.com/Bug/view.php?id=9978 and because I found it
// actually quite confusing in bigger projects with many directories and
// projects, Alex
std::string sourceLinkedResourceName = "[Source directory]";
std::string linkSourceDirectory = this->GetEclipsePath(
mf->GetCurrentSourceDirectory());
// .project dir can't be subdir of a linked resource dir
if (!cmSystemTools::IsSubDirectory(this->HomeOutputDirectory,
linkSourceDirectory))
{
this->AppendLinkedResource(fout, sourceLinkedResourceName,
this->GetEclipsePath(linkSourceDirectory),
LinkToFolder);
this->SrcLinkedResources.push_back(sourceLinkedResourceName);
}
}
if (this->SupportsVirtualFolders)
{
this->CreateLinksToSubprojects(fout, this->HomeOutputDirectory);
this->CreateLinksForTargets(fout);
}
fout << "\t</linkedResources>\n";
fout << "</projectDescription>\n";
}
//----------------------------------------------------------------------------
void cmExtraEclipseCDT4Generator::CreateLinksForTargets(
cmGeneratedFileStream& fout)
{
std::string linkName = "[Targets]";
this->AppendLinkedResource(fout, linkName, "virtual:/virtual",VirtualFolder);
for (std::vector<cmLocalGenerator*>::const_iterator
lgIt = this->GlobalGenerator->GetLocalGenerators().begin();
lgIt != this->GlobalGenerator->GetLocalGenerators().end();
++lgIt)
{
cmMakefile* makefile = (*lgIt)->GetMakefile();
const cmTargets& targets = makefile->GetTargets();
for(cmTargets::const_iterator ti=targets.begin(); ti!=targets.end();++ti)
{
std::string linkName2 = linkName;
linkName2 += "/";
switch(ti->second.GetType())
{
case cmTarget::EXECUTABLE:
case cmTarget::STATIC_LIBRARY:
case cmTarget::SHARED_LIBRARY:
case cmTarget::MODULE_LIBRARY:
case cmTarget::OBJECT_LIBRARY:
{
const char* prefix = (ti->second.GetType()==cmTarget::EXECUTABLE ?
"[exe] " : "[lib] ");
linkName2 += prefix;
linkName2 += ti->first;
this->AppendLinkedResource(fout, linkName2, "virtual:/virtual",
VirtualFolder);
if (!this->GenerateLinkedResources)
{
break; // skip generating the linked resources to the source files
}
std::vector<cmSourceGroup> sourceGroups=makefile->GetSourceGroups();
// get the files from the source lists then add them to the groups
cmTarget* tgt = const_cast<cmTarget*>(&ti->second);
std::vector<cmSourceFile*> files;
tgt->GetSourceFiles(files,
makefile->GetSafeDefinition("CMAKE_BUILD_TYPE"));
for(std::vector<cmSourceFile*>::const_iterator sfIt = files.begin();
sfIt != files.end();
sfIt++)
{
// Add the file to the list of sources.
std::string source = (*sfIt)->GetFullPath();
cmSourceGroup* sourceGroup =
makefile->FindSourceGroup(source.c_str(), sourceGroups);
sourceGroup->AssignSource(*sfIt);
}
for(std::vector<cmSourceGroup>::iterator sgIt = sourceGroups.begin();
sgIt != sourceGroups.end();
++sgIt)
{
std::string linkName3 = linkName2;
linkName3 += "/";
linkName3 += sgIt->GetFullName();
this->AppendLinkedResource(fout, linkName3, "virtual:/virtual",
VirtualFolder);
std::vector<const cmSourceFile*> sFiles = sgIt->GetSourceFiles();
for(std::vector<const cmSourceFile*>::const_iterator fileIt =
sFiles.begin();
fileIt != sFiles.end();
++fileIt)
{
std::string fullPath = (*fileIt)->GetFullPath();
if (!cmSystemTools::FileIsDirectory(fullPath))
{
std::string linkName4 = linkName3;
linkName4 += "/";
linkName4 += cmSystemTools::GetFilenameName(fullPath);
this->AppendLinkedResource(fout, linkName4,
this->GetEclipsePath(fullPath),
LinkToFile);
}
}
}
}
break;
// ignore all others:
default:
break;
}
}
}
}
//----------------------------------------------------------------------------
void cmExtraEclipseCDT4Generator::CreateLinksToSubprojects(
cmGeneratedFileStream& fout, const std::string& baseDir)
{
if (!this->GenerateLinkedResources)
{
return;
}
// for each sub project create a linked resource to the source dir
// - only if it is an out-of-source build
this->AppendLinkedResource(fout, "[Subprojects]",
"virtual:/virtual", VirtualFolder);
for (std::map<std::string, std::vector<cmLocalGenerator*> >::const_iterator
it = this->GlobalGenerator->GetProjectMap().begin();
it != this->GlobalGenerator->GetProjectMap().end();
++it)
{
std::string linkSourceDirectory = this->GetEclipsePath(
it->second[0]->GetMakefile()->GetCurrentSourceDirectory());
// a linked resource must not point to a parent directory of .project or
// .project itself
if ((baseDir != linkSourceDirectory) &&
!cmSystemTools::IsSubDirectory(baseDir,
linkSourceDirectory))
{
std::string linkName = "[Subprojects]/";
linkName += it->first;
this->AppendLinkedResource(fout, linkName,
this->GetEclipsePath(linkSourceDirectory),
LinkToFolder
);
// Don't add it to the srcLinkedResources, because listing multiple
// directories confuses the Eclipse indexer (#13596).
}
}
}
//----------------------------------------------------------------------------
void cmExtraEclipseCDT4Generator::AppendIncludeDirectories(
cmGeneratedFileStream& fout,
const std::vector<std::string>& includeDirs,
std::set<std::string>& emittedDirs)
{
for(std::vector<std::string>::const_iterator inc = includeDirs.begin();
inc != includeDirs.end();
++inc)
{
if (!inc->empty())
{
std::string dir = cmSystemTools::CollapseFullPath(*inc);
// handle framework include dirs on OSX, the remainder after the
// Frameworks/ part has to be stripped
// /System/Library/Frameworks/GLUT.framework/Headers
cmsys::RegularExpression frameworkRx("(.+/Frameworks)/.+\\.framework/");
if(frameworkRx.find(dir.c_str()))
{
dir = frameworkRx.match(1);
}
if(emittedDirs.find(dir) == emittedDirs.end())
{
emittedDirs.insert(dir);
fout << "<pathentry include=\""
<< cmExtraEclipseCDT4Generator::EscapeForXML(
cmExtraEclipseCDT4Generator::GetEclipsePath(dir))
<< "\" kind=\"inc\" path=\"\" system=\"true\"/>\n";
}
}
}
}
//----------------------------------------------------------------------------
void cmExtraEclipseCDT4Generator::CreateCProjectFile() const
{
std::set<std::string> emmited;
const cmMakefile* mf
= this->GlobalGenerator->GetLocalGenerators()[0]->GetMakefile();
const std::string filename = this->HomeOutputDirectory + "/.cproject";
cmGeneratedFileStream fout(filename.c_str());
if (!fout)
{
return;
}
// add header
fout <<
"<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>\n"
"<?fileVersion 4.0.0?>\n\n"
"<cproject>\n"
"<storageModule moduleId=\"org.eclipse.cdt.core.settings\">\n"
;
fout << "<cconfiguration id=\"org.eclipse.cdt.core.default.config.1\">\n";
// Configuration settings...
fout <<
"<storageModule"
" buildSystemId=\"org.eclipse.cdt.core.defaultConfigDataProvider\""
" id=\"org.eclipse.cdt.core.default.config.1\""
" moduleId=\"org.eclipse.cdt.core.settings\" name=\"Configuration\">\n"
"<externalSettings/>\n"
"<extensions>\n"
;
// TODO: refactor this out...
std::string executableFormat = mf->GetSafeDefinition(
"CMAKE_EXECUTABLE_FORMAT");
if (executableFormat == "ELF")
{
fout << "<extension id=\"org.eclipse.cdt.core.ELF\""
" point=\"org.eclipse.cdt.core.BinaryParser\"/>\n"
;
fout << "<extension id=\"org.eclipse.cdt.core.GNU_ELF\""
" point=\"org.eclipse.cdt.core.BinaryParser\">\n"
"<attribute key=\"addr2line\" value=\"addr2line\"/>\n"
"<attribute key=\"c++filt\" value=\"c++filt\"/>\n"
"</extension>\n"
;
}
else
{
std::string systemName = mf->GetSafeDefinition("CMAKE_SYSTEM_NAME");
if (systemName == "CYGWIN")
{
fout << "<extension id=\"org.eclipse.cdt.core.Cygwin_PE\""
" point=\"org.eclipse.cdt.core.BinaryParser\">\n"
"<attribute key=\"addr2line\" value=\"addr2line\"/>\n"
"<attribute key=\"c++filt\" value=\"c++filt\"/>\n"
"<attribute key=\"cygpath\" value=\"cygpath\"/>\n"
"<attribute key=\"nm\" value=\"nm\"/>\n"
"</extension>\n"
;
}
else if (systemName == "Windows")
{
fout << "<extension id=\"org.eclipse.cdt.core.PE\""
" point=\"org.eclipse.cdt.core.BinaryParser\"/>\n"
;
}
else if (systemName == "Darwin")
{
fout << "<extension id=\"" <<
(this->SupportsMachO64Parser ? "org.eclipse.cdt.core.MachO64"
: "org.eclipse.cdt.core.MachO") << "\""
" point=\"org.eclipse.cdt.core.BinaryParser\">\n"
"<attribute key=\"c++filt\" value=\"c++filt\"/>\n"
"</extension>\n"
;
}
else
{
// *** Should never get here ***
fout << "<error_toolchain_type/>\n";
}
}
fout << "</extensions>\n"
"</storageModule>\n"
;
// ???
fout <<
"<storageModule moduleId=\"org.eclipse.cdt.core.language.mapping\">\n"
"<project-mappings/>\n"
"</storageModule>\n"
;
// ???
fout<<"<storageModule moduleId=\"org.eclipse.cdt.core.externalSettings\"/>\n"
;
// set the path entries (includes, libs, source dirs, etc.)
fout << "<storageModule moduleId=\"org.eclipse.cdt.core.pathentry\">\n"
;
// for each sub project with a linked resource to the source dir:
// - make it type 'src'
// - and exclude it from type 'out'
std::string excludeFromOut;
/* I don't know what the pathentry kind="src" are good for, e.g. autocompletion
* works also without them. Done wrong, the indexer complains, see #12417
* and #12213.
* According to #13596, this entry at least limits the directories the
* indexer is searching for files. So now the "src" entry contains only
* the linked resource to CMAKE_SOURCE_DIR.
* The CDT documentation is very terse on that:
* "CDT_SOURCE: Entry kind constant describing a path entry identifying a
* folder containing source code to be compiled."
* Also on the cdt-dev list didn't bring any information:
* http://web.archiveorange.com/archive/v/B4NlJDNIpYoOS1SbxFNy
* Alex */
for (std::vector<std::string>::const_iterator
it = this->SrcLinkedResources.begin();
it != this->SrcLinkedResources.end();
++it)
{
fout << "<pathentry kind=\"src\" path=\"" << this->EscapeForXML(*it)
<< "\"/>\n";
// exlude source directory from output search path
// - only if not named the same as an output directory
if (!cmSystemTools::FileIsDirectory(
std::string(this->HomeOutputDirectory + "/" + *it)))
{
excludeFromOut += this->EscapeForXML(*it) + "/|";
}
}
excludeFromOut += "**/CMakeFiles/";
fout << "<pathentry excluding=\"" << excludeFromOut
<< "\" kind=\"out\" path=\"\"/>\n";
// add pre-processor definitions to allow eclipse to gray out sections
emmited.clear();
for (std::vector<cmLocalGenerator*>::const_iterator
it = this->GlobalGenerator->GetLocalGenerators().begin();
it != this->GlobalGenerator->GetLocalGenerators().end();
++it)
{
if(const char* cdefs = (*it)->GetMakefile()->GetProperty(
"COMPILE_DEFINITIONS"))
{
// Expand the list.
std::vector<std::string> defs;
cmGeneratorExpression::Split(cdefs, defs);
for(std::vector<std::string>::const_iterator di = defs.begin();
di != defs.end(); ++di)
{
if (cmGeneratorExpression::Find(*di) != std::string::npos)
{
continue;
}
std::string::size_type equals = di->find('=', 0);
std::string::size_type enddef = di->length();
std::string def;
std::string val;
if (equals != std::string::npos && equals < enddef)
{
// we have -DFOO=BAR
def = di->substr(0, equals);
val = di->substr(equals + 1, enddef - equals + 1);
}
else
{
// we have -DFOO
def = *di;
}
// insert the definition if not already added.
if(emmited.find(def) == emmited.end())
{
emmited.insert(def);
fout << "<pathentry kind=\"mac\" name=\"" << def
<< "\" path=\"\" value=\"" << this->EscapeForXML(val)
<< "\"/>\n";
}
}
}
}
// add system defined c macros
const char* cDefs=mf->GetDefinition(
"CMAKE_EXTRA_GENERATOR_C_SYSTEM_DEFINED_MACROS");
if(cDefs)
{
// Expand the list.
std::vector<std::string> defs;
cmSystemTools::ExpandListArgument(cDefs, defs, true);
// the list must contain only definition-value pairs:
if ((defs.size() % 2) == 0)
{
std::vector<std::string>::const_iterator di = defs.begin();
while (di != defs.end())
{
std::string def = *di;
++di;
std::string val;
if (di != defs.end())
{
val = *di;
++di;
}
// insert the definition if not already added.
if(emmited.find(def) == emmited.end())
{
emmited.insert(def);
fout << "<pathentry kind=\"mac\" name=\"" << def
<< "\" path=\"\" value=\"" << this->EscapeForXML(val)
<< "\"/>\n";
}
}
}
}
// add system defined c++ macros
const char* cxxDefs = mf->GetDefinition(
"CMAKE_EXTRA_GENERATOR_CXX_SYSTEM_DEFINED_MACROS");
if(cxxDefs)
{
// Expand the list.
std::vector<std::string> defs;
cmSystemTools::ExpandListArgument(cxxDefs, defs, true);
// the list must contain only definition-value pairs:
if ((defs.size() % 2) == 0)
{
std::vector<std::string>::const_iterator di = defs.begin();
while (di != defs.end())
{
std::string def = *di;
++di;
std::string val;
if (di != defs.end())
{
val = *di;
++di;
}
// insert the definition if not already added.
if(emmited.find(def) == emmited.end())
{
emmited.insert(def);
fout << "<pathentry kind=\"mac\" name=\"" << def
<< "\" path=\"\" value=\"" << this->EscapeForXML(val)
<< "\"/>\n";
}
}
}
}
// include dirs
emmited.clear();
for (std::vector<cmLocalGenerator*>::const_iterator
it = this->GlobalGenerator->GetLocalGenerators().begin();
it != this->GlobalGenerator->GetLocalGenerators().end();
++it)
{
cmGeneratorTargetsType targets = (*it)->GetMakefile()
->GetGeneratorTargets();
for (cmGeneratorTargetsType::iterator l = targets.begin();
l != targets.end(); ++l)
{
if (l->first->IsImported())
{
continue;
}
std::vector<std::string> includeDirs;
std::string config = mf->GetSafeDefinition("CMAKE_BUILD_TYPE");
(*it)->GetIncludeDirectories(includeDirs, l->second, "C", config);
this->AppendIncludeDirectories(fout, includeDirs, emmited);
}
}
// now also the system include directories, in case we found them in
// CMakeSystemSpecificInformation.cmake. This makes Eclipse find the
// standard headers.
std::string compiler = mf->GetSafeDefinition("CMAKE_C_COMPILER");
if (!compiler.empty())
{
std::string systemIncludeDirs = mf->GetSafeDefinition(
"CMAKE_EXTRA_GENERATOR_C_SYSTEM_INCLUDE_DIRS");
std::vector<std::string> dirs;
cmSystemTools::ExpandListArgument(systemIncludeDirs, dirs);
this->AppendIncludeDirectories(fout, dirs, emmited);
}
compiler = mf->GetSafeDefinition("CMAKE_CXX_COMPILER");
if (!compiler.empty())
{
std::string systemIncludeDirs = mf->GetSafeDefinition(
"CMAKE_EXTRA_GENERATOR_CXX_SYSTEM_INCLUDE_DIRS");
std::vector<std::string> dirs;
cmSystemTools::ExpandListArgument(systemIncludeDirs, dirs);
this->AppendIncludeDirectories(fout, dirs, emmited);
}
fout << "</storageModule>\n";
// add build targets
fout <<
"<storageModule moduleId=\"org.eclipse.cdt.make.core.buildtargets\">\n"
"<buildTargets>\n"
;
emmited.clear();
const std::string make = mf->GetRequiredDefinition("CMAKE_MAKE_PROGRAM");
const std::string makeArgs = mf->GetSafeDefinition(
"CMAKE_ECLIPSE_MAKE_ARGUMENTS");
cmGlobalGenerator* generator
= const_cast<cmGlobalGenerator*>(this->GlobalGenerator);
std::string allTarget;
std::string cleanTarget;
if (generator->GetAllTargetName())
{
allTarget = generator->GetAllTargetName();
}
if (generator->GetCleanTargetName())
{
cleanTarget = generator->GetCleanTargetName();
}
// add all executable and library targets and some of the GLOBAL
// and UTILITY targets
for (std::vector<cmLocalGenerator*>::const_iterator
it = this->GlobalGenerator->GetLocalGenerators().begin();
it != this->GlobalGenerator->GetLocalGenerators().end();
++it)
{
const cmTargets& targets = (*it)->GetMakefile()->GetTargets();
cmMakefile* makefile=(*it)->GetMakefile();
std::string subdir = (*it)->Convert(makefile->GetCurrentBinaryDirectory(),
cmLocalGenerator::HOME_OUTPUT);
if (subdir == ".")
{
subdir = "";
}
for(cmTargets::const_iterator ti=targets.begin(); ti!=targets.end(); ++ti)
{
switch(ti->second.GetType())
{
case cmTarget::GLOBAL_TARGET:
{
// Only add the global targets from CMAKE_BINARY_DIR,
// not from the subdirs
if (subdir.empty())
{
this->AppendTarget(fout, ti->first, make, makeArgs, subdir, ": ");
}
}
break;
case cmTarget::UTILITY:
// Add all utility targets, except the Nightly/Continuous/
// Experimental-"sub"targets as e.g. NightlyStart
if (((ti->first.find("Nightly")==0) &&(ti->first!="Nightly"))
|| ((ti->first.find("Continuous")==0)&&(ti->first!="Continuous"))
|| ((ti->first.find("Experimental")==0)
&& (ti->first!="Experimental")))
{
break;
}
this->AppendTarget(fout, ti->first, make, makeArgs, subdir, ": ");
break;
case cmTarget::EXECUTABLE:
case cmTarget::STATIC_LIBRARY:
case cmTarget::SHARED_LIBRARY:
case cmTarget::MODULE_LIBRARY:
case cmTarget::OBJECT_LIBRARY:
{
const char* prefix = (ti->second.GetType()==cmTarget::EXECUTABLE ?
"[exe] " : "[lib] ");
this->AppendTarget(fout, ti->first, make, makeArgs, subdir, prefix);
std::string fastTarget = ti->first;
fastTarget += "/fast";
this->AppendTarget(fout, fastTarget, make, makeArgs, subdir, prefix);
// Add Build and Clean targets in the virtual folder of targets:
if (this->SupportsVirtualFolders)
{
std::string virtDir = "[Targets]/";
virtDir += prefix;
virtDir += ti->first;
std::string buildArgs = "-C \"";
buildArgs += makefile->GetHomeOutputDirectory();
buildArgs += "\" ";
buildArgs += makeArgs;
this->AppendTarget(fout, "Build", make, buildArgs, virtDir, "",
ti->first.c_str());
std::string cleanArgs = "-E chdir \"";
cleanArgs += makefile->GetCurrentBinaryDirectory();
cleanArgs += "\" \"";
cleanArgs += cmSystemTools::GetCMakeCommand();
cleanArgs += "\" -P \"";
cleanArgs += (*it)->GetTargetDirectory(ti->second);
cleanArgs += "/cmake_clean.cmake\"";
this->AppendTarget(fout, "Clean", cmSystemTools::GetCMakeCommand(),
cleanArgs, virtDir, "", "");
}
}
break;
default:
break;
}
}
// insert the all and clean targets in every subdir
if (!allTarget.empty())
{
this->AppendTarget(fout, allTarget, make, makeArgs, subdir, ": ");
}
if (!cleanTarget.empty())
{
this->AppendTarget(fout, cleanTarget, make, makeArgs, subdir, ": ");
}
//insert rules for compiling, preprocessing and assembling individual files
std::vector<std::string> objectFileTargets;
(*it)->GetIndividualFileTargets(objectFileTargets);
for(std::vector<std::string>::const_iterator fit=objectFileTargets.begin();
fit != objectFileTargets.end();
++fit)
{
const char* prefix = "[obj] ";
if ((*fit)[fit->length()-1] == 's')
{
prefix = "[to asm] ";
}
else if ((*fit)[fit->length()-1] == 'i')
{
prefix = "[pre] ";
}
this->AppendTarget(fout, *fit, make, makeArgs, subdir, prefix);
}
}
fout << "</buildTargets>\n"
"</storageModule>\n"
;
this->AppendStorageScanners(fout, *mf);
fout << "</cconfiguration>\n"
"</storageModule>\n"
"<storageModule moduleId=\"cdtBuildSystem\" version=\"4.0.0\">\n"
"<project id=\"" << this->EscapeForXML(mf->GetProjectName())
<< ".null.1\" name=\"" << this->EscapeForXML(mf->GetProjectName())
<< "\"/>\n"
"</storageModule>\n"
"</cproject>\n"
;
}
//----------------------------------------------------------------------------
std::string
cmExtraEclipseCDT4Generator::GetEclipsePath(const std::string& path)
{
#if defined(__CYGWIN__)
std::string cmd = "cygpath -m " + path;
std::string out;
if (!cmSystemTools::RunSingleCommand(cmd.c_str(), &out, &out))
{
return path;
}
else
{
out.erase(out.find_last_of('\n'));
return out;
}
#else
return path;
#endif
}
std::string
cmExtraEclipseCDT4Generator::GetPathBasename(const std::string& path)
{
std::string outputBasename = path;
while (!outputBasename.empty() &&
(outputBasename[outputBasename.size() - 1] == '/' ||
outputBasename[outputBasename.size() - 1] == '\\'))
{
outputBasename.resize(outputBasename.size() - 1);
}
std::string::size_type loc = outputBasename.find_last_of("/\\");
if (loc != std::string::npos)
{
outputBasename = outputBasename.substr(loc + 1);
}
return outputBasename;
}
std::string
cmExtraEclipseCDT4Generator::GenerateProjectName(const std::string& name,
const std::string& type,
const std::string& path)
{
return cmExtraEclipseCDT4Generator::EscapeForXML(name)
+(type.empty() ? "" : "-") + type + "@" + path;
}
std::string cmExtraEclipseCDT4Generator::EscapeForXML(const std::string& value)
{
std::string str = value;
cmSystemTools::ReplaceString(str, "&", "&");
cmSystemTools::ReplaceString(str, "<", "<");
cmSystemTools::ReplaceString(str, ">", ">");
cmSystemTools::ReplaceString(str, "\"", """);
// NOTE: This one is not necessary, since as of Eclipse CDT4 it will
// automatically change this to the original value (').
//cmSystemTools::ReplaceString(str, "'", "'");
return str;
}
//----------------------------------------------------------------------------
// Helper functions
//----------------------------------------------------------------------------
void cmExtraEclipseCDT4Generator
::AppendStorageScanners(cmGeneratedFileStream& fout,
const cmMakefile& makefile)
{
// we need the "make" and the C (or C++) compiler which are used, Alex
std::string make = makefile.GetRequiredDefinition("CMAKE_MAKE_PROGRAM");
std::string compiler = makefile.GetSafeDefinition("CMAKE_C_COMPILER");
std::string arg1 = makefile.GetSafeDefinition("CMAKE_C_COMPILER_ARG1");
if (compiler.empty())
{
compiler = makefile.GetSafeDefinition("CMAKE_CXX_COMPILER");
arg1 = makefile.GetSafeDefinition("CMAKE_CXX_COMPILER_ARG1");
}
if (compiler.empty()) //Hmm, what to do now ?
{
compiler = "gcc";
}
// the following right now hardcodes gcc behaviour :-/
std::string compilerArgs =
"-E -P -v -dD ${plugin_state_location}/${specs_file}";
if (!arg1.empty())
{
arg1 += " ";
compilerArgs = arg1 + compilerArgs;
}
fout <<
"<storageModule moduleId=\"scannerConfiguration\">\n"
"<autodiscovery enabled=\"true\" problemReportingEnabled=\"true\""
" selectedProfileId="
"\"org.eclipse.cdt.make.core.GCCStandardMakePerProjectProfile\"/>\n"
;
cmExtraEclipseCDT4Generator::AppendScannerProfile(fout,
"org.eclipse.cdt.make.core.GCCStandardMakePerProjectProfile",
true, "", true, "specsFile",
compilerArgs,
compiler, true, true);
cmExtraEclipseCDT4Generator::AppendScannerProfile(fout,
"org.eclipse.cdt.make.core.GCCStandardMakePerFileProfile",
true, "", true, "makefileGenerator",
"-f ${project_name}_scd.mk",
make, true, true);
fout << "</storageModule>\n";
}
// The prefix is prepended before the actual name of the target. The purpose
// of that is to sort the targets in the view of Eclipse, so that at first
// the global/utility/all/clean targets appear ": ", then the executable
// targets "[exe] ", then the libraries "[lib]", then the rules for the
// object files "[obj]", then for preprocessing only "[pre] " and
// finally the assembly files "[to asm] ". Note the "to" in "to asm",
// without it, "asm" would be the first targets in the list, with the "to"
// they are the last targets, which makes more sense.
void cmExtraEclipseCDT4Generator::AppendTarget(cmGeneratedFileStream& fout,
const std::string& target,
const std::string& make,
const std::string& makeArgs,
const std::string& path,
const char* prefix,
const char* makeTarget
)
{
std::string targetXml = cmExtraEclipseCDT4Generator::EscapeForXML(target);
std::string makeTargetXml = targetXml;
if (makeTarget != NULL)
{
makeTargetXml = cmExtraEclipseCDT4Generator::EscapeForXML(makeTarget);
}
cmExtraEclipseCDT4Generator::EscapeForXML(target);
std::string pathXml = cmExtraEclipseCDT4Generator::EscapeForXML(path);
fout <<
"<target name=\"" << prefix << targetXml << "\""
" path=\"" << pathXml << "\""
" targetID=\"org.eclipse.cdt.make.MakeTargetBuilder\">\n"
"<buildCommand>"
<< cmExtraEclipseCDT4Generator::GetEclipsePath(make)
<< "</buildCommand>\n"
"<buildArguments>" << makeArgs << "</buildArguments>\n"
"<buildTarget>" << makeTargetXml << "</buildTarget>\n"
"<stopOnError>true</stopOnError>\n"
"<useDefaultCommand>false</useDefaultCommand>\n"
"</target>\n"
;
}
void cmExtraEclipseCDT4Generator
::AppendScannerProfile(cmGeneratedFileStream& fout,
const std::string& profileID,
bool openActionEnabled,
const std::string& openActionFilePath,
bool pParserEnabled,
const std::string& scannerInfoProviderID,
const std::string& runActionArguments,
const std::string& runActionCommand,
bool runActionUseDefault,
bool sipParserEnabled)
{
fout <<
"<profile id=\"" << profileID << "\">\n"
"<buildOutputProvider>\n"
"<openAction enabled=\"" << (openActionEnabled ? "true" : "false")
<< "\" filePath=\"" << openActionFilePath << "\"/>\n"
"<parser enabled=\"" << (pParserEnabled ? "true" : "false") << "\"/>\n"
"</buildOutputProvider>\n"
"<scannerInfoProvider id=\"" << scannerInfoProviderID << "\">\n"
"<runAction arguments=\"" << runActionArguments << "\""
" command=\"" << runActionCommand
<< "\" useDefault=\"" << (runActionUseDefault ? "true":"false") << "\"/>\n"
"<parser enabled=\"" << (sipParserEnabled ? "true" : "false") << "\"/>\n"
"</scannerInfoProvider>\n"
"</profile>\n"
;
}
void cmExtraEclipseCDT4Generator
::AppendLinkedResource (cmGeneratedFileStream& fout,
const std::string& name,
const std::string& path,
LinkType linkType)
{
const char* locationTag = "location";
const char* typeTag = "2";
if (linkType == VirtualFolder) // ... and not a linked folder
{
locationTag = "locationURI";
}
if (linkType == LinkToFile)
{
typeTag = "1";
}
fout <<
"\t\t<link>\n"
"\t\t\t<name>"
<< cmExtraEclipseCDT4Generator::EscapeForXML(name)
<< "</name>\n"
"\t\t\t<type>" << typeTag << "</type>\n"
"\t\t\t<" << locationTag << ">"
<< cmExtraEclipseCDT4Generator::EscapeForXML(path)
<< "</" << locationTag << ">\n"
"\t\t</link>\n"
;
}
| 35.074453 | 79 | 0.567052 | [
"object",
"vector"
] |
44c5e2fc47b0908315ed4c30ec7833077e46b794 | 3,774 | hpp | C++ | Vitis-AI-Library/xnnpp/include/vitis/ai/nnpp/multitask.hpp | dendisuhubdy/Vitis-AI | 524f65224c52314155dafc011d488ed30e458fcb | [
"Apache-2.0"
] | 19 | 2020-10-26T17:37:22.000Z | 2022-01-20T09:32:38.000Z | Vitis-AI-Library/xnnpp/include/vitis/ai/nnpp/multitask.hpp | dendisuhubdy/Vitis-AI | 524f65224c52314155dafc011d488ed30e458fcb | [
"Apache-2.0"
] | 20 | 2020-10-31T03:19:03.000Z | 2020-11-02T18:59:49.000Z | Vitis-AI-Library/xnnpp/include/vitis/ai/nnpp/multitask.hpp | dendisuhubdy/Vitis-AI | 524f65224c52314155dafc011d488ed30e458fcb | [
"Apache-2.0"
] | 19 | 2020-10-21T19:15:17.000Z | 2022-01-04T08:32:08.000Z | /*
* Copyright 2019 Xilinx Inc.
*
* 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
*
* 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.
*/
#pragma once
#include <vitis/ai/proto/dpu_model_param.pb.h>
#include <opencv2/core.hpp>
#include <vitis/ai/library/tensor.hpp>
namespace vitis {
namespace ai {
/**
*@struct VehicleResult
*@brief A struct to define detection result of MultiTask
*/
struct VehicleResult {
/// number of classes
/// \li \c 0 : "background"
/// \li \c 1 : "person"
/// \li \c 2 : "car"
/// \li \c 3 : "truck"
/// \li \c 4 : "bus"
/// \li \c 5 : "bike"
/// \li \c 6 : "sign"
/// \li \c 7 : "light"
int label;
/// confidence of this target
float score;
/// x-coordinate, x is normalized relative to the input image cols ,the value
/// range from 0 to 1.
float x;
/// y-coordinate ,y is normalized relative to the input image rows ,the value
/// range from 0 to 1.
float y;
/// width, width is normalized relative to the input image cols ,the value
/// range from 0 to 1.
float width;
/// height, height is normalized relative to the input image rows ,the value
/// range from 0 to 1.
float height;
/// the angle between the target vehicle and ourself.
float angle;
};
/**
*@struct MultiTaskResult
*@brief Struct of the result returned by the MultiTask network, when you need
*to visualize.
*/
struct MultiTaskResult {
/// Width of input image.
int width;
/// Height of input image.
int height;
/// Detection result of SSD task
std::vector<VehicleResult> vehicle;
/// Segmentation result to visualize , cv::Mat type is CV_8UC1 or CV_8UC3.
cv::Mat segmentation;
};
class MultiTaskPostProcess {
public:
/**
* @brief Factory function to get an instance of derived classes of
* MultiTaskPostProcess
* @param input_tensors A vector of all input-tensors in the network.
* Usage: input_tensors[kernel_index][input_tensor_index].
* @param output_tensors A vector of all output-tensors in the network.
* Usage: output_tensors[kernel_index][output_index].
* @param config The dpu model configuration information.
* @return The struct of MultiTaskResult.
*/
static std::unique_ptr<MultiTaskPostProcess> create(
const std::vector<std::vector<vitis::ai::library::InputTensor>>&
input_tensors,
const std::vector<std::vector<vitis::ai::library::OutputTensor>>&
output_tensors,
const vitis::ai::proto::DpuModelParam& config);
/**
* @cond NOCOMMENTS
*/
protected:
explicit MultiTaskPostProcess();
MultiTaskPostProcess(const MultiTaskPostProcess&) = delete;
MultiTaskPostProcess& operator=(const MultiTaskPostProcess&) = delete;
public:
virtual ~MultiTaskPostProcess();
/**
* @endcond
*/
/**
* @brief The post-processing function of the multitask which stored the
* original segmentation classes.
* @return The struct of SegmentationResult.
*/
virtual std::vector<MultiTaskResult> post_process_seg() = 0;
/**
* @brief The post-processing function of the multitask which return a result
* include segmentation image mapped to color.
* @return The struct of SegmentationResult.
*/
virtual std::vector<MultiTaskResult> post_process_seg_visualization() = 0;
};
} // namespace ai
} // namespace vitis
| 31.190083 | 79 | 0.692369 | [
"vector",
"model"
] |
44c7c6bc0a50fff19e281d00250874ad4e738ec9 | 8,908 | cc | C++ | src/xml_doc_frag.cc | fictivekin/libxmljs | 0da040b6bb7a80677ded708480c9e00eae3bfcc3 | [
"MIT"
] | null | null | null | src/xml_doc_frag.cc | fictivekin/libxmljs | 0da040b6bb7a80677ded708480c9e00eae3bfcc3 | [
"MIT"
] | null | null | null | src/xml_doc_frag.cc | fictivekin/libxmljs | 0da040b6bb7a80677ded708480c9e00eae3bfcc3 | [
"MIT"
] | null | null | null | // Copyright 2009, Squish Tech, LLC.
#include "xml_doc_frag.h"
#include "xml_element.h"
#include "xml_document.h"
#include "xml_attribute.h"
#include "xml_xpath_context.h"
namespace libxmljs {
#define NAME_SYMBOL v8::String::NewSymbol("name")
#define CONTENT_SYMBOL v8::String::NewSymbol("content")
v8::Persistent<v8::FunctionTemplate> XmlDocFrag::constructor_template;
// doc, name, attrs, content, callback
v8::Handle<v8::Value>
XmlDocFrag::New(const v8::Arguments& args) {
v8::HandleScope scope;
// was created by BUILD_NODE
if (args.Length() == 0 || args[0]->StrictEquals(v8::Null()))
return scope.Close(args.This());
XmlDocument *document = LibXmlObj::Unwrap<XmlDocument>(args[0]->ToObject());
v8::String::Utf8Value name(args[1]);
v8::Handle<v8::Function> callback;
char* content = NULL;
if(!args[3]->IsUndefined() && !args[3]->IsNull()) {
v8::String::Utf8Value content_(args[3]);
content = strdup(*content_);
}
if (args[4]->IsFunction())
callback = v8::Handle<v8::Function>::Cast(args[4]);
xmlNode* elem = xmlNewDocNode(document->xml_obj,
NULL,
(const xmlChar*)*name,
(const xmlChar*)content);
UpdateV8Memory();
if(content)
free(content);
v8::Handle<v8::Object> obj =
LibXmlObj::GetMaybeBuild<XmlDocFrag, xmlNode>(elem);
XmlDocFrag *frag = LibXmlObj::Unwrap<XmlDocFrag>(obj);
if (args[2]->IsObject()) {
v8::Handle<v8::Object> attributes = args[2]->ToObject();
v8::Handle<v8::Array> props = attributes->GetPropertyNames();
for (unsigned int i = 0; i < props->Length(); i++) {
v8::String::Utf8Value name(
props->Get(v8::Number::New(i)));
v8::String::Utf8Value value(
attributes->Get(props->Get(v8::Number::New(i))));
// element->set_attr(*name, *value);
}
}
obj->Set(v8::String::NewSymbol("document"), args[0]->ToObject());
if (*callback && !callback->IsNull()) {
v8::Handle<v8::Value> argv[1] = { obj };
*callback->Call(obj, 1, argv);
}
return scope.Close(obj);
}
v8::Handle<v8::Value>
XmlDocFrag::Name(const v8::Arguments& args) {
v8::HandleScope scope;
XmlDocFrag *frag = LibXmlObj::Unwrap<XmlDocFrag>(args.This());
assert(frag);
if (args.Length() == 0)
return scope.Close(frag->get_name());
v8::String::Utf8Value name(args[0]->ToString());
frag->set_name(*name);
return scope.Close(args.This());
}
v8::Handle<v8::Value>
XmlDocFrag::AddChild(const v8::Arguments& args) {
v8::HandleScope scope;
XmlDocFrag *frag = LibXmlObj::Unwrap<XmlDocFrag>(args.This());
assert(frag);
XmlElement *child = LibXmlObj::Unwrap<XmlElement>(args[0]->ToObject());
assert(child);
child = frag->import_element(child);
if(child == NULL) {
LIBXMLJS_THROW_EXCEPTION("Could not add child. Failed to copy node to new Document.");
}
frag->add_child(child);
return scope.Close(LibXmlObj::GetMaybeBuild<XmlElement, xmlNode>(child->xml_obj));
}
v8::Handle<v8::Value>
XmlDocFrag::Find(const v8::Arguments& args) {
v8::HandleScope scope;
XmlDocFrag *frag = LibXmlObj::Unwrap<XmlDocFrag>(args.This());
assert(frag);
v8::String::Utf8Value xpath(args[0]);
XmlXpathContext ctxt(frag->xml_obj);
if (args.Length() == 2) {
if (args[1]->IsString()) {
v8::String::Utf8Value uri(args[1]);
ctxt.register_ns((const xmlChar*)"xmlns", (const xmlChar*)*uri);
} else if (args[1]->IsObject()) {
v8::Handle<v8::Object> namespaces = args[1]->ToObject();
v8::Handle<v8::Array> properties = namespaces->GetPropertyNames();
for (unsigned int i = 0; i < properties->Length(); i++) {
v8::Local<v8::String> prop_name = properties->Get(
v8::Number::New(i))->ToString();
v8::String::Utf8Value prefix(prop_name);
v8::String::Utf8Value uri(namespaces->Get(prop_name));
ctxt.register_ns((const xmlChar*)*prefix, (const xmlChar*)*uri);
}
}
}
return scope.Close(ctxt.evaluate((const xmlChar*)*xpath));
}
v8::Handle<v8::Value>
XmlDocFrag::Text(const v8::Arguments& args) {
v8::HandleScope scope;
XmlDocFrag *frag = LibXmlObj::Unwrap<XmlDocFrag>(args.This());
assert(frag);
if (args.Length() == 0) {
return scope.Close(frag->get_content());
} else {
frag->set_content(*v8::String::Utf8Value(args[0]));
}
return scope.Close(args.This());
}
v8::Handle<v8::Value>
XmlDocFrag::clone(bool deep) {
v8::HandleScope scope;
return scope.Close(LibXmlObj::GetMaybeBuild<XmlDocFrag, xmlNode>(xmlCopyNode(xml_obj, deep ? 1 : 0)));
}
v8::Handle<v8::Value>
XmlDocFrag::Child(const v8::Arguments& args) {
v8::HandleScope scope;
XmlDocFrag *frag = LibXmlObj::Unwrap<XmlDocFrag>(args.This());
assert(frag);
double idx = 1;
if (args.Length() > 0) {
if (!args[0]->IsNumber()) {
LIBXMLJS_THROW_EXCEPTION(
"Bad argument: must provide #child() with a number");
} else {
idx = args[0]->ToNumber()->Value();
}
}
return scope.Close(frag->get_child(idx));
}
v8::Handle<v8::Value>
XmlDocFrag::ChildNodes(const v8::Arguments& args) {
v8::HandleScope scope;
XmlDocFrag *frag = LibXmlObj::Unwrap<XmlDocFrag>(args.This());
assert(frag);
if (args[0]->IsNumber())
return scope.Close(frag->get_child(args[0]->ToNumber()->Value()));
return scope.Close(frag->get_child_nodes());
}
void
XmlDocFrag::set_name(const char* name) {
xmlNodeSetName(xml_obj, (const xmlChar*)name);
}
v8::Handle<v8::Value>
XmlDocFrag::get_name() {
return v8::String::New((const char*)xml_obj->name);
}
// TODO(sprsquish) make these work with namespaces
void
XmlDocFrag::add_child(XmlElement* child) {
xmlAddChild(xml_obj, child->xml_obj);
}
v8::Handle<v8::Value>
XmlDocFrag::get_child(double idx) {
v8::HandleScope scope;
double i = 1;
xmlNode* child = xml_obj->children;
while (child && i < idx) {
child = child->next;
i++;
}
if (!child)
return v8::Null();
return scope.Close(LibXmlObj::GetMaybeBuild<XmlElement, xmlNode>(child));
}
v8::Handle<v8::Value>
XmlDocFrag::get_child_nodes() {
v8::HandleScope scope;
xmlNode* child = xml_obj->children;
if (!child)
return scope.Close(v8::Array::New(0));
xmlNodeSetPtr set = xmlXPathNodeSetCreate(child);
do {
xmlXPathNodeSetAdd(set, child);
} while ((child = child->next));
v8::Handle<v8::Array> children = v8::Array::New(set->nodeNr);
for (int i = 0; i < set->nodeNr; ++i) {
xmlNode *node = set->nodeTab[i];
children->Set(v8::Number::New(i),
LibXmlObj::GetMaybeBuild<XmlElement, xmlNode>(node));
}
xmlXPathFreeNodeSet(set);
return scope.Close(children);
}
void
XmlDocFrag::set_content(const char* content) {
xmlNodeSetContent(xml_obj, (const xmlChar*)content);
}
v8::Handle<v8::Value>
XmlDocFrag::get_content() {
xmlChar* content = xmlNodeGetContent(xml_obj);
if (content) {
v8::Handle<v8::String> ret_content =
v8::String::New((const char *)content);
xmlFree(content);
return ret_content;
}
return v8::String::Empty();
}
XmlElement *
XmlDocFrag::import_element(XmlElement *element) {
xmlNode *new_child;
if(xml_obj->doc == element->xml_obj->doc) {
return element;
} else {
new_child = xmlDocCopyNode(element->xml_obj, xml_obj->doc, 1);
if(new_child == NULL) {
return NULL;
}
xmlUnlinkNode(element->xml_obj);
UpdateV8Memory();
v8::Handle<v8::Object> obj =
LibXmlObj::GetMaybeBuild<XmlElement, xmlNode>(new_child);
return LibXmlObj::Unwrap<XmlElement>(obj);
}
}
void
XmlDocFrag::Initialize(v8::Handle<v8::Object> target) {
v8::HandleScope scope;
v8::Local<v8::FunctionTemplate> t = v8::FunctionTemplate::New(New);
constructor_template = v8::Persistent<v8::FunctionTemplate>::New(t);
constructor_template->Inherit(XmlNode::constructor_template);
constructor_template->InstanceTemplate()->SetInternalFieldCount(1);
LXJS_SET_PROTO_METHOD(constructor_template,
"addChild",
XmlDocFrag::AddChild);
LXJS_SET_PROTO_METHOD(constructor_template,
"child",
XmlDocFrag::Child);
LXJS_SET_PROTO_METHOD(constructor_template,
"childNodes",
XmlDocFrag::ChildNodes);
LXJS_SET_PROTO_METHOD(constructor_template,
"find",
XmlDocFrag::Find);
LXJS_SET_PROTO_METHOD(constructor_template,
"name",
XmlDocFrag::Name);
LXJS_SET_PROTO_METHOD(constructor_template,
"text",
XmlDocFrag::Text);
target->Set(v8::String::NewSymbol("DocumentFragment"),
constructor_template->GetFunction());
}
} // namespace libxmljs
| 27.158537 | 104 | 0.636282 | [
"object"
] |
44c8e7558001c92057a2e846572910213274f8f8 | 59,027 | cpp | C++ | tools/quickbook/src/bb2html.cpp | cpp-pm/boost | 38c6c8c07f2fcc42d573b10807fef27ec14930f8 | [
"BSL-1.0"
] | 11,356 | 2017-12-08T19:42:32.000Z | 2022-03-31T16:55:25.000Z | tools/quickbook/src/bb2html.cpp | cpp-pm/boost | 38c6c8c07f2fcc42d573b10807fef27ec14930f8 | [
"BSL-1.0"
] | 2,402 | 2017-12-08T22:31:01.000Z | 2022-03-28T19:25:52.000Z | tools/quickbook/src/bb2html.cpp | cpp-pm/boost | 38c6c8c07f2fcc42d573b10807fef27ec14930f8 | [
"BSL-1.0"
] | 1,343 | 2017-12-08T19:47:19.000Z | 2022-03-26T11:31:36.000Z | /*=============================================================================
Copyright (c) 2017 Daniel James
Use, modification and distribution is subject to the Boost Software
License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
http://www.boost.org/LICENSE_1_0.txt)
=============================================================================*/
#include "bb2html.hpp"
#include <cassert>
#include <vector>
#include <boost/algorithm/string/predicate.hpp>
#include <boost/filesystem/fstream.hpp>
#include <boost/filesystem/operations.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/preprocessor/cat.hpp>
#include <boost/preprocessor/stringize.hpp>
#include <boost/unordered_map.hpp>
#include <boost/unordered_set.hpp>
#include "boostbook_chunker.hpp"
#include "files.hpp"
#include "for.hpp"
#include "html_printer.hpp"
#include "path.hpp"
#include "post_process.hpp"
#include "stream.hpp"
#include "utils.hpp"
#include "xml_parse.hpp"
namespace quickbook
{
namespace fs = boost::filesystem;
}
namespace quickbook
{
namespace detail
{
struct html_state;
struct html_gen;
struct docinfo_gen;
struct id_info;
typedef boost::unordered_map<string_view, id_info> ids_type;
typedef void (*node_parser)(html_gen&, xml_element*);
typedef boost::unordered_map<quickbook::string_view, node_parser>
node_parsers_type;
static node_parsers_type node_parsers;
struct docinfo_node_parser
{
typedef void (*parser_type)(docinfo_gen&, xml_element*);
enum docinfo_node_category
{
docinfo_general = 0,
docinfo_author
};
docinfo_node_category category;
parser_type parser;
};
typedef boost::
unordered_map<quickbook::string_view, docinfo_node_parser>
docinfo_node_pasers_type;
static docinfo_node_pasers_type docinfo_node_parsers;
void generate_chunked_documentation(
chunk*, ids_type const&, html_options const&);
void generate_chunks(html_state&, chunk*);
void generate_chunk_navigation(html_gen&, chunk*);
void generate_inline_chunks(html_gen&, chunk*);
void generate_chunk_body(html_gen&, chunk*);
void generate_toc_html(html_gen& gen, chunk*);
void generate_toc_subtree(
html_gen& gen, chunk* page, chunk*, unsigned section_depth);
void generate_toc_item_html(html_gen&, xml_element*);
void generate_footnotes_html(html_gen&);
void number_callouts(html_gen& gen, xml_element* x);
void number_calloutlist_children(
html_gen& gen, unsigned& count, xml_element* x);
void generate_docinfo_html(html_gen&, xml_element*);
void generate_tree_html(html_gen&, xml_element*);
void generate_children_html(html_gen&, xml_element*);
void write_file(
html_state&, std::string const& path, std::string const& content);
std::string get_link_from_path(
html_gen&, quickbook::string_view, quickbook::string_view);
std::string relative_path_or_url(html_gen&, path_or_url const&);
std::string relative_path_from_fs_paths(
fs::path const&, fs::path const&);
std::string relative_path_from_url_paths(
quickbook::string_view, quickbook::string_view);
ids_type get_id_paths(chunk* chunk);
void get_id_paths_impl(ids_type&, chunk*);
void get_id_paths_impl2(ids_type&, chunk*, xml_element*);
void tag(html_gen& gen, quickbook::string_view name, xml_element* x);
void tag_start_with_id(
html_gen& gen, quickbook::string_view name, xml_element* x);
void open_tag_with_id(
html_gen& gen, quickbook::string_view name, xml_element* x);
void tag_self_close(
html_gen& gen, quickbook::string_view name, xml_element* x);
void graphics_tag(
html_gen& gen,
quickbook::string_view path,
quickbook::string_view fallback);
struct id_info
{
private:
chunk* chunk_;
xml_element* element_;
public:
explicit id_info(chunk* c, xml_element* x) : chunk_(c), element_(x)
{
assert(c);
assert(!x || x->has_attribute("id"));
}
std::string path() const
{
std::string p = chunk_->path_;
if (element_) {
p += '#';
p += element_->get_attribute("id");
}
else if (chunk_->inline_) {
p += '#';
p += chunk_->id_;
}
return p;
}
};
struct html_state
{
ids_type const& ids;
html_options const& options;
unsigned int error_count;
explicit html_state(
ids_type const& ids_, html_options const& options_)
: ids(ids_), options(options_), error_count(0)
{
}
};
struct callout_data
{
quickbook::string_view link_id;
unsigned number;
};
struct chunk_state
{
std::vector<xml_element*> footnotes;
boost::unordered_map<string_view, callout_data> callout_numbers;
boost::unordered_set<string_view> fragment_ids;
};
struct html_gen
{
html_printer printer;
html_state& state;
chunk_state& chunk;
string_view path;
bool in_toc;
explicit html_gen(
html_state& state_, chunk_state& chunk_, string_view p)
: printer()
, state(state_)
, chunk(chunk_)
, path(p)
, in_toc(false)
{
}
html_gen(html_gen const& x)
: printer()
, state(x.state)
, chunk(x.chunk)
, path(x.path)
, in_toc(false)
{
}
};
struct docinfo_gen
{
html_gen& gen;
std::vector<std::string> copyrights;
std::vector<std::string> pubdates;
std::vector<std::string> legalnotices;
std::vector<std::string> authors;
std::vector<std::string> editors;
std::vector<std::string> collabs;
docinfo_gen(html_gen& gen_) : gen(gen_) {}
};
int boostbook_to_html(
quickbook::string_view source, html_options const& options)
{
xml_tree tree;
try {
tree = xml_parse(source);
} catch (quickbook::detail::xml_parse_error e) {
string_view source_view(source);
file_position p = relative_position(source_view.begin(), e.pos);
string_view::iterator line_start =
e.pos - (p.column < 40 ? p.column - 1 : 39);
string_view::iterator line_end =
std::find(e.pos, source_view.end(), '\n');
if (line_end - e.pos > 80) {
line_end = e.pos + 80;
}
std::string indent;
for (auto i = e.pos - line_start; i; --i) {
indent += ' ';
}
::quickbook::detail::outerr()
<< "converting boostbook at line " << p.line << " char "
<< p.column << ": " << e.message << "\n"
<< string_view(line_start, line_end - line_start) << "\n"
<< indent << "^"
<< "\n\n";
return 1;
}
chunk_tree chunked = chunk_document(tree);
// Overwrite paths depending on whether output is chunked or not.
// Really want to do something better, e.g. incorporate many section
// chunks into their parent.
chunked.root()->path_ =
path_to_generic(options.home_path.filename());
if (options.chunked_output) {
inline_sections(chunked.root(), 0);
// Create the root directory if necessary for chunked
// documentation.
fs::path parent = options.home_path.parent_path();
if (!parent.empty() && !fs::exists(parent)) {
fs::create_directory(parent);
}
}
else {
inline_all(chunked.root());
}
ids_type ids = get_id_paths(chunked.root());
html_state state(ids, options);
if (chunked.root()) {
generate_chunks(state, chunked.root());
}
return state.error_count;
}
void gather_chunk_ids(chunk_state& c_state, xml_element* x)
{
if (!x) {
return;
}
if (x->has_attribute("id")) {
c_state.fragment_ids.emplace(x->get_attribute("id"));
}
for (auto it = x->children(); it; it = it->next()) {
gather_chunk_ids(c_state, it);
}
}
void gather_chunk_ids(chunk_state& c_state, chunk* x)
{
gather_chunk_ids(c_state, x->contents_.root());
gather_chunk_ids(c_state, x->title_.root());
gather_chunk_ids(c_state, x->info_.root());
for (chunk* it = x->children(); it && it->inline_;
it = it->next()) {
gather_chunk_ids(c_state, it);
}
}
string_view generate_id(
chunk_state& c_state,
xml_element* x,
string_view name,
string_view base)
{
std::string result;
result.reserve(base.size() + 2);
result.assign(base.begin(), base.end());
result += '-';
// TODO: Share implementation with id_generation.cpp?
for (unsigned count = 1;; ++count) {
auto num = boost::lexical_cast<std::string>(count);
result.reserve(base.size() + 1 + num.size());
result.erase(base.size() + 1);
result += num;
if (c_state.fragment_ids.find(result) ==
c_state.fragment_ids.end()) {
auto r = x->set_attribute(name, result);
c_state.fragment_ids.emplace(r);
return r;
}
}
}
void generate_chunks(html_state& state, chunk* x)
{
chunk_state c_state;
gather_chunk_ids(c_state, x);
html_gen gen(state, c_state, x->path_);
gen.printer.html += "<!DOCTYPE html>\n";
open_tag(gen.printer, "html");
open_tag(gen.printer, "head");
if (state.options.css_path) {
tag_start(gen.printer, "link");
tag_attribute(gen.printer, "rel", "stylesheet");
tag_attribute(gen.printer, "type", "text/css");
tag_attribute(
gen.printer, "href",
relative_path_or_url(gen, state.options.css_path));
tag_end_self_close(gen.printer);
}
close_tag(gen.printer, "head");
open_tag(gen.printer, "body");
generate_chunk_navigation(gen, x);
generate_chunk_body(gen, x);
chunk* it = x->children();
for (; it && it->inline_; it = it->next()) {
generate_inline_chunks(gen, it);
}
generate_footnotes_html(gen);
close_tag(gen.printer, "body");
close_tag(gen.printer, "html");
write_file(state, x->path_, gen.printer.html);
for (; it; it = it->next()) {
assert(!it->inline_);
generate_chunks(state, it);
}
}
void generate_chunk_navigation(html_gen& gen, chunk* x)
{
chunk* next = 0;
for (chunk* it = x->children(); it; it = it->next()) {
if (!it->inline_) {
next = it;
break;
}
}
if (!next) {
next = x->next();
}
chunk* prev = x->prev();
if (prev) {
while (prev->children()) {
for (prev = prev->children(); prev->next();
prev = prev->next()) {
}
}
}
else {
prev = x->parent();
}
if (next || prev || x->parent()) {
tag_start(gen.printer, "div");
tag_attribute(gen.printer, "class", "spirit-nav");
tag_end(gen.printer);
if (prev) {
tag_start(gen.printer, "a");
tag_attribute(
gen.printer, "href",
get_link_from_path(gen, prev->path_, x->path_));
tag_attribute(gen.printer, "accesskey", "p");
tag_end(gen.printer);
graphics_tag(gen, "/prev.png", "prev");
close_tag(gen.printer, "a");
gen.printer.html += " ";
}
if (x->parent()) {
tag_start(gen.printer, "a");
tag_attribute(
gen.printer, "href",
get_link_from_path(gen, x->parent()->path_, x->path_));
tag_attribute(gen.printer, "accesskey", "u");
tag_end(gen.printer);
graphics_tag(gen, "/up.png", "up");
close_tag(gen.printer, "a");
gen.printer.html += " ";
tag_start(gen.printer, "a");
tag_attribute(
gen.printer, "href",
get_link_from_path(gen, "index.html", x->path_));
tag_attribute(gen.printer, "accesskey", "h");
tag_end(gen.printer);
graphics_tag(gen, "/home.png", "home");
close_tag(gen.printer, "a");
if (next) {
gen.printer.html += " ";
}
}
if (next) {
tag_start(gen.printer, "a");
tag_attribute(
gen.printer, "href",
get_link_from_path(gen, next->path_, x->path_));
tag_attribute(gen.printer, "accesskey", "n");
tag_end(gen.printer);
graphics_tag(gen, "/next.png", "next");
close_tag(gen.printer, "a");
}
close_tag(gen.printer, "div");
}
}
void generate_inline_chunks(html_gen& gen, chunk* x)
{
tag_start(gen.printer, "div");
tag_attribute(gen.printer, "id", x->id_);
tag_end(gen.printer);
generate_chunk_body(gen, x);
for (chunk* it = x->children(); it; it = it->next()) {
assert(it->inline_);
generate_inline_chunks(gen, it);
}
close_tag(gen.printer, "div");
}
void generate_chunk_body(html_gen& gen, chunk* x)
{
gen.chunk.callout_numbers.clear();
number_callouts(gen, x->title_.root());
number_callouts(gen, x->info_.root());
number_callouts(gen, x->contents_.root());
generate_tree_html(gen, x->title_.root());
generate_docinfo_html(gen, x->info_.root());
generate_toc_html(gen, x);
generate_tree_html(gen, x->contents_.root());
}
void generate_toc_html(html_gen& gen, chunk* x)
{
if (x->children() && x->contents_.root()->name_ != "section") {
tag_start(gen.printer, "div");
tag_attribute(gen.printer, "class", "toc");
tag_end(gen.printer);
open_tag(gen.printer, "p");
open_tag(gen.printer, "b");
gen.printer.html += "Table of contents";
close_tag(gen.printer, "b");
close_tag(gen.printer, "p");
generate_toc_subtree(gen, x, x, 1);
close_tag(gen.printer, "div");
}
}
void generate_toc_subtree(
html_gen& gen, chunk* page, chunk* x, unsigned section_depth)
{
if (x != page && section_depth == 0) {
bool has_non_section_child = false;
for (chunk* it = x->children(); it; it = it->next()) {
if (it->contents_.root()->name_ != "section") {
has_non_section_child = true;
}
}
if (!has_non_section_child) {
return;
}
}
gen.printer.html += "<ul>";
for (chunk* it = x->children(); it; it = it->next()) {
auto link = gen.state.ids.find(it->id_);
gen.printer.html += "<li>";
if (link != gen.state.ids.end()) {
gen.printer.html += "<a href=\"";
gen.printer.html += encode_string(get_link_from_path(
gen, link->second.path(), page->path_));
gen.printer.html += "\">";
generate_toc_item_html(gen, it->title_.root());
gen.printer.html += "</a>";
}
else {
generate_toc_item_html(gen, it->title_.root());
}
if (it->children()) {
generate_toc_subtree(
gen, page, it,
it->contents_.root()->name_ == "section" &&
section_depth > 0
? section_depth - 1
: section_depth);
}
gen.printer.html += "</li>";
}
gen.printer.html += "</ul>";
}
void generate_toc_item_html(html_gen& gen, xml_element* x)
{
if (x) {
bool old = gen.in_toc;
gen.in_toc = true;
generate_children_html(gen, x);
gen.in_toc = old;
}
else {
gen.printer.html += "<i>Untitled</i>";
}
}
void generate_footnotes_html(html_gen& gen)
{
if (!gen.chunk.footnotes.empty()) {
tag_start(gen.printer, "div");
tag_attribute(gen.printer, "class", "footnotes");
tag_end(gen.printer);
gen.printer.html += "<br/>";
gen.printer.html += "<hr/>";
for (std::vector<xml_element*>::iterator it =
gen.chunk.footnotes.begin();
it != gen.chunk.footnotes.end(); ++it) {
auto footnote_id =
(*it)->get_attribute("(((footnote-id)))");
tag_start(gen.printer, "div");
tag_attribute(gen.printer, "id", footnote_id);
tag_attribute(gen.printer, "class", "footnote");
tag_end(gen.printer);
generate_children_html(gen, *it);
close_tag(gen.printer, "div");
}
close_tag(gen.printer, "div");
}
}
void number_callouts(html_gen& gen, xml_element* x)
{
if (!x) {
return;
}
if (x->type_ == xml_element::element_node) {
if (x->name_ == "calloutlist") {
unsigned count = 0;
number_calloutlist_children(gen, count, x);
}
else if (x->name_ == "co") {
if (x->has_attribute("linkends")) {
auto linkends = x->get_attribute("linkends");
if (!x->has_attribute("id")) {
generate_id(gen.chunk, x, "id", linkends);
}
gen.chunk.callout_numbers[linkends].link_id =
x->get_attribute("id");
}
}
}
for (xml_element* it = x->children(); it; it = it->next()) {
number_callouts(gen, it);
}
}
void number_calloutlist_children(
html_gen& gen, unsigned& count, xml_element* x)
{
for (xml_element* it = x->children(); it; it = it->next()) {
if (it->type_ == xml_element::element_node &&
it->name_ == "callout") {
if (it->has_attribute("id")) {
gen.chunk.callout_numbers[it->get_attribute("id")]
.number = ++count;
}
}
number_calloutlist_children(gen, count, it);
}
}
void generate_tree_html(html_gen& gen, xml_element* x)
{
if (!x) {
return;
}
switch (x->type_) {
case xml_element::element_text: {
gen.printer.html += x->contents_;
break;
}
case xml_element::element_html: {
gen.printer.html += x->contents_;
break;
}
case xml_element::element_node: {
node_parsers_type::iterator parser =
node_parsers.find(x->name_);
if (parser != node_parsers.end()) {
parser->second(gen, x);
}
else {
quickbook::detail::out()
<< "Unsupported tag: " << x->name_ << std::endl;
generate_children_html(gen, x);
}
break;
}
default:
assert(false);
}
}
void generate_children_html(html_gen& gen, xml_element* x)
{
for (xml_element* it = x->children(); it; it = it->next()) {
generate_tree_html(gen, it);
}
}
void generate_docinfo_html_impl(docinfo_gen& d, xml_element* x)
{
for (xml_element* it = x->children(); it; it = it->next()) {
if (it->type_ == xml_element::element_node) {
auto parser = docinfo_node_parsers.find(it->name_);
if (parser != docinfo_node_parsers.end()) {
parser->second.parser(d, it);
}
else {
quickbook::detail::out()
<< "Unsupported docinfo tag: " << x->name_
<< std::endl;
generate_docinfo_html_impl(d, it);
}
}
}
}
void generate_docinfo_html(html_gen& gen, xml_element* x)
{
if (!x) {
return;
}
docinfo_gen d(gen);
generate_docinfo_html_impl(d, x);
if (!d.authors.empty() || !d.editors.empty() ||
!d.collabs.empty()) {
gen.printer.html += "<div class=\"authorgroup\">\n";
QUICKBOOK_FOR (auto const& author, d.authors) {
gen.printer.html += "<h3 class=\"author\">";
gen.printer.html += author;
gen.printer.html += "</h3>\n";
}
QUICKBOOK_FOR (auto const& editor, d.editors) {
gen.printer.html += "<h3 class=\"editor\">";
gen.printer.html += editor;
gen.printer.html += "</h3>\n";
}
QUICKBOOK_FOR (auto const& collab, d.collabs) {
gen.printer.html += "<h3 class=\"collab\">";
gen.printer.html += collab;
gen.printer.html += "</h3>\n";
}
gen.printer.html += "</div>\n";
}
QUICKBOOK_FOR (auto const& copyright, d.copyrights) {
gen.printer.html += "<p class=\"copyright\">";
gen.printer.html += copyright;
gen.printer.html += "</p>";
}
QUICKBOOK_FOR (auto const& legalnotice, d.legalnotices) {
gen.printer.html += "<div class=\"legalnotice\">";
gen.printer.html += legalnotice;
gen.printer.html += "</div>";
}
}
void write_file(
html_state& state,
std::string const& generic_path,
std::string const& content)
{
fs::path path = state.options.home_path.parent_path() /
generic_to_path(generic_path);
std::string html = content;
if (state.options.pretty_print) {
try {
html = post_process(html, -1, -1, true);
} catch (quickbook::post_process_failure&) {
::quickbook::detail::outerr(path)
<< "Post Processing Failed." << std::endl;
++state.error_count;
}
}
fs::path parent = path.parent_path();
if (state.options.chunked_output && !parent.empty() &&
!fs::exists(parent)) {
fs::create_directories(parent);
}
fs::ofstream fileout(path);
if (fileout.fail()) {
::quickbook::detail::outerr(path)
<< "Error opening output file" << std::endl;
++state.error_count;
return;
}
fileout << html;
if (fileout.fail()) {
::quickbook::detail::outerr(path)
<< "Error writing to output file" << std::endl;
++state.error_count;
return;
}
}
std::string get_link_from_path(
html_gen& gen,
quickbook::string_view link,
quickbook::string_view path)
{
if (boost::starts_with(link, "boost:")) {
// TODO: Parameterize the boost location, so that it can use
// relative paths.
string_iterator it = link.begin() + strlen("boost:");
if (*it == '/') {
++it;
}
if (!gen.state.options.boost_root_path) {
std::string result =
"http://www.boost.org/doc/libs/release/";
result.append(it, link.end());
return result;
}
else {
return relative_path_or_url(
gen,
gen.state.options.boost_root_path /
string_view(it, link.end() - it));
}
}
return relative_path_from_url_paths(link, path);
}
std::string relative_path_or_url(html_gen& gen, path_or_url const& x)
{
assert(x);
if (x.is_url()) {
return x.get_url();
}
else {
return relative_path_from_fs_paths(
x.get_path(),
gen.state.options.home_path.parent_path() /
gen.path.to_s());
}
}
// Note: assume that base is a file, not a directory.
std::string relative_path_from_fs_paths(
fs::path const& p, fs::path const& base)
{
return path_to_generic(path_difference(base.parent_path(), p));
}
std::string relative_path_from_url_paths(
quickbook::string_view path, quickbook::string_view base)
{
string_iterator path_it = path.begin();
string_iterator base_it = base.begin();
string_iterator path_diff_start = path_it;
string_iterator base_diff_start = base_it;
for (; path_it != path.end() && base_it != base.end() &&
*path_it == *base_it;
++path_it, ++base_it) {
if (*path_it == '/') {
path_diff_start = path_it + 1;
base_diff_start = base_it + 1;
}
else if (*path_it == '#') {
return std::string(path_it, path.end());
}
}
if (base_it == base.end() && path_it != path.end() &&
*path_it == '#') {
return std::string(path_it, path.end());
}
if (path_it == path.end() &&
(base_it == base.end() || *base_it == '#')) {
return std::string("#");
}
auto up_count = std::count(
base_diff_start, std::find(base_it, base.end(), '#'), '/');
std::string result;
for (int i = 0; i < up_count; ++i) {
result += "../";
}
result.append(path_diff_start, path.end());
return result;
}
// get_id_paths
ids_type get_id_paths(chunk* chunk)
{
ids_type ids;
if (chunk) {
get_id_paths_impl(ids, chunk);
}
return ids;
}
void get_id_paths_impl(ids_type& ids, chunk* c)
{
std::string p = c->path_;
if (c->inline_) {
p += '#';
p += c->id_;
}
ids.emplace(c->id_, id_info(c, 0));
get_id_paths_impl2(ids, c, c->title_.root());
get_id_paths_impl2(ids, c, c->info_.root());
get_id_paths_impl2(ids, c, c->contents_.root());
for (chunk* i = c->children(); i; i = i->next()) {
get_id_paths_impl(ids, i);
}
}
void get_id_paths_impl2(ids_type& ids, chunk* c, xml_element* node)
{
if (!node) {
return;
}
if (node->has_attribute("id")) {
ids.emplace(node->get_attribute("id"), id_info(c, node));
}
for (xml_element* i = node->children(); i; i = i->next()) {
get_id_paths_impl2(ids, c, i);
}
}
void tag(html_gen& gen, quickbook::string_view name, xml_element* x)
{
open_tag_with_id(gen, name, x);
generate_children_html(gen, x);
close_tag(gen.printer, name);
}
void open_tag_with_id(
html_gen& gen, quickbook::string_view name, xml_element* x)
{
tag_start_with_id(gen, name, x);
tag_end(gen.printer);
}
void tag_self_close(
html_gen& gen, quickbook::string_view name, xml_element* x)
{
tag_start_with_id(gen, name, x);
tag_end_self_close(gen.printer);
}
void graphics_tag(
html_gen& gen,
quickbook::string_view path,
quickbook::string_view fallback)
{
if (gen.state.options.graphics_path) {
tag_start(gen.printer, "img");
tag_attribute(
gen.printer, "src",
relative_path_or_url(
gen, gen.state.options.graphics_path / path));
tag_attribute(gen.printer, "alt", fallback);
tag_end(gen.printer);
}
else {
gen.printer.html.append(fallback.begin(), fallback.end());
}
}
void tag_start_with_id(
html_gen& gen, quickbook::string_view name, xml_element* x)
{
tag_start(gen.printer, name);
if (!gen.in_toc) {
if (x->has_attribute("id")) {
tag_attribute(gen.printer, "id", x->get_attribute("id"));
}
}
}
// Handle boostbook nodes
#define NODE_RULE(tag_name, gen, x) \
void BOOST_PP_CAT(parser_, tag_name)(html_gen&, xml_element*); \
static struct BOOST_PP_CAT(register_parser_type_, tag_name) \
{ \
BOOST_PP_CAT(register_parser_type_, tag_name)() \
{ \
node_parsers.emplace( \
BOOST_PP_STRINGIZE(tag_name), \
&BOOST_PP_CAT(parser_, tag_name)); \
} \
} BOOST_PP_CAT(register_parser_, tag_name); \
void BOOST_PP_CAT(parser_, tag_name)(html_gen & gen, xml_element * x)
#define DOCINFO_NODE_RULE(tag_name, category, gen, x) \
void BOOST_PP_CAT(docinfo_parser_, tag_name)(docinfo_gen&, xml_element*); \
static struct BOOST_PP_CAT(register_docinfo_parser_type_, tag_name) \
{ \
BOOST_PP_CAT(register_docinfo_parser_type_, tag_name)() \
{ \
docinfo_node_parser p = { \
docinfo_node_parser::category, \
&BOOST_PP_CAT(docinfo_parser_, tag_name)}; \
docinfo_node_parsers.emplace(BOOST_PP_STRINGIZE(tag_name), p); \
} \
} BOOST_PP_CAT(register_docinfo_parser_, tag_name); \
void BOOST_PP_CAT(docinfo_parser_, tag_name)( \
docinfo_gen & gen, xml_element * x)
#define NODE_MAP(tag_name, html_name) \
NODE_RULE(tag_name, gen, x) { tag(gen, BOOST_PP_STRINGIZE(html_name), x); }
#define NODE_MAP_CLASS(tag_name, html_name, class_name) \
NODE_RULE(tag_name, gen, x) \
{ \
tag_start_with_id(gen, BOOST_PP_STRINGIZE(html_name), x); \
tag_attribute(gen.printer, "class", BOOST_PP_STRINGIZE(class_name)); \
tag_end(gen.printer); \
generate_children_html(gen, x); \
close_tag(gen.printer, BOOST_PP_STRINGIZE(html_name)); \
}
// TODO: For some reason 'hr' generates an empty paragraph?
NODE_MAP(simpara, div)
NODE_MAP(orderedlist, ol)
NODE_MAP(itemizedlist, ul)
NODE_MAP(listitem, li)
NODE_MAP(blockquote, blockquote)
NODE_MAP(quote, q)
NODE_MAP(code, code)
NODE_MAP(macronname, code)
NODE_MAP(classname, code)
NODE_MAP_CLASS(programlisting, pre, programlisting)
NODE_MAP(literal, tt)
NODE_MAP(subscript, sub)
NODE_MAP(superscript, sup)
NODE_MAP(section, div)
NODE_MAP(anchor, span)
NODE_MAP(title, h3)
NODE_MAP_CLASS(warning, div, warning)
NODE_MAP_CLASS(caution, div, caution)
NODE_MAP_CLASS(important, div, important)
NODE_MAP_CLASS(note, div, note)
NODE_MAP_CLASS(tip, div, tip)
NODE_MAP_CLASS(replaceable, em, replaceable)
NODE_RULE(sidebar, gen, x)
{
auto role = x->get_attribute("role");
tag_start_with_id(gen, "div", x);
if (role == "blurb") {
tag_attribute(gen.printer, "class", "blurb");
}
else {
tag_attribute(gen.printer, "class", "sidebar");
}
tag_end(gen.printer);
generate_children_html(gen, x);
close_tag(gen.printer, "div");
}
NODE_RULE(sbr, gen, x)
{
if (!x->children()) {
tag_self_close(gen, "br", x);
}
else {
tag(gen, "br", x);
}
}
NODE_RULE(bridgehead, gen, x)
{
auto renderas = x->get_attribute("renderas");
char header[3] = "h3";
if (renderas.size() == 5 && boost::starts_with(renderas, "sect")) {
char l = renderas[4];
if (l >= '1' && l <= '6') {
header[1] = l;
}
}
return tag(gen, header, x);
}
NODE_RULE(ulink, gen, x)
{
tag_start_with_id(gen, "a", x);
// TODO: error if missing?
if (x->has_attribute("url")) {
tag_attribute(
gen.printer, "href",
get_link_from_path(gen, x->get_attribute("url"), gen.path));
}
tag_end(gen.printer);
generate_children_html(gen, x);
close_tag(gen.printer, "a");
}
NODE_RULE(link, gen, x)
{
// TODO: error if missing or not found?
auto it = gen.state.ids.end();
if (x->has_attribute("linkend")) {
it = gen.state.ids.find(x->get_attribute("linkend"));
if (it == gen.state.ids.end()) {
fs::path docbook("(generated docbook)");
detail::outwarn(docbook)
<< "link not found: " << x->get_attribute("linkend")
<< std::endl;
}
}
tag_start_with_id(gen, "a", x);
if (it != gen.state.ids.end()) {
tag_attribute(
gen.printer, "href",
relative_path_from_url_paths(it->second.path(), gen.path));
}
tag_end(gen.printer);
generate_children_html(gen, x);
close_tag(gen.printer, "a");
}
NODE_RULE(phrase, gen, x)
{
auto role = x->get_attribute("role");
tag_start_with_id(gen, "span", x);
if (!role.empty()) {
tag_attribute(gen.printer, "class", role);
}
tag_end(gen.printer);
generate_children_html(gen, x);
close_tag(gen.printer, "span");
}
NODE_RULE(para, gen, x)
{
auto role = x->get_attribute("role");
tag_start_with_id(gen, "p", x);
if (!role.empty()) {
tag_attribute(gen.printer, "class", role);
}
tag_end(gen.printer);
generate_children_html(gen, x);
close_tag(gen.printer, "p");
}
NODE_RULE(emphasis, gen, x)
{
auto role = x->get_attribute("role");
quickbook::string_view tag_name;
quickbook::string_view class_name;
if (role.empty()) {
tag_name = "em";
class_name = "emphasis";
}
else if (role == "bold" || role == "strong") {
tag_name = "strong";
class_name = role;
}
else {
class_name = role;
}
tag_start_with_id(gen, "span", x);
if (!class_name.empty()) {
tag_attribute(gen.printer, "class", class_name);
}
tag_end(gen.printer);
if (!tag_name.empty()) {
open_tag(gen.printer, tag_name);
generate_children_html(gen, x);
close_tag(gen.printer, tag_name);
}
else {
generate_children_html(gen, x);
}
close_tag(gen.printer, "span");
}
NODE_RULE(inlinemediaobject, gen, x)
{
bool has_image = false;
string_view image;
// Get image link
for (xml_element* i = x->children(); i; i = i->next()) {
if (i->type_ == xml_element::element_node &&
i->name_ == "imageobject") {
for (xml_element* j = i->children(); j; j = j->next()) {
if (j->type_ == xml_element::element_node &&
j->name_ == "imagedata") {
if (j->has_attribute("fileref")) {
has_image = true;
image = j->get_attribute("fileref");
break;
}
}
}
}
}
std::string alt;
for (xml_element* i = x->children(); i; i = i->next()) {
if (i->type_ == xml_element::element_node &&
i->name_ == "textobject") {
for (xml_element* j = i->children(); j; j = j->next()) {
if (j->type_ == xml_element::element_node &&
j->name_ == "phrase") {
if (j->get_attribute("role") == "alt") {
html_gen gen2(gen);
generate_tree_html(gen2, j);
alt = gen2.printer.html;
}
}
}
}
}
// TODO: This was in the original php code, not sure why.
if (alt.empty()) {
alt = "[]";
}
if (has_image) {
tag_start(gen.printer, "span");
tag_attribute(gen.printer, "class", "inlinemediaobject");
tag_end(gen.printer);
tag_start_with_id(gen, "img", x);
tag_attribute(
gen.printer, "src",
get_link_from_path(gen, image, gen.path));
tag_attribute(gen.printer, "alt", alt);
tag_end_self_close(gen.printer);
close_tag(gen.printer, "span");
}
}
NODE_RULE(variablelist, gen, x)
{
typedef std::vector<std::pair<xml_element*, xml_element*> >
items_type;
items_type items;
for (xml_element* i = x->children(); i; i = i->next()) {
if (i && i->type_ == xml_element::element_node) {
if (i->name_ == "title") {
// TODO: What to do with titles?
continue;
}
else if (i->name_ == "varlistentry") {
// TODO: What if i has an id?
xml_element* term = 0;
xml_element* listitem = 0;
for (xml_element* j = i->children(); j; j = j->next()) {
if (j && j->type_ == xml_element::element_node) {
if (j->name_ == "term") {
term = j;
}
else if (j->name_ == "listitem") {
listitem = j;
}
}
}
if (term && listitem) {
items.push_back(std::make_pair(term, listitem));
}
}
}
}
if (!items.empty()) {
open_tag_with_id(gen, "dl", x);
for (items_type::iterator i = items.begin(); i != items.end();
++i) {
tag(gen, "dt", i->first);
tag(gen, "dd", i->second);
}
close_tag(gen.printer, "dl");
}
}
void write_table_rows(html_gen& gen, xml_element* x, char const* td_tag)
{
for (xml_element* i = x->children(); i; i = i->next()) {
if (i->type_ == xml_element::element_node &&
i->name_ == "row") {
open_tag_with_id(gen, "tr", i);
for (xml_element* j = i->children(); j; j = j->next()) {
if (j->type_ == xml_element::element_node &&
j->name_ == "entry") {
auto role = x->get_attribute("role");
tag_start_with_id(gen, td_tag, j);
if (!role.empty()) {
tag_attribute(gen.printer, "class", role);
}
tag_end(gen.printer);
generate_children_html(gen, j);
close_tag(gen.printer, td_tag);
}
}
close_tag(gen.printer, "tr");
}
}
}
void write_table(html_gen& gen, xml_element* x)
{
xml_element* title = 0;
xml_element* tgroup = 0;
xml_element* thead = 0;
xml_element* tbody = 0;
for (xml_element* i = x->children(); i; i = i->next()) {
if (i->type_ == xml_element::element_node &&
i->name_ == "title") {
title = i;
}
if (i->type_ == xml_element::element_node &&
i->name_ == "tgroup") {
tgroup = i;
}
}
if (!tgroup) {
return;
}
for (xml_element* i = tgroup->children(); i; i = i->next()) {
if (i->type_ == xml_element::element_node &&
i->name_ == "thead") {
thead = i;
}
if (i->type_ == xml_element::element_node &&
i->name_ == "tbody") {
tbody = i;
}
}
tag_start_with_id(gen, "div", x);
tag_attribute(gen.printer, "class", x->name_);
tag_end(gen.printer);
open_tag(gen.printer, "table");
if (title) {
tag(gen, "caption", title);
}
if (thead) {
open_tag(gen.printer, "thead");
write_table_rows(gen, thead, "th");
close_tag(gen.printer, "thead");
}
if (tbody) {
open_tag(gen.printer, "tbody");
write_table_rows(gen, tbody, "td");
close_tag(gen.printer, "tbody");
}
close_tag(gen.printer, "table");
close_tag(gen.printer, "div");
}
NODE_RULE(table, gen, x) { write_table(gen, x); }
NODE_RULE(informaltable, gen, x) { write_table(gen, x); }
NODE_MAP(calloutlist, div)
NODE_RULE(callout, gen, x)
{
boost::unordered_map<string_view, callout_data>::const_iterator
data = gen.chunk.callout_numbers.end();
auto link = gen.state.ids.end();
if (x->has_attribute("id")) {
data = gen.chunk.callout_numbers.find(x->get_attribute("id"));
}
if (data != gen.chunk.callout_numbers.end() &&
!data->second.link_id.empty()) {
link = gen.state.ids.find(data->second.link_id);
}
open_tag_with_id(gen, "div", x);
if (link != gen.state.ids.end()) {
tag_start(gen.printer, "a");
tag_attribute(
gen.printer, "href", relative_path_from_url_paths(
link->second.path(), gen.path));
tag_end(gen.printer);
}
graphics_tag(
gen,
"/callouts/" +
boost::lexical_cast<std::string>(data->second.number) +
".png",
"(" + boost::lexical_cast<std::string>(data->second.number) +
")");
if (link != gen.state.ids.end()) {
close_tag(gen.printer, "a");
}
gen.printer.html += " ";
generate_children_html(gen, x);
close_tag(gen.printer, "div");
}
NODE_RULE(co, gen, x)
{
boost::unordered_map<string_view, callout_data>::const_iterator
data = gen.chunk.callout_numbers.end();
auto link = gen.state.ids.end();
if (x->has_attribute("linkends")) {
auto linkends = x->get_attribute("linkends");
data = gen.chunk.callout_numbers.find(linkends);
link = gen.state.ids.find(linkends);
}
if (link != gen.state.ids.end()) {
tag_start(gen.printer, "a");
tag_attribute(
gen.printer, "href", relative_path_from_url_paths(
link->second.path(), gen.path));
tag_end(gen.printer);
}
if (data != gen.chunk.callout_numbers.end()) {
graphics_tag(
gen,
"/callouts/" +
boost::lexical_cast<std::string>(data->second.number) +
".png",
"(" +
boost::lexical_cast<std::string>(data->second.number) +
")");
}
else {
gen.printer.html += "(0)";
}
if (link != gen.state.ids.end()) {
close_tag(gen.printer, "a");
}
}
NODE_RULE(footnote, gen, x)
{
// TODO: Better id generation....
static int footnote_number = 0;
++footnote_number;
std::string footnote_label =
boost::lexical_cast<std::string>(footnote_number);
auto footnote_id =
generate_id(gen.chunk, x, "(((footnote-id)))", "footnote");
if (!x->has_attribute("id")) {
generate_id(gen.chunk, x, "id", "footnote");
}
tag_start_with_id(gen, "a", x);
std::string href = "#";
href += footnote_id;
tag_attribute(gen.printer, "href", href);
tag_end(gen.printer);
tag_start(gen.printer, "sup");
tag_attribute(gen.printer, "class", "footnote");
tag_end(gen.printer);
gen.printer.html += "[" + footnote_label + "]";
close_tag(gen.printer, "sup");
close_tag(gen.printer, "a");
// Generate HTML to add to footnote.
html_printer printer;
tag_start(printer, "a");
std::string href2 = "#";
href2 += x->get_attribute("id");
tag_attribute(printer, "href", href2);
tag_end(printer);
tag_start(printer, "sup");
tag_end(printer);
printer.html += "[" + footnote_label + "]";
close_tag(printer, "sup");
close_tag(printer, "a");
printer.html += ' ';
xml_tree_builder builder;
builder.add_element(xml_element::html_node(printer.html));
// Find position to insert.
auto pos = x->children();
for (; pos && pos->type_ == xml_element::element_text;
pos = pos->next()) {
if (pos->contents_.find_first_not_of("\t\n ") !=
std::string::npos) {
break;
}
}
if (!pos) {
x->add_first_child(builder.release());
}
else
switch (pos->type_) {
case xml_element::element_node:
// TODO: Check type of node? Recurse?
pos->add_first_child(builder.release());
break;
default:
pos->add_before(builder.release());
break;
}
gen.chunk.footnotes.push_back(x);
}
std::string docinfo_get_contents(docinfo_gen& d, xml_element* x)
{
html_gen gen2(d.gen);
generate_children_html(gen2, x);
return gen2.printer.html;
}
std::string docinfo_get_author(docinfo_gen& d, xml_element* x)
{
auto personname = x->get_child("personname");
if (personname) {
return docinfo_get_author(d, personname);
}
std::string name;
char const* name_parts[] = {"honorific", "firstname", "surname"};
std::size_t const length =
sizeof(name_parts) / sizeof(name_parts[0]);
for (std::size_t i = 0; i < length; ++i) {
auto child = x->get_child(name_parts[i]);
if (child) {
if (name.size()) {
name += " ";
}
name += docinfo_get_contents(d, child);
}
}
return name;
}
// docinfo parsers
// No support for:
//
// graphic, mediaobject
// modespec
// subjectset, keywordset
// itermset, indexterm
// abbrev
// abstract
// address
// artpagenums
// authorinitials
// bibliomisc, biblioset
// confgroup
// contractnum, contractsponsor
// corpname
// date
// edition
// invpartnumber, isbn, issn, issuenum, biblioid
// orgname
// citebiblioid, citetitle
// bibliosource, bibliorelation, bibliocoverage - Dublin core
// pagenums
// printhistory
// productname, productnumber
// pubdate ***
// publisher, publishername, pubsnumber
// releaseinfo
// revhistory
// seriesvolnums
// title, subtitle, titleabbrev - *** extract into parent?
// volumenum
// personname, honorific, firstname, surname, lineage, othername,
// affiliation, authorblurb, contrib - add to authors?
DOCINFO_NODE_RULE(copyright, docinfo_general, d, x)
{
std::vector<xml_element*> years;
std::vector<xml_element*> holders;
for (auto child = x->children(); child; child = child->next()) {
if (child->type_ == xml_element::element_node) {
if (child->name_ == "year") {
years.push_back(child);
}
else if (child->name_ == "holder") {
holders.push_back(child);
}
else {
quickbook::detail::out()
<< "Unsupported copyright tag: " << x->name_
<< std::endl;
}
}
}
// TODO: Format years, e.g. 2005 2006 2007 2010 => 2005-2007, 2010
std::string copyright;
QUICKBOOK_FOR (auto year, years) {
if (!copyright.empty()) {
copyright += ", ";
}
copyright += docinfo_get_contents(d, year);
}
bool first = true;
QUICKBOOK_FOR (auto holder, holders) {
if (first) {
if (!copyright.empty()) {
copyright += " ";
}
first = false;
}
else {
copyright += ", ";
}
copyright += docinfo_get_contents(d, holder);
}
d.copyrights.push_back(copyright);
}
DOCINFO_NODE_RULE(legalnotice, docinfo_general, d, x)
{
d.legalnotices.push_back(docinfo_get_contents(d, x));
}
DOCINFO_NODE_RULE(pubdate, docinfo_general, d, x)
{
d.pubdates.push_back(docinfo_get_contents(d, x));
}
DOCINFO_NODE_RULE(authorgroup, docinfo_general, d, x)
{
// TODO: Check children are docinfo_author
generate_docinfo_html_impl(d, x);
}
DOCINFO_NODE_RULE(author, docinfo_author, d, x)
{
d.authors.push_back(docinfo_get_author(d, x));
}
DOCINFO_NODE_RULE(editor, docinfo_author, d, x)
{
d.editors.push_back(docinfo_get_author(d, x));
}
DOCINFO_NODE_RULE(collab, docinfo_author, d, x)
{
// Ignoring affiliation.
auto collabname = x->get_child("collabname");
if (collabname) {
d.collabs.push_back(docinfo_get_contents(d, collabname));
}
}
DOCINFO_NODE_RULE(corpauthor, docinfo_author, d, x)
{
d.authors.push_back(docinfo_get_contents(d, x));
}
DOCINFO_NODE_RULE(corpcredit, docinfo_author, d, x)
{
std::string text = docinfo_get_contents(d, x);
string_view class_ = x->get_attribute("class");
if (!class_.empty()) {
text = class_.to_s() + ": " + text;
}
d.authors.push_back(text);
}
DOCINFO_NODE_RULE(othercredit, docinfo_author, d, x)
{
std::string text = docinfo_get_author(d, x);
string_view class_ = x->get_attribute("class");
if (!class_.empty()) {
text = class_.to_s() + ": " + text;
}
d.authors.push_back(text);
}
}
}
| 36.279656 | 80 | 0.448252 | [
"vector"
] |
44ca6864db48e42199ad963540dc9ee4fa14b2c4 | 1,533 | cc | C++ | Boss2D/addon/_old/webrtc-qt5.11.2_for_boss/rtc_base/openssladapter_unittest.cc | Yash-Wasalwar-07/Boss2D | 37c5ba0f1c83c89810359a207cabfa0905f803d2 | [
"MIT"
] | null | null | null | Boss2D/addon/_old/webrtc-qt5.11.2_for_boss/rtc_base/openssladapter_unittest.cc | Yash-Wasalwar-07/Boss2D | 37c5ba0f1c83c89810359a207cabfa0905f803d2 | [
"MIT"
] | null | null | null | Boss2D/addon/_old/webrtc-qt5.11.2_for_boss/rtc_base/openssladapter_unittest.cc | Yash-Wasalwar-07/Boss2D | 37c5ba0f1c83c89810359a207cabfa0905f803d2 | [
"MIT"
] | null | null | null | /*
* Copyright 2017 The WebRTC Project Authors. All rights reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include <sstream>
#include <string>
#include <vector>
#include BOSS_WEBRTC_U_rtc_base__gunit_h //original-code:"rtc_base/gunit.h"
#include BOSS_WEBRTC_U_rtc_base__openssladapter_h //original-code:"rtc_base/openssladapter.h"
namespace rtc {
TEST(OpenSSLAdapterTest, TestTransformAlpnProtocols) {
EXPECT_EQ("", TransformAlpnProtocols(std::vector<std::string>()));
// Protocols larger than 255 characters (whose size can't be fit in a byte),
// can't be converted, and an empty string will be returned.
std::string large_protocol(256, 'a');
EXPECT_EQ("",
TransformAlpnProtocols(std::vector<std::string>{large_protocol}));
// One protocol test.
std::vector<std::string> alpn_protos{"h2"};
std::stringstream expected_response;
expected_response << static_cast<char>(2) << "h2";
EXPECT_EQ(expected_response.str(), TransformAlpnProtocols(alpn_protos));
// Standard protocols test (h2,http/1.1).
alpn_protos.push_back("http/1.1");
expected_response << static_cast<char>(8) << "http/1.1";
EXPECT_EQ(expected_response.str(), TransformAlpnProtocols(alpn_protos));
}
} // namespace rtc
| 36.5 | 93 | 0.738421 | [
"vector"
] |
44ccf04149ba64daa383ebcb02cbd494c8707c35 | 7,843 | cpp | C++ | src/shader.cpp | CommitteeOfZero/impacto | 87e0aa27d59d8f350849dfb20048679b2a3db1e3 | [
"0BSD"
] | 45 | 2020-02-01T19:10:13.000Z | 2022-03-11T01:45:52.000Z | src/shader.cpp | Enorovan/impacto | 807c5247dca2720e3e1205fca4724ad1fafb1ab4 | [
"0BSD"
] | 7 | 2020-01-26T17:30:00.000Z | 2021-09-26T10:00:46.000Z | src/shader.cpp | Enorovan/impacto | 807c5247dca2720e3e1205fca4724ad1fafb1ab4 | [
"0BSD"
] | 11 | 2020-02-01T23:01:50.000Z | 2021-12-15T14:39:27.000Z | #include <algorithm>
#include "shader.h"
#include "impacto.h"
#include "io/io.h"
#include "log.h"
#include "3d/model.h"
#include "util.h"
#include "window.h"
namespace Impacto {
static char const ShaderPath[] = "./shaders";
static char const FragShaderExtension[] = "_frag.glsl";
static char const VertShaderExtension[] = "_vert.glsl";
// We need highp in vertex shaders, but uniforms shared between vertex and
// fragment shaders need to have the same precision in both
static char const ShaderHeader[] =
"#version 330\n#define UNIFORM_PRECISION highp\n\n";
static GLint const ShaderHeaderLength =
sizeof(ShaderHeader) - 1; // without null terminator, for glShaderSource()
static char const ShaderHeaderES[] =
"#version 300 es\n#define UNIFORM_PRECISION mediump\n\n";
static GLint const ShaderHeaderESLength = sizeof(ShaderHeaderES) - 1;
static char const ShaderHeaderVert[] =
"#define VERTEX_SHADER\n#ifdef GL_ES\nprecision highp float;\n#endif\n\n";
static GLint const ShaderHeaderVertLength = sizeof(ShaderHeaderVert) - 1;
static char const ShaderHeaderFrag[] =
"#define FRAGMENT_SHADER\n#ifdef GL_ES\nprecision mediump "
"float;\n#endif\n\n";
static GLint const ShaderHeaderFragLength = sizeof(ShaderHeaderFrag) - 1;
int PrintParameter(char* dest, int destSz, char const* name,
ShaderParameter const& param) {
switch (param.Type) {
case SPT_Float:
return snprintf(dest, destSz, "const float %s = %f;\n", name,
param.Val_Float);
break;
case SPT_Int:
return snprintf(dest, destSz, "const int %s = %d;\n", name,
param.Val_Int);
break;
case SPT_MacroFloat:
return snprintf(dest, destSz, "#define %s %f\n", name, param.Val_Float);
break;
case SPT_MacroInt:
return snprintf(dest, destSz, "#define %s %d\n", name, param.Val_Int);
break;
case SPT_Vec2:
return snprintf(dest, destSz, "const vec2 %s = vec2(%f, %f);\n", name,
param.Val_Vec2.x, param.Val_Vec2.y);
break;
case SPT_Vec3:
return snprintf(dest, destSz, "const vec3 %s = vec3(%f, %f, %f);\n", name,
param.Val_Vec3.x, param.Val_Vec3.y, param.Val_Vec3.z);
break;
case SPT_Vec4:
return snprintf(dest, destSz, "const vec4 %s = vec4(%f, %f, %f, %f);\n",
name, param.Val_Vec4.x, param.Val_Vec4.y,
param.Val_Vec4.z, param.Val_Vec4.w);
break;
case SPT_Ivec2:
return snprintf(dest, destSz, "const ivec2 %s = ivec2(%d, %d);\n", name,
param.Val_Ivec2.x, param.Val_Ivec2.y);
break;
case SPT_Ivec3:
return snprintf(dest, destSz, "const ivec3 %s = ivec3(%d, %d, %d);\n",
name, param.Val_Ivec3.x, param.Val_Ivec3.y,
param.Val_Ivec3.z);
break;
case SPT_Ivec4:
return snprintf(dest, destSz, "const ivec4 %s = ivec4(%d, %d, %d, %d);\n",
name, param.Val_Ivec4.x, param.Val_Ivec4.y,
param.Val_Ivec4.z, param.Val_Ivec4.w);
break;
default:
ImpLog(LL_Error, LC_Render, "Invalid shader parameter type %d\n",
param.Type);
if (destSz > 0) *dest = '\0';
return 0;
}
}
GLuint ShaderAttach(GLuint program, GLenum shaderType, char const* path,
char const* params) {
ImpLog(LL_Debug, LC_Render, "Loading shader object (type %d) \"%s\"\n",
shaderType, path);
size_t sourceRawSz;
char* source = (char*)SDL_LoadFile(path, &sourceRawSz);
if (!source) {
ImpLog(LL_Debug, LC_Render, "Failed to read shader source file\n");
return 0;
}
GLuint shader = glCreateShader(shaderType);
if (!shader) {
ImpLog(LL_Fatal, LC_Render, "Failed to create shader object\n");
SDL_free(source);
return 0;
}
const GLchar* codeParts[4];
codeParts[0] = (Window::ActualGraphicsApi != Window::GfxApi_GL)
? ShaderHeaderES
: ShaderHeader;
codeParts[1] =
shaderType == GL_VERTEX_SHADER ? ShaderHeaderVert : ShaderHeaderFrag;
codeParts[2] = params;
codeParts[3] = source;
GLint codeLengths[4];
codeLengths[0] = (Window::ActualGraphicsApi != Window::GfxApi_GL)
? ShaderHeaderESLength
: ShaderHeaderLength;
codeLengths[1] = shaderType == GL_VERTEX_SHADER ? ShaderHeaderVertLength
: ShaderHeaderFragLength;
codeLengths[2] = strlen(params);
codeLengths[3] = strlen(source);
glShaderSource(shader, 4, codeParts, codeLengths);
GLint result = 0;
static GLchar errorLog[1024] = {0};
glCompileShader(shader);
glGetShaderiv(shader, GL_COMPILE_STATUS, &result);
if (!result) {
glGetShaderInfoLog(shader, sizeof(errorLog), NULL, errorLog);
ImpLog(LL_Fatal, LC_Render, "Error compiling shader: %s\n", errorLog);
SDL_free(source);
glDeleteShader(shader);
return 0;
}
glAttachShader(program, shader);
SDL_free(source);
return shader;
}
GLuint ShaderCompile(char const* name, ShaderParamMap const& params) {
GLuint program = glCreateProgram();
if (!program) {
ImpLog(LL_Fatal, LC_Render, "Could not create shader program\n");
return program;
}
ImpLog(LL_Debug, LC_Render, "Compiling shader \"%s\"\n", name);
size_t pathSz =
std::max(
snprintf(NULL, 0, "%s/%s%s", ShaderPath, name, FragShaderExtension),
snprintf(NULL, 0, "%s/%s%s", ShaderPath, name, VertShaderExtension)) +
1;
char* fullPath = (char*)ImpStackAlloc(pathSz);
int paramSz = 1;
for (auto const& param : params) {
paramSz += PrintParameter(0, 0, param.first.c_str(), param.second);
}
char* paramStr = (char*)ImpStackAlloc(paramSz);
char* paramWrite = paramStr;
int bytesLeft = paramSz;
for (auto const& param : params) {
int thisParamSz = PrintParameter(paramWrite, bytesLeft, param.first.c_str(),
param.second);
bytesLeft -= thisParamSz;
paramWrite += thisParamSz;
}
paramStr[paramSz - 1] = '\0';
sprintf(fullPath, "%s/%s%s", ShaderPath, name, VertShaderExtension);
GLuint vs = ShaderAttach(program, GL_VERTEX_SHADER, fullPath, paramStr);
if (!vs) {
glDeleteProgram(program);
ImpStackFree(paramStr);
ImpStackFree(fullPath);
return 0;
}
sprintf(fullPath, "%s/%s%s", ShaderPath, name, FragShaderExtension);
GLuint fs = ShaderAttach(program, GL_FRAGMENT_SHADER, fullPath, paramStr);
if (!fs) {
static GLchar errorLog[1024] = {};
glGetProgramInfoLog(program, sizeof(errorLog), NULL, errorLog);
ImpLog(LL_Fatal, LC_Render, "Error linking shader program: %s\n", errorLog);
glDeleteShader(vs);
glDeleteProgram(program);
ImpStackFree(paramStr);
ImpStackFree(fullPath);
return 0;
}
ImpStackFree(paramStr);
ImpStackFree(fullPath);
GLint result = 0;
static GLchar errorLog[1024] = {};
glLinkProgram(program);
glDetachShader(program, vs);
glDetachShader(program, fs);
glDeleteShader(vs);
glDeleteShader(fs);
glGetProgramiv(program, GL_LINK_STATUS, &result);
if (!result) {
glGetProgramInfoLog(program, sizeof(errorLog), NULL, errorLog);
ImpLog(LL_Fatal, LC_Render, "Error linking shader program: %s\n", errorLog);
glDeleteProgram(program);
return 0;
}
// TODO: Figure out why this actually doesn't work on macOS
#ifndef __APPLE__
glValidateProgram(program);
glGetProgramiv(program, GL_VALIDATE_STATUS, &result);
if (!result) {
glGetProgramInfoLog(program, sizeof(errorLog), NULL, errorLog);
ImpLog(LL_Fatal, LC_Render, "Shader program failed to validate: %s\n",
errorLog);
glDeleteProgram(program);
return 0;
}
#endif
return program;
}
} // namespace Impacto | 32.409091 | 80 | 0.645926 | [
"object",
"model",
"3d"
] |
44d05950e2d325d2978b183753ad19624a5fe6d0 | 801 | cpp | C++ | TWMapper/TWMapper/Shape.cpp | zbeckerman/attac | ca07aeb7fbb14e2aea8d19aeb0b044bbc27721e7 | [
"Apache-2.0"
] | 1 | 2019-05-01T23:43:55.000Z | 2019-05-01T23:43:55.000Z | TWMapper/TWMapper/Shape.cpp | zbeckerman/attac | ca07aeb7fbb14e2aea8d19aeb0b044bbc27721e7 | [
"Apache-2.0"
] | null | null | null | TWMapper/TWMapper/Shape.cpp | zbeckerman/attac | ca07aeb7fbb14e2aea8d19aeb0b044bbc27721e7 | [
"Apache-2.0"
] | null | null | null | // Shape.cpp : implementation file
//
#include "stdafx.h"
#include "MouseSel.h"
#include "Shape.h"
#include "Sphere.h"
// CShape
//IMPLEMENT_SERIAL(CShape, CObject, 2)
CShape::CShape()
{
m_winx=0;
m_winz=0;
m_winy=0;
m_Select=FALSE;
m_visible=TRUE;
}
CShape::~CShape()
{
}
BOOL CShape::Intersects(CShape *s) {
if (this->IsKindOf(RUNTIME_CLASS(CSphere)) && s->IsKindOf(RUNTIME_CLASS(CSphere))) {
double x1 = this->m_xc;
double y1 = this->m_yc;
double z1 = this->m_zc;
double x2 = s->m_xc;
double y2 = s->m_yc;
double z2 = s->m_zc;
double distance = sqrt( ((x1-x2)*(x1-x2)) + ((y1-y2)*(y1-y2)) + ((z1-z2)*(z1-z2)) );
double radiusSum = ((CSphere*)this)->m_Radius + ((CSphere*)s)->m_Radius;
if (distance<radiusSum)
return 1;
else
return 0;
}
return 0;
}
| 16.346939 | 86 | 0.627965 | [
"shape"
] |
44d25c0e5ff327352614c25032cfe81d164296bd | 6,274 | cpp | C++ | src/qt/parkratevotedialog.cpp | CoinGame/NuShadowTestnet | 32ad6b407bea6490513790d15c2a2ed83f5917f3 | [
"MIT"
] | 2 | 2018-01-22T13:54:42.000Z | 2018-01-22T13:54:46.000Z | src/qt/parkratevotedialog.cpp | CoinGame/NuShadowTestnet | 32ad6b407bea6490513790d15c2a2ed83f5917f3 | [
"MIT"
] | null | null | null | src/qt/parkratevotedialog.cpp | CoinGame/NuShadowTestnet | 32ad6b407bea6490513790d15c2a2ed83f5917f3 | [
"MIT"
] | 1 | 2018-01-22T13:54:39.000Z | 2018-01-22T13:54:39.000Z | #include <QMessageBox>
#include "parkratevotedialog.h"
#include "ui_parkratevotedialog.h"
#include "walletmodel.h"
#include "vote.h"
#include "optionsmodel.h"
#include "bitcoinunits.h"
#include "guiutil.h"
using namespace std;
ParkRateVoteDialog::ParkRateVoteDialog(QWidget *parent) :
QDialog(parent),
ui(new Ui::ParkRateVoteDialog)
{
ui->setupUi(this);
setWindowTitle("Park rate vote");
}
ParkRateVoteDialog::~ParkRateVoteDialog()
{
delete ui;
}
class QCompactDurationTableWidgetItem : public QTableWidgetItem
{
public:
QCompactDurationTableWidgetItem(int compactDuration) :
QTableWidgetItem(compactDuration),
compactDuration(compactDuration)
{
}
QVariant data(int role = Qt::UserRole + 1) const
{
switch (role)
{
case Qt::EditRole:
return compactDuration;
case Qt::DisplayRole:
return GUIUtil::blocksToTime((qint64)1 << compactDuration);
default:
return QTableWidgetItem::data(role);
}
}
void setData(int role, const QVariant& value)
{
if (role == Qt::EditRole)
compactDuration = value.toInt();
else
QTableWidgetItem::setData(role, value);
}
int getCompactDuration() const
{
return compactDuration;
}
private:
int compactDuration;
};
void ParkRateVoteDialog::setModel(WalletModel *model)
{
this->model = model;
CVote vote = model->getVote();
CParkRateVote parkRateVote;
for (int i = 0; i < vote.vParkRateVote.size(); i++)
if (vote.vParkRateVote[i].cUnit == 'B')
{
parkRateVote = vote.vParkRateVote[i];
break;
}
const vector<CParkRate>& vParkRate = parkRateVote.vParkRate;
ui->table->setRowCount(vParkRate.size());
for (int i = 0; i < vParkRate.size(); i++)
{
const CParkRate& parkRate = vParkRate[i];
setDuration(i, parkRate.nCompactDuration);
setAnnualRatePercentage(i, GUIUtil::annualInterestRatePercentage(parkRate.nRate, parkRate.GetDuration()));
}
ui->table->setVisible(false);
ui->table->resizeColumnsToContents();
ui->table->setVisible(true);
}
double ParkRateVoteDialog::getAnnualRatePercentage(int row)
{
QTableWidgetItem *rateItem = ui->table->item(row, 1);
if (rateItem)
return rateItem->data(Qt::DisplayRole).toDouble();
else
return 0;
}
qint64 ParkRateVoteDialog::getRate(int row)
{
return GUIUtil::annualInterestRatePercentageToRate(getAnnualRatePercentage(row), getDuration(row));
}
qint64 ParkRateVoteDialog::getDuration(int row)
{
return (qint64)1 << getCompactDuration(row);
}
int ParkRateVoteDialog::getCompactDuration(int row)
{
QCompactDurationTableWidgetItem *durationItem = (QCompactDurationTableWidgetItem*)ui->table->item(row, 0);
if (!durationItem)
return 0;
return durationItem->getCompactDuration();
}
void ParkRateVoteDialog::on_table_cellChanged(int row, int column)
{
if (column == 1)
{
// Round to nearest possible annual interest rate
qint64 rate = getRate(row);
double interestRatePercentage = GUIUtil::annualInterestRatePercentage(rate, getDuration(row));
QTableWidgetItem *rateItem = ui->table->item(row, column);
rateItem->setData(Qt::DisplayRole, interestRatePercentage);
}
}
void ParkRateVoteDialog::setDuration(int row, qint64 duration)
{
QTableWidgetItem *durationItem = new QCompactDurationTableWidgetItem(duration);
durationItem->setData(Qt::TextAlignmentRole, QVariant(Qt::AlignRight | Qt::AlignVCenter));
durationItem->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled);
ui->table->setItem(row, 0, durationItem);
}
void ParkRateVoteDialog::setAnnualRatePercentage(int row, double rate)
{
QTableWidgetItem *rateItem = new QTableWidgetItem();
rateItem->setData(Qt::DisplayRole, QVariant(rate));
rateItem->setData(Qt::TextAlignmentRole, QVariant(Qt::AlignRight | Qt::AlignVCenter));
ui->table->setItem(row, 1, rateItem);
}
void ParkRateVoteDialog::on_addShorter_clicked()
{
int duration = 17;
double rate = 1.0;
if (ui->table->rowCount() > 0)
{
duration = getCompactDuration(0) - 1;
rate = getAnnualRatePercentage(0);
}
if (duration < 0)
return;
ui->table->insertRow(0);
setDuration(0, duration);
setAnnualRatePercentage(0, rate);
}
void ParkRateVoteDialog::on_addLonger_clicked()
{
int duration = 17;
double rate = 1.0;
int rowCount = ui->table->rowCount();
if (rowCount > 0)
{
duration = getCompactDuration(rowCount - 1) + 1;
rate = getAnnualRatePercentage(rowCount - 1);
}
if (duration <= 0 || duration >= 30)
return;
ui->table->setRowCount(rowCount + 1);
setDuration(rowCount, duration);
setAnnualRatePercentage(rowCount, rate);
}
void ParkRateVoteDialog::on_remove_clicked()
{
QItemSelection selection(ui->table->selectionModel()->selection());
QList<int> rows;
foreach(const QModelIndex& index, selection.indexes())
rows.append(index.row());
qSort(rows);
int prev = -1;
for (int i = rows.count() - 1; i >= 0; i -= 1)
{
int current = rows[i];
if (current != prev)
{
ui->table->removeRow(current);
prev = current;
}
}
}
void ParkRateVoteDialog::error(const QString& message)
{
QMessageBox::critical(this, tr("Error"), message);
}
void ParkRateVoteDialog::accept()
{
QTableWidget *table = ui->table;
int rows = table->rowCount();
CParkRateVote parkRateVote;
parkRateVote.cUnit = 'B';
vector<CParkRate>& vParkRate = parkRateVote.vParkRate;
for (int i = 0; i < rows; i++)
{
CParkRate parkRate;
parkRate.nCompactDuration = getCompactDuration(i);
parkRate.nRate = getRate(i);
vParkRate.push_back(parkRate);
}
CVote vote = model->getVote();
vote.vParkRateVote.clear();
vote.vParkRateVote.push_back(parkRateVote);
if (!vote.IsValid(model->getProtocolVersion()))
{
error(tr("The new vote is invalid"));
return;
}
model->setVote(vote);
QDialog::accept();
}
| 25.92562 | 114 | 0.653969 | [
"vector",
"model"
] |
44d81dad10a10eaf88e68b6f7cbae63685243bcc | 12,196 | cpp | C++ | Dev/Cpp/Effekseer/Effekseer/ForceField/ForceFields.cpp | softwarecapital/effekseer.Effekseer | e8d84a0ce317baa6f4405ad2939510ae5032568c | [
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null | Dev/Cpp/Effekseer/Effekseer/ForceField/ForceFields.cpp | softwarecapital/effekseer.Effekseer | e8d84a0ce317baa6f4405ad2939510ae5032568c | [
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null | Dev/Cpp/Effekseer/Effekseer/ForceField/ForceFields.cpp | softwarecapital/effekseer.Effekseer | e8d84a0ce317baa6f4405ad2939510ae5032568c | [
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null | #include "ForceFields.h"
#include "../Effekseer.Matrix44.h"
#include "../SIMD/Utils.h"
#include "../Utils/Effekseer.BinaryReader.h"
namespace Effekseer
{
ForceFieldTurbulenceParameter::ForceFieldTurbulenceParameter(ForceFieldTurbulenceType type, int32_t seed, float scale, float strength, int octave)
{
if (type == ForceFieldTurbulenceType::Simple)
{
LightNoise = std::make_unique<LightCurlNoise>(seed, scale, octave);
}
else if (type == ForceFieldTurbulenceType::Complicated)
{
Noise = std::make_unique<CurlNoise>(seed, scale, octave);
}
Power = strength;
}
bool LocalForceFieldElementParameter::Load(uint8_t*& pos, int32_t version)
{
auto br = BinaryReader<false>(pos, std::numeric_limits<int>::max());
LocalForceFieldType type{};
br.Read(type);
HasValue = true;
float power = 1.0f;
if (version >= 1600)
{
br.Read(power);
br.Read(Position.X);
br.Read(Position.Y);
br.Read(Position.Z);
Vector3D rotation;
br.Read(rotation.X);
br.Read(rotation.Y);
br.Read(rotation.Z);
IsRotated = rotation.X != 0.0f || rotation.Y != 0.0f || rotation.Z != 0.0f;
if (IsRotated)
{
Rotation = SIMD::Mat44f::RotationZXY(rotation.Z, rotation.X, rotation.Y);
Matrix44 invMat;
InvRotation = SIMD::Mat44f(Matrix44::Inverse(invMat, ToStruct(Rotation)));
}
}
if (type == LocalForceFieldType::Force)
{
int gravitation = 0;
br.Read(gravitation);
// convert it by frames
power /= 60.0f;
auto ff = new ForceFieldForceParameter();
ff->Power = power;
ff->Gravitation = gravitation > 0;
Force = std::unique_ptr<ForceFieldForceParameter>(ff);
}
else if (type == LocalForceFieldType::Wind)
{
// convert it by frames
power /= 60.0f;
auto ff = new ForceFieldWindParameter();
ff->Power = power;
Wind = std::unique_ptr<ForceFieldWindParameter>(ff);
}
else if (type == LocalForceFieldType::Vortex)
{
if (version < Version16Alpha2)
{
power /= 5.0f;
}
// convert it by frames
power /= 12.0f;
ForceFieldVortexType ftype{};
if (version < Version16Alpha2)
{
ftype = ForceFieldVortexType::ConstantSpeed;
}
else
{
br.Read(ftype);
}
auto ff = new ForceFieldVortexParameter();
ff->Power = power;
ff->Type = ftype;
Vortex = std::unique_ptr<ForceFieldVortexParameter>(ff);
}
else if (type == LocalForceFieldType::Turbulence)
{
ForceFieldTurbulenceType ftype{};
int32_t seed{};
float scale{};
float strength{};
int octave{};
if (version < Version16Alpha2)
{
ftype = ForceFieldTurbulenceType::Complicated;
}
else
{
br.Read(ftype);
}
br.Read(seed);
br.Read(scale);
if (version < Version16Alpha2)
{
br.Read(strength);
strength *= 10.0f;
}
else
{
strength = power;
}
br.Read(octave);
scale = 1.0f / scale;
strength /= 10.0f;
Turbulence = std::unique_ptr<ForceFieldTurbulenceParameter>(new ForceFieldTurbulenceParameter(ftype, seed, scale, strength, octave));
}
else if (type == LocalForceFieldType::Drag)
{
// convert it by frames
power /= 60.0f;
auto ff = new ForceFieldDragParameter();
ff->Power = power;
Drag = std::unique_ptr<ForceFieldDragParameter>(ff);
}
else if (type == LocalForceFieldType::Gravity)
{
std::array<float, 3> values;
br.Read(values);
SIMD::Vec3f gravity{values};
Gravity = std::make_unique<ForceFieldGravityParameter>();
Gravity->Gravity = gravity;
IsGlobal = true;
}
else if (type == LocalForceFieldType::AttractiveForce)
{
AttractiveForce = std::make_unique<ForceFieldAttractiveForceParameter>();
AttractiveForce->Force = power;
br.Read(AttractiveForce->Control);
br.Read(AttractiveForce->MinRange);
br.Read(AttractiveForce->MaxRange);
IsGlobal = true;
}
else
{
HasValue = false;
}
if (version >= 1600)
{
LocalForceFieldFalloffType ffType{};
br.Read(ffType);
if (ffType != LocalForceFieldFalloffType::None)
{
FalloffCommon = std::make_unique<ForceFieldFalloffCommonParameter>();
br.Read(FalloffCommon->Power);
br.Read(FalloffCommon->MaxDistance);
br.Read(FalloffCommon->MinDistance);
}
if (ffType == LocalForceFieldFalloffType::None)
{
}
else if (ffType == LocalForceFieldFalloffType::Sphere)
{
FalloffSphere = std::make_unique<ForceFieldFalloffSphereParameter>();
}
else if (ffType == LocalForceFieldFalloffType::Tube)
{
FalloffTube = std::make_unique<ForceFieldFalloffTubeParameter>();
br.Read(FalloffTube->RadiusPower);
br.Read(FalloffTube->MaxRadius);
br.Read(FalloffTube->MinRadius);
}
else if (ffType == LocalForceFieldFalloffType::Cone)
{
FalloffCone = std::make_unique<ForceFieldFalloffConeParameter>();
br.Read(FalloffCone->AnglePower);
br.Read(FalloffCone->MaxAngle);
br.Read(FalloffCone->MinAngle);
}
else
{
assert(0);
}
}
else
{
IsRotated = false;
}
pos += br.GetOffset();
return true;
}
bool LocalForceFieldParameter::Load(uint8_t*& pos, int32_t version)
{
int32_t count = 0;
memcpy(&count, pos, sizeof(int));
pos += sizeof(int);
for (int32_t i = 0; i < count; i++)
{
if (!LocalForceFields[i].Load(pos, version))
{
return false;
}
}
for (auto& ff : LocalForceFields)
{
if (ff.HasValue)
{
HasValue = true;
if (ff.Gravity != nullptr || ff.AttractiveForce != nullptr)
{
IsGlobalEnabled = true;
}
}
}
return true;
}
void LocalForceFieldParameter::MaintainGravityCompatibility(const SIMD::Vec3f& gravity)
{
HasValue = true;
IsGlobalEnabled = true;
LocalForceFields[3].Gravity = std::make_unique<ForceFieldGravityParameter>();
LocalForceFields[3].HasValue = true;
LocalForceFields[3].Gravity->Gravity = gravity;
LocalForceFields[3].IsGlobal = true;
}
void LocalForceFieldParameter::MaintainAttractiveForceCompatibility(const float force, const float control, const float minRange, const float maxRange)
{
HasValue = true;
IsGlobalEnabled = true;
LocalForceFields[3].AttractiveForce = std::make_unique<ForceFieldAttractiveForceParameter>();
LocalForceFields[3].HasValue = true;
LocalForceFields[3].AttractiveForce->Force = force;
LocalForceFields[3].AttractiveForce->Control = control;
LocalForceFields[3].AttractiveForce->MinRange = minRange;
LocalForceFields[3].AttractiveForce->MaxRange = maxRange;
LocalForceFields[3].IsGlobal = true;
}
void LocalForceFieldInstance::Update(const LocalForceFieldParameter& parameter, const SIMD::Vec3f& location, float magnification, float deltaFrame, CoordinateSystem coordinateSystem)
{
for (size_t i = 0; i < parameter.LocalForceFields.size(); i++)
{
auto& field = parameter.LocalForceFields[i];
if (!field.HasValue)
{
continue;
}
if (parameter.LocalForceFields[i].IsGlobal)
continue;
ForceFieldCommonParameter ffcp;
ffcp.FieldCenter = parameter.LocalForceFields[i].Position;
ffcp.Position = location / magnification;
ffcp.PreviousSumVelocity = (VelocitySum + ExternalVelocity / deltaFrame) / magnification;
ffcp.PreviousVelocity = Velocities[i] / magnification;
ffcp.DeltaFrame = deltaFrame;
ffcp.IsFieldRotated = field.IsRotated;
if (coordinateSystem == CoordinateSystem::LH)
{
ffcp.Position.SetZ(-ffcp.Position.GetZ());
ffcp.PreviousVelocity.SetZ(-ffcp.PreviousVelocity.GetZ());
ffcp.PreviousSumVelocity.SetZ(-ffcp.PreviousSumVelocity.GetZ());
}
if (field.IsRotated)
{
ffcp.PreviousSumVelocity = SIMD::Vec3f::Transform(ffcp.PreviousSumVelocity, field.InvRotation);
ffcp.PreviousVelocity = SIMD::Vec3f::Transform(ffcp.PreviousVelocity, field.InvRotation);
ffcp.Position = SIMD::Vec3f::Transform(ffcp.Position, field.InvRotation);
}
ForceField ff;
SIMD::Vec3f acc = SIMD::Vec3f(0, 0, 0);
if (field.Force != nullptr)
{
acc = ff.GetAcceleration(ffcp, *field.Force) * magnification;
}
if (field.Wind != nullptr)
{
acc = ff.GetAcceleration(ffcp, *field.Wind) * magnification;
}
if (field.Vortex != nullptr)
{
acc = ff.GetAcceleration(ffcp, *field.Vortex) * magnification;
}
if (field.Turbulence != nullptr)
{
acc = ff.GetAcceleration(ffcp, *field.Turbulence) * magnification;
}
if (field.Drag != nullptr)
{
acc = ff.GetAcceleration(ffcp, *field.Drag) * magnification;
}
float power = 1.0f;
if (field.FalloffCommon != nullptr && field.FalloffCone != nullptr)
{
ForceFieldFalloff fff;
power = fff.GetPower(power, ffcp, *field.FalloffCommon, *field.FalloffCone);
}
if (field.FalloffCommon != nullptr && field.FalloffSphere != nullptr)
{
ForceFieldFalloff fff;
power = fff.GetPower(power, ffcp, *field.FalloffCommon, *field.FalloffSphere);
}
if (field.FalloffCommon != nullptr && field.FalloffTube != nullptr)
{
ForceFieldFalloff fff;
power = fff.GetPower(power, ffcp, *field.FalloffCommon, *field.FalloffTube);
}
acc *= power;
if (field.IsRotated)
{
acc = SIMD::Vec3f::Transform(acc, field.Rotation);
}
if (coordinateSystem == CoordinateSystem::LH)
{
acc.SetZ(-acc.GetZ());
}
Velocities[i] += acc;
}
VelocitySum = SIMD::Vec3f(0, 0, 0);
for (size_t i = 0; i < parameter.LocalForceFields.size(); i++)
{
if (parameter.LocalForceFields[i].IsGlobal)
continue;
VelocitySum += Velocities[i];
}
ModifyLocation += VelocitySum * deltaFrame;
}
void LocalForceFieldInstance::UpdateGlobal(const LocalForceFieldParameter& parameter, const SIMD::Vec3f& location, float magnification, const SIMD::Vec3f& targetPosition, float deltaFrame, CoordinateSystem coordinateSystem)
{
for (size_t i = 0; i < parameter.LocalForceFields.size(); i++)
{
auto& field = parameter.LocalForceFields[i];
if (!field.HasValue)
{
continue;
}
if (!parameter.LocalForceFields[i].IsGlobal)
continue;
ForceFieldCommonParameter ffcp;
ffcp.FieldCenter = parameter.LocalForceFields[i].Position;
ffcp.Position = location / magnification;
ffcp.PreviousSumVelocity = VelocitySum / magnification;
ffcp.PreviousVelocity = Velocities[i] / magnification;
ffcp.TargetPosition = targetPosition / magnification;
ffcp.DeltaFrame = deltaFrame;
ffcp.IsFieldRotated = field.IsRotated;
if (coordinateSystem == CoordinateSystem::LH)
{
ffcp.Position.SetZ(-ffcp.Position.GetZ());
ffcp.PreviousVelocity.SetZ(-ffcp.PreviousVelocity.GetZ());
ffcp.PreviousSumVelocity.SetZ(-ffcp.PreviousSumVelocity.GetZ());
}
if (field.IsRotated)
{
ffcp.PreviousSumVelocity = SIMD::Vec3f::Transform(ffcp.PreviousSumVelocity, field.InvRotation);
ffcp.PreviousVelocity = SIMD::Vec3f::Transform(ffcp.PreviousVelocity, field.InvRotation);
ffcp.Position = SIMD::Vec3f::Transform(ffcp.Position, field.InvRotation);
}
ForceField ff;
SIMD::Vec3f acc = SIMD::Vec3f(0, 0, 0);
if (field.Gravity != nullptr)
{
acc = ff.GetAcceleration(ffcp, *field.Gravity) * magnification;
}
if (field.AttractiveForce != nullptr)
{
acc = ff.GetAcceleration(ffcp, *field.AttractiveForce) * magnification;
}
float power = 1.0f;
if (field.FalloffCommon != nullptr && field.FalloffCone != nullptr)
{
ForceFieldFalloff fff;
power = fff.GetPower(power, ffcp, *field.FalloffCommon, *field.FalloffCone);
}
if (field.FalloffCommon != nullptr && field.FalloffSphere != nullptr)
{
ForceFieldFalloff fff;
power = fff.GetPower(power, ffcp, *field.FalloffCommon, *field.FalloffSphere);
}
if (field.FalloffCommon != nullptr && field.FalloffTube != nullptr)
{
ForceFieldFalloff fff;
power = fff.GetPower(power, ffcp, *field.FalloffCommon, *field.FalloffTube);
}
acc *= power;
if (field.IsRotated)
{
acc = SIMD::Vec3f::Transform(acc, field.Rotation);
}
if (coordinateSystem == CoordinateSystem::LH)
{
acc.SetZ(-acc.GetZ());
}
Velocities[i] += acc;
}
VelocitySum = SIMD::Vec3f(0, 0, 0);
for (size_t i = 0; i < parameter.LocalForceFields.size(); i++)
{
if (!parameter.LocalForceFields[i].IsGlobal)
continue;
VelocitySum += Velocities[i];
}
GlobalModifyLocation += VelocitySum * deltaFrame;
}
void LocalForceFieldInstance::Reset()
{
Velocities.fill(SIMD::Vec3f(0, 0, 0));
VelocitySum = SIMD::Vec3f(0, 0, 0);
ModifyLocation = SIMD::Vec3f(0, 0, 0);
GlobalVelocitySum = SIMD::Vec3f(0, 0, 0);
GlobalModifyLocation = SIMD::Vec3f(0, 0, 0);
ExternalVelocity = SIMD::Vec3f(0, 0, 0);
}
} // namespace Effekseer | 24.839104 | 223 | 0.702689 | [
"transform"
] |
44dec7bb3295db1ca3e2bc6dda9711bddff5167a | 7,336 | cpp | C++ | Source/source/mobs/enemy.cpp | Superkman23/Pikifen | 44ee4e954cbf74288bb46d6be8e837f216e82956 | [
"MIT"
] | null | null | null | Source/source/mobs/enemy.cpp | Superkman23/Pikifen | 44ee4e954cbf74288bb46d6be8e837f216e82956 | [
"MIT"
] | null | null | null | Source/source/mobs/enemy.cpp | Superkman23/Pikifen | 44ee4e954cbf74288bb46d6be8e837f216e82956 | [
"MIT"
] | null | null | null | /*
* Copyright (c) Andre 'Espyo' Silva 2013.
* The following source file belongs to the open-source project Pikifen.
* Please read the included README and LICENSE files for more information.
* Pikmin is copyright (c) Nintendo.
*
* === FILE DESCRIPTION ===
* Enemy class and enemy-related functions.
*/
#include <algorithm>
#include <unordered_set>
#include "enemy.h"
#include "../drawing.h"
#include "../functions.h"
#include "../game.h"
#include "../mob_types/mob_type.h"
#include "../utils/math_utils.h"
#include "../utils/string_utils.h"
/* ----------------------------------------------------------------------------
* Creates an enemy mob.
* pos:
* Starting coordinates.
* type:
* Enemy type this mob belongs to.
* angle:
* Starting angle.
*/
enemy::enemy(const point &pos, enemy_type* type, const float angle) :
mob(pos, type, angle),
ene_type(type) {
}
/* ----------------------------------------------------------------------------
* Returns whether or not an enemy can receive a given status effect.
* s:
* Status type to check.
*/
bool enemy::can_receive_status(status_type* s) const {
return s->affects & STATUS_AFFECTS_ENEMIES;
}
/* ----------------------------------------------------------------------------
* Draws an enemy, tinting it if necessary (for Onion delivery).
*/
void enemy::draw_mob() {
sprite* s_ptr = anim.get_cur_sprite();
if(!s_ptr) return;
bitmap_effect_info eff;
ALLEGRO_COLOR delivery_color = map_gray(0);
float delivery_time_ratio_left = LARGE_FLOAT;
if(fsm.cur_state->id == ENEMY_EXTRA_STATE_BEING_DELIVERED) {
delivery_color = delivery_info->color;
delivery_time_ratio_left = script_timer.get_ratio_left();
}
get_sprite_bitmap_effects(
s_ptr, &eff, true, true,
delivery_time_ratio_left, delivery_color
);
draw_bitmap_with_effects(s_ptr->bitmap, eff);
draw_status_effect_bmp(this, eff);
}
//Normally, the spirit's diameter is the enemy's. Multiply the spirit by this.
const float ENEMY_SPIRIT_SIZE_MULT = 0.7;
//Maximum diameter an enemy's spirit can be.
const float ENEMY_SPIRIT_MAX_SIZE = 128;
//Minimum diameter an enemy's spirit can be.
const float ENEMY_SPIRIT_MIN_SIZE = 16;
/* ----------------------------------------------------------------------------
* Logic specific to enemies for when they finish dying.
*/
void enemy::finish_dying_class_specifics() {
if(ene_type->drops_corpse) {
become_carriable(CARRY_DESTINATION_ONION);
fsm.set_state(ENEMY_EXTRA_STATE_CARRIABLE_WAITING);
}
particle par(
PARTICLE_TYPE_ENEMY_SPIRIT, pos, LARGE_FLOAT,
clamp(
type->radius * 2 * ENEMY_SPIRIT_SIZE_MULT,
ENEMY_SPIRIT_MIN_SIZE, ENEMY_SPIRIT_MAX_SIZE
),
2, PARTICLE_PRIORITY_MEDIUM
);
par.bitmap = game.sys_assets.bmp_enemy_spirit;
par.speed.x = 0;
par.speed.y = -50;
par.friction = 0.5;
par.gravity = 0;
par.color = al_map_rgb(255, 192, 255);
game.states.gameplay->particles.add(par);
}
/* ----------------------------------------------------------------------------
* Reads the provided script variables, if any, and does stuff with them.
* svr:
* Script var reader to read with.
*/
void enemy::read_script_vars(const script_var_reader &svr) {
mob::read_script_vars(svr);
string spoils_var;
string random_pellet_spoils_var;
if(svr.get("spoils", spoils_var)) {
vector<string> spoils_strs = semicolon_list_to_vector(spoils_var, ",");
for(size_t s = 0; s < spoils_strs.size(); ++s) {
mob_type* type_ptr =
game.mob_categories.find_mob_type(spoils_strs[s]);
if(!type_ptr) {
log_error(
"A mob (" + get_error_message_mob_info(this) +
") is set to have a spoil of type \"" + spoils_strs[s] +
"\", but no such mob type exists!"
);
continue;
}
specific_spoils.push_back(type_ptr);
}
}
if(svr.get("random_pellet_spoils", random_pellet_spoils_var)) {
vector<string> random_pellet_spoils_strs =
semicolon_list_to_vector(random_pellet_spoils_var, ",");
for(size_t s = 0; s < random_pellet_spoils_strs.size(); ++s) {
random_pellet_spoils.push_back(s2i(random_pellet_spoils_strs[s]));
}
}
}
/* ----------------------------------------------------------------------------
* Sets up stuff for the beginning of the enemy's death process.
*/
void enemy::start_dying_class_specifics() {
vector<mob_type*> spoils_to_spawn = specific_spoils;
//If there are random pellets to spawn, then prepare some data.
if(!random_pellet_spoils.empty()) {
vector<pikmin_type*> available_pik_types;
//Start by obtaining a list of available Pikmin types, given the
//Onions currently in the area.
for(size_t o = 0; o < game.states.gameplay->mobs.onions.size(); ++o) {
onion* o_ptr = game.states.gameplay->mobs.onions[o];
for(
size_t t = 0;
t < o_ptr->oni_type->nest->pik_types.size();
++t
) {
available_pik_types.push_back(
o_ptr->oni_type->nest->pik_types[t]
);
}
}
//Remove duplicates from the list.
sort(available_pik_types.begin(), available_pik_types.end());
available_pik_types.erase(
unique(available_pik_types.begin(), available_pik_types.end()),
available_pik_types.end()
);
for(size_t s = 0; s < random_pellet_spoils.size(); ++s) {
//For every pellet that we want to spawn...
vector<pellet_type*> possible_pellets;
//Check the pellet types that match that number and
//also match the available Pikmin types.
for(auto &p : game.mob_types.pellet) {
bool pik_type_ok = false;
for(size_t pt = 0; pt < available_pik_types.size(); ++pt) {
if(p.second->pik_type == available_pik_types[pt]) {
pik_type_ok = true;
break;
}
}
if(!pik_type_ok) {
//There is no Onion for this pellet type. Pass.
continue;
}
if(p.second->number == random_pellet_spoils[s]) {
possible_pellets.push_back(p.second);
}
}
//And now, pick a random one out of the possible pellets.
if(!possible_pellets.empty()) {
spoils_to_spawn.push_back(
possible_pellets[randomi(0, possible_pellets.size() - 1)]
);
}
}
}
for(size_t s = 0; s < spoils_to_spawn.size(); ++s) {
mob_type::spawn_struct str;
str.angle = 0;
str.coords_z = 0;
str.relative = true;
str.momentum = 100;
spawn(&str, spoils_to_spawn[s]);
}
game.states.results->enemies_beaten++;
}
| 32.75 | 79 | 0.554935 | [
"vector"
] |
44e655c6034586decc21c4c2fada2c695e6f371a | 1,204 | cpp | C++ | Contests/USACO Solutions/2011-12/Jan/12 Jan G3.cpp | wanglawrence9990/USACO | 45c9bce4b3ac77d2a4ba2e646ff45a02563b59d2 | [
"CC0-1.0"
] | null | null | null | Contests/USACO Solutions/2011-12/Jan/12 Jan G3.cpp | wanglawrence9990/USACO | 45c9bce4b3ac77d2a4ba2e646ff45a02563b59d2 | [
"CC0-1.0"
] | null | null | null | Contests/USACO Solutions/2011-12/Jan/12 Jan G3.cpp | wanglawrence9990/USACO | 45c9bce4b3ac77d2a4ba2e646ff45a02563b59d2 | [
"CC0-1.0"
] | null | null | null | #include <fstream>
#include <vector>
using namespace std;
//using namespace __gnu_pbds;
typedef long long ll;
typedef vector<int> vi;
typedef pair<int, int> pi;
//typedef tree<int,null_type,less<int>,rb_tree_tag,tree_order_statistics_node_update> ordered_set;
#define FOR(i, a, b) for (int i=a; i<b; i++)
#define F0R(i, a) for (int i=0; i<a; i++)
#define FORd(i,a,b) for (int i = (b)-1; i >= a; i--)
#define F0Rd(i,a) for (int i = (a)-1; i >= 0; i--)
#define mp make_pair
#define pb push_back
#define f first
#define s second
#define lb lower_bound
#define ub upper_bound
const int MOD = 1000000007;
int N,M,visit[100001];
int sum = 0, cycle = 0;
ll ans = 1;
vi adj[100001];
void dfs(int par, int node) {
if (visit[node]) {
cycle = 1;
return;
}
sum ++; visit[node] = 1;
for (int i: adj[node]) if (i != par) dfs(node,i);
}
int main() {
ifstream cin ("alliance.in");
ofstream cout ("alliance.out");
cin >> N >> M;
F0R(i,M) {
int u,v; cin >> u >> v;
adj[u].pb(v), adj[v].pb(u);
}
FOR(i,1,N+1) if (!visit[i]) {
sum = 0, cycle = 0;
dfs(0,i);
if (cycle) ans = (ans*2) % MOD;
else ans = (ans*sum) % MOD;
}
cout << ans;
}
| 21.5 | 98 | 0.584718 | [
"vector"
] |
44e7fc4ded577cc15179aa55cf8ec4002dcf9148 | 5,228 | cpp | C++ | apps/tetrahedralize_hybrid.cpp | ldXiao/polyfem | d4103af16979ff67d461a9ebe46a14bbc4dc8c7c | [
"MIT"
] | null | null | null | apps/tetrahedralize_hybrid.cpp | ldXiao/polyfem | d4103af16979ff67d461a9ebe46a14bbc4dc8c7c | [
"MIT"
] | null | null | null | apps/tetrahedralize_hybrid.cpp | ldXiao/polyfem | d4103af16979ff67d461a9ebe46a14bbc4dc8c7c | [
"MIT"
] | null | null | null | #include <polyfem/Mesh3D.hpp>
#include <polyfem/MeshUtils.hpp>
#include <CLI/CLI.hpp>
#include <geogram/basic/command_line.h>
#include <geogram/basic/command_line_args.h>
#include <geogram/basic/logger.h>
#include <geogram/basic/progress.h>
#include <geogram/basic/stopwatch.h>
#include <igl/read_triangle_mesh.h>
#include <igl/writeMESH.h>
#include <igl/writeOBJ.h>
#include <igl/copyleft/tetgen/tetrahedralize.h>
using namespace polyfem;
////////////////////////////////////////////////////////////////////////////////
int main(int argc, char** argv) {
#ifndef WIN32
setenv("GEO_NO_SIGNAL_HANDLER", "1", 1);
#endif
// Initialize the Geogram library
GEO::initialize();
// Import standard command line arguments, and custom ones
GEO::CmdLine::import_arg_group("standard");
GEO::CmdLine::import_arg_group("pre");
struct {
std::string mesh_path = "";
} args;
CLI::App app{"tetrahedralize mesh"};
app.add_option("mesh_path", args.mesh_path, "volume mesh")->required();
try {
app.parse(argc, argv);
} catch (const CLI::ParseError &e) {
return app.exit(e);
}
std::string mesh_path = args.mesh_path;
std::string out_mesh_path = mesh_path + ".mesh";
// Display input and output filenames
GEO::Logger::div("Command line");
GEO::Logger::out("I/O") << "Input file: " << mesh_path << std::endl;
GEO::Logger::out("I/O") << "Output file: " << out_mesh_path << std::endl;
std::unique_ptr<Mesh> tmp;
GEO::Logger::div("Loading");
{
GEO::Stopwatch W("Load");
tmp = Mesh::create(mesh_path);
if (!tmp) {
return 1;
}
}
Mesh3D &mesh = *dynamic_cast<Mesh3D *>(tmp.get());
mesh.normalize();
// Load the mesh and call tetgen
Eigen::MatrixXd IV, OV;
Eigen::MatrixXi IF, OF, OT;
IV.resize(2*mesh.n_vertices(), 3);
IF.resize(mesh.n_faces()*4, 3);
Eigen::MatrixXi remap(mesh.n_vertices(), 1);
remap.setConstant(-1);
int n_vertices_copied = 0;
int n_faces = 0;
for(int c = 0; c < mesh.n_cells(); ++c)
{
for(int lf = 0; lf < mesh.n_cell_faces(c); ++lf)
{
auto index = mesh.get_index_from_element(c, lf, 0);
if(!mesh.is_boundary_face(index.face))
continue;
std::vector<int> vids(mesh.n_face_vertices(index.face));
for(int lv = 0; lv < mesh.n_face_vertices(index.face); ++lv)
{
const int v_id = index.vertex;
int new_vid;
if(remap(v_id) < 0)
{
remap(v_id) = n_vertices_copied;
new_vid = n_vertices_copied;
IV.row(n_vertices_copied) = mesh.point(v_id);
++n_vertices_copied;
}
else
{
new_vid = remap(v_id);
}
vids[lv] = new_vid;
index = mesh.next_around_face(index);
}
if(vids.size() == 3)
{
IF(n_faces, 0) = vids[0];
IF(n_faces, 2) = vids[1];
IF(n_faces, 1) = vids[2];
n_faces++;
}
else if (vids.size() == 4)
{
IF(n_faces, 0) = vids[0];
IF(n_faces, 2) = vids[1];
IF(n_faces, 1) = vids[2];
n_faces++;
IF(n_faces, 0) = vids[0];
IF(n_faces, 2) = vids[2];
IF(n_faces, 1) = vids[3];
n_faces++;
}
else
{
IV.row(n_vertices_copied) = mesh.face_barycenter(index.face);
const int center = n_vertices_copied;
for(size_t v = 0; v < vids.size(); ++v)
{
IF(n_faces, 0) = vids[v];
IF(n_faces, 2) = vids[(v+1)%vids.size()];
IF(n_faces, 1) = center;
n_faces++;
}
++n_vertices_copied;
}
}
}
IV = IV.block(0, 0, n_vertices_copied, 3).eval();
IF = IF.block(0, 0, n_faces, 3).eval();
igl::writeOBJ(mesh_path + ".obj", IV, IF);
double start_vol = 0.01;
double end_vol = 1;
const int target_v = mesh.n_vertices();
std::cout<<"target v "<<target_v<<std::endl;
while(true)
{
std::string flags = "QpYa" + std::to_string(start_vol);
int res = igl::copyleft::tetgen::tetrahedralize(IV, IF, flags, OV, OT, OF);
if(abs(OV.rows() - target_v) < target_v * 0.051)
{
igl::writeMESH(out_mesh_path, OV, OT, OF);
std::cout<<"created mesh with "<<OV.rows()<<" vertices"<<std::endl;
return 0;
}
if(OV.rows() > target_v)
break;
start_vol /= 1.5;
std::cout<<"vol "<<start_vol<<" "<<OV.rows()<<std::endl;
}
while(true)
{
std::string flags = "QpYa" + std::to_string(end_vol);
int res = igl::copyleft::tetgen::tetrahedralize(IV, IF, flags, OV, OT, OF);
if(abs(OV.rows() - target_v) < target_v * 0.051)
{
igl::writeMESH(out_mesh_path, OV, OT, OF);
std::cout<<"created mesh with "<<OV.rows()<<" vertices"<<std::endl;
return 0;
}
if(OV.rows() < target_v)
break;
end_vol *= 1.5;
std::cout<<"vol "<<end_vol<<" "<<OV.rows()<<std::endl;
}
while((end_vol - start_vol) > 1e-10)
{
const double vol = (end_vol+start_vol)/2.0;
std::string flags = "QpYa" + std::to_string(vol);
int res = igl::copyleft::tetgen::tetrahedralize(IV, IF, flags, OV, OT, OF);
if(abs(OV.rows() - target_v) < target_v * 0.051)
{
igl::writeMESH(out_mesh_path, OV, OT, OF);
std::cout<<"created mesh with "<<OV.rows()<<" vertices"<<std::endl;
return 0;
}
if(OV.rows() > target_v)
start_vol = vol;
else
end_vol = vol;
std::cout<<"vol "<<start_vol<<" - "<<end_vol<<" "<<OV.rows()<<std::endl;
}
igl::writeMESH(out_mesh_path, OV, OT, OF);
std::cout<<"created mesh with "<<OV.rows()<<" vertices"<<std::endl;
return 0;
}
| 22.829694 | 80 | 0.608263 | [
"mesh",
"vector"
] |
44ee9153f3c216c56fca419353c76cfd9c329d3e | 13,920 | cpp | C++ | export/debug/windows/obj/src/lime/_internal/graphics/_ImageDataUtil/ImageDataView.cpp | bobisdabbing/Vs-The-United-Lands-stable | 0807e58b6d8ad1440bdd350bf006b37a1b7ca9b5 | [
"MIT"
] | 1 | 2021-07-19T05:10:43.000Z | 2021-07-19T05:10:43.000Z | export/debug/windows/obj/src/lime/_internal/graphics/_ImageDataUtil/ImageDataView.cpp | bobisdabbing/Vs-The-United-Lands-stable | 0807e58b6d8ad1440bdd350bf006b37a1b7ca9b5 | [
"MIT"
] | null | null | null | export/debug/windows/obj/src/lime/_internal/graphics/_ImageDataUtil/ImageDataView.cpp | bobisdabbing/Vs-The-United-Lands-stable | 0807e58b6d8ad1440bdd350bf006b37a1b7ca9b5 | [
"MIT"
] | null | null | null | // Generated by Haxe 4.1.5
#include <hxcpp.h>
#ifndef INCLUDED_95f339a1d026d52c
#define INCLUDED_95f339a1d026d52c
#include "hxMath.h"
#endif
#ifndef INCLUDED_lime__internal_graphics__ImageDataUtil_ImageDataView
#include <lime/_internal/graphics/_ImageDataUtil/ImageDataView.h>
#endif
#ifndef INCLUDED_lime_graphics_Image
#include <lime/graphics/Image.h>
#endif
#ifndef INCLUDED_lime_graphics_ImageBuffer
#include <lime/graphics/ImageBuffer.h>
#endif
#ifndef INCLUDED_lime_math_Rectangle
#include <lime/math/Rectangle.h>
#endif
HX_DEFINE_STACK_FRAME(_hx_pos_0f70c5927802d56d_1672_new,"lime._internal.graphics._ImageDataUtil.ImageDataView","new",0x36089ace,"lime._internal.graphics._ImageDataUtil.ImageDataView.new","lime/_internal/graphics/ImageDataUtil.hx",1672,0x59dddace)
HX_LOCAL_STACK_FRAME(_hx_pos_0f70c5927802d56d_1696_clip,"lime._internal.graphics._ImageDataUtil.ImageDataView","clip",0x0a3ec4a2,"lime._internal.graphics._ImageDataUtil.ImageDataView.clip","lime/_internal/graphics/ImageDataUtil.hx",1696,0x59dddace)
HX_LOCAL_STACK_FRAME(_hx_pos_0f70c5927802d56d_1706_hasRow,"lime._internal.graphics._ImageDataUtil.ImageDataView","hasRow",0xdbd8dd32,"lime._internal.graphics._ImageDataUtil.ImageDataView.hasRow","lime/_internal/graphics/ImageDataUtil.hx",1706,0x59dddace)
HX_LOCAL_STACK_FRAME(_hx_pos_0f70c5927802d56d_1710_offset,"lime._internal.graphics._ImageDataUtil.ImageDataView","offset",0x80da85e5,"lime._internal.graphics._ImageDataUtil.ImageDataView.offset","lime/_internal/graphics/ImageDataUtil.hx",1710,0x59dddace)
HX_LOCAL_STACK_FRAME(_hx_pos_0f70c5927802d56d_1738_row,"lime._internal.graphics._ImageDataUtil.ImageDataView","row",0x360bac88,"lime._internal.graphics._ImageDataUtil.ImageDataView.row","lime/_internal/graphics/ImageDataUtil.hx",1738,0x59dddace)
HX_LOCAL_STACK_FRAME(_hx_pos_0f70c5927802d56d_1742___update,"lime._internal.graphics._ImageDataUtil.ImageDataView","__update",0xdf2597fb,"lime._internal.graphics._ImageDataUtil.ImageDataView.__update","lime/_internal/graphics/ImageDataUtil.hx",1742,0x59dddace)
namespace lime{
namespace _internal{
namespace graphics{
namespace _ImageDataUtil{
void ImageDataView_obj::__construct( ::lime::graphics::Image image, ::lime::math::Rectangle rect){
HX_STACKFRAME(&_hx_pos_0f70c5927802d56d_1672_new)
HXLINE(1673) this->image = image;
HXLINE(1675) if (::hx::IsNull( rect )) {
HXLINE(1677) this->rect = image->get_rect();
}
else {
HXLINE(1681) if ((rect->x < 0)) {
HXLINE(1681) rect->x = ( (Float)(0) );
}
HXLINE(1682) if ((rect->y < 0)) {
HXLINE(1682) rect->y = ( (Float)(0) );
}
HXLINE(1683) if (((rect->x + rect->width) > image->width)) {
HXLINE(1683) rect->width = (( (Float)(image->width) ) - rect->x);
}
HXLINE(1684) if (((rect->y + rect->height) > image->height)) {
HXLINE(1684) rect->height = (( (Float)(image->height) ) - rect->y);
}
HXLINE(1685) if ((rect->width < 0)) {
HXLINE(1685) rect->width = ( (Float)(0) );
}
HXLINE(1686) if ((rect->height < 0)) {
HXLINE(1686) rect->height = ( (Float)(0) );
}
HXLINE(1687) this->rect = rect;
}
HXLINE(1690) this->stride = image->buffer->get_stride();
HXLINE(1692) this->_hx___update();
}
Dynamic ImageDataView_obj::__CreateEmpty() { return new ImageDataView_obj; }
void *ImageDataView_obj::_hx_vtable = 0;
Dynamic ImageDataView_obj::__Create(::hx::DynamicArray inArgs)
{
::hx::ObjectPtr< ImageDataView_obj > _hx_result = new ImageDataView_obj();
_hx_result->__construct(inArgs[0],inArgs[1]);
return _hx_result;
}
bool ImageDataView_obj::_hx_isInstanceOf(int inClassId) {
return inClassId==(int)0x00000001 || inClassId==(int)0x178fc370;
}
void ImageDataView_obj::clip(int x,int y,int width,int height){
HX_GC_STACKFRAME(&_hx_pos_0f70c5927802d56d_1696_clip)
HXLINE(1697) if (::hx::IsNull( this->tempRect )) {
HXLINE(1697) this->tempRect = ::lime::math::Rectangle_obj::__alloc( HX_CTX ,null(),null(),null(),null());
}
HXLINE(1698) this->tempRect->setTo(( (Float)(x) ),( (Float)(y) ),( (Float)(width) ),( (Float)(height) ));
HXLINE(1700) this->rect->intersection(this->tempRect,this->rect);
HXLINE(1701) this->_hx___update();
}
HX_DEFINE_DYNAMIC_FUNC4(ImageDataView_obj,clip,(void))
bool ImageDataView_obj::hasRow(int y){
HX_STACKFRAME(&_hx_pos_0f70c5927802d56d_1706_hasRow)
HXDLIN(1706) if ((y >= 0)) {
HXDLIN(1706) return (y < this->height);
}
else {
HXDLIN(1706) return false;
}
HXDLIN(1706) return false;
}
HX_DEFINE_DYNAMIC_FUNC1(ImageDataView_obj,hasRow,return )
void ImageDataView_obj::offset(int x,int y){
HX_STACKFRAME(&_hx_pos_0f70c5927802d56d_1710_offset)
HXLINE(1711) if ((x < 0)) {
HXLINE(1713) ::lime::math::Rectangle _hx_tmp = this->rect;
HXDLIN(1713) _hx_tmp->x = (_hx_tmp->x + x);
HXLINE(1714) if ((this->rect->x < 0)) {
HXLINE(1714) this->rect->x = ( (Float)(0) );
}
}
else {
HXLINE(1718) ::lime::math::Rectangle _hx_tmp = this->rect;
HXDLIN(1718) _hx_tmp->x = (_hx_tmp->x + x);
HXLINE(1719) ::lime::math::Rectangle _hx_tmp1 = this->rect;
HXDLIN(1719) _hx_tmp1->width = (_hx_tmp1->width - ( (Float)(x) ));
}
HXLINE(1722) if ((y < 0)) {
HXLINE(1724) ::lime::math::Rectangle _hx_tmp = this->rect;
HXDLIN(1724) _hx_tmp->y = (_hx_tmp->y + y);
HXLINE(1725) if ((this->rect->y < 0)) {
HXLINE(1725) this->rect->y = ( (Float)(0) );
}
}
else {
HXLINE(1729) ::lime::math::Rectangle _hx_tmp = this->rect;
HXDLIN(1729) _hx_tmp->y = (_hx_tmp->y + y);
HXLINE(1730) ::lime::math::Rectangle _hx_tmp1 = this->rect;
HXDLIN(1730) _hx_tmp1->height = (_hx_tmp1->height - ( (Float)(y) ));
}
HXLINE(1733) this->_hx___update();
}
HX_DEFINE_DYNAMIC_FUNC2(ImageDataView_obj,offset,(void))
int ImageDataView_obj::row(int y){
HX_STACKFRAME(&_hx_pos_0f70c5927802d56d_1738_row)
HXDLIN(1738) return (this->byteOffset + (this->stride * y));
}
HX_DEFINE_DYNAMIC_FUNC1(ImageDataView_obj,row,return )
void ImageDataView_obj::_hx___update(){
HX_STACKFRAME(&_hx_pos_0f70c5927802d56d_1742___update)
HXLINE(1743) this->x = ::Math_obj::ceil(this->rect->x);
HXLINE(1744) this->y = ::Math_obj::ceil(this->rect->y);
HXLINE(1745) this->width = ::Math_obj::floor(this->rect->width);
HXLINE(1746) this->height = ::Math_obj::floor(this->rect->height);
HXLINE(1747) this->byteOffset = ((this->stride * (this->y + this->image->offsetY)) + ((this->x + this->image->offsetX) * 4));
}
HX_DEFINE_DYNAMIC_FUNC0(ImageDataView_obj,_hx___update,(void))
::hx::ObjectPtr< ImageDataView_obj > ImageDataView_obj::__new( ::lime::graphics::Image image, ::lime::math::Rectangle rect) {
::hx::ObjectPtr< ImageDataView_obj > __this = new ImageDataView_obj();
__this->__construct(image,rect);
return __this;
}
::hx::ObjectPtr< ImageDataView_obj > ImageDataView_obj::__alloc(::hx::Ctx *_hx_ctx, ::lime::graphics::Image image, ::lime::math::Rectangle rect) {
ImageDataView_obj *__this = (ImageDataView_obj*)(::hx::Ctx::alloc(_hx_ctx, sizeof(ImageDataView_obj), true, "lime._internal.graphics._ImageDataUtil.ImageDataView"));
*(void **)__this = ImageDataView_obj::_hx_vtable;
__this->__construct(image,rect);
return __this;
}
ImageDataView_obj::ImageDataView_obj()
{
}
void ImageDataView_obj::__Mark(HX_MARK_PARAMS)
{
HX_MARK_BEGIN_CLASS(ImageDataView);
HX_MARK_MEMBER_NAME(x,"x");
HX_MARK_MEMBER_NAME(y,"y");
HX_MARK_MEMBER_NAME(height,"height");
HX_MARK_MEMBER_NAME(width,"width");
HX_MARK_MEMBER_NAME(byteOffset,"byteOffset");
HX_MARK_MEMBER_NAME(image,"image");
HX_MARK_MEMBER_NAME(rect,"rect");
HX_MARK_MEMBER_NAME(stride,"stride");
HX_MARK_MEMBER_NAME(tempRect,"tempRect");
HX_MARK_END_CLASS();
}
void ImageDataView_obj::__Visit(HX_VISIT_PARAMS)
{
HX_VISIT_MEMBER_NAME(x,"x");
HX_VISIT_MEMBER_NAME(y,"y");
HX_VISIT_MEMBER_NAME(height,"height");
HX_VISIT_MEMBER_NAME(width,"width");
HX_VISIT_MEMBER_NAME(byteOffset,"byteOffset");
HX_VISIT_MEMBER_NAME(image,"image");
HX_VISIT_MEMBER_NAME(rect,"rect");
HX_VISIT_MEMBER_NAME(stride,"stride");
HX_VISIT_MEMBER_NAME(tempRect,"tempRect");
}
::hx::Val ImageDataView_obj::__Field(const ::String &inName,::hx::PropertyAccess inCallProp)
{
switch(inName.length) {
case 1:
if (HX_FIELD_EQ(inName,"x") ) { return ::hx::Val( x ); }
if (HX_FIELD_EQ(inName,"y") ) { return ::hx::Val( y ); }
break;
case 3:
if (HX_FIELD_EQ(inName,"row") ) { return ::hx::Val( row_dyn() ); }
break;
case 4:
if (HX_FIELD_EQ(inName,"rect") ) { return ::hx::Val( rect ); }
if (HX_FIELD_EQ(inName,"clip") ) { return ::hx::Val( clip_dyn() ); }
break;
case 5:
if (HX_FIELD_EQ(inName,"width") ) { return ::hx::Val( width ); }
if (HX_FIELD_EQ(inName,"image") ) { return ::hx::Val( image ); }
break;
case 6:
if (HX_FIELD_EQ(inName,"height") ) { return ::hx::Val( height ); }
if (HX_FIELD_EQ(inName,"stride") ) { return ::hx::Val( stride ); }
if (HX_FIELD_EQ(inName,"hasRow") ) { return ::hx::Val( hasRow_dyn() ); }
if (HX_FIELD_EQ(inName,"offset") ) { return ::hx::Val( offset_dyn() ); }
break;
case 8:
if (HX_FIELD_EQ(inName,"tempRect") ) { return ::hx::Val( tempRect ); }
if (HX_FIELD_EQ(inName,"__update") ) { return ::hx::Val( _hx___update_dyn() ); }
break;
case 10:
if (HX_FIELD_EQ(inName,"byteOffset") ) { return ::hx::Val( byteOffset ); }
}
return super::__Field(inName,inCallProp);
}
::hx::Val ImageDataView_obj::__SetField(const ::String &inName,const ::hx::Val &inValue,::hx::PropertyAccess inCallProp)
{
switch(inName.length) {
case 1:
if (HX_FIELD_EQ(inName,"x") ) { x=inValue.Cast< int >(); return inValue; }
if (HX_FIELD_EQ(inName,"y") ) { y=inValue.Cast< int >(); return inValue; }
break;
case 4:
if (HX_FIELD_EQ(inName,"rect") ) { rect=inValue.Cast< ::lime::math::Rectangle >(); return inValue; }
break;
case 5:
if (HX_FIELD_EQ(inName,"width") ) { width=inValue.Cast< int >(); return inValue; }
if (HX_FIELD_EQ(inName,"image") ) { image=inValue.Cast< ::lime::graphics::Image >(); return inValue; }
break;
case 6:
if (HX_FIELD_EQ(inName,"height") ) { height=inValue.Cast< int >(); return inValue; }
if (HX_FIELD_EQ(inName,"stride") ) { stride=inValue.Cast< int >(); return inValue; }
break;
case 8:
if (HX_FIELD_EQ(inName,"tempRect") ) { tempRect=inValue.Cast< ::lime::math::Rectangle >(); return inValue; }
break;
case 10:
if (HX_FIELD_EQ(inName,"byteOffset") ) { byteOffset=inValue.Cast< int >(); return inValue; }
}
return super::__SetField(inName,inValue,inCallProp);
}
void ImageDataView_obj::__GetFields(Array< ::String> &outFields)
{
outFields->push(HX_("x",78,00,00,00));
outFields->push(HX_("y",79,00,00,00));
outFields->push(HX_("height",e7,07,4c,02));
outFields->push(HX_("width",06,b6,62,ca));
outFields->push(HX_("byteOffset",bb,20,44,38));
outFields->push(HX_("image",5b,1f,69,bd));
outFields->push(HX_("rect",24,4d,a7,4b));
outFields->push(HX_("stride",19,20,30,11));
outFields->push(HX_("tempRect",58,56,1b,9b));
super::__GetFields(outFields);
};
#ifdef HXCPP_SCRIPTABLE
static ::hx::StorageInfo ImageDataView_obj_sMemberStorageInfo[] = {
{::hx::fsInt,(int)offsetof(ImageDataView_obj,x),HX_("x",78,00,00,00)},
{::hx::fsInt,(int)offsetof(ImageDataView_obj,y),HX_("y",79,00,00,00)},
{::hx::fsInt,(int)offsetof(ImageDataView_obj,height),HX_("height",e7,07,4c,02)},
{::hx::fsInt,(int)offsetof(ImageDataView_obj,width),HX_("width",06,b6,62,ca)},
{::hx::fsInt,(int)offsetof(ImageDataView_obj,byteOffset),HX_("byteOffset",bb,20,44,38)},
{::hx::fsObject /* ::lime::graphics::Image */ ,(int)offsetof(ImageDataView_obj,image),HX_("image",5b,1f,69,bd)},
{::hx::fsObject /* ::lime::math::Rectangle */ ,(int)offsetof(ImageDataView_obj,rect),HX_("rect",24,4d,a7,4b)},
{::hx::fsInt,(int)offsetof(ImageDataView_obj,stride),HX_("stride",19,20,30,11)},
{::hx::fsObject /* ::lime::math::Rectangle */ ,(int)offsetof(ImageDataView_obj,tempRect),HX_("tempRect",58,56,1b,9b)},
{ ::hx::fsUnknown, 0, null()}
};
static ::hx::StaticInfo *ImageDataView_obj_sStaticStorageInfo = 0;
#endif
static ::String ImageDataView_obj_sMemberFields[] = {
HX_("x",78,00,00,00),
HX_("y",79,00,00,00),
HX_("height",e7,07,4c,02),
HX_("width",06,b6,62,ca),
HX_("byteOffset",bb,20,44,38),
HX_("image",5b,1f,69,bd),
HX_("rect",24,4d,a7,4b),
HX_("stride",19,20,30,11),
HX_("tempRect",58,56,1b,9b),
HX_("clip",d0,6e,c2,41),
HX_("hasRow",e0,ee,3d,bb),
HX_("offset",93,97,3f,60),
HX_("row",1a,e2,56,00),
HX_("__update",29,f1,34,2f),
::String(null()) };
::hx::Class ImageDataView_obj::__mClass;
void ImageDataView_obj::__register()
{
ImageDataView_obj _hx_dummy;
ImageDataView_obj::_hx_vtable = *(void **)&_hx_dummy;
::hx::Static(__mClass) = new ::hx::Class_obj();
__mClass->mName = HX_("lime._internal.graphics._ImageDataUtil.ImageDataView",dc,db,9b,c0);
__mClass->mSuper = &super::__SGetClass();
__mClass->mConstructEmpty = &__CreateEmpty;
__mClass->mConstructArgs = &__Create;
__mClass->mGetStaticField = &::hx::Class_obj::GetNoStaticField;
__mClass->mSetStaticField = &::hx::Class_obj::SetNoStaticField;
__mClass->mStatics = ::hx::Class_obj::dupFunctions(0 /* sStaticFields */);
__mClass->mMembers = ::hx::Class_obj::dupFunctions(ImageDataView_obj_sMemberFields);
__mClass->mCanCast = ::hx::TCanCast< ImageDataView_obj >;
#ifdef HXCPP_SCRIPTABLE
__mClass->mMemberStorageInfo = ImageDataView_obj_sMemberStorageInfo;
#endif
#ifdef HXCPP_SCRIPTABLE
__mClass->mStaticStorageInfo = ImageDataView_obj_sStaticStorageInfo;
#endif
::hx::_hx_RegisterClass(__mClass->mName, __mClass);
}
} // end namespace lime
} // end namespace _internal
} // end namespace graphics
} // end namespace _ImageDataUtil
| 40.701754 | 260 | 0.695043 | [
"3d"
] |
60217f0947e266f1da9df151867d2a186666bb89 | 2,268 | cpp | C++ | src/GeosQCoordinateTranform.cpp | sempr-tk/sempr-gui | ba96dca6945122a157f61fec9e41f4aa6060e3b2 | [
"BSD-3-Clause"
] | null | null | null | src/GeosQCoordinateTranform.cpp | sempr-tk/sempr-gui | ba96dca6945122a157f61fec9e41f4aa6060e3b2 | [
"BSD-3-Clause"
] | null | null | null | src/GeosQCoordinateTranform.cpp | sempr-tk/sempr-gui | ba96dca6945122a157f61fec9e41f4aa6060e3b2 | [
"BSD-3-Clause"
] | null | null | null | #include "GeosQCoordinateTranform.hpp"
#include <geos/geom/CoordinateSequence.h>
#include <QGeoCoordinate>
namespace sempr { namespace gui {
// -------------------------------------------------------------------------
// ReadCoordinates
// -------------------------------------------------------------------------
ReadCoordinates::ReadCoordinates()
: done_(false)
{
}
void ReadCoordinates::read(const geos::geom::CoordinateSequence& sequence)
{
for (size_t i = 0; i < sequence.size(); i++)
{
auto& coordinate = sequence.getAt(i);
coordinates_.push_back(
QVariant::fromValue(
// lat long alt
QGeoCoordinate(coordinate.y, coordinate.x, coordinate.z)
)
);
}
done_ = true;
}
void ReadCoordinates::filter_rw(geos::geom::CoordinateSequence& sequence, size_t)
{
read(sequence);
}
void ReadCoordinates::filter_ro(const geos::geom::CoordinateSequence& sequence, size_t)
{
read(sequence);
}
bool ReadCoordinates::isDone() const
{
return done_;
}
bool ReadCoordinates::isGeometryChanged() const
{
return false;
}
QList<QVariant> ReadCoordinates::coordinates() const
{
return coordinates_;
}
void ReadCoordinates::reset()
{
coordinates_.clear();
done_ = false;
}
// -------------------------------------------------------------------------
// WriteCoordinates
// -------------------------------------------------------------------------
WriteCoordinates::WriteCoordinates(const QList<QGeoCoordinate>& coordinates)
: coordinates_(coordinates), done_(false)
{
}
void WriteCoordinates::filter_ro(const geos::geom::CoordinateSequence&, size_t)
{
// wtf are you doing?!
throw std::exception();
}
void WriteCoordinates::filter_rw(geos::geom::CoordinateSequence& sequence, size_t)
{
std::vector<geos::geom::Coordinate> points;
for (auto& qcoord : coordinates_)
{
geos::geom::Coordinate coord(qcoord.longitude(), qcoord.latitude(), qcoord.altitude());
points.push_back(coord);
}
sequence.setPoints(points);
done_ = true;
}
bool WriteCoordinates::isDone() const
{
return done_;
}
bool WriteCoordinates::isGeometryChanged() const
{
return true;
}
}}
| 22.019417 | 95 | 0.578042 | [
"vector"
] |
6026f6aba21a23754ff29b77fd547add56e7a390 | 2,197 | hpp | C++ | apps/openmw/mwscript/scriptmanagerimp.hpp | Bodillium/openmw | 5fdd264d0704e33b44b1ccf17ab4fb721f362e34 | [
"Unlicense"
] | null | null | null | apps/openmw/mwscript/scriptmanagerimp.hpp | Bodillium/openmw | 5fdd264d0704e33b44b1ccf17ab4fb721f362e34 | [
"Unlicense"
] | null | null | null | apps/openmw/mwscript/scriptmanagerimp.hpp | Bodillium/openmw | 5fdd264d0704e33b44b1ccf17ab4fb721f362e34 | [
"Unlicense"
] | null | null | null | #ifndef GAME_SCRIPT_SCRIPTMANAGER_H
#define GAME_SCRIPT_SCRIPTMANAGER_H
#include <map>
#include <string>
#include <components/compiler/streamerrorhandler.hpp>
#include <components/compiler/fileparser.hpp>
#include <components/interpreter/interpreter.hpp>
#include <components/interpreter/types.hpp>
#include "../mwbase/scriptmanager.hpp"
#include "globalscripts.hpp"
namespace MWWorld
{
struct ESMStore;
}
namespace Compiler
{
class Context;
}
namespace Interpreter
{
class Context;
class Interpreter;
}
namespace MWScript
{
class ScriptManager : public MWBase::ScriptManager
{
Compiler::StreamErrorHandler mErrorHandler;
const MWWorld::ESMStore& mStore;
bool mVerbose;
Compiler::Context& mCompilerContext;
Compiler::FileParser mParser;
Interpreter::Interpreter mInterpreter;
bool mOpcodesInstalled;
typedef std::pair<std::vector<Interpreter::Type_Code>, Compiler::Locals> CompiledScript;
typedef std::map<std::string, CompiledScript> ScriptCollection;
ScriptCollection mScripts;
GlobalScripts mGlobalScripts;
std::map<std::string, Compiler::Locals> mOtherLocals;
std::vector<std::string> mScriptBlacklist;
public:
ScriptManager (const MWWorld::ESMStore& store, bool verbose,
Compiler::Context& compilerContext, int warningsMode,
const std::vector<std::string>& scriptBlacklist);
virtual void run (const std::string& name, Interpreter::Context& interpreterContext);
///< Run the script with the given name (compile first, if not compiled yet)
virtual bool compile (const std::string& name);
///< Compile script with the given namen
/// \return Success?
virtual std::pair<int, int> compileAll();
///< Compile all scripts
/// \return count, success
virtual const Compiler::Locals& getLocals (const std::string& name);
///< Return locals for script \a name.
virtual GlobalScripts& getGlobalScripts();
};
}
#endif
| 28.166667 | 100 | 0.652253 | [
"vector"
] |
602979f78f59a2094287af077096f98dca8d1e54 | 38,635 | cpp | C++ | DynamicShaderLinkageFX11/DynamicShaderLinkageFX11.cpp | huidong-chen/directx-sdk-samples | ebe25a4dc63576ba281fd878887856c3599a3da4 | [
"MIT"
] | 1,145 | 2015-04-21T00:58:37.000Z | 2022-03-29T14:03:14.000Z | DynamicShaderLinkageFX11/DynamicShaderLinkageFX11.cpp | huidong-chen/directx-sdk-samples | ebe25a4dc63576ba281fd878887856c3599a3da4 | [
"MIT"
] | 21 | 2015-12-31T20:23:42.000Z | 2022-03-04T03:01:00.000Z | DynamicShaderLinkageFX11/DynamicShaderLinkageFX11.cpp | huidong-chen/directx-sdk-samples | ebe25a4dc63576ba281fd878887856c3599a3da4 | [
"MIT"
] | 377 | 2015-06-15T12:53:54.000Z | 2022-03-30T00:49:10.000Z | //--------------------------------------------------------------------------------------
// File: DyanmicShaderLinkageFX11.cpp
//
// This sample shows a simple example of the Microsoft Direct3D's High-Level
// Shader Language (HLSL) using Dynamic Shader Linkage in conjunction
// with Effects 11.
//
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License (MIT).
//--------------------------------------------------------------------------------------
#include "DXUT.h"
#include "DXUTcamera.h"
#include "DXUTgui.h"
#include "DXUTsettingsDlg.h"
#include "SDKmisc.h"
#include "SDKMesh.h"
#include "resource.h"
#include <d3dx11effect.h>
#pragma warning( disable : 4100 )
using namespace DirectX;
// We show two ways of handling dynamic linkage binding.
// This #define selects between a single technique where
// bindings are done via effect variables and multiple
// techniques where the bindings are done with BindInterfaces
// in the technqiues.
#define USE_BIND_INTERFACES 0
//--------------------------------------------------------------------------------------
// Global variables
//--------------------------------------------------------------------------------------
CDXUTDialogResourceManager g_DialogResourceManager; // manager for shared resources of dialogs
CModelViewerCamera g_Camera; // A model viewing camera
CDXUTDirectionWidget g_LightControl;
CD3DSettingsDlg g_D3DSettingsDlg; // Device settings dialog
CDXUTDialog g_HUD; // manages the 3D
CDXUTDialog g_SampleUI; // dialog for sample specific controls
XMMATRIX g_mCenterMesh;
float g_fLightScale;
int g_nNumActiveLights;
int g_nActiveLight;
bool g_bShowHelp = false; // If true, it renders the UI control text
// Lighting Settings
bool g_bHemiAmbientLighting = false;
bool g_bDirectLighting = false;
bool g_bLightingOnly = false;
bool g_bWireFrame = false;
// Resources
CDXUTTextHelper* g_pTxtHelper = nullptr;
CDXUTSDKMesh g_Mesh11;
ID3D11Buffer* g_pVertexBuffer = nullptr;
ID3D11Buffer* g_pIndexBuffer = nullptr;
ID3D11InputLayout* g_pVertexLayout11 = nullptr;
ID3DX11Effect* g_pEffect = nullptr;
ID3DX11EffectTechnique* g_pTechnique = nullptr;
ID3DX11EffectMatrixVariable* g_pWorldViewProjection = nullptr;
ID3DX11EffectMatrixVariable* g_pWorld = nullptr;
ID3DX11EffectScalarVariable* g_pFillMode = nullptr;
ID3D11ShaderResourceView* g_pEnvironmentMapSRV = nullptr;
ID3DX11EffectShaderResourceVariable* g_pEnvironmentMapVar = nullptr;
// Shader Linkage Interface and Class variables
ID3DX11EffectInterfaceVariable* g_pAmbientLightIface = nullptr;
ID3DX11EffectInterfaceVariable* g_pDirectionalLightIface = nullptr;
ID3DX11EffectInterfaceVariable* g_pEnvironmentLightIface = nullptr;
ID3DX11EffectInterfaceVariable* g_pMaterialIface = nullptr;
ID3DX11EffectClassInstanceVariable* g_pAmbientLightClass = nullptr;
ID3DX11EffectVectorVariable* g_pAmbientLightColor = nullptr;
ID3DX11EffectScalarVariable* g_pAmbientLightEnable = nullptr;
ID3DX11EffectClassInstanceVariable* g_pHemiAmbientLightClass = nullptr;
ID3DX11EffectVectorVariable* g_pHemiAmbientLightColor = nullptr;
ID3DX11EffectScalarVariable* g_pHemiAmbientLightEnable = nullptr;
ID3DX11EffectVectorVariable* g_pHemiAmbientLightGroundColor = nullptr;
ID3DX11EffectVectorVariable* g_pHemiAmbientLightDirUp = nullptr;
ID3DX11EffectClassInstanceVariable* g_pDirectionalLightClass = nullptr;
ID3DX11EffectVectorVariable* g_pDirectionalLightColor = nullptr;
ID3DX11EffectScalarVariable* g_pDirectionalLightEnable = nullptr;
ID3DX11EffectVectorVariable* g_pDirectionalLightDir = nullptr;
ID3DX11EffectClassInstanceVariable* g_pEnvironmentLightClass = nullptr;
ID3DX11EffectVectorVariable* g_pEnvironmentLightColor = nullptr;
ID3DX11EffectScalarVariable* g_pEnvironmentLightEnable = nullptr;
ID3DX11EffectVectorVariable* g_pEyeDir = nullptr;
// Material Dynamic Permutation
enum E_MATERIAL_TYPES
{
MATERIAL_PLASTIC,
MATERIAL_PLASTIC_TEXTURED,
MATERIAL_PLASTIC_LIGHTING_ONLY,
MATERIAL_ROUGH,
MATERIAL_ROUGH_TEXTURED,
MATERIAL_ROUGH_LIGHTING_ONLY,
MATERIAL_TYPE_COUNT
};
char* g_pMaterialClassNames[ MATERIAL_TYPE_COUNT ] =
{
"g_plasticMaterial", // cPlasticMaterial
"g_plasticTexturedMaterial", // cPlasticTexturedMaterial
"g_plasticLightingOnlyMaterial", // cPlasticLightingOnlyMaterial
"g_roughMaterial", // cRoughMaterial
"g_roughTexturedMaterial", // cRoughTexturedMaterial
"g_roughLightingOnlyMaterial" // cRoughLightingOnlyMaterial
};
E_MATERIAL_TYPES g_iMaterial = MATERIAL_PLASTIC_TEXTURED;
struct MaterialVars
{
ID3DX11EffectTechnique* pTechnique;
ID3DX11EffectClassInstanceVariable* pClass;
ID3DX11EffectVectorVariable* pColor;
ID3DX11EffectScalarVariable* pSpecPower;
};
MaterialVars g_MaterialClasses[ MATERIAL_TYPE_COUNT ] = { nullptr };
//--------------------------------------------------------------------------------------
// UI control IDs
//--------------------------------------------------------------------------------------
#define IDC_TOGGLEFULLSCREEN 1
#define IDC_TOGGLEREF 3
#define IDC_CHANGEDEVICE 4
#define IDC_TOGGLEWIRE 5
// Lighting Controls
#define IDC_AMBIENT_LIGHTING_GROUP 6
#define IDC_LIGHT_CONST_AMBIENT 7
#define IDC_LIGHT_HEMI_AMBIENT 8
#define IDC_LIGHT_DIRECT 9
#define IDC_LIGHTING_ONLY 10
// Material Controls
#define IDC_MATERIAL_GROUP 11
#define IDC_MATERIAL_PLASTIC 12
#define IDC_MATERIAL_PLASTIC_TEXTURED 13
#define IDC_MATERIAL_ROUGH 14
#define IDC_MATERIAL_ROUGH_TEXTURED 15
//--------------------------------------------------------------------------------------
// Forward declarations
//--------------------------------------------------------------------------------------
bool CALLBACK ModifyDeviceSettings( DXUTDeviceSettings* pDeviceSettings, void* pUserContext );
void CALLBACK OnFrameMove( double fTime, float fElapsedTime, void* pUserContext );
LRESULT CALLBACK MsgProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam, bool* pbNoFurtherProcessing,
void* pUserContext );
void CALLBACK OnKeyboard( UINT nChar, bool bKeyDown, bool bAltDown, void* pUserContext );
void CALLBACK OnGUIEvent( UINT nEvent, int nControlID, CDXUTControl* pControl, void* pUserContext );
bool CALLBACK IsD3D11DeviceAcceptable( const CD3D11EnumAdapterInfo *AdapterInfo, UINT Output, const CD3D11EnumDeviceInfo *DeviceInfo,
DXGI_FORMAT BackBufferFormat, bool bWindowed, void* pUserContext );
HRESULT CALLBACK OnD3D11CreateDevice( ID3D11Device* pd3dDevice, const DXGI_SURFACE_DESC* pBackBufferSurfaceDesc,
void* pUserContext );
HRESULT CALLBACK OnD3D11ResizedSwapChain( ID3D11Device* pd3dDevice, IDXGISwapChain* pSwapChain,
const DXGI_SURFACE_DESC* pBackBufferSurfaceDesc, void* pUserContext );
void CALLBACK OnD3D11ReleasingSwapChain( void* pUserContext );
void CALLBACK OnD3D11DestroyDevice( void* pUserContext );
void CALLBACK OnD3D11FrameRender( ID3D11Device* pd3dDevice, ID3D11DeviceContext* pd3dImmediateContext, double fTime,
float fElapsedTime, void* pUserContext );
void InitApp();
void RenderText();
//--------------------------------------------------------------------------------------
// Entry point to the program. Initializes everything and goes into a message processing
// loop. Idle time is used to render the scene.
//--------------------------------------------------------------------------------------
int WINAPI wWinMain( _In_ HINSTANCE hInstance, _In_opt_ HINSTANCE hPrevInstance, _In_ LPWSTR lpCmdLine, _In_ int nCmdShow )
{
// Enable run-time memory check for debug builds.
#ifdef _DEBUG
_CrtSetDbgFlag( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF );
#endif
// DXUT will create and use the best device feature level available
// that is available on the system depending on which D3D callbacks are set below
// Set DXUT callbacks
DXUTSetCallbackDeviceChanging( ModifyDeviceSettings );
DXUTSetCallbackMsgProc( MsgProc );
DXUTSetCallbackKeyboard( OnKeyboard );
DXUTSetCallbackFrameMove( OnFrameMove );
DXUTSetCallbackD3D11DeviceAcceptable( IsD3D11DeviceAcceptable );
DXUTSetCallbackD3D11DeviceCreated( OnD3D11CreateDevice );
DXUTSetCallbackD3D11SwapChainResized( OnD3D11ResizedSwapChain );
DXUTSetCallbackD3D11FrameRender( OnD3D11FrameRender );
DXUTSetCallbackD3D11SwapChainReleasing( OnD3D11ReleasingSwapChain );
DXUTSetCallbackD3D11DeviceDestroyed( OnD3D11DestroyDevice );
InitApp();
DXUTInit( true, true, nullptr ); // Parse the command line, show msgboxes on error, no extra command line params
DXUTSetCursorSettings( true, true ); // Show the cursor and clip it when in full screen
DXUTCreateWindow( L"DynamicShaderLinkageFX11" );
DXUTCreateDevice(D3D_FEATURE_LEVEL_10_0, true, 800, 600 );
DXUTMainLoop(); // Enter into the DXUT render loop
return DXUTGetExitCode();
}
//--------------------------------------------------------------------------------------
// Initialize the app
//--------------------------------------------------------------------------------------
void InitApp()
{
static const XMVECTORF32 s_vLightDir = { -1.f, 1.f, -1.f, 0.f };
XMVECTOR vLightDir = XMVector3Normalize( s_vLightDir );
g_LightControl.SetLightDirection( vLightDir );
// Initialize dialogs
g_D3DSettingsDlg.Init( &g_DialogResourceManager );
g_HUD.Init( &g_DialogResourceManager );
g_SampleUI.Init( &g_DialogResourceManager );
g_HUD.SetCallback( OnGUIEvent ); int iY = 25;
g_HUD.AddButton( IDC_TOGGLEFULLSCREEN, L"Toggle full screen", 0, iY, 170, 22 );
g_HUD.AddButton( IDC_TOGGLEREF, L"Toggle REF (F3)", 0, iY += 26, 170, 22, VK_F3 );
g_HUD.AddButton( IDC_CHANGEDEVICE, L"Change device (F2)", 0, iY += 26, 170, 22, VK_F2 );
g_HUD.AddButton( IDC_TOGGLEWIRE, L"Toggle Wires (F4)", 0, iY += 26, 170, 22, VK_F4 );
// Material Controls
iY = 10;
g_SampleUI.AddRadioButton( IDC_MATERIAL_PLASTIC, IDC_MATERIAL_GROUP, L"Plastic", 0, iY += 26, 170, 22 );
g_SampleUI.AddRadioButton( IDC_MATERIAL_PLASTIC_TEXTURED, IDC_MATERIAL_GROUP, L"Plastic Textured", 0, iY += 26, 170, 22 );
g_SampleUI.AddRadioButton( IDC_MATERIAL_ROUGH, IDC_MATERIAL_GROUP, L"Rough", 0, iY += 26, 170, 22 );
g_SampleUI.AddRadioButton( IDC_MATERIAL_ROUGH_TEXTURED, IDC_MATERIAL_GROUP, L"Rough Textured", 0, iY += 26, 170, 22 );
auto pRadioButton = g_SampleUI.GetRadioButton( IDC_MATERIAL_PLASTIC_TEXTURED );
pRadioButton->SetChecked( true );
iY += 24;
// Lighting Controls
g_SampleUI.AddRadioButton( IDC_LIGHT_CONST_AMBIENT, IDC_AMBIENT_LIGHTING_GROUP, L"Constant Ambient", 0, iY += 26, 170, 22 );
g_SampleUI.AddRadioButton( IDC_LIGHT_HEMI_AMBIENT, IDC_AMBIENT_LIGHTING_GROUP, L"Hemi Ambient", 0, iY += 26, 170, 22 );
pRadioButton = g_SampleUI.GetRadioButton( IDC_LIGHT_CONST_AMBIENT );
pRadioButton->SetChecked( true );
g_SampleUI.AddCheckBox( IDC_LIGHT_DIRECT, L"Direct Lighting", 0, iY += 26, 170, 22, g_bDirectLighting );
g_SampleUI.AddCheckBox( IDC_LIGHTING_ONLY, L"Lighting Only", 0, iY += 26, 170, 22, g_bLightingOnly );
g_SampleUI.SetCallback( OnGUIEvent );
}
//--------------------------------------------------------------------------------------
// Called right before creating a D3D device, allowing the app to modify the device settings as needed
//--------------------------------------------------------------------------------------
bool CALLBACK ModifyDeviceSettings( DXUTDeviceSettings* pDeviceSettings, void* pUserContext )
{
return true;
}
//--------------------------------------------------------------------------------------
// Handle updates to the scene. This is called regardless of which D3D API is used
//--------------------------------------------------------------------------------------
void CALLBACK OnFrameMove( double fTime, float fElapsedTime, void* pUserContext )
{
// Update the camera's position based on user input
g_Camera.FrameMove( fElapsedTime );
}
//--------------------------------------------------------------------------------------
// Render the help and statistics text
//--------------------------------------------------------------------------------------
void RenderText()
{
UINT nBackBufferHeight = DXUTGetDXGIBackBufferSurfaceDesc()->Height;
g_pTxtHelper->Begin();
g_pTxtHelper->SetInsertionPos( 2, 0 );
g_pTxtHelper->SetForegroundColor( Colors::Yellow );
g_pTxtHelper->DrawTextLine( DXUTGetFrameStats( DXUTIsVsyncEnabled() ) );
g_pTxtHelper->DrawTextLine( DXUTGetDeviceStats() );
// Draw help
if( g_bShowHelp )
{
g_pTxtHelper->SetInsertionPos( 2, nBackBufferHeight - 20 * 6 );
g_pTxtHelper->SetForegroundColor( Colors::Orange );
g_pTxtHelper->DrawTextLine( L"Controls:" );
g_pTxtHelper->SetInsertionPos( 20, nBackBufferHeight - 20 * 5 );
g_pTxtHelper->DrawTextLine( L"Rotate model: Left mouse button\n"
L"Rotate light: Right mouse button\n"
L"Rotate camera: Middle mouse button\n"
L"Zoom camera: Mouse wheel scroll\n" );
g_pTxtHelper->SetInsertionPos( 350, nBackBufferHeight - 20 * 5 );
g_pTxtHelper->DrawTextLine( L"Hide help: F1\n"
L"Quit: ESC\n" );
}
else
{
g_pTxtHelper->SetForegroundColor( Colors::White );
g_pTxtHelper->DrawTextLine( L"Press F1 for help" );
}
g_pTxtHelper->End();
}
//--------------------------------------------------------------------------------------
// Handle messages to the application
//--------------------------------------------------------------------------------------
LRESULT CALLBACK MsgProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam, bool* pbNoFurtherProcessing,
void* pUserContext )
{
// Pass messages to dialog resource manager calls so GUI state is updated correctly
*pbNoFurtherProcessing = g_DialogResourceManager.MsgProc( hWnd, uMsg, wParam, lParam );
if( *pbNoFurtherProcessing )
return 0;
// Pass messages to settings dialog if its active
if( g_D3DSettingsDlg.IsActive() )
{
g_D3DSettingsDlg.MsgProc( hWnd, uMsg, wParam, lParam );
return 0;
}
// Give the dialogs a chance to handle the message first
*pbNoFurtherProcessing = g_HUD.MsgProc( hWnd, uMsg, wParam, lParam );
if( *pbNoFurtherProcessing )
return 0;
*pbNoFurtherProcessing = g_SampleUI.MsgProc( hWnd, uMsg, wParam, lParam );
if( *pbNoFurtherProcessing )
return 0;
g_LightControl.HandleMessages( hWnd, uMsg, wParam, lParam );
// Pass all remaining windows messages to camera so it can respond to user input
g_Camera.HandleMessages( hWnd, uMsg, wParam, lParam );
return 0;
}
//--------------------------------------------------------------------------------------
// Handle key presses
//--------------------------------------------------------------------------------------
void CALLBACK OnKeyboard( UINT nChar, bool bKeyDown, bool bAltDown, void* pUserContext )
{
if( bKeyDown )
{
switch( nChar )
{
case VK_F1:
g_bShowHelp = !g_bShowHelp; break;
}
}
}
//--------------------------------------------------------------------------------------
// Handles the GUI events
//--------------------------------------------------------------------------------------
void CALLBACK OnGUIEvent( UINT nEvent, int nControlID, CDXUTControl* pControl, void* pUserContext )
{
switch( nControlID )
{
case IDC_TOGGLEFULLSCREEN:
DXUTToggleFullScreen();
break;
case IDC_TOGGLEREF:
DXUTToggleREF();
break;
case IDC_CHANGEDEVICE:
g_D3DSettingsDlg.SetActive( !g_D3DSettingsDlg.IsActive() );
break;
case IDC_TOGGLEWIRE:
g_bWireFrame = !g_bWireFrame;
break;
// Lighting Controls
case IDC_LIGHT_CONST_AMBIENT:
g_bHemiAmbientLighting = false;
break;
case IDC_LIGHT_HEMI_AMBIENT:
g_bHemiAmbientLighting = true;
break;
case IDC_LIGHT_DIRECT:
g_bDirectLighting = !g_bDirectLighting;
break;
case IDC_LIGHTING_ONLY:
g_bLightingOnly = !g_bLightingOnly;
break;
// Material Controls
case IDC_MATERIAL_PLASTIC:
g_iMaterial = MATERIAL_PLASTIC;
break;
case IDC_MATERIAL_PLASTIC_TEXTURED:
g_iMaterial = MATERIAL_PLASTIC_TEXTURED;
break;
case IDC_MATERIAL_ROUGH:
g_iMaterial = MATERIAL_ROUGH;
break;
case IDC_MATERIAL_ROUGH_TEXTURED:
g_iMaterial = MATERIAL_ROUGH_TEXTURED;
break;
}
}
//--------------------------------------------------------------------------------------
// Reject any D3D devices that aren't acceptable by returning false
//--------------------------------------------------------------------------------------
bool CALLBACK IsD3D11DeviceAcceptable( const CD3D11EnumAdapterInfo *AdapterInfo, UINT Output, const CD3D11EnumDeviceInfo *DeviceInfo,
DXGI_FORMAT BackBufferFormat, bool bWindowed, void* pUserContext )
{
return true;
}
//--------------------------------------------------------------------------------------
// Create any D3D resources that aren't dependant on the back buffer
//--------------------------------------------------------------------------------------
HRESULT CALLBACK OnD3D11CreateDevice( ID3D11Device* pd3dDevice, const DXGI_SURFACE_DESC* pBackBufferSurfaceDesc,
void* pUserContext )
{
HRESULT hr = S_OK;
auto pd3dImmediateContext = DXUTGetD3D11DeviceContext();
V_RETURN( g_DialogResourceManager.OnD3D11CreateDevice( pd3dDevice, pd3dImmediateContext ) );
V_RETURN( g_D3DSettingsDlg.OnD3D11CreateDevice( pd3dDevice ) );
g_pTxtHelper = new CDXUTTextHelper( pd3dDevice, pd3dImmediateContext, &g_DialogResourceManager, 15 );
XMFLOAT3 vCenter( 0.25767413f, -28.503521f, 111.00689f );
FLOAT fObjectRadius = 378.15607f;
g_mCenterMesh = XMMatrixTranslation( -vCenter.x, -vCenter.y, -vCenter.z );
XMMATRIX m;
m = XMMatrixRotationY( XM_PI );
g_mCenterMesh *= m;
m = XMMatrixRotationX( XM_PI / 2.0f );
g_mCenterMesh *= m;
// Init the UI widget for directional lighting
V_RETURN( CDXUTDirectionWidget::StaticOnD3D11CreateDevice( pd3dDevice, pd3dImmediateContext ) );
g_LightControl.SetRadius( fObjectRadius );
// Compile and create the effect.
DWORD dwShaderFlags = D3DCOMPILE_ENABLE_STRICTNESS;
#ifdef _DEBUG
// Set the D3DCOMPILE_DEBUG flag to embed debug information in the shaders.
// Setting this flag improves the shader debugging experience, but still allows
// the shaders to be optimized and to run exactly the way they will run in
// the release configuration of this program.
dwShaderFlags |= D3DCOMPILE_DEBUG;
// Disable optimizations to further improve shader debugging
dwShaderFlags |= D3DCOMPILE_SKIP_OPTIMIZATION;
#endif
#if D3D_COMPILER_VERSION >= 46
WCHAR str[MAX_PATH];
V_RETURN( DXUTFindDXSDKMediaFileCch( str, MAX_PATH, L"DynamicShaderLinkageFX11.fx" ) );
ID3DBlob* pErrorBlob = nullptr;
hr = D3DX11CompileEffectFromFile( str, nullptr, D3D_COMPILE_STANDARD_FILE_INCLUDE, dwShaderFlags, D3DCOMPILE_EFFECT_ALLOW_SLOW_OPS, pd3dDevice, &g_pEffect, &pErrorBlob );
if ( pErrorBlob )
{
OutputDebugStringA( reinterpret_cast<const char*>( pErrorBlob->GetBufferPointer() ) );
pErrorBlob->Release();
}
if( FAILED(hr) )
{
return hr;
}
#else
ID3DBlob* pEffectBuffer = nullptr;
V_RETURN( DXUTCompileFromFile( L"DynamicShaderLinkageFX11.fx", nullptr, "none", "fx_5_0", dwShaderFlags, D3DCOMPILE_EFFECT_ALLOW_SLOW_OPS, &pEffectBuffer ) );
hr = D3DX11CreateEffectFromMemory( pEffectBuffer->GetBufferPointer(), pEffectBuffer->GetBufferSize(), 0, pd3dDevice, &g_pEffect );
SAFE_RELEASE( pEffectBuffer );
if ( FAILED(hr) )
return hr;
#endif
// Get the light Class Interfaces for setting values
// and as potential binding sources.
g_pAmbientLightClass = g_pEffect->GetVariableByName( "g_ambientLight" )->AsClassInstance();
g_pAmbientLightColor = g_pAmbientLightClass->GetMemberByName( "m_vLightColor" )->AsVector();
g_pAmbientLightEnable = g_pAmbientLightClass->GetMemberByName( "m_bEnable" )->AsScalar();
g_pHemiAmbientLightClass = g_pEffect->GetVariableByName( "g_hemiAmbientLight" )->AsClassInstance();
g_pHemiAmbientLightColor = g_pHemiAmbientLightClass->GetMemberByName( "m_vLightColor" )->AsVector();
g_pHemiAmbientLightEnable = g_pHemiAmbientLightClass->GetMemberByName( "m_bEnable" )->AsScalar();
g_pHemiAmbientLightGroundColor = g_pHemiAmbientLightClass->GetMemberByName( "m_vGroundColor" )->AsVector();
g_pHemiAmbientLightDirUp = g_pHemiAmbientLightClass->GetMemberByName( "m_vDirUp" )->AsVector();
g_pDirectionalLightClass = g_pEffect->GetVariableByName( "g_directionalLight")->AsClassInstance();
g_pDirectionalLightColor = g_pDirectionalLightClass->GetMemberByName( "m_vLightColor" )->AsVector();
g_pDirectionalLightEnable = g_pDirectionalLightClass->GetMemberByName( "m_bEnable" )->AsScalar();
g_pDirectionalLightDir = g_pDirectionalLightClass->GetMemberByName( "m_vLightDir" )->AsVector();
g_pEnvironmentLightClass = g_pEffect->GetVariableByName( "g_environmentLight")->AsClassInstance();
g_pEnvironmentLightColor = g_pEnvironmentLightClass->GetMemberByName( "m_vLightColor" )->AsVector();
g_pEnvironmentLightEnable = g_pEnvironmentLightClass->GetMemberByName( "m_bEnable" )->AsScalar();
g_pEyeDir = g_pEffect->GetVariableByName( "g_vEyeDir" )->AsVector();
// Acquire the material Class Instances for all possible material settings
for( UINT i=0; i < MATERIAL_TYPE_COUNT; i++)
{
char pTechName[50];
sprintf_s( pTechName, sizeof(pTechName),
"FeatureLevel11_%s",
g_pMaterialClassNames[ i ] );
g_MaterialClasses[i].pTechnique = g_pEffect->GetTechniqueByName( pTechName );
g_MaterialClasses[i].pClass = g_pEffect->GetVariableByName( g_pMaterialClassNames[i] )->AsClassInstance();
g_MaterialClasses[i].pColor = g_MaterialClasses[i].pClass->GetMemberByName( "m_vColor" )->AsVector();
g_MaterialClasses[i].pSpecPower = g_MaterialClasses[i].pClass->GetMemberByName( "m_iSpecPower" )->AsScalar();
}
// Select which technique to use based on the feature level we acquired
D3D_FEATURE_LEVEL supportedFeatureLevel = DXUTGetD3D11DeviceFeatureLevel();
if (supportedFeatureLevel >= D3D_FEATURE_LEVEL_11_0)
{
// We are going to use Dynamic shader linkage with SM5 so we need to look up interface and class instance variables
// Get the abstract class interfaces so we can dynamically permute and assign linkages
g_pAmbientLightIface = g_pEffect->GetVariableByName( "g_abstractAmbientLighting" )->AsInterface();
g_pDirectionalLightIface = g_pEffect->GetVariableByName( "g_abstractDirectLighting" )->AsInterface();
g_pEnvironmentLightIface = g_pEffect->GetVariableByName( "g_abstractEnvironmentLighting" )->AsInterface();
g_pMaterialIface = g_pEffect->GetVariableByName( "g_abstractMaterial" )->AsInterface();
g_pTechnique = g_pEffect->GetTechniqueByName( "FeatureLevel11" );
}
else // Lower feature levels than 11 have no support for Dynamic Shader Linkage - need to use a statically specialized shaders
{
LPCSTR pTechniqueName;
g_pAmbientLightIface = nullptr;
g_pDirectionalLightIface = nullptr;
g_pEnvironmentLightIface = nullptr;
g_pMaterialIface = nullptr;
switch( supportedFeatureLevel )
{
case D3D_FEATURE_LEVEL_10_1:
pTechniqueName = "FeatureLevel10_1";
break;
case D3D_FEATURE_LEVEL_10_0:
pTechniqueName = "FeatureLevel10";
break;
default:
return E_FAIL;
}
g_pTechnique = g_pEffect->GetTechniqueByName( pTechniqueName );
}
// Create our vertex input layout
const D3D11_INPUT_ELEMENT_DESC layout[] =
{
{ "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 },
{ "NORMAL", 0, DXGI_FORMAT_R10G10B10A2_UNORM, 0, 12, D3D11_INPUT_PER_VERTEX_DATA, 0 },
{ "TEXCOORD", 0, DXGI_FORMAT_R16G16_FLOAT, 0, 16, D3D11_INPUT_PER_VERTEX_DATA, 0 },
{ "TANGENT", 0, DXGI_FORMAT_R10G10B10A2_UNORM, 0, 20, D3D11_INPUT_PER_VERTEX_DATA, 0 },
{ "BINORMAL", 0, DXGI_FORMAT_R10G10B10A2_UNORM, 0, 24, D3D11_INPUT_PER_VERTEX_DATA, 0 }
};
D3DX11_PASS_SHADER_DESC VsPassDesc;
D3DX11_EFFECT_SHADER_DESC VsDesc;
V_RETURN( g_pTechnique->GetPassByIndex(0)->GetVertexShaderDesc(&VsPassDesc) );
V_RETURN( VsPassDesc.pShaderVariable->GetShaderDesc(VsPassDesc.ShaderIndex, &VsDesc) );
V_RETURN( pd3dDevice->CreateInputLayout( layout, ARRAYSIZE( layout ),
VsDesc.pBytecode,
VsDesc.BytecodeLength,
&g_pVertexLayout11 ) );
DXUT_SetDebugName( g_pVertexLayout11, "Primary" );
// Load the mesh
V_RETURN( g_Mesh11.Create( pd3dDevice, L"Squid\\squid.sdkmesh", false ) );
g_pWorldViewProjection = g_pEffect->GetVariableByName( "g_mWorldViewProjection" )->AsMatrix();
g_pWorld = g_pEffect->GetVariableByName( "g_mWorld" )->AsMatrix();
// Load a HDR Environment for reflections
V_RETURN( DXUTCreateShaderResourceViewFromFile( pd3dDevice, L"Light Probes\\uffizi_cross.dds", &g_pEnvironmentMapSRV ));
g_pEnvironmentMapVar = g_pEffect->GetVariableByName( "g_txEnvironmentMap" )->AsShaderResource();
g_pEnvironmentMapVar->SetResource( g_pEnvironmentMapSRV );
// Setup the camera's view parameters
static const XMVECTORF32 s_vecEye = { 0.0f, 0.0f, -50.0f, 0.f };
g_Camera.SetViewParams( s_vecEye, g_XMZero );
g_Camera.SetRadius( fObjectRadius , fObjectRadius , fObjectRadius );
// Find Rasterizer State Object index for WireFrame / Solid rendering
g_pFillMode = g_pEffect->GetVariableByName( "g_fillMode" )->AsScalar();
return hr;
}
//--------------------------------------------------------------------------------------
// Create any D3D11 resources that depend on the back buffer
//--------------------------------------------------------------------------------------
HRESULT CALLBACK OnD3D11ResizedSwapChain( ID3D11Device* pd3dDevice, IDXGISwapChain* pSwapChain,
const DXGI_SURFACE_DESC* pBackBufferSurfaceDesc, void* pUserContext )
{
HRESULT hr = S_OK;
V_RETURN( g_DialogResourceManager.OnD3D11ResizedSwapChain( pd3dDevice, pBackBufferSurfaceDesc ) );
V_RETURN( g_D3DSettingsDlg.OnD3D11ResizedSwapChain( pd3dDevice, pBackBufferSurfaceDesc ) );
// Setup the camera's projection parameters
float fAspectRatio = pBackBufferSurfaceDesc->Width / ( FLOAT )pBackBufferSurfaceDesc->Height;
g_Camera.SetProjParams( XM_PI / 4, fAspectRatio, 2.0f, 4000.0f );
g_Camera.SetWindow( pBackBufferSurfaceDesc->Width, pBackBufferSurfaceDesc->Height );
g_Camera.SetButtonMasks( MOUSE_LEFT_BUTTON, MOUSE_WHEEL, MOUSE_MIDDLE_BUTTON );
g_HUD.SetLocation( pBackBufferSurfaceDesc->Width - 170, 0 );
g_HUD.SetSize( 170, 170 );
g_SampleUI.SetLocation( pBackBufferSurfaceDesc->Width - 170, pBackBufferSurfaceDesc->Height - 300 );
g_SampleUI.SetSize( 170, 300 );
return hr;
}
//--------------------------------------------------------------------------------------
// Render the scene using the D3D11 device
//--------------------------------------------------------------------------------------
void CALLBACK OnD3D11FrameRender( ID3D11Device* pd3dDevice, ID3D11DeviceContext* pd3dImmediateContext, double fTime,
float fElapsedTime, void* pUserContext )
{
HRESULT hr;
// If the settings dialog is being shown, then render it instead of rendering the app's scene
if( g_D3DSettingsDlg.IsActive() )
{
g_D3DSettingsDlg.OnRender( fElapsedTime );
return;
}
// Clear the render target and depth stencil
auto pRTV = DXUTGetD3D11RenderTargetView();
pd3dImmediateContext->ClearRenderTargetView( pRTV, Colors::MidnightBlue );
auto pDSV = DXUTGetD3D11DepthStencilView();
pd3dImmediateContext->ClearDepthStencilView( pDSV, D3D11_CLEAR_DEPTH, 1.0, 0 );
// Get the projection & view matrix from the camera class
XMMATRIX mWorld = g_Camera.GetWorldMatrix();
XMMATRIX mProj = g_Camera.GetProjMatrix();
XMMATRIX mView = g_Camera.GetViewMatrix();
// Get the light direction
XMVECTOR vLightDir = g_LightControl.GetLightDirection();
// Render the light arrow so the user can visually see the light dir
V( g_LightControl.OnRender( Colors::Yellow, mView, mProj, g_Camera.GetEyePt() ) );
// Ambient Light
static const XMVECTORF32 s_vLightColorA = { 0.1f, 0.1f, 0.1f, 1.0f };
g_pAmbientLightColor->SetFloatVector( s_vLightColorA );
g_pAmbientLightEnable->SetBool(true);
// Hemi Ambient Light
static const XMVECTORF32 s_vLightColorH1 = { 0.3f, 0.3f, 0.4f, 1.0f };
g_pHemiAmbientLightColor->SetFloatVector( s_vLightColorH1 );
g_pHemiAmbientLightEnable->SetBool(true);
XMFLOAT4 vLightGrndClr( 0.05f, 0.05f, 0.05f, 1.f );
g_pHemiAmbientLightGroundColor->SetFloatVector( reinterpret_cast<float*>( &vLightGrndClr ) );
XMFLOAT4 vVec(0.0f, 1.0f, 0.0f, 1.0f);
g_pHemiAmbientLightDirUp->SetFloatVector( reinterpret_cast<float*>( &vVec ) );
// Directional Light
g_pDirectionalLightColor->SetFloatVector( Colors::White );
g_pDirectionalLightEnable->SetBool(true);
XMFLOAT4 tmp;
XMStoreFloat4( &tmp, vLightDir );
tmp.w = 1.f;
g_pDirectionalLightDir->SetFloatVector( reinterpret_cast<float*>( &tmp ) );
// Environment Light - color comes from the texture
g_pEnvironmentLightColor->SetFloatVector( Colors::Black );
g_pEnvironmentLightEnable->SetBool(true);
// Setup the Eye based on the DXUT camera
XMVECTOR vEyePt = g_Camera.GetEyePt();
XMVECTOR vDir = g_Camera.GetLookAtPt() - vEyePt;
XMStoreFloat4( &tmp, vDir );
tmp.w = 1.f;
g_pEyeDir->SetFloatVector( reinterpret_cast<float*>( &tmp ) );
//Get the mesh
//IA setup
pd3dImmediateContext->IASetInputLayout( g_pVertexLayout11 );
UINT Strides[1];
UINT Offsets[1];
ID3D11Buffer* pVB[1];
pVB[0] = g_Mesh11.GetVB11( 0, 0 );
Strides[0] = ( UINT )g_Mesh11.GetVertexStride( 0, 0 );
Offsets[0] = 0;
pd3dImmediateContext->IASetVertexBuffers( 0, 1, pVB, Strides, Offsets );
pd3dImmediateContext->IASetIndexBuffer( g_Mesh11.GetIB11( 0 ), g_Mesh11.GetIBFormat11( 0 ), 0 );
// Set the per object constant data
XMMATRIX mWorldViewProjection = mWorld * mView * mProj;
// VS Per object
XMFLOAT4X4 tmp4x4;
XMStoreFloat4x4( &tmp4x4, mWorldViewProjection );
g_pWorldViewProjection->SetMatrix( reinterpret_cast<float*>( &tmp4x4 ) );
XMStoreFloat4x4( &tmp4x4, mWorld );
g_pWorld->SetMatrix( reinterpret_cast<float*>( &tmp4x4 ) );
// Setup the Shader Linkage based on the user settings for Lighting
ID3DX11EffectClassInstanceVariable* pLightClassVar;
// Ambient Lighting First - Constant or Hemi?
if ( g_bHemiAmbientLighting )
{
pLightClassVar = g_pHemiAmbientLightClass;
}
else
{
pLightClassVar = g_pAmbientLightClass;
}
if (g_pAmbientLightIface)
{
g_pAmbientLightIface->SetClassInstance(pLightClassVar);
}
// Direct Light - None or Directional
if (g_bDirectLighting)
{
pLightClassVar = g_pDirectionalLightClass;
}
else
{
// Disable ALL Direct Lighting
pLightClassVar = g_pAmbientLightClass;
}
if (g_pDirectionalLightIface)
{
g_pDirectionalLightIface->SetClassInstance(pLightClassVar);
}
// Setup the selected material class instance
E_MATERIAL_TYPES iMaterialTech = g_iMaterial;
switch( g_iMaterial )
{
case MATERIAL_PLASTIC:
case MATERIAL_PLASTIC_TEXTURED:
// Bind the Environment light for reflections
pLightClassVar = g_pEnvironmentLightClass;
if (g_bLightingOnly)
{
iMaterialTech = MATERIAL_PLASTIC_LIGHTING_ONLY;
}
break;
case MATERIAL_ROUGH:
case MATERIAL_ROUGH_TEXTURED:
// UnBind the Environment light
pLightClassVar = g_pAmbientLightClass;
if (g_bLightingOnly)
{
iMaterialTech = MATERIAL_ROUGH_LIGHTING_ONLY;
}
break;
}
if (g_pEnvironmentLightIface)
{
g_pEnvironmentLightIface->SetClassInstance(pLightClassVar);
}
ID3DX11EffectTechnique* pTechnique = g_pTechnique;
if (g_pMaterialIface)
{
#if USE_BIND_INTERFACES
// We're using the techniques with pre-bound materials,
// so select the appropriate technique.
pTechnique = g_MaterialClasses[ iMaterialTech ].pTechnique;
#else
// We're using a single technique and need to explicitly
// bind a concrete material instance.
g_pMaterialIface->SetClassInstance( g_MaterialClasses[ iMaterialTech ].pClass );
#endif
}
// PS Per Prim
// Shiny Plastic
XMFLOAT3 clr1(1, 0, 0.5f);
g_MaterialClasses[MATERIAL_PLASTIC].pColor->SetFloatVector( reinterpret_cast<float*>( &clr1 ) );
g_MaterialClasses[MATERIAL_PLASTIC].pSpecPower->SetInt(255);
// Shiny Plastic with Textures
XMFLOAT3 clr2(1, 0, 0.5f);
g_MaterialClasses[MATERIAL_PLASTIC_TEXTURED].pColor->SetFloatVector( reinterpret_cast<float*>( &clr2 ) );
g_MaterialClasses[MATERIAL_PLASTIC_TEXTURED].pSpecPower->SetInt(128);
// Lighting Only Plastic
XMFLOAT3 clr3(1, 1, 1);
g_MaterialClasses[MATERIAL_PLASTIC_LIGHTING_ONLY].pColor->SetFloatVector( reinterpret_cast<float*>( &clr3 ) );
g_MaterialClasses[MATERIAL_PLASTIC_LIGHTING_ONLY].pSpecPower->SetInt(128);
// Rough Material
XMFLOAT3 clr4(0, 0.5f, 1);
g_MaterialClasses[MATERIAL_ROUGH].pColor->SetFloatVector( reinterpret_cast<float*>( &clr4 ) );
g_MaterialClasses[MATERIAL_ROUGH].pSpecPower->SetInt(6);
// Rough Material with Textures
XMFLOAT3 clr5(0, 0.5f, 1);
g_MaterialClasses[MATERIAL_ROUGH_TEXTURED].pColor->SetFloatVector( reinterpret_cast<float*>( &clr5 ) );
g_MaterialClasses[MATERIAL_ROUGH_TEXTURED].pSpecPower->SetInt(6);
// Lighting Only Rough
XMFLOAT3 clr6(1, 1, 1);
g_MaterialClasses[MATERIAL_ROUGH_LIGHTING_ONLY].pColor->SetFloatVector( reinterpret_cast<float*>( &clr6 ) );
g_MaterialClasses[MATERIAL_ROUGH_LIGHTING_ONLY].pSpecPower->SetInt(6);
if (g_bWireFrame)
g_pFillMode->SetInt(1);
else
g_pFillMode->SetInt(0);
// Apply the technique to update state.
pTechnique->GetPassByIndex(0)->Apply(0, pd3dImmediateContext);
//Render
g_Mesh11.Render( pd3dImmediateContext, 0, 1, INVALID_SAMPLER_SLOT);
// Tell the UI items to render
DXUT_BeginPerfEvent( DXUT_PERFEVENTCOLOR, L"HUD / Stats" );
g_HUD.OnRender( fElapsedTime );
g_SampleUI.OnRender( fElapsedTime );
RenderText();
DXUT_EndPerfEvent();
}
//--------------------------------------------------------------------------------------
// Release D3D11 resources created in OnD3D11ResizedSwapChain
//--------------------------------------------------------------------------------------
void CALLBACK OnD3D11ReleasingSwapChain( void* pUserContext )
{
g_DialogResourceManager.OnD3D11ReleasingSwapChain();
}
//--------------------------------------------------------------------------------------
// Release D3D11 resources created in OnD3D11CreateDevice
//--------------------------------------------------------------------------------------
void CALLBACK OnD3D11DestroyDevice( void* pUserContext )
{
g_DialogResourceManager.OnD3D11DestroyDevice();
g_D3DSettingsDlg.OnD3D11DestroyDevice();
CDXUTDirectionWidget::StaticOnD3D11DestroyDevice();
DXUTGetGlobalResourceCache().OnDestroyDevice();
SAFE_DELETE( g_pTxtHelper );
g_Mesh11.Destroy();
SAFE_RELEASE( g_pEffect );
SAFE_RELEASE( g_pVertexLayout11 );
SAFE_RELEASE( g_pVertexBuffer );
SAFE_RELEASE( g_pIndexBuffer );
SAFE_RELEASE( g_pEnvironmentMapSRV );
}
| 42.690608 | 175 | 0.629455 | [
"mesh",
"render",
"object",
"model",
"3d",
"solid"
] |
602f95e0567470e1295966727656eac12d5464a6 | 22,747 | cc | C++ | HolmesBot.cc | adamlerer/Hanabi | 5614c8c9eb96f974b907d15f24f5171f16fefa55 | [
"MIT"
] | 37 | 2015-06-16T02:22:21.000Z | 2022-03-26T07:09:50.000Z | HolmesBot.cc | adamlerer/Hanabi | 5614c8c9eb96f974b907d15f24f5171f16fefa55 | [
"MIT"
] | 1 | 2019-05-16T02:08:41.000Z | 2019-05-16T02:08:41.000Z | HolmesBot.cc | adamlerer/Hanabi | 5614c8c9eb96f974b907d15f24f5171f16fefa55 | [
"MIT"
] | 4 | 2018-07-24T21:54:30.000Z | 2021-12-21T21:11:01.000Z |
#include <algorithm>
#include <cassert>
#include <cstdlib>
#include <cstring>
#include "Hanabi.h"
#include "HolmesBot.h"
using namespace Hanabi;
static const bool UseMulligans = true;
CardKnowledge::CardKnowledge()
{
color_ = -1;
value_ = -1;
std::memset(cantBe_, '\0', sizeof cantBe_);
isPlayable = false;
isValuable = false;
isWorthless = false;
}
bool CardKnowledge::mustBe(Hanabi::Color color) const { return (this->color_ == color); }
bool CardKnowledge::mustBe(Hanabi::Value value) const { return (this->value_ == value); }
bool CardKnowledge::cannotBe(Hanabi::Card card) const { return cantBe_[card.color][card.value]; }
bool CardKnowledge::cannotBe(Hanabi::Color color) const
{
if (this->color_ != -1) return (this->color_ != color);
for (int v = 1; v <= 5; ++v) {
if (!cantBe_[color][v]) return false;
}
return true;
}
bool CardKnowledge::cannotBe(Hanabi::Value value) const
{
if (this->value_ != -1) return (this->value_ != value);
for (Color k = RED; k <= BLUE; ++k) {
if (!cantBe_[k][value]) return false;
}
return true;
}
int CardKnowledge::color() const { return this->color_; }
int CardKnowledge::value() const { return this->value_; }
void CardKnowledge::setMustBe(Hanabi::Color color)
{
for (Color k = RED; k <= BLUE; ++k) {
if (k != color) setCannotBe(k);
}
color_ = color;
}
void CardKnowledge::setMustBe(Hanabi::Value value)
{
for (int v = 1; v <= 5; ++v) {
if (v != value) setCannotBe(Value(v));
}
value_ = value;
}
void CardKnowledge::setCannotBe(Hanabi::Color color)
{
for (int v = 1; v <= 5; ++v) {
cantBe_[color][v] = true;
}
}
void CardKnowledge::setCannotBe(Hanabi::Value value)
{
for (Color k = RED; k <= BLUE; ++k) {
cantBe_[k][value] = true;
}
}
void CardKnowledge::update(const Server &server, const HolmesBot &bot)
{
int color = this->color_;
int value = this->value_;
repeat_loop:
if (color == -1) {
for (Color k = RED; k <= BLUE; ++k) {
if (this->cannotBe(k)) continue;
else if (color == -1) color = k;
else { color = -1; break; }
}
if (color != -1) this->setMustBe(Color(color));
}
if (value == -1) {
for (int v = 1; v <= 5; ++v) {
if (this->cannotBe(Value(v))) continue;
else if (value == -1) value = v;
else { value = -1; break; }
}
if (value != -1) this->setMustBe(Value(value));
}
// this is the complicated part
assert(color == this->color_);
assert(value == this->value_);
/* See if we can identify the card based on what we know
* about its properties. */
if (value == -1 || color == -1) {
bool restart = false;
for (Color k = RED; k <= BLUE; ++k) {
for (int v = 1; v <= 5; ++v) {
if (this->cantBe_[k][v]) continue;
const int total = (v == 1 ? 3 : (v == 5 ? 1 : 2));
const int played = bot.playedCount_[k][v];
const int held = bot.locatedCount_[k][v];
assert(played+held <= total);
if ((played+held == total) ||
(isValuable && !bot.isValuable(server, Card(k,v))) ||
(isPlayable && !server.pileOf(k).nextValueIs(v)) ||
(isWorthless && !server.pileOf(k).contains(v)))
{
this->cantBe_[k][v] = true;
restart = true;
}
}
}
if (restart) goto repeat_loop;
}
/* If the card is worthless, it's not valuable or playable. */
if (this->isWorthless) return;
if (!this->isPlayable && !this->isValuable) {
for (Color k = RED; k <= BLUE; ++k) {
for (int v = 1; v <= 5; ++v) {
if (this->cantBe_[k][v]) continue;
if (!server.pileOf(k).contains(v)) {
goto mightBeUseful;
}
}
}
this->isWorthless = true;
return;
mightBeUseful:;
}
/* Valuableness and playableness are orthogonal. */
assert(!this->isWorthless);
if (!this->isValuable) {
for (Color k = RED; k <= BLUE; ++k) {
for (int v = 1; v <= 5; ++v) {
if (this->cantBe_[k][v]) continue;
if (!bot.isValuable(server, Card(k,v))) {
goto mightNotBeValuable;
}
}
}
this->isValuable = true;
mightNotBeValuable:;
}
if (!this->isPlayable) {
for (Color k = RED; k <= BLUE; ++k) {
for (int v = 1; v <= 5; ++v) {
if (this->cantBe_[k][v]) continue;
if (!server.pileOf(k).nextValueIs(v)) {
goto mightBeUnplayable;
}
}
}
this->isPlayable = true;
mightBeUnplayable:;
}
}
Hint::Hint()
{
information_content = -1;
color = -1;
value = -1;
to = -1;
}
void Hint::give(Server &server)
{
assert(to != -1);
if (color != -1) {
server.pleaseGiveColorHint(to, Color(color));
} else if (value != -1) {
server.pleaseGiveValueHint(to, Value(value));
} else {
assert(false);
}
}
HolmesBot::HolmesBot(int index, int numPlayers, int handSize)
{
me_ = index;
handKnowledge_.resize(numPlayers);
for (int i=0; i < numPlayers; ++i) {
handKnowledge_[i].resize(handSize);
}
std::memset(playedCount_, '\0', sizeof playedCount_);
}
bool HolmesBot::isValuable(const Server &server, Card card) const
{
/* A card which has not yet been played, and which is the
* last of its kind, is valuable. */
if (server.pileOf(card.color).contains(card.value)) return false;
return (playedCount_[card.color][card.value] == card.count()-1);
}
bool HolmesBot::couldBeValuable(const Server &server, const CardKnowledge &knol, int value) const
{
if (value < 1 || 5 < value) return false;
for (Color k = RED; k <= BLUE; ++k) {
Card card(k, value);
if (knol.cannotBe(card)) continue;
if (this->isValuable(server, card))
return true;
}
return false;
}
void HolmesBot::invalidateKnol(int player_index, int card_index)
{
/* The other cards are shifted down and a new one drawn at the end. */
std::vector<CardKnowledge> &vec = handKnowledge_[player_index];
for (int i = card_index; i+1 < vec.size(); ++i) {
vec[i] = vec[i+1];
}
vec.back() = CardKnowledge();
}
void HolmesBot::seePublicCard(const Card &card)
{
int &entry = this->playedCount_[card.color][card.value];
entry += 1;
assert(1 <= entry && entry <= card.count());
}
bool HolmesBot::updateLocatedCount(const Hanabi::Server& server)
{
int newCount[Hanabi::NUMCOLORS][5+1] = {};
for (int p=0; p < handKnowledge_.size(); ++p) {
const int numCards = server.sizeOfHandOfPlayer(p);
for (int i=0; i < numCards; ++i) {
CardKnowledge &knol = handKnowledge_[p][i];
int k = knol.color();
if (k != -1) {
int v = knol.value();
if (v != -1) {
newCount[k][v] += 1;
}
}
}
}
if (std::memcmp(this->locatedCount_, newCount, sizeof newCount) != 0) {
std::memcpy(this->locatedCount_, newCount, sizeof newCount);
return true; /* there was a change */
}
return false;
}
void HolmesBot::pleaseObserveBeforeMove(const Server &server)
{
assert(server.whoAmI() == me_);
myHandSize_ = server.sizeOfHandOfPlayer(me_);
for (int p=0; p < handKnowledge_.size(); ++p) {
const int numCards = server.sizeOfHandOfPlayer(p);
assert(handKnowledge_[p].size() >= numCards);
handKnowledge_[p].resize(numCards);
}
std::memset(this->locatedCount_, '\0', sizeof this->locatedCount_);
this->updateLocatedCount(server);
do {
for (int p=0; p < handKnowledge_.size(); ++p) {
const int numCards = server.sizeOfHandOfPlayer(p);
for (int i=0; i < numCards; ++i) {
CardKnowledge &knol = handKnowledge_[p][i];
knol.update(server, *this);
}
}
} while (this->updateLocatedCount(server));
lowestPlayableValue_ = 6;
for (Color color = RED; color <= BLUE; ++color) {
lowestPlayableValue_ = std::min(lowestPlayableValue_, server.pileOf(color).size()+1);
}
}
void HolmesBot::pleaseObserveBeforeDiscard(const Hanabi::Server &server, int from, int card_index)
{
assert(server.whoAmI() == me_);
this->seePublicCard(server.activeCard());
this->invalidateKnol(from, card_index);
}
void HolmesBot::pleaseObserveBeforePlay(const Hanabi::Server &server, int from, int card_index)
{
assert(server.whoAmI() == me_);
Card card = server.activeCard();
assert(!handKnowledge_[from][card_index].isWorthless);
if (handKnowledge_[from][card_index].isValuable) {
/* We weren't wrong about this card being valuable, were we? */
assert(this->isValuable(server, card));
}
if (server.pileOf(card.color).nextValueIs(card.value)) {
/* This card is getting played, not discarded. */
if (!this->isValuable(server, card)) {
this->wipeOutPlayables(card);
}
}
this->seePublicCard(card);
this->invalidateKnol(from, card_index);
}
void HolmesBot::pleaseObserveColorHint(const Hanabi::Server &server, int /*from*/, int to, Color color, CardIndices card_indices)
{
assert(server.whoAmI() == me_);
/* Someone has given me a color hint. Using HolmesBot's strategy,
* this means that all the named cards are playable; except for
* any whose values I already know, which I can deduce for myself
* whether they're playable or not. */
Pile pile = server.pileOf(color);
int value = pile.size() + 1;
assert(1 <= value && value <= 5);
for (int i=0; i < server.sizeOfHandOfPlayer(to); ++i) {
CardKnowledge &knol = handKnowledge_[to][i];
if (card_indices.contains(i)) {
knol.setMustBe(color);
if (knol.value() == -1 && !knol.isWorthless) {
knol.setMustBe(Value(value));
}
} else {
knol.setCannotBe(color);
}
}
}
int HolmesBot::nextDiscardIndex(const Hanabi::Server& server, int to) const
{
const int numCards = server.sizeOfHandOfPlayer(to);
for (int i=0; i < numCards; ++i) {
if (handKnowledge_[to][i].isPlayable) return -1;
if (handKnowledge_[to][i].isWorthless) return -1;
}
for (int i=0; i < numCards; ++i) {
if (!handKnowledge_[to][i].isValuable) return i;
}
return -1;
}
void HolmesBot::pleaseObserveValueHint(const Hanabi::Server &server, int from, int to, Value value, CardIndices card_indices)
{
assert(server.whoAmI() == me_);
/* Someone has given Bob a value hint. If the named cards
* include the one Bob would normally be discarding next,
* then this must be a warning that that card is valuable.
* Otherwise, all the named cards are playable. */
const int discardIndex = this->nextDiscardIndex(server, to);
const bool isPointless = (value < lowestPlayableValue_);
const bool isWarning =
card_indices.contains(discardIndex) &&
couldBeValuable(server, handKnowledge_[to][discardIndex], value);
const bool isHintStoneReclaim =
(!server.discardingIsAllowed()) &&
(from == (to+1) % server.numPlayers()) &&
card_indices.contains(0);
if (isHintStoneReclaim) {
return;
}
assert(!isPointless);
if (isWarning) {
assert(discardIndex != -1);
handKnowledge_[to][discardIndex].isValuable = true;
if (value == lowestPlayableValue_) {
/* This card is valuable, i.e., not worthless; therefore it
* must be playable sometime in the future. And since it's
* the lowest playable value already, it must in fact be
* playable right now! But we can't say the same thing for
* any of the other named cards. */
handKnowledge_[to][discardIndex].isPlayable = true;
}
}
const int numCards = server.sizeOfHandOfPlayer(to);
for (int i=0; i < numCards; ++i) {
CardKnowledge &knol = handKnowledge_[to][i];
if (card_indices.contains(i)) {
knol.setMustBe(value);
if (knol.color() == -1 && !isWarning && !knol.isWorthless) {
knol.isPlayable = true;
}
} else {
knol.setCannotBe(value);
}
}
}
void HolmesBot::pleaseObserveAfterMove(const Hanabi::Server &server)
{
assert(server.whoAmI() == me_);
}
void HolmesBot::wipeOutPlayables(const Card &card)
{
const int numPlayers = handKnowledge_.size();
for (int player = 0; player < numPlayers; ++player) {
for (int c = 0; c < handKnowledge_[player].size(); ++c) {
CardKnowledge &knol = handKnowledge_[player][c];
if (!knol.isPlayable) continue;
if (knol.isValuable) continue;
if (knol.cannotBe(card)) continue;
/* This card might or might not be playable, anymore. */
knol.isPlayable = false;
}
}
}
bool HolmesBot::maybePlayLowestPlayableCard(Server &server)
{
/* Find the lowest-valued playable card in my hand.
* Notice that this has the useful side-effect of preferring to play
* cards whose values are unknown (-1) but which have been deduced
* to be playable by CardKnowledge::update(). */
int best_index = -1;
int best_value = 6;
for (int i=0; i < server.sizeOfHandOfPlayer(me_); ++i) {
const CardKnowledge &knol = handKnowledge_[me_][i];
if (knol.isPlayable && knol.value() < best_value) {
best_index = i;
best_value = knol.value();
}
}
/* If I found a card to play, play it. */
if (best_index != -1) {
server.pleasePlay(best_index);
return true;
}
return false;
}
bool HolmesBot::maybeDiscardWorthlessCard(Server &server)
{
for (int i=0; i < server.sizeOfHandOfPlayer(me_); ++i) {
const CardKnowledge &knol = handKnowledge_[me_][i];
if (knol.isWorthless) {
server.pleaseDiscard(i);
return true;
}
}
return false;
}
Hint HolmesBot::bestHintForPlayer(const Server &server, int partner) const
{
assert(partner != me_);
const std::vector<Card> partners_hand = server.handOfPlayer(partner);
bool is_really_playable[5];
for (int c=0; c < partners_hand.size(); ++c) {
is_really_playable[c] =
server.pileOf(partners_hand[c].color).nextValueIs(partners_hand[c].value);
}
Hint best_so_far;
best_so_far.to = partner;
/* Can we construct a color hint that gives our partner information
* about unknown-playable cards, without also including any
* unplayable cards? */
for (Color color = RED; color <= BLUE; ++color) {
int information_content = 0;
bool misinformative = false;
for (int c=0; c < partners_hand.size(); ++c) {
const CardKnowledge &knol = handKnowledge_[partner][c];
if (partners_hand[c].color != color) continue;
if (is_really_playable[c] && !knol.isPlayable) {
information_content += 1;
} else if (!is_really_playable[c] && (knol.value() == -1 && !knol.isWorthless)) {
misinformative = true;
break;
}
}
if (misinformative) continue;
if (information_content > best_so_far.information_content) {
best_so_far.information_content = information_content;
best_so_far.color = color;
best_so_far.value = -1;
}
}
/* Avoid giving hints that could be misinterpreted as warnings. */
const int discardIndex = nextDiscardIndex(server, partner);
int valueToAvoid = -1;
if (discardIndex != -1) {
const CardKnowledge &knol = handKnowledge_[partner][discardIndex];
valueToAvoid = partners_hand[discardIndex].value;
if (!couldBeValuable(server, knol, valueToAvoid)) valueToAvoid = -1;
}
for (int value = 1; value <= 5; ++value) {
if (value == valueToAvoid) continue;
int information_content = 0;
bool misinformative = false;
for (int c=0; c < partners_hand.size(); ++c) {
const CardKnowledge &knol = handKnowledge_[partner][c];
if (partners_hand[c].value != value) continue;
if (is_really_playable[c] && !knol.isPlayable)
{
information_content += 1;
} else if (!is_really_playable[c] && (knol.color() == -1 && !knol.isWorthless)) {
misinformative = true;
break;
}
}
if (misinformative) continue;
if (information_content > best_so_far.information_content) {
best_so_far.information_content = information_content;
best_so_far.color = -1;
best_so_far.value = value;
}
}
return best_so_far;
}
bool HolmesBot::maybeGiveValuableWarning(Server &server)
{
const int numPlayers = handKnowledge_.size();
const int player_to_warn = (me_ + 1) % numPlayers;
/* Is the player to our left just about to discard a card
* that is really valuable? */
int discardIndex = this->nextDiscardIndex(server, player_to_warn);
if (discardIndex == -1) return false;
Card targetCard = server.handOfPlayer(player_to_warn)[discardIndex];
if (!this->isValuable(server, targetCard)) {
/* The target card isn't actually valuable. Good. */
return false;
}
/* Oh no! Warn him before he discards it! */
assert(!handKnowledge_[player_to_warn][discardIndex].isValuable);
assert(!handKnowledge_[player_to_warn][discardIndex].isPlayable);
assert(!handKnowledge_[player_to_warn][discardIndex].isWorthless);
/* Sometimes we just can't give a hint. */
if (server.hintStonesRemaining() == 0) return false;
Hint bestHint = bestHintForPlayer(server, player_to_warn);
if (bestHint.information_content > 0) {
/* Excellent; we found a hint that will cause him to play a card
* instead of discarding. */
bestHint.give(server);
return true;
}
/* Otherwise, we'll have to give a warning. */
if (targetCard.value == lowestPlayableValue_) {
assert(server.pileOf(targetCard.color).nextValueIs(targetCard.value));
} else {
assert(targetCard.value > lowestPlayableValue_);
}
server.pleaseGiveValueHint(player_to_warn, targetCard.value);
return true;
}
bool HolmesBot::maybeGiveHelpfulHint(Server &server)
{
if (server.hintStonesRemaining() == 0) return false;
const int numPlayers = handKnowledge_.size();
Hint bestHint;
for (int i = 1; i < numPlayers; ++i) {
const int partner = (me_ + i) % numPlayers;
Hint candidate = bestHintForPlayer(server, partner);
if (candidate.information_content > bestHint.information_content) {
bestHint = candidate;
}
}
if (bestHint.information_content <= 0) return false;
/* Give the hint. */
bestHint.give(server);
return true;
}
bool HolmesBot::maybePlayMysteryCard(Server &server)
{
if (!UseMulligans) return false;
int table[4] = { -99, 1, 1, 1 };
if (server.cardsRemainingInDeck() <= table[server.mulligansRemaining()]) {
/* We could temporize, or we could do something that forces us to
* draw a card. If we got here, temporizing has been rejected as
* an option; so let's do something that forces us to draw a card.
* At this point, we might as well try to play something random
* and hope we get lucky. */
for (int i = myHandSize_ - 1; i >= 0; --i) {
const CardKnowledge &knol = handKnowledge_[me_][i];
assert(!knol.isPlayable); /* or we would have played it already */
if (knol.isWorthless) continue;
if (knol.color() != -1 && knol.value() != -1) {
/* A known card shouldn't be playable. */
assert(!server.pileOf(Color(knol.color())).nextValueIs(knol.value()));
continue;
}
server.pleasePlay(i);
return true;
}
}
return false;
}
bool HolmesBot::maybeDiscardOldCard(Server &server)
{
for (int i=0; i < myHandSize_; ++i) {
const CardKnowledge &knol = handKnowledge_[me_][i];
assert(!knol.isPlayable);
if (knol.isValuable) continue;
server.pleaseDiscard(i);
return true;
}
/* I didn't find anything I was willing to discard. */
return false;
}
void HolmesBot::pleaseMakeMove(Server &server)
{
assert(server.whoAmI() == me_);
assert(server.activePlayer() == me_);
assert(UseMulligans || !server.mulligansUsed());
/* If I have a playable card, play it.
* Otherwise, if someone else has an unknown-playable card, hint it.
* Otherwise, just discard my oldest (index-0) card. */
if (maybeGiveValuableWarning(server)) return;
if (maybePlayLowestPlayableCard(server)) return;
if (maybeGiveHelpfulHint(server)) return;
if (maybePlayMysteryCard(server)) return;
/* We couldn't find a good hint to give, or else we're out of hint-stones.
* Discard a card. However, discarding is not allowed when we have all
* the hint stones, so in that case, just hint to the player on our right
* about his oldest card. */
if (!server.discardingIsAllowed()) {
const int numPlayers = server.numPlayers();
const int right_partner = (me_ + numPlayers - 1) % numPlayers;
server.pleaseGiveValueHint(right_partner, server.handOfPlayer(right_partner)[0].value);
} else {
if (maybeDiscardWorthlessCard(server)) return;
if (maybeDiscardOldCard(server)) return;
/* In this unfortunate case, which still happens fairly often, I find
* that my whole hand is composed of valuable cards, and I just have
* to discard the one of them that will block our progress the least. */
int best_index = 0;
for (int i=0; i < myHandSize_; ++i) {
assert(handKnowledge_[me_][i].isValuable);
if (handKnowledge_[me_][i].value() > handKnowledge_[me_][best_index].value()) {
best_index = i;
}
}
server.pleaseDiscard(best_index);
}
}
| 32.729496 | 129 | 0.59199 | [
"vector"
] |
6032b617343405e02d9bd6f221a2f59b7677e133 | 2,974 | cpp | C++ | macros/test_ay_4he.cpp | serjinio/thesis_ana | 633a61dee56cf2cf4dcb67997ac87338537fb578 | [
"MIT"
] | null | null | null | macros/test_ay_4he.cpp | serjinio/thesis_ana | 633a61dee56cf2cf4dcb67997ac87338537fb578 | [
"MIT"
] | null | null | null | macros/test_ay_4he.cpp | serjinio/thesis_ana | 633a61dee56cf2cf4dcb67997ac87338537fb578 | [
"MIT"
] | null | null | null |
#include "TChain.h"
#include "TGraph.h"
#include "init_6he_ds.hpp"
#include "macroincludes.hpp"
using namespace s13::ana;
ScatteringYield compute_asymmetry(ElasticScatteringCuts& cuts) {
// Yields
int bin_num = 5;
ScatteringYield left{bin_num, 55, 70};
ScatteringYield right{bin_num, 55, 70};
ScatteringYield left_up{bin_num, 55, 70};
ScatteringYield right_up{bin_num, 55, 70};
ScatteringYield left_down{bin_num, 55, 70};
ScatteringYield right_down{bin_num, 55, 70};
int evt_counter = 0;
int total_evt_counter = 0;
auto compute_asym = [&left, &right, &cuts, &evt_counter, &total_evt_counter]
(ScatteringEvent& evt) -> void {
if (!cuts(evt)) { // not elastic scattering
return;
}
if (evt.p_theta < 55 || evt.p_theta > 70) {
return;
}
if (evt.IsLeftScattering()) {
left.AddEvent(evt.p_theta);
} else {
right.AddEvent(evt.p_theta);
}
++evt_counter;
++total_evt_counter;
};
ScatteringTreeWalker tree_walker;
tree_walker.Walk(g_chain_up, compute_asym);
std::cout << "Left up: " << left << std::endl;
std::cout << "Right up: " << right << std::endl;
std::cout << "Pol. up total events # " << evt_counter << std::endl;
evt_counter = 0;
left_up = left; right_up = right;
left.Reset(); right.Reset();
tree_walker.Walk(g_chain_down, compute_asym);
std::cout << "Left down: " << left << std::endl;
std::cout << "Right down: " << right << std::endl;
std::cout << "Pol. down total events # " << evt_counter << std::endl;
left_down = left; right_down = right;
left.Reset(); right.Reset();
auto asymmetry_num = sqrt(left_up * right_down) - sqrt(right_up * left_down);
auto asymmetry_den = sqrt(left_up * right_down) + sqrt(right_up * left_down);
auto asymmetry = asymmetry_num / asymmetry_den;
std::cout << "Asymmetry: " << asymmetry << std::endl;
std::cout << "Total events # " << total_evt_counter << std::endl;
return asymmetry;
}
void test_ay_4he() {
init_dataset();
RootScript script("test_asymmetry");
ElasticScatteringCuts cuts;
cuts.phi_width = 8;
cuts.vertexXY_radius = 9;x
cuts.theta_width = 2;
cuts.apply_vertexXY_cut = true;
cuts.apply_phi_cut = true;
cuts.apply_theta_cut = false;
cuts.apply_hodf_he6_cut = true;
// show S/N
script.NewPage(2, 1);
draw_theta_corr_2d(g_chain_total, cuts);
script.cd(2);
draw_theta_corr_1d(g_chain_total, cuts);
draw_marker_line(-cuts.theta_width/2, 0, -cuts.theta_width/2, 650);
draw_marker_line(cuts.theta_width/2, 0, cuts.theta_width/2, 650);
// compute asymmetry
cuts.apply_theta_cut = true;
auto asym = compute_asymmetry(cuts) * -4;
script.NewPage(1, 1);
TString title = "Test asymmetry";
std::vector<TGraph*> graphs = {Build4HeAyGraph(),
BuildAyGraph(asym, title)};
auto multi_graph = PrepareAyMultiGraph(title, graphs);
multi_graph->Draw("ACP");
//script.GetCanvas().BuildLegend(0.15, 0.67, 0.5, 0.88);
}
| 28.873786 | 79 | 0.66846 | [
"vector"
] |
60353c744d175560a87cd58a6e3a2c46b894d32e | 8,469 | cpp | C++ | MXIF/Quan3D++/vvQuan3D.cpp | vais-ral/CCPi-Quantification | cb53ff9abf865c48b1cf240932f6aa0f647b6a4f | [
"Apache-2.0"
] | null | null | null | MXIF/Quan3D++/vvQuan3D.cpp | vais-ral/CCPi-Quantification | cb53ff9abf865c48b1cf240932f6aa0f647b6a4f | [
"Apache-2.0"
] | 1 | 2019-01-30T12:42:14.000Z | 2019-02-14T16:17:03.000Z | MXIF/Quan3D++/vvQuan3D.cpp | vais-ral/CCPi-Quantification | cb53ff9abf865c48b1cf240932f6aa0f647b6a4f | [
"Apache-2.0"
] | null | null | null | /*=========================================================================
Copyright (c) Yue Sheng, University of Manchester and David Worth, STFC
All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
/** \file vvQuan3D.cpp
\brief This is a VolView plugin to calculate several characteristics from a
labelled image. It uses the CCPi class CCPiQuantification3D to do all the work.
The following characteristics are calculated:
\li Volume by voxel counts
\li Equivalent sphere diameter by voxel counts
\li Bounding box diagonal
\li Principal Component Analysis
\li Ellipsoid fitting by PCA
\li Equivalent circle diameter by PCA
\li Isosurface by marching cube
\li Surface area
\li Surface volume
\li Equivalent sphere diameter from surface volume
\li Sphercity
\li Normalised surface area to volume ratio (Radius*Sa/Vol)
*/
#include <iostream>
#include <stdlib.h>
#include <stdio.h>
#include "Quan3D.hpp"
#include "QuanWorker.hpp"
#include "vtkVVPluginAPI.h"
/**
\brief Template function to calculate the data from the image
\c IT represents the input volumes data type (e.g. float, short, etc).
\author David Worth, STFC
\date May 2012
\param info Pointer to object that holds data for this plugin. The voxel size
can be obtained from it.
\param pds Pointer to object that carries information on data set to be
processed. Includes actual buffer of voxel data, number of voxels along each
dimension, voxel spacing and voxel type.
*/
template <class IT>
void vvQuan3DTemplate(vtkVVPluginInfo *info,
vtkVVProcessDataStruct *pds,
IT *)
{
CCPiQuantification3D<IT> quan3D;
info->UpdateProgress(info,0.01,"Initialising...");
quan3D.Initialise((void*)info, (void*)pds);
quan3D.CreateVoxelIndexList();
quan3D.PrepareForQuantification();
quan3D.PrintSummaryData();
quan3D.WriteCSVData("3D_data.csv");
int totalVoxels = quan3D.GetNumVoxelValues(), n = 0;
info->UpdateProgress(info,0.05,"Processing...");
#pragma omp parallel for schedule(dynamic)
for(int i = 0; i < totalVoxels; i++) {
CCPiQuantificationWorker<IT> *worker = NULL;
// Do the real work
#pragma omp critical(nextworker)
{
worker = quan3D.GetNextWorker();
}
if (worker != NULL) {
if (0 == worker->Run()) {
#pragma omp critical(writefile)
{
worker->WriteCSVData("3D_data.csv");
}
}
delete worker;
}
#pragma omp atomic
n++;
#pragma omp critical(progress)
{
int count = 40*n/totalVoxels;
std::cout << '\r';
for (int j = 1; j < count+1; j++) {
std::cout << '*';
}
for (int j = count+1; j < 41; j++) {
std::cout << '.';
}
std::cout << "| " << 100*n/totalVoxels << "%";
}
}
std::cout << std::endl;
/*
#pragma omp parallel for
for(int i = 0; i < totalVoxels; i++) {
#pragma omp flush (abort)
if (!abort) {
// See if we should abort
if (atoi(info->GetProperty(info,VVP_ABORT_PROCESSING)) == 1) {
abort = true;
#pragma omp flush (abort)
}
#pragma omp critical(UpdateProgress)
info->UpdateProgress(info,(float)1.0*n/totalVoxels,"Processing...");
// Do the real work
CCPiQuantificationWorker<IT> *worker = quan3D.GetWorker(i);
if (worker != NULL) {
worker->Run();
delete worker;
}
#pragma omp critical(UpdateProgress)
++n;
}
}
*/
// while (quan3D.NextValueQuantification() != 0) {
/* Show user we're doing something! */
// info->UpdateProgress(info,(float)1.0*counter/totalVoxels,"Processing...");
/* See if we should abort */
// int abort = atoi(info->GetProperty(info,VVP_ABORT_PROCESSING));
// if (abort) break;
// counter++;
// }
info->UpdateProgress(info,(float)1.0,"Processing Complete");
}
/**
\brief Function called by VolView to run the plug in.
It hands off the actual work to the template function vvQuan3DTemplate.
\param inf Pointer to object that holds data for this plugin. The voxel size
can be obtained from it.
\param pds Pointer to object that carries information on data set to be
processed. Includes actual buffer of voxel data, number of voxels along each
dimension, voxel spacing and voxel type.
*/
static int ProcessData(void *inf, vtkVVProcessDataStruct *pds)
{
vtkVVPluginInfo *info = (vtkVVPluginInfo *)inf;
switch (info->InputVolumeScalarType) {
vtkTemplateMacro3(vvQuan3DTemplate, info, pds,
static_cast<VTK_TT *>(0));
}
return 0;
}
/**
\brief Update the VolView GUI to display user parameters.
Sets one GUI parameter - the physical size of the voxels in the image. It
gets called prior to the plugin executing.
\param inf Pointer to object that should be modified to set up GUI elements for
this plugin. It also contains details of the input and output images.
*/
static int UpdateGUI(void *inf)
{
vtkVVPluginInfo *info = (vtkVVPluginInfo *)inf;
/* Create required GUI elements here */
info->SetGUIProperty(info, 0, VVP_GUI_LABEL, "Minimum feature Size");
info->SetGUIProperty(info, 0, VVP_GUI_TYPE, VVP_GUI_SCALE);
info->SetGUIProperty(info, 0, VVP_GUI_DEFAULT , "100");
info->SetGUIProperty(info, 0, VVP_GUI_HELP,
"Minimum number of voxels for a feature to be analysed");
/* Range for possible output values */
info->SetGUIProperty(info, 0, VVP_GUI_HINTS , "1 1000 1");
/* By default the output image's properties match those of the input */
info->OutputVolumeScalarType = info->InputVolumeScalarType;
info->OutputVolumeNumberOfComponents = info->InputVolumeNumberOfComponents;
for (int i = 0; i < 3; i++) {
info->OutputVolumeDimensions[i] = info->InputVolumeDimensions[i];
info->OutputVolumeSpacing[i] = info->InputVolumeSpacing[i];
info->OutputVolumeOrigin[i] = info->InputVolumeOrigin[i];
}
return 1;
}
/**
\brief Initialise this plugin.
Sets the name and group for this plugin in the plugin list shown to the VolView
user and gives some documentation. Also defines properties so VolView can judge
the memory requirements and potential for undoing this plugin.
\param info Pointer to object that should be modified to give details about this
plugin.
*/
extern "C"
{
void VV_PLUGIN_EXPORT vvQuan3DInit(vtkVVPluginInfo *info)
{
/* Always check the version */
vvPluginVersionCheck();
/* Set up information that never changes */
info->ProcessData = ProcessData;
info->UpdateGUI = UpdateGUI;
/* Set the properties this plugin uses */
info->SetProperty(info, VVP_NAME, "Quantify 3D");
info->SetProperty(info, VVP_GROUP, "Quantification");
/* Set terse and full documentation displayed to user */
info->SetProperty(info, VVP_TERSE_DOCUMENTATION,
"Quantify several characteristics from a labelled image");
info->SetProperty(info, VVP_FULL_DOCUMENTATION,
"Quantify the following characteristics from a labelled image: Volume by \
voxel counts, Equivalent sphere diameter by voxel counts, Bounding box \
diagonal, Principal Component Analysis, Ellipsoid fitting by PCA, Equivalent \
circle diameter by PCA, Isosurface by marching cube, Surface area, Surface \
volume, Equivalent sphere diameter from surface volume, Sphercity, Normalised \
surface area to volume ratio. \nPLEASE NOTE that the Cancel button and progress \
bar do not work for this OpenMP plug-in.");
/* Set these two values to "0" or "1" based on how your plugin
* handles data all possible combinations of 0 and 1 are valid. */
info->SetProperty(info, VVP_SUPPORTS_IN_PLACE_PROCESSING, "1");
info->SetProperty(info, VVP_SUPPORTS_PROCESSING_PIECES, "0");
/* Set the number of GUI items used by this plugin */
info->SetProperty(info, VVP_NUMBER_OF_GUI_ITEMS, "1");
info->SetProperty(info, VVP_REQUIRED_Z_OVERLAP, "0");
info->SetProperty(info, VVP_REQUIRES_SERIES_INPUT, "0");
info->SetProperty(info, VVP_SUPPORTS_PROCESSING_SERIES_BY_VOLUMES, "0");
info->SetProperty(info, VVP_PRODUCES_OUTPUT_SERIES, "0");
info->SetProperty(info, VVP_PRODUCES_PLOTTING_OUTPUT, "0");
}
}
| 31.366667 | 81 | 0.678947 | [
"object",
"3d"
] |
6035d38f1752cdd3e65454949a11d4dc49d3decb | 1,497 | cpp | C++ | src/tests/functional/inference_engine/serialization/single_layer/pad.cpp | pazamelin/openvino | b7e8ef910d7ed8e52326d14dc6fd53b71d16ed48 | [
"Apache-2.0"
] | 2,406 | 2020-04-22T15:47:54.000Z | 2022-03-31T10:27:37.000Z | inference-engine/tests/functional/inference_engine/serialization/single_layer/pad.cpp | thomas-yanxin/openvino | 031e998a15ec738c64cc2379d7f30fb73087c272 | [
"Apache-2.0"
] | 4,948 | 2020-04-22T15:12:39.000Z | 2022-03-31T18:45:42.000Z | inference-engine/tests/functional/inference_engine/serialization/single_layer/pad.cpp | thomas-yanxin/openvino | 031e998a15ec738c64cc2379d7f30fb73087c272 | [
"Apache-2.0"
] | 991 | 2020-04-23T18:21:09.000Z | 2022-03-31T18:40:57.000Z | // Copyright (C) 2018-2021 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
//
#include <vector>
#include "shared_test_classes/single_layer/pad.hpp"
using namespace LayerTestsDefinitions;
namespace {
TEST_P(PadLayerTest, Serialize) { Serialize(); }
const std::vector<InferenceEngine::Precision> netPrecisions = {
InferenceEngine::Precision::FP32, InferenceEngine::Precision::FP16};
const std::vector<std::vector<int64_t>> padsBegin2D = {
{0, 0}, {1, 1}, {2, 0}, {0, 3}};
const std::vector<std::vector<int64_t>> padsEnd2D = {
{0, 0}, {1, 1}, {0, 1}, {3, 2}};
const std::vector<float> argPadValue = {0.f, 1.f, 2.f, -1.f};
const std::vector<ngraph::helpers::PadMode> padMode = {
ngraph::helpers::PadMode::EDGE, ngraph::helpers::PadMode::REFLECT,
ngraph::helpers::PadMode::SYMMETRIC};
const auto pad2DConstparams = testing::Combine(
testing::ValuesIn(padsBegin2D), testing::ValuesIn(padsEnd2D),
testing::ValuesIn(argPadValue),
testing::Values(ngraph::helpers::PadMode::CONSTANT),
testing::ValuesIn(netPrecisions),
testing::Values(InferenceEngine::Precision::UNSPECIFIED),
testing::Values(InferenceEngine::Precision::UNSPECIFIED),
testing::Values(InferenceEngine::Layout::ANY),
testing::Values(std::vector<size_t>{13, 5}),
testing::Values(CommonTestUtils::DEVICE_CPU));
INSTANTIATE_TEST_SUITE_P(smoke_Pad2DConstSerialization, PadLayerTest, pad2DConstparams,
PadLayerTest::getTestCaseName);
} // namespace
| 36.512195 | 87 | 0.711423 | [
"vector"
] |
60388d3779343d15c18db904dc7c16bfb3101529 | 37,105 | cpp | C++ | corelib/src/CameraStereo.cpp | GeekLiB/rtabmap | db81b37fda225d597d4cf068c64182b2b79bbed4 | [
"BSD-3-Clause"
] | null | null | null | corelib/src/CameraStereo.cpp | GeekLiB/rtabmap | db81b37fda225d597d4cf068c64182b2b79bbed4 | [
"BSD-3-Clause"
] | null | null | null | corelib/src/CameraStereo.cpp | GeekLiB/rtabmap | db81b37fda225d597d4cf068c64182b2b79bbed4 | [
"BSD-3-Clause"
] | null | null | null | /*
Copyright (c) 2010-2016, Mathieu Labbe - IntRoLab - Universite de Sherbrooke
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the Universite de Sherbrooke nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "rtabmap/core/CameraStereo.h"
#include "rtabmap/core/util2d.h"
#include "rtabmap/core/CameraRGB.h"
#include "rtabmap/core/Version.h"
#include <rtabmap/utilite/UEventsManager.h>
#include <rtabmap/utilite/UConversion.h>
#include <rtabmap/utilite/UStl.h>
#include <rtabmap/utilite/UConversion.h>
#include <rtabmap/utilite/UFile.h>
#include <rtabmap/utilite/UDirectory.h>
#include <rtabmap/utilite/UTimer.h>
#include <rtabmap/utilite/UMath.h>
#ifdef RTABMAP_DC1394
#include <dc1394/dc1394.h>
#endif
#ifdef RTABMAP_FLYCAPTURE2
#include <triclops.h>
#include <fc2triclops.h>
#endif
#ifdef RTABMAP_ZED
#include <zed/Camera.hpp>
#endif
namespace rtabmap
{
//
// CameraStereoDC1394
// Inspired from ROS camera1394stereo package
//
#ifdef RTABMAP_DC1394
class DC1394Device
{
public:
DC1394Device() :
camera_(0),
context_(0)
{
}
~DC1394Device()
{
if (camera_)
{
if (DC1394_SUCCESS != dc1394_video_set_transmission(camera_, DC1394_OFF) ||
DC1394_SUCCESS != dc1394_capture_stop(camera_))
{
UWARN("unable to stop camera");
}
// Free resources
dc1394_capture_stop(camera_);
dc1394_camera_free(camera_);
camera_ = NULL;
}
if(context_)
{
dc1394_free(context_);
context_ = NULL;
}
}
const std::string & guid() const {return guid_;}
bool init()
{
if(camera_)
{
// Free resources
dc1394_capture_stop(camera_);
dc1394_camera_free(camera_);
camera_ = NULL;
}
// look for a camera
int err;
if(context_ == NULL)
{
context_ = dc1394_new ();
if (context_ == NULL)
{
UERROR( "Could not initialize dc1394_context.\n"
"Make sure /dev/raw1394 exists, you have access permission,\n"
"and libraw1394 development package is installed.");
return false;
}
}
dc1394camera_list_t *list;
err = dc1394_camera_enumerate(context_, &list);
if (err != DC1394_SUCCESS)
{
UERROR("Could not get camera list");
return false;
}
if (list->num == 0)
{
UERROR("No cameras found");
dc1394_camera_free_list (list);
return false;
}
uint64_t guid = list->ids[0].guid;
dc1394_camera_free_list (list);
// Create a camera
camera_ = dc1394_camera_new (context_, guid);
if (!camera_)
{
UERROR("Failed to initialize camera with GUID [%016lx]", guid);
return false;
}
uint32_t value[3];
value[0]= camera_->guid & 0xffffffff;
value[1]= (camera_->guid >>32) & 0x000000ff;
value[2]= (camera_->guid >>40) & 0xfffff;
guid_ = uFormat("%06x%02x%08x", value[2], value[1], value[0]);
UINFO("camera model: %s %s", camera_->vendor, camera_->model);
// initialize camera
// Enable IEEE1394b mode if the camera and bus support it
bool bmode = camera_->bmode_capable;
if (bmode
&& (DC1394_SUCCESS !=
dc1394_video_set_operation_mode(camera_,
DC1394_OPERATION_MODE_1394B)))
{
bmode = false;
UWARN("failed to set IEEE1394b mode");
}
// start with highest speed supported
dc1394speed_t request = DC1394_ISO_SPEED_3200;
int rate = 3200;
if (!bmode)
{
// not IEEE1394b capable: so 400Mb/s is the limit
request = DC1394_ISO_SPEED_400;
rate = 400;
}
// round requested speed down to next-lower defined value
while (rate > 400)
{
if (request <= DC1394_ISO_SPEED_MIN)
{
// get current ISO speed of the device
dc1394speed_t curSpeed;
if (DC1394_SUCCESS == dc1394_video_get_iso_speed(camera_, &curSpeed) && curSpeed <= DC1394_ISO_SPEED_MAX)
{
// Translate curSpeed back to an int for the parameter
// update, works as long as any new higher speeds keep
// doubling.
request = curSpeed;
rate = 100 << (curSpeed - DC1394_ISO_SPEED_MIN);
}
else
{
UWARN("Unable to get ISO speed; assuming 400Mb/s");
rate = 400;
request = DC1394_ISO_SPEED_400;
}
break;
}
// continue with next-lower possible value
request = (dc1394speed_t) ((int) request - 1);
rate = rate / 2;
}
// set the requested speed
if (DC1394_SUCCESS != dc1394_video_set_iso_speed(camera_, request))
{
UERROR("Failed to set iso speed");
return false;
}
// set video mode
dc1394video_modes_t vmodes;
err = dc1394_video_get_supported_modes(camera_, &vmodes);
if (err != DC1394_SUCCESS)
{
UERROR("unable to get supported video modes");
return (dc1394video_mode_t) 0;
}
// see if requested mode is available
bool found = false;
dc1394video_mode_t videoMode = DC1394_VIDEO_MODE_FORMAT7_3; // bumblebee
for (uint32_t i = 0; i < vmodes.num; ++i)
{
if (vmodes.modes[i] == videoMode)
{
found = true;
}
}
if(!found)
{
UERROR("unable to get video mode %d", videoMode);
return false;
}
if (DC1394_SUCCESS != dc1394_video_set_mode(camera_, videoMode))
{
UERROR("Failed to set video mode %d", videoMode);
return false;
}
// special handling for Format7 modes
if (dc1394_is_video_mode_scalable(videoMode) == DC1394_TRUE)
{
if (DC1394_SUCCESS != dc1394_format7_set_color_coding(camera_, videoMode, DC1394_COLOR_CODING_RAW16))
{
UERROR("Could not set color coding");
return false;
}
uint32_t packetSize;
if (DC1394_SUCCESS != dc1394_format7_get_recommended_packet_size(camera_, videoMode, &packetSize))
{
UERROR("Could not get default packet size");
return false;
}
if (DC1394_SUCCESS != dc1394_format7_set_packet_size(camera_, videoMode, packetSize))
{
UERROR("Could not set packet size");
return false;
}
}
else
{
UERROR("Video is not in mode scalable");
}
// start the device streaming data
// Set camera to use DMA, improves performance.
if (DC1394_SUCCESS != dc1394_capture_setup(camera_, 4, DC1394_CAPTURE_FLAGS_DEFAULT))
{
UERROR("Failed to open device!");
return false;
}
// Start transmitting camera data
if (DC1394_SUCCESS != dc1394_video_set_transmission(camera_, DC1394_ON))
{
UERROR("Failed to start device!");
return false;
}
return true;
}
bool getImages(cv::Mat & left, cv::Mat & right)
{
if(camera_)
{
dc1394video_frame_t * frame = NULL;
UDEBUG("[%016lx] waiting camera", camera_->guid);
dc1394_capture_dequeue (camera_, DC1394_CAPTURE_POLICY_WAIT, &frame);
if (!frame)
{
UERROR("Unable to capture frame");
return false;
}
dc1394video_frame_t frame1 = *frame;
// deinterlace frame into two imagesCount one on top the other
size_t frame1_size = frame->total_bytes;
frame1.image = (unsigned char *) malloc(frame1_size);
frame1.allocated_image_bytes = frame1_size;
frame1.color_coding = DC1394_COLOR_CODING_RAW8;
int err = dc1394_deinterlace_stereo_frames(frame, &frame1, DC1394_STEREO_METHOD_INTERLACED);
if (err != DC1394_SUCCESS)
{
free(frame1.image);
dc1394_capture_enqueue(camera_, frame);
UERROR("Could not extract stereo frames");
return false;
}
uint8_t* capture_buffer = reinterpret_cast<uint8_t *>(frame1.image);
UASSERT(capture_buffer);
cv::Mat image(frame->size[1], frame->size[0], CV_8UC3);
cv::Mat image2 = image.clone();
//DC1394_COLOR_CODING_RAW16:
//DC1394_COLOR_FILTER_BGGR
cv::cvtColor(cv::Mat(frame->size[1], frame->size[0], CV_8UC1, capture_buffer), left, CV_BayerRG2BGR);
cv::cvtColor(cv::Mat(frame->size[1], frame->size[0], CV_8UC1, capture_buffer+image.total()), right, CV_BayerRG2GRAY);
dc1394_capture_enqueue(camera_, frame);
free(frame1.image);
return true;
}
return false;
}
private:
dc1394camera_t *camera_;
dc1394_t *context_;
std::string guid_;
};
#endif
bool CameraStereoDC1394::available()
{
#ifdef RTABMAP_DC1394
return true;
#else
return false;
#endif
}
CameraStereoDC1394::CameraStereoDC1394(float imageRate, const Transform & localTransform) :
Camera(imageRate, localTransform)
#ifdef RTABMAP_DC1394
,
device_(0)
#endif
{
#ifdef RTABMAP_DC1394
device_ = new DC1394Device();
#endif
}
CameraStereoDC1394::~CameraStereoDC1394()
{
#ifdef RTABMAP_DC1394
if(device_)
{
delete device_;
}
#endif
}
bool CameraStereoDC1394::init(const std::string & calibrationFolder, const std::string & cameraName)
{
#ifdef RTABMAP_DC1394
if(device_)
{
bool ok = device_->init();
if(ok)
{
// look for calibration files
if(!calibrationFolder.empty())
{
if(!stereoModel_.load(calibrationFolder, cameraName.empty()?device_->guid():cameraName))
{
UWARN("Missing calibration files for camera \"%s\" in \"%s\" folder, you should calibrate the camera!",
cameraName.empty()?device_->guid().c_str():cameraName.c_str(), calibrationFolder.c_str());
}
else
{
UINFO("Stereo parameters: fx=%f cx=%f cy=%f baseline=%f",
stereoModel_.left().fx(),
stereoModel_.left().cx(),
stereoModel_.left().cy(),
stereoModel_.baseline());
}
}
}
return ok;
}
#else
UERROR("CameraDC1394: RTAB-Map is not built with dc1394 support!");
#endif
return false;
}
bool CameraStereoDC1394::isCalibrated() const
{
#ifdef RTABMAP_DC1394
return stereoModel_.isValidForProjection();
#else
return false;
#endif
}
std::string CameraStereoDC1394::getSerial() const
{
#ifdef RTABMAP_DC1394
if(device_)
{
return device_->guid();
}
#endif
return "";
}
SensorData CameraStereoDC1394::captureImage(CameraInfo * info)
{
SensorData data;
#ifdef RTABMAP_DC1394
if(device_)
{
cv::Mat left, right;
device_->getImages(left, right);
if(!left.empty() && !right.empty())
{
// Rectification
if(stereoModel_.left().isValidForRectification())
{
left = stereoModel_.left().rectifyImage(left);
}
if(stereoModel_.right().isValidForRectification())
{
right = stereoModel_.right().rectifyImage(right);
}
StereoCameraModel model;
if(stereoModel_.isValidForProjection())
{
model = StereoCameraModel(
stereoModel_.left().fx(), //fx
stereoModel_.left().fy(), //fy
stereoModel_.left().cx(), //cx
stereoModel_.left().cy(), //cy
stereoModel_.baseline(),
this->getLocalTransform(),
left.size());
}
data = SensorData(left, right, model, this->getNextSeqID(), UTimer::now());
}
}
#else
UERROR("CameraDC1394: RTAB-Map is not built with dc1394 support!");
#endif
return data;
}
//
// CameraTriclops
//
CameraStereoFlyCapture2::CameraStereoFlyCapture2(float imageRate, const Transform & localTransform) :
Camera(imageRate, localTransform)
#ifdef RTABMAP_FLYCAPTURE2
,
camera_(0),
triclopsCtx_(0)
#endif
{
#ifdef RTABMAP_FLYCAPTURE2
camera_ = new FlyCapture2::Camera();
#endif
}
CameraStereoFlyCapture2::~CameraStereoFlyCapture2()
{
#ifdef RTABMAP_FLYCAPTURE2
// Close the camera
camera_->StopCapture();
camera_->Disconnect();
// Destroy the Triclops context
triclopsDestroyContext( triclopsCtx_ ) ;
delete camera_;
#endif
}
bool CameraStereoFlyCapture2::available()
{
#ifdef RTABMAP_FLYCAPTURE2
return true;
#else
return false;
#endif
}
bool CameraStereoFlyCapture2::init(const std::string & calibrationFolder, const std::string & cameraName)
{
#ifdef RTABMAP_FLYCAPTURE2
if(camera_)
{
// Close the camera
camera_->StopCapture();
camera_->Disconnect();
}
if(triclopsCtx_)
{
triclopsDestroyContext(triclopsCtx_);
triclopsCtx_ = 0;
}
// connect camera
FlyCapture2::Error fc2Error = camera_->Connect();
if(fc2Error != FlyCapture2::PGRERROR_OK)
{
UERROR("Failed to connect the camera.");
return false;
}
// configure camera
Fc2Triclops::StereoCameraMode mode = Fc2Triclops::TWO_CAMERA_NARROW;
if(Fc2Triclops::setStereoMode(*camera_, mode ))
{
UERROR("Failed to set stereo mode.");
return false;
}
// generate the Triclops context
FlyCapture2::CameraInfo camInfo;
if(camera_->GetCameraInfo(&camInfo) != FlyCapture2::PGRERROR_OK)
{
UERROR("Failed to get camera info.");
return false;
}
float dummy;
unsigned packetSz;
FlyCapture2::Format7ImageSettings imageSettings;
int maxWidth = 640;
int maxHeight = 480;
if(camera_->GetFormat7Configuration(&imageSettings, &packetSz, &dummy) == FlyCapture2::PGRERROR_OK)
{
maxHeight = imageSettings.height;
maxWidth = imageSettings.width;
}
// Get calibration from th camera
if(Fc2Triclops::getContextFromCamera(camInfo.serialNumber, &triclopsCtx_))
{
UERROR("Failed to get calibration from the camera.");
return false;
}
float fx, cx, cy, baseline;
triclopsGetFocalLength(triclopsCtx_, &fx);
triclopsGetImageCenter(triclopsCtx_, &cy, &cx);
triclopsGetBaseline(triclopsCtx_, &baseline);
UINFO("Stereo parameters: fx=%f cx=%f cy=%f baseline=%f", fx, cx, cy, baseline);
triclopsSetCameraConfiguration(triclopsCtx_, TriCfg_2CAM_HORIZONTAL_NARROW );
UASSERT(triclopsSetResolutionAndPrepare(triclopsCtx_, maxHeight, maxWidth, maxHeight, maxWidth) == Fc2Triclops::ERRORTYPE_OK);
if(camera_->StartCapture() != FlyCapture2::PGRERROR_OK)
{
UERROR("Failed to start capture.");
return false;
}
return true;
#else
UERROR("CameraStereoFlyCapture2: RTAB-Map is not built with Triclops support!");
#endif
return false;
}
bool CameraStereoFlyCapture2::isCalibrated() const
{
#ifdef RTABMAP_FLYCAPTURE2
if(triclopsCtx_)
{
float fx, cx, cy, baseline;
triclopsGetFocalLength(triclopsCtx_, &fx);
triclopsGetImageCenter(triclopsCtx_, &cy, &cx);
triclopsGetBaseline(triclopsCtx_, &baseline);
return fx > 0.0f && cx > 0.0f && cy > 0.0f && baseline > 0.0f;
}
#endif
return false;
}
std::string CameraStereoFlyCapture2::getSerial() const
{
#ifdef RTABMAP_FLYCAPTURE2
if(camera_ && camera_->IsConnected())
{
FlyCapture2::CameraInfo camInfo;
if(camera_->GetCameraInfo(&camInfo) == FlyCapture2::PGRERROR_OK)
{
return uNumber2Str(camInfo.serialNumber);
}
}
#endif
return "";
}
// struct containing image needed for processing
#ifdef RTABMAP_FLYCAPTURE2
struct ImageContainer
{
FlyCapture2::Image tmp[2];
FlyCapture2::Image unprocessed[2];
} ;
#endif
SensorData CameraStereoFlyCapture2::captureImage(CameraInfo * info)
{
SensorData data;
#ifdef RTABMAP_FLYCAPTURE2
if(camera_ && triclopsCtx_ && camera_->IsConnected())
{
// grab image from camera.
// this image contains both right and left imagesCount
FlyCapture2::Image grabbedImage;
if(camera_->RetrieveBuffer(&grabbedImage) == FlyCapture2::PGRERROR_OK)
{
// right and left image extracted from grabbed image
ImageContainer imageCont;
// generate triclops input from grabbed image
FlyCapture2::Image imageRawRight;
FlyCapture2::Image imageRawLeft;
FlyCapture2::Image * unprocessedImage = imageCont.unprocessed;
// Convert the pixel interleaved raw data to de-interleaved and color processed data
if(Fc2Triclops::unpackUnprocessedRawOrMono16Image(
grabbedImage,
true /*assume little endian*/,
imageRawLeft /* right */,
imageRawRight /* left */) == Fc2Triclops::ERRORTYPE_OK)
{
// convert to color
FlyCapture2::Image srcImgRightRef(imageRawRight);
FlyCapture2::Image srcImgLeftRef(imageRawLeft);
bool ok = true;;
if ( srcImgRightRef.SetColorProcessing(FlyCapture2::HQ_LINEAR) != FlyCapture2::PGRERROR_OK ||
srcImgLeftRef.SetColorProcessing(FlyCapture2::HQ_LINEAR) != FlyCapture2::PGRERROR_OK)
{
ok = false;
}
if(ok)
{
FlyCapture2::Image imageColorRight;
FlyCapture2::Image imageColorLeft;
if ( srcImgRightRef.Convert(FlyCapture2::PIXEL_FORMAT_MONO8, &imageColorRight) != FlyCapture2::PGRERROR_OK ||
srcImgLeftRef.Convert(FlyCapture2::PIXEL_FORMAT_BGRU, &imageColorLeft) != FlyCapture2::PGRERROR_OK)
{
ok = false;
}
if(ok)
{
//RECTIFY RIGHT
TriclopsInput triclopsColorInputs;
triclopsBuildRGBTriclopsInput(
grabbedImage.GetCols(),
grabbedImage.GetRows(),
imageColorRight.GetStride(),
(unsigned long)grabbedImage.GetTimeStamp().seconds,
(unsigned long)grabbedImage.GetTimeStamp().microSeconds,
imageColorRight.GetData(),
imageColorRight.GetData(),
imageColorRight.GetData(),
&triclopsColorInputs);
triclopsRectify(triclopsCtx_, const_cast<TriclopsInput *>(&triclopsColorInputs) );
// Retrieve the rectified image from the triclops context
TriclopsImage rectifiedImage;
triclopsGetImage( triclopsCtx_,
TriImg_RECTIFIED,
TriCam_REFERENCE,
&rectifiedImage );
cv::Mat left,right;
right = cv::Mat(rectifiedImage.nrows, rectifiedImage.ncols, CV_8UC1, rectifiedImage.data).clone();
//RECTIFY LEFT COLOR
triclopsBuildPackedTriclopsInput(
grabbedImage.GetCols(),
grabbedImage.GetRows(),
imageColorLeft.GetStride(),
(unsigned long)grabbedImage.GetTimeStamp().seconds,
(unsigned long)grabbedImage.GetTimeStamp().microSeconds,
imageColorLeft.GetData(),
&triclopsColorInputs );
cv::Mat pixelsLeftBuffer( grabbedImage.GetRows(), grabbedImage.GetCols(), CV_8UC4);
TriclopsPackedColorImage colorImage;
triclopsSetPackedColorImageBuffer(
triclopsCtx_,
TriCam_LEFT,
(TriclopsPackedColorPixel*)pixelsLeftBuffer.data );
triclopsRectifyPackedColorImage(
triclopsCtx_,
TriCam_LEFT,
&triclopsColorInputs,
&colorImage );
cv::cvtColor(pixelsLeftBuffer, left, CV_RGBA2RGB);
// Set calibration stuff
float fx, cy, cx, baseline;
triclopsGetFocalLength(triclopsCtx_, &fx);
triclopsGetImageCenter(triclopsCtx_, &cy, &cx);
triclopsGetBaseline(triclopsCtx_, &baseline);
StereoCameraModel model(
fx,
fx,
cx,
cy,
baseline,
this->getLocalTransform(),
left.size());
data = SensorData(left, right, model, this->getNextSeqID(), UTimer::now());
}
}
}
}
}
#else
UERROR("CameraStereoFlyCapture2: RTAB-Map is not built with Triclops support!");
#endif
return data;
}
//
// CameraStereoZED
//
bool CameraStereoZed::available()
{
#ifdef RTABMAP_ZED
return true;
#else
return false;
#endif
}
CameraStereoZed::CameraStereoZed(
int deviceId,
int resolution,
int quality,
int sensingMode,
int confidenceThr,
bool computeOdometry,
float imageRate,
const Transform & localTransform,
bool selfCalibration) :
Camera(imageRate, localTransform)
#ifdef RTABMAP_ZED
,
zed_(0),
src_(CameraVideo::kUsbDevice),
usbDevice_(deviceId),
svoFilePath_(""),
resolution_(resolution),
quality_(quality),
selfCalibration_(selfCalibration),
sensingMode_(sensingMode),
confidenceThr_(confidenceThr),
computeOdometry_(computeOdometry),
lost_(true)
#endif
{
UDEBUG("");
#ifdef RTABMAP_ZED
UASSERT(resolution_ >= sl::zed::HD2K && resolution_ <sl::zed::LAST_RESOLUTION);
UASSERT(quality_ >= sl::zed::NONE && quality_ <sl::zed::LAST_MODE);
UASSERT(sensingMode_ >= sl::zed::FILL && sensingMode_ <sl::zed::LAST_SENSING_MODE);
UASSERT(confidenceThr_ >= 0 && confidenceThr_ <=100);
#endif
}
CameraStereoZed::CameraStereoZed(
const std::string & filePath,
int quality,
int sensingMode,
int confidenceThr,
bool computeOdometry,
float imageRate,
const Transform & localTransform,
bool selfCalibration) :
Camera(imageRate, localTransform)
#ifdef RTABMAP_ZED
,
zed_(0),
src_(CameraVideo::kVideoFile),
usbDevice_(0),
svoFilePath_(filePath),
resolution_(2),
quality_(quality),
selfCalibration_(selfCalibration),
sensingMode_(sensingMode),
confidenceThr_(confidenceThr),
computeOdometry_(computeOdometry),
lost_(true)
#endif
{
UDEBUG("");
#ifdef RTABMAP_ZED
UASSERT(resolution_ >= sl::zed::HD2K && resolution_ <sl::zed::LAST_RESOLUTION);
UASSERT(quality_ >= sl::zed::NONE && quality_ <sl::zed::LAST_MODE);
UASSERT(sensingMode_ >= sl::zed::FILL && sensingMode_ <sl::zed::LAST_SENSING_MODE);
UASSERT(confidenceThr_ >= 0 && confidenceThr_ <=100);
#endif
}
CameraStereoZed::~CameraStereoZed()
{
#ifdef RTABMAP_ZED
if(zed_)
{
delete zed_;
}
#endif
}
bool CameraStereoZed::init(const std::string & calibrationFolder, const std::string & cameraName)
{
UDEBUG("");
#ifdef RTABMAP_ZED
if(zed_)
{
delete zed_;
zed_ = 0;
}
lost_ = true;
if(src_ == CameraVideo::kVideoFile)
{
UINFO("svo file = %s", svoFilePath_.c_str());
zed_ = new sl::zed::Camera(svoFilePath_); // Use in SVO playback mode
}
else
{
UINFO("Resolution=%d imagerate=%f device=%d", resolution_, getImageRate(), usbDevice_);
zed_ = new sl::zed::Camera((sl::zed::ZEDResolution_mode)resolution_, getImageRate(), usbDevice_); // Use in Live Mode
}
sl::zed::InitParams parameters(
(sl::zed::MODE)quality_, //MODE
(sl::zed::UNIT)sl::zed::METER, //UNIT
(sl::zed::COORDINATE_SYSTEM)sl::zed::IMAGE, //COORDINATE_SYSTEM
false, // verbose
-1, //device (GPU)
-1., //minDist
!selfCalibration_, //disableSelfCalib: false = self calibrated
false); //vflip
UINFO("Init ZED: Mode=%d Unit=%d CoordinateSystem=%d Verbose=false device=-1 minDist=-1 self-calibration=%s vflip=false",
quality_, sl::zed::METER, sl::zed::IMAGE, selfCalibration_?"true":"false");
sl::zed::ERRCODE err = zed_->init(parameters);
UDEBUG("");
// Quit if an error occurred
if (err != sl::zed::SUCCESS)
{
UERROR("ZED camera initialization failed: %s", sl::zed::errcode2str(err).c_str());
delete zed_;
zed_ = 0;
return false;
}
zed_->setConfidenceThreshold(confidenceThr_);
if (computeOdometry_)
{
Eigen::Matrix4f initPose;
initPose.setIdentity(4, 4);
zed_->enableTracking(initPose, false);
}
sl::zed::StereoParameters * stereoParams = zed_->getParameters();
sl::zed::resolution res = zed_->getImageSize();
stereoModel_ = StereoCameraModel(
stereoParams->LeftCam.fx,
stereoParams->LeftCam.fy,
stereoParams->LeftCam.cx,
stereoParams->LeftCam.cy,
stereoParams->baseline,
this->getLocalTransform(),
cv::Size(res.width, res.height));
return true;
#else
UERROR("CameraStereoZED: RTAB-Map is not built with ZED sdk support!");
#endif
return false;
}
bool CameraStereoZed::isCalibrated() const
{
#ifdef RTABMAP_ZED
return stereoModel_.isValidForProjection();
#else
return false;
#endif
}
std::string CameraStereoZed::getSerial() const
{
#ifdef RTABMAP_ZED
if(zed_)
{
return uFormat("%x", zed_->getZEDSerial());
}
#endif
return "";
}
bool CameraStereoZed::odomProvided() const
{
#ifdef RTABMAP_ZED
return computeOdometry_;
#else
return false;
#endif
}
SensorData CameraStereoZed::captureImage(CameraInfo * info)
{
SensorData data;
#ifdef RTABMAP_ZED
if(zed_)
{
UTimer timer;
bool res = zed_->grab((sl::zed::SENSING_MODE)sensingMode_, quality_ > 0, quality_ > 0, false);
while (src_ == CameraVideo::kUsbDevice && res && timer.elapsed() < 2.0)
{
// maybe there is a latency with the USB, try again in 10 ms (for the next 2 seconds)
uSleep(10);
res = zed_->grab((sl::zed::SENSING_MODE)sensingMode_, quality_ > 0, quality_ > 0, false);
}
if(!res)
{
// get left image
cv::Mat rgbaLeft = sl::zed::slMat2cvMat(zed_->retrieveImage(static_cast<sl::zed::SIDE> (sl::zed::LEFT)));
cv::Mat left;
cv::cvtColor(rgbaLeft, left, cv::COLOR_BGRA2BGR);
if(quality_ > 0)
{
// get depth image
cv::Mat depth;
slMat2cvMat(zed_->retrieveMeasure(sl::zed::MEASURE::DEPTH)).copyTo(depth);
data = SensorData(left, depth, stereoModel_.left(), this->getNextSeqID(), UTimer::now());
}
else
{
// get right image
cv::Mat rgbaRight = sl::zed::slMat2cvMat(zed_->retrieveImage(static_cast<sl::zed::SIDE> (sl::zed::RIGHT)));
cv::Mat right;
cv::cvtColor(rgbaRight, right, cv::COLOR_BGRA2GRAY);
data = SensorData(left, right, stereoModel_, this->getNextSeqID(), UTimer::now());
}
if (computeOdometry_ && info)
{
Eigen::Matrix4f path;
int trackingConfidence = zed_->getTrackingConfidence();
if (trackingConfidence)
{
zed_->getPosition(path);
info->odomPose = Transform::fromEigen4f(path);
if (!info->odomPose.isNull())
{
//transform x->forward, y->left, z->up
Transform opticalTransform(0, 0, 1, 0, -1, 0, 0, 0, 0, -1, 0, 0);
info->odomPose = opticalTransform * info->odomPose * opticalTransform.inverse();
}
if (lost_)
{
info->odomCovariance = cv::Mat::eye(6, 6, CV_64FC1) * 9999.0f; // don't know transform with previous pose
lost_ = false;
UDEBUG("Init %s (var=%f)", info->odomPose.prettyPrint().c_str(), 9999.0f);
}
else
{
info->odomCovariance = cv::Mat::eye(6, 6, CV_64FC1) * 1.0f / float(trackingConfidence);
UDEBUG("Run %s (var=%f)", info->odomPose.prettyPrint().c_str(), 1.0f / float(trackingConfidence));
}
}
else
{
info->odomCovariance = cv::Mat::eye(6, 6, CV_64FC1) * 9999.0f; // lost
lost_ = true;
UWARN("ZED lost!");
}
}
}
else if(src_ == CameraVideo::kUsbDevice)
{
UERROR("CameraStereoZed: Failed to grab images after 2 seconds!");
}
else
{
UWARN("CameraStereoZed: end of stream is reached!");
}
}
#else
UERROR("CameraStereoZED: RTAB-Map is not built with ZED sdk support!");
#endif
return data;
}
//
// CameraStereoImages
//
bool CameraStereoImages::available()
{
return true;
}
CameraStereoImages::CameraStereoImages(
const std::string & pathLeftImages,
const std::string & pathRightImages,
bool rectifyImages,
float imageRate,
const Transform & localTransform) :
CameraImages(pathLeftImages, imageRate, localTransform),
camera2_(new CameraImages(pathRightImages))
{
this->setImagesRectified(rectifyImages);
}
CameraStereoImages::CameraStereoImages(
const std::string & pathLeftRightImages,
bool rectifyImages,
float imageRate,
const Transform & localTransform) :
CameraImages("", imageRate, localTransform),
camera2_(0)
{
std::vector<std::string> paths = uListToVector(uSplit(pathLeftRightImages, uStrContains(pathLeftRightImages, ":")?':':';'));
if(paths.size() >= 1)
{
this->setPath(paths[0]);
this->setImagesRectified(rectifyImages);
if(paths.size() >= 2)
{
camera2_ = new CameraImages(paths[1]);
}
}
else
{
UERROR("The path is empty!");
}
}
CameraStereoImages::~CameraStereoImages()
{
UDEBUG("");
if(camera2_)
{
delete camera2_;
}
UDEBUG("");
}
bool CameraStereoImages::init(const std::string & calibrationFolder, const std::string & cameraName)
{
// look for calibration files
if(!calibrationFolder.empty() && !cameraName.empty())
{
if(!stereoModel_.load(calibrationFolder, cameraName))
{
UWARN("Missing calibration files for camera \"%s\" in \"%s\" folder, you should calibrate the camera!",
cameraName.c_str(), calibrationFolder.c_str());
}
else
{
UINFO("Stereo parameters: fx=%f cx=%f cy=%f baseline=%f",
stereoModel_.left().fx(),
stereoModel_.left().cx(),
stereoModel_.left().cy(),
stereoModel_.baseline());
}
}
stereoModel_.setLocalTransform(this->getLocalTransform());
stereoModel_.setName(cameraName);
if(this->isImagesRectified() && !stereoModel_.isValidForRectification())
{
UERROR("Parameter \"rectifyImages\" is set, but no stereo model is loaded or valid.");
return false;
}
//desactivate before init as we will do it in this class instead for convenience
bool rectify = this->isImagesRectified();
this->setImagesRectified(false);
bool success = false;
if(CameraImages::init())
{
if(camera2_)
{
camera2_->setBayerMode(this->getBayerMode());
if(camera2_->init())
{
if(this->imagesCount() == camera2_->imagesCount())
{
success = true;
}
else
{
UERROR("Cameras don't have the same number of images (%d vs %d)",
this->imagesCount(), camera2_->imagesCount());
}
}
else
{
UERROR("Cannot initialize the second camera.");
}
}
else
{
success = true;
}
}
this->setImagesRectified(rectify); // reset the flag
return success;
}
bool CameraStereoImages::isCalibrated() const
{
return stereoModel_.isValidForProjection();
}
std::string CameraStereoImages::getSerial() const
{
return stereoModel_.name();
}
SensorData CameraStereoImages::captureImage(CameraInfo * info)
{
SensorData data;
SensorData left, right;
left = CameraImages::captureImage(info);
if(!left.imageRaw().empty())
{
if(camera2_)
{
right = camera2_->takeImage(info);
}
else
{
right = this->takeImage(info);
}
if(!right.imageRaw().empty())
{
// Rectification
cv::Mat leftImage = left.imageRaw();
cv::Mat rightImage = right.imageRaw();
if(rightImage.type() != CV_8UC1)
{
cv::Mat tmp;
cv::cvtColor(rightImage, tmp, CV_BGR2GRAY);
rightImage = tmp;
}
if(this->isImagesRectified() && stereoModel_.isValidForRectification())
{
leftImage = stereoModel_.left().rectifyImage(leftImage);
rightImage = stereoModel_.right().rectifyImage(rightImage);
}
if(stereoModel_.left().imageHeight() == 0 || stereoModel_.left().imageWidth() == 0)
{
stereoModel_.setImageSize(leftImage.size());
}
data = SensorData(left.laserScanRaw(), left.laserScanInfo(), leftImage, rightImage, stereoModel_, left.id()/(camera2_?1:2), left.stamp());
data.setGroundTruth(left.groundTruth());
}
}
return data;
}
//
// CameraStereoVideo
//
bool CameraStereoVideo::available()
{
return true;
}
CameraStereoVideo::CameraStereoVideo(
const std::string & path,
bool rectifyImages,
float imageRate,
const Transform & localTransform) :
Camera(imageRate, localTransform),
path_(path),
rectifyImages_(rectifyImages),
src_(CameraVideo::kVideoFile),
usbDevice_(0)
{
}
CameraStereoVideo::CameraStereoVideo(
const std::string & pathLeft,
const std::string & pathRight,
bool rectifyImages,
float imageRate,
const Transform & localTransform) :
Camera(imageRate, localTransform),
path_(pathLeft),
path2_(pathRight),
rectifyImages_(rectifyImages),
src_(CameraVideo::kVideoFile),
usbDevice_(0)
{
}
CameraStereoVideo::CameraStereoVideo(
int device,
bool rectifyImages,
float imageRate,
const Transform & localTransform) :
Camera(imageRate, localTransform),
rectifyImages_(rectifyImages),
src_(CameraVideo::kUsbDevice),
usbDevice_(device)
{
}
CameraStereoVideo::~CameraStereoVideo()
{
capture_.release();
capture2_.release();
}
bool CameraStereoVideo::init(const std::string & calibrationFolder, const std::string & cameraName)
{
cameraName_ = cameraName;
if(capture_.isOpened())
{
capture_.release();
}
if(capture2_.isOpened())
{
capture2_.release();
}
if (src_ == CameraVideo::kUsbDevice)
{
ULOGGER_DEBUG("CameraStereoVideo: Usb device initialization on device %d", usbDevice_);
capture_.open(usbDevice_);
}
else if (src_ == CameraVideo::kVideoFile)
{
if(path2_.empty())
{
ULOGGER_DEBUG("CameraStereoVideo: filename=\"%s\"", path_.c_str());
capture_.open(path_.c_str());
}
else
{
ULOGGER_DEBUG("CameraStereoVideo: filenames=\"%s\" and \"%s\"", path_.c_str(), path2_.c_str());
capture_.open(path_.c_str());
capture2_.open(path2_.c_str());
}
}
else
{
ULOGGER_ERROR("CameraStereoVideo: Unknown source...");
}
if(!capture_.isOpened() || (!path2_.empty() && !capture2_.isOpened()))
{
ULOGGER_ERROR("CameraStereoVideo: Failed to create a capture object!");
capture_.release();
capture2_.release();
return false;
}
if (cameraName_.empty())
{
unsigned int guid = (unsigned int)capture_.get(CV_CAP_PROP_GUID);
if (guid != 0 && guid != 0xffffffff)
{
cameraName_ = uFormat("%08x", guid);
}
}
// look for calibration files
if(!calibrationFolder.empty() && !cameraName_.empty())
{
if(!stereoModel_.load(calibrationFolder, cameraName_))
{
UWARN("Missing calibration files for camera \"%s\" in \"%s\" folder, you should calibrate the camera!",
cameraName_.c_str(), calibrationFolder.c_str());
}
else
{
UINFO("Stereo parameters: fx=%f cx=%f cy=%f baseline=%f",
stereoModel_.left().fx(),
stereoModel_.left().cx(),
stereoModel_.left().cy(),
stereoModel_.baseline());
}
}
stereoModel_.setLocalTransform(this->getLocalTransform());
if(rectifyImages_ && !stereoModel_.isValidForRectification())
{
UERROR("Parameter \"rectifyImages\" is set, but no stereo model is loaded or valid.");
return false;
}
return true;
}
bool CameraStereoVideo::isCalibrated() const
{
return stereoModel_.isValidForProjection();
}
std::string CameraStereoVideo::getSerial() const
{
return cameraName_;
}
SensorData CameraStereoVideo::captureImage(CameraInfo * info)
{
SensorData data;
cv::Mat img;
if(capture_.isOpened() && (path2_.empty() || capture2_.isOpened()))
{
cv::Mat leftImage;
cv::Mat rightImage;
if(path2_.empty())
{
if(!capture_.read(img))
{
return data;
}
// Side by side stream
leftImage = cv::Mat(img, cv::Rect( 0, 0, img.size().width/2, img.size().height ));
rightImage = cv::Mat(img, cv::Rect( img.size().width/2, 0, img.size().width/2, img.size().height ));
}
else if(!capture_.read(leftImage) || !capture2_.read(rightImage))
{
return data;
}
else if(leftImage.cols != rightImage.cols || leftImage.rows != rightImage.rows)
{
UERROR("Left and right streams don't have image of the same size: left=%dx%d right=%dx%d",
leftImage.cols, leftImage.rows, rightImage.cols, rightImage.rows);
return data;
}
// Rectification
bool rightCvt = false;
if(rightImage.type() != CV_8UC1)
{
cv::Mat tmp;
cv::cvtColor(rightImage, tmp, CV_BGR2GRAY);
rightImage = tmp;
rightCvt = true;
}
if(rectifyImages_ && stereoModel_.left().isValidForRectification() && stereoModel_.right().isValidForRectification())
{
leftImage = stereoModel_.left().rectifyImage(leftImage);
rightImage = stereoModel_.right().rectifyImage(rightImage);
}
else
{
leftImage = leftImage.clone();
if(!rightCvt)
{
rightImage = rightImage.clone();
}
}
if(stereoModel_.left().imageHeight() == 0 || stereoModel_.left().imageWidth() == 0)
{
stereoModel_.setImageSize(leftImage.size());
}
data = SensorData(leftImage, rightImage, stereoModel_, this->getNextSeqID(), UTimer::now());
}
else
{
ULOGGER_WARN("The camera must be initialized before requesting an image.");
}
return data;
}
} // namespace rtabmap
| 26.09353 | 142 | 0.668913 | [
"object",
"vector",
"model",
"transform"
] |
603a34333daa682276d63ef0178c53a4657e9d6f | 11,374 | cpp | C++ | src/libP/src/meshBasisHex3D.cpp | krowe-alcf/nekRS | 0fbedd6c14ce12e644fa617236e26ad806492ab9 | [
"BSD-3-Clause"
] | null | null | null | src/libP/src/meshBasisHex3D.cpp | krowe-alcf/nekRS | 0fbedd6c14ce12e644fa617236e26ad806492ab9 | [
"BSD-3-Clause"
] | null | null | null | src/libP/src/meshBasisHex3D.cpp | krowe-alcf/nekRS | 0fbedd6c14ce12e644fa617236e26ad806492ab9 | [
"BSD-3-Clause"
] | null | null | null | /*
The MIT License (MIT)
Copyright (c) 2020 Tim Warburton, Noel Chalmers, Jesse Chan, Ali Karakus
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#include "mesh.h"
#include "mesh3D.h"
// ------------------------------------------------------------------------
// HEX 3D NODES
// ------------------------------------------------------------------------
void NodesHex3D(int _N, dfloat *_r, dfloat *_s, dfloat *_t){
int _Nq = _N+1;
dfloat *r1D = (dfloat*) malloc(_Nq*sizeof(dfloat));
JacobiGLL(_N, r1D); //Gauss-Legendre-Lobatto nodes
//Tensor product
for (int k=0;k<_Nq;k++) {
for (int j=0;j<_Nq;j++) {
for (int i=0;i<_Nq;i++) {
_r[i+j*_Nq+k*_Nq*_Nq] = r1D[i];
_s[i+j*_Nq+k*_Nq*_Nq] = r1D[j];
_t[i+j*_Nq+k*_Nq*_Nq] = r1D[k];
}
}
}
free(r1D);
}
void FaceNodesHex3D(int _N, dfloat *_r, dfloat *_s, dfloat *_t, int *_faceNodes){
int _Nq = _N+1;
int _Nfp = _Nq*_Nq;
int _Np = _Nq*_Nq*_Nq;
int cnt[6];
for (int i=0;i<6;i++) cnt[i]=0;
dfloat deps = 1.;
while((1.+deps)>1.)
deps *= 0.5;
const dfloat NODETOL = 1000.*deps;
for (int n=0;n<_Np;n++) {
if(fabs(_t[n]+1)<NODETOL)
_faceNodes[0*_Nfp+(cnt[0]++)] = n;
if(fabs(_s[n]+1)<NODETOL)
_faceNodes[1*_Nfp+(cnt[1]++)] = n;
if(fabs(_r[n]-1)<NODETOL)
_faceNodes[2*_Nfp+(cnt[2]++)] = n;
if(fabs(_s[n]-1)<NODETOL)
_faceNodes[3*_Nfp+(cnt[3]++)] = n;
if(fabs(_r[n]+1)<NODETOL)
_faceNodes[4*_Nfp+(cnt[4]++)] = n;
if(fabs(_t[n]-1)<NODETOL)
_faceNodes[5*_Nfp+(cnt[5]++)] = n;
}
}
#if 0
void mesh_t::VertexNodesHex3D(int _N, dfloat *_r, dfloat *_s, dfloat *_t, int *_vertexNodes){
int _Nq = _N+1;
int _Np = _Nq*_Nq*_Nq;
dfloat deps = 1.;
while((1.+deps)>1.)
deps *= 0.5;
const dfloat NODETOL = 1000.*deps;
for(int n=0;n<_Np;++n){
if( (_r[n]+1)*(_r[n]+1)+(_s[n]+1)*(_s[n]+1)+(_t[n]+1)*(_t[n]+1)<NODETOL)
_vertexNodes[0] = n;
if( (_r[n]-1)*(_r[n]-1)+(_s[n]+1)*(_s[n]+1)+(_t[n]+1)*(_t[n]+1)<NODETOL)
_vertexNodes[1] = n;
if( (_r[n]-1)*(_r[n]-1)+(_s[n]-1)*(_s[n]-1)+(_t[n]+1)*(_t[n]+1)<NODETOL)
_vertexNodes[2] = n;
if( (_r[n]+1)*(_r[n]+1)+(_s[n]-1)*(_s[n]-1)+(_t[n]+1)*(_t[n]+1)<NODETOL)
_vertexNodes[3] = n;
if( (_r[n]+1)*(_r[n]+1)+(_s[n]+1)*(_s[n]+1)+(_t[n]-1)*(_t[n]-1)<NODETOL)
_vertexNodes[4] = n;
if( (_r[n]-1)*(_r[n]-1)+(_s[n]+1)*(_s[n]+1)+(_t[n]-1)*(_t[n]-1)<NODETOL)
_vertexNodes[5] = n;
if( (_r[n]-1)*(_r[n]-1)+(_s[n]-1)*(_s[n]-1)+(_t[n]-1)*(_t[n]-1)<NODETOL)
_vertexNodes[6] = n;
if( (_r[n]+1)*(_r[n]+1)+(_s[n]-1)*(_s[n]-1)+(_t[n]-1)*(_t[n]-1)<NODETOL)
_vertexNodes[7] = n;
}
}
void mesh_t::EquispacedNodesHex3D(int _N, dfloat *_r, dfloat *_s, dfloat *_t){
int _Nq = _N+1;
//Equispaced 1D nodes
dfloat *r1D = (dfloat*) malloc(_Nq*sizeof(dfloat));
dfloat dr = 2.0/_N;
for (int i=0;i<_Nq;i++) r1D[i] = -1.0 + i*dr;
//Tensor product
for (int k=0;k<_Nq;k++) {
for (int j=0;j<_Nq;j++) {
for (int i=0;i<_Nq;i++) {
_r[i+j*_Nq+k*_Nq*_Nq] = r1D[i];
_s[i+j*_Nq+k*_Nq*_Nq] = r1D[j];
_t[i+j*_Nq+k*_Nq*_Nq] = r1D[k];
}
}
}
free(r1D);
}
void mesh_t::EquispacedEToVHex3D(int _N, int *_EToV){
int _Nq = _N+1;
int _Nverts = 4;
//Tensor product
int cnt=0;
for (int k=0;k<_N;k++) {
for (int j=0;j<_N;j++) {
for (int i=0;i<_N;i++) {
//tet 1 (0,3,2,7)
_EToV[cnt*_Nverts+0] = i +(j )*_Nq+(k )*_Nq*_Nq;
_EToV[cnt*_Nverts+1] = i+1+(j+1)*_Nq+(k )*_Nq*_Nq;
_EToV[cnt*_Nverts+2] = i +(j+1)*_Nq+(k )*_Nq*_Nq;
_EToV[cnt*_Nverts+3] = i+1+(j+1)*_Nq+(k+1)*_Nq*_Nq;
cnt++;
//tet 2 (0,1,3,7)
_EToV[cnt*_Nverts+0] = i +(j )*_Nq+(k )*_Nq*_Nq;
_EToV[cnt*_Nverts+1] = i+1+(j )*_Nq+(k )*_Nq*_Nq;
_EToV[cnt*_Nverts+2] = i+1+(j+1)*_Nq+(k )*_Nq*_Nq;
_EToV[cnt*_Nverts+3] = i+1+(j+1)*_Nq+(k+1)*_Nq*_Nq;
cnt++;
//tet 3 (0,2,6,7)
_EToV[cnt*_Nverts+0] = i +(j )*_Nq+(k )*_Nq*_Nq;
_EToV[cnt*_Nverts+1] = i +(j+1)*_Nq+(k )*_Nq*_Nq;
_EToV[cnt*_Nverts+2] = i +(j+1)*_Nq+(k+1)*_Nq*_Nq;
_EToV[cnt*_Nverts+3] = i+1+(j+1)*_Nq+(k+1)*_Nq*_Nq;
cnt++;
//tet 4 (0,6,4,7)
_EToV[cnt*_Nverts+0] = i +(j )*_Nq+(k )*_Nq*_Nq;
_EToV[cnt*_Nverts+1] = i +(j+1)*_Nq+(k+1)*_Nq*_Nq;
_EToV[cnt*_Nverts+2] = i +(j )*_Nq+(k+1)*_Nq*_Nq;
_EToV[cnt*_Nverts+3] = i+1+(j+1)*_Nq+(k+1)*_Nq*_Nq;
cnt++;
//tet 5 (0,5,1,7)
_EToV[cnt*_Nverts+0] = i +(j )*_Nq+(k )*_Nq*_Nq;
_EToV[cnt*_Nverts+1] = i+1+(j )*_Nq+(k+1)*_Nq*_Nq;
_EToV[cnt*_Nverts+2] = i+1+(j )*_Nq+(k )*_Nq*_Nq;
_EToV[cnt*_Nverts+3] = i+1+(j+1)*_Nq+(k+1)*_Nq*_Nq;
cnt++;
//tet 6 (0,4,5,7)
_EToV[cnt*_Nverts+0] = i +(j )*_Nq+(k )*_Nq*_Nq;
_EToV[cnt*_Nverts+1] = i +(j )*_Nq+(k+1)*_Nq*_Nq;
_EToV[cnt*_Nverts+2] = i+1+(j )*_Nq+(k+1)*_Nq*_Nq;
_EToV[cnt*_Nverts+3] = i+1+(j+1)*_Nq+(k+1)*_Nq*_Nq;
cnt++;
}
}
}
}
void mesh_t::SEMFEMEToVHex3D(int _N, int *_EToV){
int _Nq = _N+1;
int _Nverts = 8;
//Tensor product
int cnt=0;
for (int k=0;k<_N;k++) {
for (int j=0;j<_N;j++) {
for (int i=0;i<_N;i++) {
_EToV[cnt*_Nverts+0] = i +(j )*_Nq+(k )*_Nq*_Nq;
_EToV[cnt*_Nverts+1] = i+1+(j )*_Nq+(k )*_Nq*_Nq;
_EToV[cnt*_Nverts+2] = i+1+(j+1)*_Nq+(k )*_Nq*_Nq;
_EToV[cnt*_Nverts+3] = i +(j+1)*_Nq+(k )*_Nq*_Nq;
_EToV[cnt*_Nverts+4] = i +(j )*_Nq+(k+1)*_Nq*_Nq;
_EToV[cnt*_Nverts+5] = i+1+(j )*_Nq+(k+1)*_Nq*_Nq;
_EToV[cnt*_Nverts+6] = i+1+(j+1)*_Nq+(k+1)*_Nq*_Nq;
_EToV[cnt*_Nverts+7] = i +(j+1)*_Nq+(k+1)*_Nq*_Nq;
cnt++;
}
}
}
}
// ------------------------------------------------------------------------
// ORTHONORMAL BASIS POLYNOMIALS
// ------------------------------------------------------------------------
void mesh_t::OrthonormalBasisHex3D(dfloat a, dfloat b, dfloat c, int i, int j, int k, dfloat *P){
*P = JacobiP(a,0,0,i)*JacobiP(b,0,0,j)*JacobiP(c,0,0,k);
}
void mesh_t::GradOrthonormalBasisHex3D(dfloat a, dfloat b, dfloat c, int i, int j, int k, dfloat *Pr, dfloat *Ps, dfloat *Pt){
*Pr = GradJacobiP(a,0,0,i)*JacobiP(b,0,0,j)*JacobiP(c,0,0,k);
*Ps = JacobiP(a,0,0,i)*GradJacobiP(b,0,0,j)*JacobiP(c,0,0,k);
*Pt = JacobiP(a,0,0,i)*JacobiP(b,0,0,j)*GradJacobiP(c,0,0,k);
}
// ------------------------------------------------------------------------
// 2D VANDERMONDE MATRICES
// ------------------------------------------------------------------------
void mesh_t::VandermondeHex3D(int _N, int Npoints, dfloat *_r, dfloat *_s, dfloat *_t, dfloat *V){
int _Nq = _N+1;
int _Np = _Nq*_Nq*_Nq;
for(int n=0; n<Npoints; n++){
for(int k=0; k<_Nq; k++){
for(int j=0; j<_Nq; j++){
for(int i=0; i<_Nq; i++){
int id = n*_Np+i+j*_Nq+k*_Nq*_Nq;
OrthonormalBasisHex3D(_r[n], _s[n], _t[n], i, j, k, V+id);
}
}
}
}
}
void mesh_t::GradVandermondeHex3D(int _N, int Npoints, dfloat *_r, dfloat *_s, dfloat *_t, dfloat *Vr, dfloat *Vs, dfloat *Vt){
int _Nq = _N+1;
int _Np = _Nq*_Nq*_Nq;
for(int n=0; n<Npoints; n++){
for(int k=0; k<_Nq; k++){
for(int j=0; j<_Nq; j++){
for(int i=0; i<_Nq; i++){
int id = n*_Np+i+j*_Nq+k*_Nq*_Nq;
GradOrthonormalBasisHex3D(_r[n], _s[n], _t[n], i, j, k, Vr+id, Vs+id, Vt+id);
}
}
}
}
}
// ------------------------------------------------------------------------
// 2D OPERATOR MATRICES
// ------------------------------------------------------------------------
void mesh_t::MassMatrixHex3D(int _Np, dfloat *V, dfloat *_MM){
// masMatrix = inv(V')*inv(V) = inv(V*V')
for(int n=0;n<_Np;++n){
for(int m=0;m<_Np;++m){
dfloat res = 0;
for(int i=0;i<_Np;++i){
res += V[n*_Np+i]*V[m*_Np+i];
}
_MM[n*_Np + m] = res;
}
}
matrixInverse(_Np, _MM);
}
void mesh_t::LumpedMassMatrixHex3D(int _N, dfloat *_gllw, dfloat *_MM){
int _Nq = _N+1;
int _Np = _Nq*_Nq*_Nq;
// LumpedMassMatrix = gllw \ctimes gllw \ctimes gllw
for(int k=0;k<_Nq;++k){
for(int n=0;n<_Nq;++n){
for(int m=0;m<_Nq;++m){
int id = n+m*_Nq+k*_Nq*_Nq;
_MM[id+id*_Np] = _gllw[n]*_gllw[m]*_gllw[k];
}
}
}
}
void mesh_t::invLumpedMassMatrixHex3D(int _N, dfloat *_gllw, dfloat *_invMM){
int _Nq = _N+1;
int _Np = _Nq*_Nq*_Nq;
// invLumpedMassMatrix = invgllw \ctimes invgllw
for(int k=0;k<_Nq;++k){
for(int n=0;n<_Nq;++n){
for(int m=0;m<_Nq;++m){
int id = n+m*_Nq+k*_Nq*_Nq;
_invMM[id+id*_Np] = 1.0/(_gllw[n]*_gllw[m]*_gllw[k]);
}
}
}
}
void mesh_t::DmatrixHex3D(int _N, int Npoints, dfloat *_r, dfloat *_s, dfloat *_t,
dfloat *_Dr, dfloat *_Ds, dfloat *_Dt){
int _Nq = _N+1;
int _Np = _Nq*_Nq*_Nq;
dfloat *V = (dfloat *) calloc(Npoints*_Np, sizeof(dfloat));
dfloat *Vr = (dfloat *) calloc(Npoints*_Np, sizeof(dfloat));
dfloat *Vs = (dfloat *) calloc(Npoints*_Np, sizeof(dfloat));
dfloat *Vt = (dfloat *) calloc(Npoints*_Np, sizeof(dfloat));
VandermondeHex3D(_N, Npoints, _r, _s, _t, V);
GradVandermondeHex3D(_N, Npoints, _r, _s, _t, Vr, Vs, Vt);
//Dr = Vr/V, Ds = Vs/V, Dt = Vt/V
matrixRightSolve(_Np, _Np, Vr, _Np, _Np, V, _Dr);
matrixRightSolve(_Np, _Np, Vs, _Np, _Np, V, _Ds);
matrixRightSolve(_Np, _Np, Vt, _Np, _Np, V, _Dt);
free(V); free(Vr); free(Vs); free(Vt);
}
void mesh_t::InterpolationMatrixHex3D(int _N,
int NpointsIn, dfloat *rIn, dfloat *sIn, dfloat *tIn,
int NpointsOut, dfloat *rOut, dfloat *sOut, dfloat *tOut,
dfloat *I){
int _Nq = _N+1;
int _Np = _Nq*_Nq*_Nq;
// need NpointsIn = _Np
if (NpointsIn != _Np)
LIBP_ABORT(string("Invalid Interplation operator requested."))
dfloat *VIn = (dfloat*) malloc(NpointsIn*_Np*sizeof(dfloat));
dfloat *VOut= (dfloat*) malloc(NpointsOut*_Np*sizeof(dfloat));
VandermondeHex3D(_N, NpointsIn, rIn, sIn, tIn, VIn);
VandermondeHex3D(_N, NpointsOut, rOut, sOut, tOut, VOut);
matrixRightSolve(NpointsOut, _Np, VOut, NpointsIn, _Np, VIn, I);
free(VIn); free(VOut);
}
#endif | 31.594444 | 127 | 0.529277 | [
"mesh",
"3d"
] |
6040ed7550d9482f1d56c537dbcd3c802e5976c8 | 12,639 | cc | C++ | paddle/fluid/operators/affine_channel_op.cc | zhaoyuchen2018/Paddle | 2cd3abdc91b3bbcae6cb4d752f872258aa0ce06a | [
"Apache-2.0"
] | 1 | 2018-06-23T10:46:40.000Z | 2018-06-23T10:46:40.000Z | paddle/fluid/operators/affine_channel_op.cc | zhaoyuchen2018/Paddle | 2cd3abdc91b3bbcae6cb4d752f872258aa0ce06a | [
"Apache-2.0"
] | null | null | null | paddle/fluid/operators/affine_channel_op.cc | zhaoyuchen2018/Paddle | 2cd3abdc91b3bbcae6cb4d752f872258aa0ce06a | [
"Apache-2.0"
] | 2 | 2017-08-10T02:35:12.000Z | 2018-06-23T10:46:01.000Z | /* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
Indicesou may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
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 <string>
#include <unordered_map>
#include "paddle/fluid/framework/data_layout.h"
#include "paddle/fluid/framework/eigen.h"
#include "paddle/fluid/framework/op_registry.h"
namespace paddle {
namespace operators {
class AffineChannelOpMaker : public framework::OpProtoAndCheckerMaker {
public:
void Make() override {
AddInput("X",
"(Tensor) Feature map input can be a 4D tensor with order NCHW "
"or NHWC. It also can be a 2D tensor and C is the second "
"dimension.");
AddInput("Scale",
"(Tensor) 1D input of shape (C), the c-th element "
"is the scale factor of the affine transformation "
"for the c-th channel of the input.");
AddInput("Bias",
"(Tensor) 1D input of shape (C), the c-th element "
"is the bias of the affine transformation for the "
"c-th channel of the input.");
AddAttr<std::string>(
"data_layout",
"(string, default NCHW) Only used in "
"An optional string from: \"NHWC\", \"NCHW\". "
"Defaults to \"NHWC\". Specify the data format of the output data, "
"the input will be transformed automatically. ")
.SetDefault("AnyLayout");
AddOutput("Out", "(Tensor) A tensor of the same shape and order with X.");
AddComment(R"DOC(
Applies a separate affine transformation to each channel of the input. Useful
for replacing spatial batch norm with its equivalent fixed transformation.
The input also can be 2D tensor and applies a affine transformation in second
dimension.
$$Out = Scale*X + Bias$$
)DOC");
}
};
class AffineChannelOp : public framework::OperatorWithKernel {
public:
using framework::OperatorWithKernel::OperatorWithKernel;
void InferShape(framework::InferShapeContext* ctx) const override {
PADDLE_ENFORCE(ctx->HasInput("X"),
"Input(X) of AffineChannelOp should not be null.");
PADDLE_ENFORCE(ctx->HasInput("Scale"),
"Input(Scale) of AffineChannelOp should not be null.");
PADDLE_ENFORCE(ctx->HasInput("Bias"),
"Input(Bias) of AffineChannelOp should not be null.");
PADDLE_ENFORCE(ctx->HasOutput("Out"),
"Output(Out) of AffineChannelOp should not be null.");
auto x_dims = ctx->GetInputDim("X");
auto scale_dims = ctx->GetInputDim("Scale");
auto b_dims = ctx->GetInputDim("Bias");
const framework::DataLayout data_layout = framework::StringToDataLayout(
ctx->Attrs().Get<std::string>("data_layout"));
const int64_t C = (data_layout == framework::DataLayout::kNCHW
? x_dims[1]
: x_dims[x_dims.size() - 1]);
PADDLE_ENFORCE_EQ(scale_dims.size(), 1UL);
PADDLE_ENFORCE_EQ(b_dims.size(), 1UL);
if (ctx->IsRuntime() || scale_dims[0] > 0) {
PADDLE_ENFORCE_EQ(scale_dims[0], C);
}
if (ctx->IsRuntime() || b_dims[0] > 0) {
PADDLE_ENFORCE_EQ(b_dims[0], C);
}
ctx->SetOutputDim("Out", ctx->GetInputDim("X"));
ctx->ShareLoD("X", "Out");
}
};
class AffineChannelOpGrad : public framework::OperatorWithKernel {
public:
using framework::OperatorWithKernel::OperatorWithKernel;
void InferShape(framework::InferShapeContext* ctx) const override {
PADDLE_ENFORCE(ctx->HasInput(framework::GradVarName("Out")),
"Input(Out@GRAD) should not be null.");
if (ctx->HasOutput(framework::GradVarName("X"))) {
PADDLE_ENFORCE(ctx->HasInput("Scale"),
"Input(Scale) should not be null.");
ctx->SetOutputDim(framework::GradVarName("X"),
ctx->GetInputDim(framework::GradVarName("Out")));
}
if (ctx->HasOutput(framework::GradVarName("Scale"))) {
// Scale@GRAD and Bias@GRAD must exist at the same time.
PADDLE_ENFORCE(ctx->HasOutput(framework::GradVarName("Bias")),
"Output(Scale@GRAD) should not be null.");
PADDLE_ENFORCE(ctx->HasInput("X"), "Input(X) should not be null.");
ctx->SetOutputDim(framework::GradVarName("Scale"),
ctx->GetInputDim("Scale"));
ctx->SetOutputDim(framework::GradVarName("Bias"),
ctx->GetInputDim("Scale"));
}
}
protected:
framework::OpKernelType GetExpectedKernelType(
const framework::ExecutionContext& ctx) const override {
return framework::OpKernelType(OperatorWithKernel::IndicateVarDataType(
ctx, framework::GradVarName("Out")),
ctx.GetPlace());
}
};
class AffineChannelGradMaker : public framework::SingleGradOpDescMaker {
public:
using framework::SingleGradOpDescMaker::SingleGradOpDescMaker;
std::unique_ptr<framework::OpDesc> Apply() const override {
auto* op = new framework::OpDesc();
op->SetType("affine_channel_grad");
op->SetInput("X", Input("X"));
op->SetInput(framework::GradVarName("Out"), OutputGrad("Out"));
op->SetInput("Scale", Input("Scale"));
op->SetAttrMap(Attrs());
op->SetOutput(framework::GradVarName("X"), InputGrad("X"));
op->SetOutput(framework::GradVarName("Scale"), InputGrad("Scale"));
op->SetOutput(framework::GradVarName("Bias"), InputGrad("Bias"));
return std::unique_ptr<framework::OpDesc>(op);
}
};
template <typename T>
using EigenArrayMap =
Eigen::Map<Eigen::Array<T, Eigen::Dynamic, Eigen::Dynamic>>;
template <typename T>
using ConstEigenArrayMap =
Eigen::Map<const Eigen::Array<T, Eigen::Dynamic, Eigen::Dynamic>>;
template <typename T>
using EigenVectorArrayMap = Eigen::Map<Eigen::Array<T, Eigen::Dynamic, 1>>;
template <typename T>
using ConstEigenVectorArrayMap =
Eigen::Map<const Eigen::Array<T, Eigen::Dynamic, 1>>;
template <typename DeviceContext, typename T>
class AffineChannelKernel : public framework::OpKernel<T> {
public:
void Compute(const framework::ExecutionContext& ctx) const override {
auto* x = ctx.Input<framework::Tensor>("X");
auto* scale = ctx.Input<framework::Tensor>("Scale");
auto* bias = ctx.Input<framework::Tensor>("Bias");
auto* y = ctx.Output<framework::Tensor>("Out");
y->mutable_data<T>(ctx.GetPlace());
const framework::DataLayout layout =
framework::StringToDataLayout(ctx.Attr<std::string>("data_layout"));
auto dims = x->dims();
int N = dims[0];
int C = layout == framework::DataLayout::kNCHW ? dims[1]
: dims[dims.size() - 1];
int HxW = x->numel() / N / C;
auto* scale_d = scale->data<T>();
auto* bias_d = bias->data<T>();
ConstEigenVectorArrayMap<T> a_e(scale_d, C);
ConstEigenVectorArrayMap<T> b_e(bias_d, C);
auto* x_d = x->data<T>();
auto* y_d = y->data<T>();
if (layout == framework::DataLayout::kNCHW) {
int stride = C * HxW;
for (int i = 0; i < N; i++) {
ConstEigenArrayMap<T> x_e(x_d, HxW, C);
EigenArrayMap<T> y_e(y_d, HxW, C);
y_e = (x_e.rowwise() * a_e.transpose()).rowwise() + b_e.transpose();
x_d += stride;
y_d += stride;
}
} else {
int num = N * HxW;
ConstEigenArrayMap<T> x_e(x_d, C, num);
EigenArrayMap<T> y_e(y_d, C, num);
y_e = (x_e.colwise() * a_e).colwise() + b_e;
}
}
};
template <typename DeviceContext, typename T>
class AffineChannelGradKernel : public framework::OpKernel<T> {
public:
void Compute(const framework::ExecutionContext& ctx) const override {
auto* x = ctx.Input<framework::Tensor>("X");
auto* scale = ctx.Input<framework::Tensor>("Scale");
auto* dy = ctx.Input<framework::Tensor>(framework::GradVarName("Out"));
auto* dx = ctx.Output<framework::Tensor>(framework::GradVarName("X"));
auto* dscale =
ctx.Output<framework::Tensor>(framework::GradVarName("Scale"));
auto* dbias = ctx.Output<framework::Tensor>(framework::GradVarName("Bias"));
const framework::DataLayout layout =
framework::StringToDataLayout(ctx.Attr<std::string>("data_layout"));
auto dims = x->dims();
int N = dims[0];
int C = layout == framework::DataLayout::kNCHW ? dims[1]
: dims[dims.size() - 1];
int HxW = x->numel() / N / C;
auto* dy_d = dy->data<T>();
auto* scale_d = scale->data<T>();
ConstEigenVectorArrayMap<T> scale_e(scale_d, C);
T* dx_d = dx ? dx->mutable_data<T>(ctx.GetPlace()) : nullptr;
T* dscale_d = dscale ? dscale->mutable_data<T>(ctx.GetPlace()) : nullptr;
T* dbias_d = dbias ? dbias->mutable_data<T>(ctx.GetPlace()) : nullptr;
EigenVectorArrayMap<T> dscale_e(dscale_d, C);
EigenVectorArrayMap<T> dbias_e(dbias_d, C);
if (layout == framework::DataLayout::kNCHW) {
// compute dscale and dbias
int stride = C * HxW;
auto* original_dy_d = dy_d;
if (dscale && dbias) {
auto* x_d = x->data<T>();
for (int i = 0; i < N; i++) {
ConstEigenArrayMap<T> x_e(x_d, HxW, C);
ConstEigenArrayMap<T> dy_e(dy_d, HxW, C);
if (i == 0) {
dscale_e = (x_e * dy_e).colwise().sum();
} else {
dscale_e += (x_e * dy_e).colwise().sum();
}
if (i == 0) {
dbias_e = dy_e.colwise().sum();
} else {
dbias_e += dy_e.colwise().sum();
}
x_d += stride;
dy_d += stride;
}
}
// compute dx
if (dx) {
dy_d = original_dy_d;
for (int i = 0; i < N; i++) {
ConstEigenArrayMap<T> dy_e(dy_d, HxW, C);
EigenArrayMap<T> dx_e(dx_d, HxW, C);
dx_e = dy_e.rowwise() * scale_e.transpose();
dy_d += stride;
dx_d += stride;
}
}
} else {
int num = N * HxW;
ConstEigenArrayMap<T> dy_e(dy_d, C, num);
// compute dscale and dbias
if (dscale && dbias) {
auto* x_d = x->data<T>();
ConstEigenArrayMap<T> x_e(x_d, C, num);
dscale_e = (x_e * dy_e).rowwise().sum();
dbias_e = dy_e.rowwise().sum();
}
// compute dx
if (dx) {
EigenArrayMap<T> dx_e(dx_d, C, num);
dx_e = dy_e.colwise() * scale_e;
}
}
}
};
class AffineChannelNoNeedBufferVarsInference
: public framework::NoNeedBufferVarsInference {
public:
using framework::NoNeedBufferVarsInference::NoNeedBufferVarsInference;
private:
inline bool HasOutput(const std::string& name) const {
auto& outputs = Outputs();
auto iter = outputs.find(name);
if (iter == outputs.end() || iter->second.empty()) {
return false;
} else {
return iter->second[0] != framework::kEmptyVarName;
}
}
public:
std::unordered_set<std::string> operator()() const override {
if (!HasOutput(framework::GradVarName("Scale")) &&
!HasOutput(framework::GradVarName("Bias"))) {
return {"X"};
} else {
return {};
}
}
};
DECLARE_INPLACE_OP_INFERER(AffineChannelInplaceInferer, {"X", "Out"});
DECLARE_INPLACE_OP_INFERER(AffineChannelGradInplaceInferer,
{framework::GradVarName("Out"),
framework::GradVarName("X")});
} // namespace operators
} // namespace paddle
namespace ops = paddle::operators;
using CPU = paddle::platform::CPUDeviceContext;
REGISTER_OPERATOR(affine_channel, ops::AffineChannelOp,
ops::AffineChannelOpMaker, ops::AffineChannelGradMaker,
ops::AffineChannelInplaceInferer);
REGISTER_OPERATOR(affine_channel_grad, ops::AffineChannelOpGrad,
ops::AffineChannelNoNeedBufferVarsInference,
ops::AffineChannelGradInplaceInferer);
REGISTER_OP_CPU_KERNEL(affine_channel, ops::AffineChannelKernel<CPU, float>,
ops::AffineChannelKernel<CPU, double>);
REGISTER_OP_CPU_KERNEL(affine_channel_grad,
ops::AffineChannelGradKernel<CPU, float>,
ops::AffineChannelGradKernel<CPU, double>);
| 36.634783 | 80 | 0.621093 | [
"shape"
] |
60437ae20b70c87d89e0a04a3c28b2c9530acd0b | 3,369 | hpp | C++ | include/yaclib/algo/detail/when_all_impl.hpp | YACLib/YACLib | fa5e13cdcc1f719e6b6363ba25a4791315e66916 | [
"MIT"
] | 106 | 2021-07-04T01:10:18.000Z | 2022-03-21T00:58:27.000Z | include/yaclib/algo/detail/when_all_impl.hpp | YACLib/YACLib | fa5e13cdcc1f719e6b6363ba25a4791315e66916 | [
"MIT"
] | 119 | 2021-07-10T14:26:24.000Z | 2022-03-22T22:48:18.000Z | include/yaclib/algo/detail/when_all_impl.hpp | YACLib/YACLib | fa5e13cdcc1f719e6b6363ba25a4791315e66916 | [
"MIT"
] | 7 | 2021-07-23T11:23:04.000Z | 2021-11-13T20:22:56.000Z | #pragma once
#include <yaclib/algo/when_policy.hpp>
#include <yaclib/async/future.hpp>
#include <yaclib/async/promise.hpp>
#include <array>
#include <iterator>
#include <type_traits>
#include <utility>
#include <vector>
namespace yaclib::detail {
template <typename T>
class AllCombinatorBase {
protected:
std::atomic<bool> _done{false};
std::atomic<size_t> _ticket{0};
T _results;
};
template <>
class AllCombinatorBase<void> {
protected:
std::atomic<bool> _done{false};
};
template <
typename T, size_t N = std::numeric_limits<size_t>::max(), bool IsArray = (N != std::numeric_limits<size_t>::max()),
typename FutureValue =
std::conditional_t<std::is_void_v<T>, void, std::conditional_t<IsArray, std::array<T, N>, std::vector<T>>>>
class AllCombinator : public InlineCore, public AllCombinatorBase<FutureValue> {
using Base = AllCombinatorBase<FutureValue>;
public:
static std::pair<Future<FutureValue>, util::Ptr<AllCombinator>> Make(size_t size = 0) {
auto [future, promise] = MakeContract<FutureValue>();
if constexpr (!IsArray) {
if (size == 0) {
if constexpr (std::is_void_v<T>) {
std::move(promise).Set();
} else {
std::move(promise).Set(std::vector<T>{});
}
return {std::move(future), nullptr};
}
}
return {std::move(future), util::MakeIntrusive<AllCombinator>(std::move(promise), size)};
}
explicit AllCombinator(Promise<FutureValue> promise, [[maybe_unused]] size_t size = 0)
: _promise{std::move(promise)} {
if constexpr (!std::is_void_v<T> && !IsArray) {
AllCombinatorBase<FutureValue>::_results.resize(size);
}
}
void CallInline(InlineCore* context) noexcept final {
if (_promise.GetCore()->GetState() != BaseCore::State::HasStop) {
Combine(std::move(static_cast<ResultCore<T>*>(context)->Get()));
}
}
void Combine(util::Result<T>&& result) noexcept(std::is_void_v<T> || std::is_nothrow_move_assignable_v<T>) {
if (Base::_done.load(std::memory_order_acquire)) {
return;
}
auto state = result.State();
if (state == util::ResultState::Value) {
if constexpr (!std::is_void_v<T>) {
const auto ticket = AllCombinatorBase<FutureValue>::_ticket.fetch_add(1, std::memory_order_acq_rel);
AllCombinatorBase<FutureValue>::_results[ticket] = std::move(result).Value();
}
return;
}
if (Base::_done.exchange(true, std::memory_order_acq_rel)) {
return;
}
if (state == util::ResultState::Error) {
std::move(_promise).Set(std::move(result).Error());
} else {
std::move(_promise).Set(std::move(result).Exception());
}
}
~AllCombinator() override {
if (!Base::_done.load(std::memory_order_acquire)) {
if constexpr (!std::is_void_v<T>) {
std::move(_promise).Set(std::move(AllCombinatorBase<FutureValue>::_results));
} else {
std::move(_promise).Set();
}
}
}
private:
Promise<FutureValue> _promise;
};
template <size_t N, typename T, typename... Ts>
void WhenAllImpl(util::Ptr<AllCombinator<T, N>>& combinator, Future<T>&& head, Future<Ts>&&... tail) {
head.GetCore()->SetCallbackInline(combinator);
std::move(head).Detach();
if constexpr (sizeof...(tail) != 0) {
WhenAllImpl(combinator, std::move(tail)...);
}
}
} // namespace yaclib::detail
| 30.351351 | 120 | 0.649154 | [
"vector"
] |
6054ed22bfc7e85b95b9b123deb6a803fbebe790 | 2,885 | hpp | C++ | tests/unit-tests/mgmt/nfd/controller-fixture.hpp | 7th-ndn-hackathon/Buffer-Interest_cxx | 7b1124674a2de5add307982f02652e752724c844 | [
"OpenSSL"
] | 1 | 2021-09-07T04:12:15.000Z | 2021-09-07T04:12:15.000Z | tests/unit-tests/mgmt/nfd/controller-fixture.hpp | 7th-ndn-hackathon/Buffer-Interest_cxx | 7b1124674a2de5add307982f02652e752724c844 | [
"OpenSSL"
] | null | null | null | tests/unit-tests/mgmt/nfd/controller-fixture.hpp | 7th-ndn-hackathon/Buffer-Interest_cxx | 7b1124674a2de5add307982f02652e752724c844 | [
"OpenSSL"
] | 1 | 2020-07-15T06:21:03.000Z | 2020-07-15T06:21:03.000Z | /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/*
* Copyright (c) 2013-2017 Regents of the University of California.
*
* This file is part of ndn-cxx library (NDN C++ library with eXperimental eXtensions).
*
* ndn-cxx library is free software: you can redistribute it and/or modify it under the
* terms of the GNU Lesser General Public License as published by the Free Software
* Foundation, either version 3 of the License, or (at your option) any later version.
*
* ndn-cxx library is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
*
* You should have received copies of the GNU General Public License and GNU Lesser
* General Public License along with ndn-cxx, e.g., in COPYING.md file. If not, see
* <http://www.gnu.org/licenses/>.
*
* See AUTHORS.md for complete list of ndn-cxx authors and contributors.
*/
#ifndef NDN_TESTS_MGMT_NFD_CONTROLLER_FIXTURE_HPP
#define NDN_TESTS_MGMT_NFD_CONTROLLER_FIXTURE_HPP
#include "mgmt/nfd/controller.hpp"
#include "util/dummy-client-face.hpp"
#include "security/v2/certificate-fetcher-offline.hpp"
#include "boost-test.hpp"
#include "dummy-validator.hpp"
#include "unit-tests/identity-management-time-fixture.hpp"
namespace ndn {
namespace nfd {
namespace tests {
using namespace ndn::tests;
class ControllerFixture : public IdentityManagementTimeFixture
{
protected:
ControllerFixture()
: face(io, m_keyChain)
, m_validator(true)
, controller(face, m_keyChain, m_validator)
, commandFailCallback(bind(&ControllerFixture::recordCommandFail, this, _1))
, datasetFailCallback(bind(&ControllerFixture::recordDatasetFail, this, _1, _2))
{
Name identityName("/localhost/ControllerFixture");
m_keyChain.setDefaultIdentity(this->addIdentity(identityName));
}
/** \brief controls whether Controller's validator should accept or reject validation requests
*
* Initially, the validator accepts all requests.
* Setting \p false causes validator to reject all requests.
*/
void
setValidationResult(bool shouldAccept)
{
m_validator.getPolicy().setResult(shouldAccept);
}
private:
void
recordCommandFail(const ControlResponse& response)
{
failCodes.push_back(response.getCode());
}
void
recordDatasetFail(uint32_t code, const std::string& reason)
{
failCodes.push_back(code);
}
protected:
ndn::util::DummyClientFace face;
DummyValidator m_validator;
Controller controller;
Controller::CommandFailCallback commandFailCallback;
Controller::DatasetFailCallback datasetFailCallback;
std::vector<uint32_t> failCodes;
};
} // namespace tests
} // namespace nfd
} // namespace ndn
#endif // NDN_TESTS_MGMT_NFD_CONTROLLER_FIXTURE_HPP
| 31.703297 | 96 | 0.752513 | [
"vector"
] |
6055d87fd2fd3ebb5547deb666197cb4a17e5f56 | 12,654 | hpp | C++ | thirdparty/yasio/detail/object_pool.hpp | rh101/engine-x | 17ad9829dd410c689857760b6ece89d99e877a95 | [
"MIT"
] | 382 | 2020-03-02T17:41:12.000Z | 2022-03-30T17:54:17.000Z | thirdparty/yasio/detail/object_pool.hpp | rh101/engine-x | 17ad9829dd410c689857760b6ece89d99e877a95 | [
"MIT"
] | 172 | 2020-02-21T08:56:42.000Z | 2021-05-12T03:18:40.000Z | thirdparty/yasio/detail/object_pool.hpp | rh101/engine-x | 17ad9829dd410c689857760b6ece89d99e877a95 | [
"MIT"
] | 102 | 2020-03-01T01:43:19.000Z | 2022-03-25T13:20:36.000Z | //////////////////////////////////////////////////////////////////////////////////////////
// A multi-platform support c++11 library with focus on asynchronous socket I/O for any
// client application.
//////////////////////////////////////////////////////////////////////////////////////////
/*
The MIT License (MIT)
Copyright (c) 2012-2021 HALX99
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
// object_pool.hpp: a simple & high-performance object pool implementation v1.3.3
#ifndef YASIO__OBJECT_POOL_HPP
#define YASIO__OBJECT_POOL_HPP
#include <assert.h>
#include <stdlib.h>
#include <memory>
#include <mutex>
#include <type_traits>
#define OBJECT_POOL_DECL inline
#if defined(_MSC_VER)
# pragma warning(push)
# pragma warning(disable : 4200)
#endif
namespace yasio
{
namespace gc
{
#define YASIO_POOL_FL_BEGIN(chunk) reinterpret_cast<free_link_node*>(chunk->data)
#define YASIO_POOL_PREALLOCATE 1
template <typename _Ty> static size_t aligned_storage_size()
{
return sizeof(typename std::aligned_storage<sizeof(_Ty), std::alignment_of<_Ty>::value>::type);
}
namespace detail
{
class object_pool
{
typedef struct free_link_node
{
free_link_node* next;
} * free_link;
typedef struct chunk_link_node
{
chunk_link_node* next;
char data[0];
} * chunk_link;
object_pool(const object_pool&) = delete;
void operator=(const object_pool&) = delete;
public:
OBJECT_POOL_DECL object_pool(size_t element_size, size_t element_count)
: free_link_(nullptr), chunk_(nullptr), element_size_(element_size),
element_count_(element_count)
{
#if YASIO_POOL_PREALLOCATE
release(allocate_from_process_heap()); // preallocate 1 chunk
#endif
}
OBJECT_POOL_DECL virtual ~object_pool(void) { this->purge(); }
OBJECT_POOL_DECL void purge(void)
{
if (this->chunk_ == nullptr)
return;
chunk_link_node *p, **q = &this->chunk_;
while ((p = *q) != nullptr)
{
*q = p->next;
free(p);
}
free_link_ = nullptr;
}
OBJECT_POOL_DECL void cleanup(void)
{
if (this->chunk_ == nullptr)
{
return;
}
chunk_link_node* chunk = this->chunk_;
free_link_node* linkend = this->tidy_chunk(chunk);
while ((chunk = chunk->next) != nullptr)
{
linkend->next = YASIO_POOL_FL_BEGIN(chunk);
linkend = this->tidy_chunk(chunk);
}
linkend->next = nullptr;
this->free_link_ = YASIO_POOL_FL_BEGIN(this->chunk_);
}
OBJECT_POOL_DECL void* get(void)
{
if (this->free_link_ != nullptr)
{
return allocate_from_chunk();
}
return allocate_from_process_heap();
}
OBJECT_POOL_DECL void release(void* _Ptr)
{
free_link_node* ptr = reinterpret_cast<free_link_node*>(_Ptr);
ptr->next = this->free_link_;
this->free_link_ = ptr;
}
private:
OBJECT_POOL_DECL void* allocate_from_chunk(void)
{
free_link_node* ptr = this->free_link_;
this->free_link_ = ptr->next;
return reinterpret_cast<void*>(ptr);
}
OBJECT_POOL_DECL void* allocate_from_process_heap(void)
{
chunk_link new_chunk =
(chunk_link)malloc(sizeof(chunk_link_node) + element_size_ * element_count_);
#ifdef _DEBUG
::memset(new_chunk, 0x00, sizeof(chunk_link_node));
#endif
tidy_chunk(new_chunk)->next = nullptr;
// link the new_chunk
new_chunk->next = this->chunk_;
this->chunk_ = new_chunk;
// allocate 1 object
auto ptr = YASIO_POOL_FL_BEGIN(new_chunk);
this->free_link_ = ptr->next;
return reinterpret_cast<void*>(ptr);
}
OBJECT_POOL_DECL free_link_node* tidy_chunk(chunk_link chunk)
{
char* rbegin = chunk->data + (element_count_ - 1) * element_size_;
for (char* ptr = chunk->data; ptr < rbegin; ptr += element_size_)
{
reinterpret_cast<free_link_node*>(ptr)->next =
reinterpret_cast<free_link_node*>(ptr + element_size_);
}
return reinterpret_cast<free_link_node*>(rbegin);
}
private:
free_link free_link_; // link to free head
chunk_link chunk_; // chunk link
const size_t element_size_;
const size_t element_count_;
};
} // namespace detail
template <typename _Ty, typename _Mutex = std::mutex> class object_pool : public detail::object_pool
{
public:
object_pool(size_t _ElemCount = 512)
: detail::object_pool(yasio::gc::aligned_storage_size<_Ty>(), _ElemCount)
{}
template <typename... _Types> _Ty* construct(_Types&&... args)
{
return new (allocate()) _Ty(std::forward<_Types>(args)...);
}
void destroy(void* _Ptr)
{
((_Ty*)_Ptr)->~_Ty(); // call the destructor
release(_Ptr);
}
void* allocate()
{
std::lock_guard<_Mutex> lk(this->mutex_);
return get();
}
void deallocate(void* _Ptr)
{
std::lock_guard<_Mutex> lk(this->mutex_);
release(_Ptr);
}
_Mutex mutex_;
};
template <typename _Ty> class object_pool<_Ty, void> : public detail::object_pool
{
object_pool(const object_pool&) = delete;
void operator=(const object_pool&) = delete;
public:
object_pool(size_t _ElemCount = 512)
: detail::object_pool(yasio::gc::aligned_storage_size<_Ty>(), _ElemCount)
{}
template <typename... _Types> _Ty* construct(_Types&&... args)
{
return new (allocate()) _Ty(std::forward<_Types>(args)...);
}
void destroy(void* _Ptr)
{
((_Ty*)_Ptr)->~_Ty(); // call the destructor
release(_Ptr);
}
void* allocate() { return get(); }
void deallocate(void* _Ptr) { release(_Ptr); }
};
#define DEFINE_OBJECT_POOL_ALLOCATION(ELEMENT_TYPE, ELEMENT_COUNT) \
public: \
static void* operator new(size_t /*size*/) { return get_pool().allocate(); } \
\
static void* operator new(size_t /*size*/, std::nothrow_t) { return get_pool().allocate(); } \
\
static void operator delete(void* p) { get_pool().deallocate(p); } \
\
static yasio::gc::object_pool<ELEMENT_TYPE, void>& get_pool() \
{ \
static yasio::gc::object_pool<ELEMENT_TYPE, void> s_pool(ELEMENT_COUNT); \
return s_pool; \
}
// The thread safe edition
#define DEFINE_CONCURRENT_OBJECT_POOL_ALLOCATION(ELEMENT_TYPE, ELEMENT_COUNT) \
public: \
static void* operator new(size_t /*size*/) { return get_pool().allocate(); } \
\
static void* operator new(size_t /*size*/, std::nothrow_t) { return get_pool().allocate(); } \
\
static void operator delete(void* p) { get_pool().deallocate(p); } \
\
static yasio::gc::object_pool<ELEMENT_TYPE, std::mutex>& get_pool() \
{ \
static yasio::gc::object_pool<ELEMENT_TYPE, std::mutex> s_pool(ELEMENT_COUNT); \
return s_pool; \
}
//////////////////////// allocator /////////////////
// TEMPLATE CLASS object_pool_allocator, can't used by std::vector, DO NOT use at non-msvc compiler.
template <class _Ty, size_t _ElemCount = 512, class _Mutex = void> class object_pool_allocator
{ // generic allocator for objects of class _Ty
public:
typedef _Ty value_type;
typedef value_type* pointer;
typedef value_type& reference;
typedef const value_type* const_pointer;
typedef const value_type& const_reference;
typedef size_t size_type;
#ifdef _WIN32
typedef ptrdiff_t difference_type;
#else
typedef long difference_type;
#endif
template <class _Other> struct rebind
{ // convert this type to _ALLOCATOR<_Other>
typedef object_pool_allocator<_Other> other;
};
pointer address(reference _Val) const
{ // return address of mutable _Val
return ((pointer) & (char&)_Val);
}
const_pointer address(const_reference _Val) const
{ // return address of nonmutable _Val
return ((const_pointer) & (const char&)_Val);
}
object_pool_allocator() throw()
{ // construct default allocator (do nothing)
}
object_pool_allocator(const object_pool_allocator<_Ty>&) throw()
{ // construct by copying (do nothing)
}
template <class _Other> object_pool_allocator(const object_pool_allocator<_Other>&) throw()
{ // construct from a related allocator (do nothing)
}
template <class _Other>
object_pool_allocator<_Ty>& operator=(const object_pool_allocator<_Other>&)
{ // assign from a related allocator (do nothing)
return (*this);
}
void deallocate(pointer _Ptr, size_type)
{ // deallocate object at _Ptr, ignore size
_Spool().release(_Ptr);
}
pointer allocate(size_type count)
{ // allocate array of _Count elements
assert(count == 1);
(void)count;
return static_cast<pointer>(_Spool().get());
}
pointer allocate(size_type count, const void*)
{ // allocate array of _Count elements, not support, such as std::vector
return allocate(count);
}
void construct(_Ty* _Ptr)
{ // default construct object at _Ptr
::new ((void*)_Ptr) _Ty();
}
void construct(pointer _Ptr, const _Ty& _Val)
{ // construct object at _Ptr with value _Val
new (_Ptr) _Ty(_Val);
}
void construct(pointer _Ptr, _Ty&& _Val)
{ // construct object at _Ptr with value _Val
new ((void*)_Ptr) _Ty(std::forward<_Ty>(_Val));
}
template <class _Other> void construct(pointer _Ptr, _Other&& _Val)
{ // construct object at _Ptr with value _Val
new ((void*)_Ptr) _Ty(std::forward<_Other>(_Val));
}
template <class _Objty, class... _Types> void construct(_Objty* _Ptr, _Types&&... _Args)
{ // construct _Objty(_Types...) at _Ptr
::new ((void*)_Ptr) _Objty(std::forward<_Types>(_Args)...);
}
template <class _Uty> void destroy(_Uty* _Ptr)
{ // destroy object at _Ptr, do nothing
_Ptr->~_Uty();
}
size_type max_size() const throw()
{ // estimate maximum array size
size_type _Count = (size_type)(-1) / sizeof(_Ty);
return (0 < _Count ? _Count : 1);
}
static object_pool<_Ty, _Mutex>& _Spool()
{
static object_pool<_Ty, _Mutex> s_pool(_ElemCount);
return s_pool;
}
};
template <class _Ty, class _Other>
inline bool operator==(const object_pool_allocator<_Ty>&,
const object_pool_allocator<_Other>&) throw()
{ // test for allocator equality
return (true);
}
template <class _Ty, class _Other>
inline bool operator!=(const object_pool_allocator<_Ty>& _Left,
const object_pool_allocator<_Other>& _Right) throw()
{ // test for allocator inequality
return (!(_Left == _Right));
}
} // namespace gc
} // namespace yasio
#if defined(_MSC_VER)
# pragma warning(pop)
#endif
#endif
| 30.863415 | 100 | 0.606528 | [
"object",
"vector"
] |
6062f8626cfb348b488008b4db345bf60f4a09e9 | 1,561 | cc | C++ | Tree/0/5_Contrust_Binary_Tree_From_Preorder_And_Inorder_Traversal/method1/solution.cc | sheriby/DandAInLeetCode | dd7f5029aa0c297ea82bb20f882b524789f35c96 | [
"MIT"
] | 1 | 2020-02-07T12:25:56.000Z | 2020-02-07T12:25:56.000Z | Tree/0/5_Contrust_Binary_Tree_From_Preorder_And_Inorder_Traversal/method1/solution.cc | sheriby/DandAInLeetCode | dd7f5029aa0c297ea82bb20f882b524789f35c96 | [
"MIT"
] | null | null | null | Tree/0/5_Contrust_Binary_Tree_From_Preorder_And_Inorder_Traversal/method1/solution.cc | sheriby/DandAInLeetCode | dd7f5029aa0c297ea82bb20f882b524789f35c96 | [
"MIT"
] | null | null | null | #include <unordered_map>
#include <vector>
#include "treenode.h"
using std::unordered_map;
using std::vector;
class Solution {
public:
// 使用了一种递归的构造方式。
// 前序遍历的第一个节点是根节点,
// 中序遍历的某一个节点的左面是其左子树,右面是其右子树
// 从而通过构造左子树和右子树递归构造出整棵树
// 不过函数的参数并不是我们想要的,所以需要重载一下
// 时间复杂度: O(N)
// 空间复杂度: O(N)
TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
for (size_t i = 0; i < inorder.size(); i++) {
rootIndexMap[inorder[i]] = i;
}
return buildTree(preorder, 0, inorder, 0, preorder.size());
}
private:
unordered_map<int, int> rootIndexMap;
TreeNode* buildTree(vector<int>& preorder, int pstart, vector<int>& inorder,
int istart, int length) {
if (length == 0) {
return nullptr;
}
if (length == 1) {
return new TreeNode(preorder[pstart]);
}
TreeNode* root = new TreeNode(preorder[pstart]);
// 这里多次在中序遍历中找根节点的位置,可以使用一个map以空间换时间
// int rootIndex = istart;
// while (inorder[rootIndex] != preorder[pstart]) {
// rootIndex++;
// }
int rootIndex = rootIndexMap[preorder[pstart]];
int leftLength = rootIndex - istart;
int rightLength = length - leftLength - 1;
root->left =
buildTree(preorder, pstart + 1, inorder, istart, leftLength);
root->right = buildTree(preorder, pstart + leftLength + 1, inorder,
rootIndex + 1, rightLength);
return root;
}
}; | 30.019231 | 80 | 0.571429 | [
"vector"
] |
60637f9b1b9b361f24c354b46947b05cbb782440 | 2,305 | cc | C++ | mindspore/lite/src/train/loss_monitor.cc | PowerOlive/mindspore | bda20724a94113cedd12c3ed9083141012da1f15 | [
"Apache-2.0"
] | 3,200 | 2020-02-17T12:45:41.000Z | 2022-03-31T20:21:16.000Z | mindspore/lite/src/train/loss_monitor.cc | zimo-geek/mindspore | 665ec683d4af85c71b2a1f0d6829356f2bc0e1ff | [
"Apache-2.0"
] | 176 | 2020-02-12T02:52:11.000Z | 2022-03-28T22:15:55.000Z | mindspore/lite/src/train/loss_monitor.cc | zimo-geek/mindspore | 665ec683d4af85c71b2a1f0d6829356f2bc0e1ff | [
"Apache-2.0"
] | 621 | 2020-03-09T01:31:41.000Z | 2022-03-30T03:43:19.000Z | /**
* Copyright 2020 Huawei Technologies Co., Ltd
*
* 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
*
* 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 "include/train/loss_monitor.h"
#include <sys/stat.h>
#include <algorithm>
#include <utility>
#include <vector>
#include <iostream>
#include "include/lite_session.h"
#include "src/common/utils.h"
#include "src/tensor.h"
namespace mindspore {
namespace lite {
void LossMonitor::Begin(const session::TrainLoopCallBackData &cb_data) {
if (cb_data.epoch_ == 0) losses_.clear();
}
void LossMonitor::EpochBegin(const session::TrainLoopCallBackData &cb_data) {
if (losses_.size() != cb_data.epoch_) {
MS_LOG(WARNING) << "losses array does not match epoch number";
} else {
losses_.push_back(std::make_pair(cb_data.epoch_, 0.0));
}
}
int LossMonitor::EpochEnd(const session::TrainLoopCallBackData &cb_data) {
if (cb_data.step_ > 0) losses_.at(cb_data.epoch_).second /= static_cast<float>(cb_data.step_ + 1);
if (print_every_n_ > 0) {
std::cout << "Epoch (" << (cb_data.epoch_ + 1) << "):\tLoss is " << losses_.at(cb_data.epoch_).second << std::endl;
}
return mindspore::session::RET_CONTINUE;
}
void LossMonitor::StepEnd(const session::TrainLoopCallBackData &cb_data) {
auto outputs = cb_data.session_->GetOutputs();
for (auto it = outputs.begin(); it != outputs.end(); ++it) {
if (it->second->ElementsNum() == 1) {
auto loss = reinterpret_cast<float *>(it->second->MutableData());
losses_.at(cb_data.epoch_).second += loss[0];
if ((cb_data.step_ + 1) % print_every_n_ == 0)
std::cout << (cb_data.epoch_ + 1) << "." << (cb_data.step_ + 1) << ":\tLoss is " << loss[0] << std::endl;
return;
}
}
MS_LOG(WARNING) << "Model does not have a loss output tensor of size 1";
}
} // namespace lite
} // namespace mindspore
| 36.015625 | 119 | 0.689371 | [
"vector",
"model"
] |
60646894913d7238d0a00117dece27e2cb7098c7 | 68,797 | cpp | C++ | Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/TimeView/TimeViewPlugin.cpp | prophetl33t/o3de | eaeeb883eee1594b1b93327f6909eebd1a826caf | [
"Apache-2.0",
"MIT"
] | null | null | null | Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/TimeView/TimeViewPlugin.cpp | prophetl33t/o3de | eaeeb883eee1594b1b93327f6909eebd1a826caf | [
"Apache-2.0",
"MIT"
] | null | null | null | Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/TimeView/TimeViewPlugin.cpp | prophetl33t/o3de | eaeeb883eee1594b1b93327f6909eebd1a826caf | [
"Apache-2.0",
"MIT"
] | null | null | null | /*
* Copyright (c) Contributors to the Open 3D Engine Project.
* For complete copyright and license terms please see the LICENSE at the root of this distribution.
*
* SPDX-License-Identifier: Apache-2.0 OR MIT
*
*/
#include <Editor/InspectorBus.h>
#include <AzCore/Math/MathUtils.h>
#include "TimeViewPlugin.h"
#include "TrackDataHeaderWidget.h"
#include "TrackDataWidget.h"
#include "TrackHeaderWidget.h"
#include "TimeInfoWidget.h"
#include "TimeViewToolBar.h"
#include <EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/MotionSetsWindow/MotionSetsWindowPlugin.h>
#include <EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/MotionEvents/MotionEventsPlugin.h>
#include <EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/MotionEvents/MotionEventPresetsWidget.h>
#include <EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/MotionEvents/MotionEventWidget.h>
#include <EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/EMStudioManager.h>
#include <EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/MainWindow.h>
#include <QCheckBox>
#include <QDir>
#include <QDockWidget>
#include <QGridLayout>
#include <QPushButton>
#include <QScrollBar>
#include <MCore/Source/LogManager.h>
#include <MCore/Source/Compare.h>
#include <MCore/Source/ReflectionSerializer.h>
#include <EMotionFX/CommandSystem/Source/SelectionCommands.h>
#include <EMotionFX/Source/AnimGraphManager.h>
#include <EMotionFX/Source/MotionInstance.h>
#include <EMotionFX/Source/MotionEvent.h>
#include <EMotionFX/Source/MotionEventTrack.h>
#include <EMotionFX/Source/MotionManager.h>
#include <EMotionFX/Source/Recorder.h>
#include <EMotionFX/Source/MotionEventTable.h>
namespace EMStudio
{
TimeViewPlugin::TimeViewPlugin()
: EMStudio::DockWidgetPlugin()
{
m_pixelsPerSecond = 60;
m_curTime = 0;
m_fps = 32;
m_timeScale = 1.0;
m_targetTimeScale = 1.0;
m_scrollX = 0.0;
m_targetScrollX = 0.0;
m_maxTime = 0.0;
m_maxHeight = 0.0;
m_minScale = 0.25;
m_maxScale = 100.0;
m_curMouseX = 0;
m_curMouseY = 0;
m_totalTime = FLT_MAX;
m_zoomInCursor = nullptr;
m_zoomOutCursor = nullptr;
m_isAnimating = false;
m_dirty = true;
m_trackDataHeaderWidget = nullptr;
m_trackDataWidget = nullptr;
m_trackHeaderWidget = nullptr;
m_timeInfoWidget = nullptr;
m_nodeHistoryItem = nullptr;
m_eventHistoryItem = nullptr;
m_actorInstanceData = nullptr;
m_eventEmitterNode = nullptr;
m_mainWidget = nullptr;
m_motionEventsPlugin = nullptr;
m_motionSetPlugin = nullptr;
m_motion = nullptr;
m_brushCurTimeHandle = QBrush(QColor(255, 180, 0));
m_penCurTimeHandle = QPen(QColor(255, 180, 0));
m_penTimeHandles = QPen(QColor(150, 150, 150), 1, Qt::DotLine);
m_penCurTimeHelper = QPen(QColor(100, 100, 100), 1, Qt::DotLine);
}
TimeViewPlugin::~TimeViewPlugin()
{
if (m_motionEventWidget)
{
delete m_motionEventWidget;
m_motionEventWidget = nullptr;
}
EMotionFX::AnimGraphEditorNotificationBus::Handler::BusDisconnect();
for (MCore::Command::Callback* callback : m_commandCallbacks)
{
GetCommandManager()->RemoveCommandCallback(callback, false);
delete callback;
}
m_commandCallbacks.clear();
RemoveAllTracks();
// get rid of the cursors
delete m_zoomInCursor;
delete m_zoomOutCursor;
// get rid of the motion infos
for (MotionInfo* motionInfo : m_motionInfos)
{
delete motionInfo;
}
}
// get the name
const char* TimeViewPlugin::GetName() const
{
return "Time View";
}
// get the plugin type id
uint32 TimeViewPlugin::GetClassID() const
{
return TimeViewPlugin::CLASS_ID;
}
// on before remove plugin
void TimeViewPlugin::OnBeforeRemovePlugin(uint32 classID)
{
if (classID == MotionEventsPlugin::CLASS_ID)
{
m_motionEventsPlugin = nullptr;
}
}
// init after the parent dock window has been created
bool TimeViewPlugin::Init()
{
m_commandCallbacks.emplace_back(new CommandAdjustMotionCallback(false));
GetCommandManager()->RegisterCommandCallback("AdjustMotion", m_commandCallbacks.back());
m_commandCallbacks.emplace_back(new CommandSelectCallback(false));
GetCommandManager()->RegisterCommandCallback("Select", m_commandCallbacks.back());
m_commandCallbacks.emplace_back(new CommandUnselectCallback(false));
GetCommandManager()->RegisterCommandCallback("Unselect", m_commandCallbacks.back());
m_commandCallbacks.emplace_back(new CommandClearSelectionCallback(false));
GetCommandManager()->RegisterCommandCallback("ClearSelection", m_commandCallbacks.back());
m_commandCallbacks.emplace_back(new CommandRecorderClearCallback(false));
GetCommandManager()->RegisterCommandCallback("RecorderClear", m_commandCallbacks.back());
m_commandCallbacks.emplace_back(new UpdateInterfaceCallback(false));
GetCommandManager()->RegisterCommandCallback("AdjustDefaultPlayBackInfo", m_commandCallbacks.back());
m_commandCallbacks.emplace_back(new UpdateInterfaceCallback(false));
GetCommandManager()->RegisterCommandCallback("PlayMotion", m_commandCallbacks.back());
// load the cursors
m_zoomInCursor = new QCursor(QPixmap(QDir{ QString(MysticQt::GetDataDir().c_str()) }.filePath("Images/Rendering/ZoomInCursor.png")).scaled(32, 32));
m_zoomOutCursor = new QCursor(QPixmap(QDir{ QString(MysticQt::GetDataDir().c_str()) }.filePath("Images/Rendering/ZoomOutCursor.png")).scaled(32, 32));
// create main widget
m_mainWidget = new QWidget(m_dock);
m_dock->setWidget(m_mainWidget);
QGridLayout* mainLayout = new QGridLayout();
mainLayout->setMargin(0);
mainLayout->setSpacing(0);
m_mainWidget->setLayout(mainLayout);
// create widgets in the header
QHBoxLayout* topLayout = new QHBoxLayout();
// Top
m_timeViewToolBar = new TimeViewToolBar(this);
// Top-left
m_timeInfoWidget = new TimeInfoWidget(this);
m_timeInfoWidget->setFixedWidth(175);
topLayout->addWidget(m_timeInfoWidget);
topLayout->addWidget(m_timeViewToolBar);
mainLayout->addLayout(topLayout, 0, 0, 1, 2);
// Top-right
m_trackDataHeaderWidget = new TrackDataHeaderWidget(this, m_dock);
m_trackDataHeaderWidget->setFixedHeight(40);
// create widgets in the body. For the body we are going to put a scroll area
// so we can get a vertical scroll bar when we have more tracks than what the
// view can show
QScrollArea* bodyWidget = new QScrollArea(m_mainWidget);
bodyWidget->setFrameShape(QFrame::NoFrame);
bodyWidget->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
bodyWidget->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
bodyWidget->setWidgetResizable(true);
// scroll areas require an inner widget to hold the layout (instead of a layout directly).
QWidget* innerWidget = new QWidget(bodyWidget);
QHBoxLayout* bodyLayout = new QHBoxLayout();
bodyLayout->setMargin(0);
bodyLayout->setSpacing(0);
innerWidget->setLayout(bodyLayout);
bodyWidget->setWidget(innerWidget);
mainLayout->addWidget(bodyWidget, 2, 0, 1, 2);
// Bottom-left
m_trackHeaderWidget = new TrackHeaderWidget(this, m_dock);
m_trackHeaderWidget->setFixedWidth(175);
bodyLayout->addWidget(m_trackHeaderWidget);
// Left
QHBoxLayout* addTrackAndTrackDataLayout = new QHBoxLayout;
addTrackAndTrackDataLayout->addWidget(m_trackHeaderWidget->GetAddTrackWidget());
m_trackHeaderWidget->GetAddTrackWidget()->setFixedWidth(175);
addTrackAndTrackDataLayout->addWidget(m_trackDataHeaderWidget);
mainLayout->addLayout(addTrackAndTrackDataLayout, 1, 0, 1, 2);
// bottom-right
m_trackDataWidget = new TrackDataWidget(this, m_dock);
bodyLayout->addWidget(m_trackDataWidget);
connect(m_trackDataWidget, &TrackDataWidget::SelectionChanged, this, &TimeViewPlugin::OnSelectionChanged);
connect(m_trackDataWidget, &TrackDataWidget::ElementTrackChanged, this, &TimeViewPlugin::MotionEventTrackChanged);
connect(m_trackDataWidget, &TrackDataWidget::MotionEventChanged, this, &TimeViewPlugin::MotionEventChanged);
connect(this, &TimeViewPlugin::DeleteKeyPressed, this, &TimeViewPlugin::RemoveSelectedMotionEvents);
connect(m_dock, &QDockWidget::visibilityChanged, this, &TimeViewPlugin::VisibilityChanged);
connect(this, &TimeViewPlugin::ManualTimeChange, this, &TimeViewPlugin::OnManualTimeChange);
connect(m_timeViewToolBar, &TimeViewToolBar::RecorderStateChanged, this, &TimeViewPlugin::RecorderStateChanged);
SetCurrentTime(0.0f);
SetScale(1.0f);
SetRedrawFlag();
m_timeViewToolBar->UpdateInterface();
EMotionFX::AnimGraphEditorNotificationBus::Handler::BusConnect();
// Create the motion event properties widget.
m_motionEventWidget = new MotionEventWidget();
m_motionEventWidget->hide();
connect(this, &TimeViewPlugin::SelectionChanged, this, [=]
{
if (!m_motionEventWidget)
{
return;
}
UpdateSelection();
if (GetNumSelectedEvents() != 1)
{
m_motionEventWidget->ReInit();
m_motionEventWidget->hide();
EMStudio::InspectorRequestBus::Broadcast(&EMStudio::InspectorRequestBus::Events::Clear); // This also gets called when just switching a motion
}
else
{
EventSelectionItem selectionItem = GetSelectedEvent(0);
m_motionEventWidget->ReInit(selectionItem.m_motion, selectionItem.GetMotionEvent());
EMStudio::InspectorRequestBus::Broadcast(&EMStudio::InspectorRequestBus::Events::UpdateWithHeader,
"Motion Event",
MotionEventWidget::s_headerIcon,
m_motionEventWidget);
}
});
return true;
}
// add a new track
void TimeViewPlugin::AddTrack(TimeTrack* track)
{
m_tracks.emplace_back(track);
SetRedrawFlag();
}
// delete all tracks
void TimeViewPlugin::RemoveAllTracks()
{
// get the number of time tracks and iterate through them
for (TimeTrack* track : m_tracks)
{
delete track;
}
m_tracks.clear();
SetRedrawFlag();
}
TimeTrack* TimeViewPlugin::FindTrackByElement(TimeTrackElement* element) const
{
const auto foundTrack = AZStd::find_if(begin(m_tracks), end(m_tracks), [element](const TimeTrack* timeTrack)
{
// get the number of time track elements and iterate through them
const size_t numElements = timeTrack->GetNumElements();
for (size_t j = 0; j < numElements; ++j)
{
if (timeTrack->GetElement(j) == element)
{
return true;
}
}
return false;
});
return foundTrack != end(m_tracks) ? *foundTrack : nullptr;
}
AZ::Outcome<size_t> TimeViewPlugin::FindTrackIndex(const TimeTrack* track) const
{
const auto foundTrack = AZStd::find(begin(m_tracks), end(m_tracks), track);
if (foundTrack != end(m_tracks))
{
return AZ::Success(static_cast<size_t>(AZStd::distance(begin(m_tracks), foundTrack)));
}
return AZ::Failure();
}
// round a double based on 0.5 (everything above is rounded up, everything else rounded down)
double TimeViewPlugin::RoundDouble(double x) const
{
if ((std::numeric_limits<double>::max() - 0.5) <= x)
{
return std::numeric_limits<double>::max();
}
if ((-1 * std::numeric_limits<double>::max() + 0.5) > x)
{
return (-1 * std::numeric_limits<double>::max());
}
double intpart;
double fractpart = modf(x, &intpart);
if (fractpart >= 0.5)
{
return (intpart + 1);
}
else
if (fractpart >= -0.5)
{
return intpart;
}
else
{
return (intpart - 1);
}
}
void TimeViewPlugin::DecomposeTime(double timeValue, uint32* outMinutes, uint32* outSeconds, uint32* outMilSecs, uint32* outFrameNr) const
{
if (outMinutes)
{
*outMinutes = aznumeric_cast<uint32>(timeValue / 60.0);
}
if (outSeconds)
{
*outSeconds = aznumeric_cast<uint32>(fmod(timeValue, 60.0));
}
if (outMilSecs)
{
*outMilSecs = aznumeric_cast<uint32>(fmod(RoundDouble(timeValue * 1000.0), 1000.0) / 10.0); //fmod(pixelTime, 1.0) * 100.0;
}
if (outFrameNr)
{
*outFrameNr = aznumeric_cast<uint32>(timeValue / (double)m_fps);
}
}
// calculate time values
void TimeViewPlugin::CalcTime(double xPixel, double* outPixelTime, uint32* outMinutes, uint32* outSeconds, uint32* outMilSecs, uint32* outFrameNr, bool scaleXPixel) const
{
if (scaleXPixel)
{
xPixel *= m_timeScale;
}
const double pixelTime = ((xPixel + m_scrollX) / m_pixelsPerSecond);
if (outPixelTime)
{
*outPixelTime = pixelTime;
}
if (outMinutes)
{
*outMinutes = aznumeric_cast<uint32>(pixelTime / 60.0);
}
if (outSeconds)
{
*outSeconds = aznumeric_cast<uint32>(fmod(pixelTime, 60.0));
}
if (outMilSecs)
{
*outMilSecs = aznumeric_cast<uint32>(fmod(RoundDouble(pixelTime * 1000.0), 1000.0) / 10.0); //fmod(pixelTime, 1.0) * 100.0;
}
if (outFrameNr)
{
*outFrameNr = aznumeric_cast<uint32>(pixelTime / (double)m_fps);
}
}
void TimeViewPlugin::UpdateCurrentMotionInfo()
{
if (EMotionFX::GetRecorder().GetRecordTime() > MCore::Math::epsilon)
{
return;
}
if (m_motion)
{
MotionInfo* motionInfo = FindMotionInfo(m_motion->GetID());
motionInfo->m_scale = m_targetTimeScale;
motionInfo->m_scrollX = m_targetScrollX;
}
}
// update the sub-widgets
void TimeViewPlugin::UpdateVisualData()
{
ValidatePluginLinks();
m_trackDataHeaderWidget->update();
m_trackDataWidget->update();
m_timeInfoWidget->update();
m_dirty = false;
}
// calc the time value to a pixel value (excluding scroll)
double TimeViewPlugin::TimeToPixel(double timeInSeconds, bool scale) const
{
double result = ((timeInSeconds * m_pixelsPerSecond)) - m_scrollX;
if (scale)
{
return (result * m_timeScale);
}
else
{
return result;
}
}
// return the element at a given pixel, or nullptr
TimeTrackElement* TimeViewPlugin::GetElementAt(int32 x, int32 y)
{
// for all tracks
for (const TimeTrack* track : m_tracks)
{
// check if the absolute pixel is inside
TimeTrackElement* result = track->GetElementAt(aznumeric_cast<int32>(x + m_scrollX), y);
if (result)
{
return result;
}
}
return nullptr;
}
// return the track at a given pixel y value, or nullptr
TimeTrack* TimeViewPlugin::GetTrackAt(int32 y)
{
// for all tracks
const auto foundTrack = AZStd::find_if(begin(m_tracks), end(m_tracks), [y](const TimeTrack* track)
{
return track->GetIsInside(y);
});
return foundTrack != end(m_tracks) ? *foundTrack : nullptr;
}
// unselect all elements
void TimeViewPlugin::UnselectAllElements()
{
// for all tracks
for (TimeTrack* track : m_tracks)
{
// for all elements, deselect it
const size_t numElems = track->GetNumElements();
for (size_t i = 0; i < numElems; ++i)
{
track->GetElement(i)->SetIsSelected(false);
}
}
SetRedrawFlag();
emit SelectionChanged();
}
// return the time of the current time marker, in seconds
double TimeViewPlugin::GetCurrentTime() const
{
return m_curTime;
}
double TimeViewPlugin::PixelToTime(double xPixel, bool isScaledPixel) const
{
if (isScaledPixel)
{
xPixel /= m_timeScale;
}
return ((xPixel + m_scrollX) / m_pixelsPerSecond);
}
void TimeViewPlugin::DeltaScrollX(double deltaX, bool animate)
{
double newTime = (m_targetScrollX + (deltaX / m_timeScale)) / m_pixelsPerSecond;
if (newTime < m_maxTime - (1 / m_timeScale))
{
SetScrollX(m_targetScrollX + (deltaX / m_timeScale), animate);
}
else
{
SetScrollX((m_maxTime - ((1 / m_timeScale))) * m_pixelsPerSecond, animate);
}
SetRedrawFlag();
}
void TimeViewPlugin::SetScrollX(double scrollX, bool animate)
{
m_targetScrollX = scrollX;
if (m_targetScrollX < 0)
{
m_targetScrollX = 0;
}
if (animate == false)
{
m_scrollX = m_targetScrollX;
}
// inform the motion info about the changes
UpdateCurrentMotionInfo();
SetRedrawFlag();
}
// set the current time in seconds
void TimeViewPlugin::SetCurrentTime(double timeInSeconds)
{
const double oneMs = 1.0 / 1000.0;
if (!AZ::IsClose(m_curTime, timeInSeconds, oneMs))
{
m_dirty = true;
}
m_curTime = timeInSeconds;
}
// snap a time value
bool TimeViewPlugin::SnapTime(double* inOutTime, TimeTrackElement* elementToIgnore, double snapThreshold)
{
double inTime = *inOutTime;
// make sure we don't go out of bounds
if (inTime < 0.0)
{
inTime = 0.0;
}
// for all tracks
for (TimeTrack* track : m_tracks)
{
if (track->GetIsVisible() == false || track->GetIsEnabled() == false)
{
continue;
}
// for all elements
const size_t numElems = track->GetNumElements();
for (size_t i = 0; i < numElems; ++i)
{
// don't snap to itself
TimeTrackElement* element = track->GetElement(i);
if (element == elementToIgnore)
{
continue;
}
// snap the input time to snap locations inside the element
element->SnapTime(&inTime, snapThreshold);
}
}
// if snapping occurred
if (MCore::Math::Abs(aznumeric_cast<float>(inTime - *inOutTime)) > 0.0001)
{
*inOutTime = inTime;
return true;
}
else // no snapping occurred
{
*inOutTime = inTime;
return false;
}
}
// render the element time handles on top of everything
void TimeViewPlugin::RenderElementTimeHandles(QPainter& painter, uint32 dataWindowHeight, const QPen& pen)
{
// for all tracks
for (const TimeTrack* track : m_tracks)
{
if (track->GetIsVisible() == false)
{
continue;
}
// for all elements
const size_t numElems = track->GetNumElements();
for (size_t i = 0; i < numElems; ++i)
{
const TimeTrackElement* elem = track->GetElement(i);
// if the element has to show its time handles, do it
if (elem->GetShowTimeHandles())
{
// calculate the dimensions
int32 startX, startY, width, height;
elem->CalcDimensions(&startX, &startY, &width, &height);
// draw the lines
painter.setPen(pen);
//painter.setRenderHint(QPainter::Antialiasing);
painter.drawLine(startX, 0, startX, dataWindowHeight);
painter.drawLine(startX + width, 0, startX + width, dataWindowHeight);
}
}
}
}
// disables all tool tips
void TimeViewPlugin::DisableAllToolTips()
{
// for all tracks
for (const TimeTrack* track : m_tracks)
{
// for all elements
const size_t numElems = track->GetNumElements();
for (size_t i = 0; i < numElems; ++i)
{
TimeTrackElement* elem = track->GetElement(i);
elem->SetShowToolTip(false);
}
}
SetRedrawFlag();
}
// check if we're at some resize point with the mouse
bool TimeViewPlugin::FindResizePoint(int32 x, int32 y, TimeTrackElement** outElement, uint32* outID)
{
// for all tracks
for (const TimeTrack* track : m_tracks)
{
if (track->GetIsVisible() == false)
{
continue;
}
// for all elements
const size_t numElems = track->GetNumElements();
for (size_t i = 0; i < numElems; ++i)
{
TimeTrackElement* elem = track->GetElement(i);
// check for a resize point in the element
uint32 id;
if (elem->FindResizePoint(x, y, &id))
{
*outElement = elem;
*outID = id;
return true;
}
}
}
// no resize point at this location
*outElement = nullptr;
*outID = MCORE_INVALIDINDEX32;
// no resize point found
return false;
}
void TimeViewPlugin::VisibilityChanged(bool visible)
{
MCORE_UNUSED(visible);
ValidatePluginLinks();
SetRedrawFlag();
}
// render the frame
void TimeViewPlugin::ProcessFrame(float timePassedInSeconds)
{
if (GetManager()->GetAvoidRendering() || m_mainWidget->visibleRegion().isEmpty())
{
return;
}
m_totalTime += timePassedInSeconds;
ValidatePluginLinks();
// animate the zoom
m_scrollX += (m_targetScrollX - m_scrollX) * 0.2;
m_isAnimating = false;
if (m_targetTimeScale > m_timeScale)
{
if (MCore::Math::Abs(aznumeric_cast<float>(m_targetScrollX - m_scrollX)) <= 1)
{
m_timeScale += (m_targetTimeScale - m_timeScale) * 0.1;
}
}
else
{
m_timeScale += (m_targetTimeScale - m_timeScale) * 0.1;
}
if (MCore::Math::Abs(aznumeric_cast<float>(m_targetScrollX - m_scrollX)) <= 1)
{
m_scrollX = m_targetScrollX;
}
else
{
m_isAnimating = true;
}
if (MCore::Math::Abs(aznumeric_cast<float>(m_targetTimeScale - m_timeScale)) <= 0.001)
{
m_timeScale = m_targetTimeScale;
}
else
{
m_isAnimating = true;
}
// get the maximum time
GetDataTimes(&m_maxTime, nullptr, nullptr);
UpdateMaxHeight();
m_trackDataWidget->UpdateRects();
if (MCore::Math::Abs(aznumeric_cast<float>(m_maxHeight - m_lastMaxHeight)) > 0.0001)
{
m_lastMaxHeight = m_maxHeight;
}
if (m_trackDataWidget->m_dragging == false && m_trackDataWidget->m_resizing == false)
{
m_timeInfoWidget->SetOverwriteTime(PixelToTime(m_curMouseX), m_maxTime);
}
// update the hovering items
m_eventEmitterNode = nullptr;
m_actorInstanceData = m_trackDataWidget->FindActorInstanceData();
if (EMotionFX::GetRecorder().GetRecordTime() > MCore::Math::epsilon)
{
m_eventHistoryItem = m_trackDataWidget->FindEventHistoryItem(m_actorInstanceData, aznumeric_cast<int32>(m_curMouseX), aznumeric_cast<int32>(m_curMouseY));
m_nodeHistoryItem = m_trackDataWidget->FindNodeHistoryItem(m_actorInstanceData, aznumeric_cast<int32>(m_curMouseX), aznumeric_cast<int32>(m_curMouseY));
if (m_eventHistoryItem)
{
EMotionFX::AnimGraph* animGraph = EMotionFX::GetAnimGraphManager().FindAnimGraphByID(m_eventHistoryItem->m_animGraphId);
if (animGraph)
{
m_eventEmitterNode = animGraph->RecursiveFindNodeById(m_eventHistoryItem->m_emitterNodeId);
}
}
}
else
{
m_actorInstanceData = nullptr;
m_nodeHistoryItem = nullptr;
m_eventHistoryItem = nullptr;
}
switch (m_mode)
{
case TimeViewMode::Motion:
{
double newCurrentTime = m_curTime;
if (!m_motion)
{
// Use the start time when either no motion is selected.
newCurrentTime = 0.0f;
}
else
{
const AZStd::vector<EMotionFX::MotionInstance*>& selectedMotionInstances = CommandSystem::GetCommandManager()->GetCurrentSelection().GetSelectedMotionInstances();
if (selectedMotionInstances.size() == 1 &&
selectedMotionInstances[0]->GetMotion() == m_motion)
{
EMotionFX::MotionInstance* motionInstance = selectedMotionInstances[0];
if (!AZ::IsClose(aznumeric_cast<float>(m_curTime), motionInstance->GetCurrentTime(), MCore::Math::epsilon))
{
newCurrentTime = motionInstance->GetCurrentTime();
}
}
}
if (!m_trackDataWidget->m_dragging && !m_trackDataWidget->m_resizing)
{
SetCurrentTime(newCurrentTime);
}
break;
}
case TimeViewMode::AnimGraph:
{
EMotionFX::Recorder& recorder = EMotionFX::GetRecorder();
if (recorder.GetRecordTime() > MCore::Math::epsilon)
{
if (recorder.GetIsInPlayMode() && recorder.GetIsInAutoPlayMode())
{
SetCurrentTime(recorder.GetCurrentPlayTime());
MakeTimeVisible(m_curTime, 0.5, false);
}
if (recorder.GetIsRecording())
{
SetCurrentTime(m_maxTime);
MakeTimeVisible(recorder.GetRecordTime(), 0.95, false);
}
}
else
{
SetCurrentTime(0.0f);
}
break;
}
default:
{
SetCurrentTime(0.0f);
break;
}
}
if (m_isAnimating)
{
m_dirty = true;
}
bool redraw = false;
float fps = 15.0f;
#ifndef MCORE_DEBUG
if (m_isAnimating)
{
fps = 60.0f;
}
else
{
fps = 40.0f;
}
#endif
if (m_totalTime >= 1.0f / fps)
{
redraw = true;
m_totalTime = 0.0f;
}
if (redraw && m_dirty)
{
UpdateVisualData();
}
}
void TimeViewPlugin::SetRedrawFlag()
{
m_dirty = true;
}
void TimeViewPlugin::UpdateViewSettings()
{
SetScale(m_timeScale);
}
void TimeViewPlugin::SetScale(double scale, bool animate)
{
double curTime = GetCurrentTime();
m_targetTimeScale = scale;
m_targetTimeScale = MCore::Clamp(scale, m_minScale, m_maxScale);
if (animate == false)
{
m_timeScale = m_targetTimeScale;
}
UpdateCurrentMotionInfo();
SetCurrentTime(curTime);
// MakeTimeVisible( centerTime, 0.5 );
}
void TimeViewPlugin::OnKeyPressEvent(QKeyEvent* event)
{
// delete pressed
if (event->key() == Qt::Key_Delete)
{
emit DeleteKeyPressed();
event->accept();
return;
}
if (event->key() == Qt::Key_Down)
{
m_trackDataWidget->scroll(0, 20);
event->accept();
return;
}
if (event->key() == Qt::Key_Up)
{
m_trackDataWidget->scroll(0, -20);
event->accept();
return;
}
if (event->key() == Qt::Key_Plus)
{
double zoomDelta = 0.1 * 3 * MCore::Clamp(m_targetTimeScale / 2.0, 1.0, 22.0);
SetScale(m_targetTimeScale + zoomDelta);
event->accept();
return;
}
if (event->key() == Qt::Key_Minus)
{
double zoomDelta = 0.1 * 3 * MCore::Clamp(m_targetTimeScale / 2.0, 1.0, 22.0);
SetScale(m_targetTimeScale - zoomDelta);
event->accept();
return;
}
if (EMotionFX::GetRecorder().GetIsRecording() == false && EMotionFX::GetRecorder().GetIsInAutoPlayMode() == false)
{
if (event->key() == Qt::Key_Left)
{
m_targetScrollX -= (m_pixelsPerSecond * 3) / m_timeScale;
if (m_targetScrollX < 0)
{
m_targetScrollX = 0;
}
event->accept();
return;
}
if (event->key() == Qt::Key_Right)
{
const double newTime = (m_scrollX + ((m_pixelsPerSecond * 3) / m_timeScale)) / m_pixelsPerSecond;
if (newTime < m_maxTime)
{
m_targetScrollX += ((m_pixelsPerSecond * 3) / m_timeScale);
}
event->accept();
return;
}
// fit the contents
if (event->key() == Qt::Key_A)
{
OnZoomAll();
event->accept();
return;
}
if (event->key() == Qt::Key_Z)
{
OnCenterOnCurTime();
event->accept();
return;
}
if (event->key() == Qt::Key_Home)
{
OnGotoTimeZero();
event->accept();
return;
}
if (event->key() == Qt::Key_PageUp)
{
m_targetScrollX -= m_trackDataWidget->geometry().width() / m_timeScale;
if (m_targetScrollX < 0)
{
m_targetScrollX = 0;
}
event->accept();
return;
}
if (event->key() == Qt::Key_PageDown)
{
const double newTime = (m_scrollX + (m_trackDataWidget->geometry().width() / m_timeScale)) / m_pixelsPerSecond;
if (newTime < m_maxTime)
{
m_targetScrollX += m_trackDataWidget->geometry().width() / m_timeScale;
}
event->accept();
return;
}
}
event->ignore();
}
void TimeViewPlugin::OnKeyReleaseEvent(QKeyEvent* event)
{
if (event->key() == Qt::Key_Delete)
{
event->accept();
return;
}
event->ignore();
}
void TimeViewPlugin::ValidatePluginLinks()
{
m_motionEventsPlugin = nullptr;
m_motionSetPlugin = nullptr;
EMStudio::PluginManager* pluginManager = EMStudio::GetPluginManager();
EMStudioPlugin* motionSetBasePlugin = pluginManager->FindActivePlugin(MotionSetsWindowPlugin::CLASS_ID);
if (motionSetBasePlugin)
{
m_motionSetPlugin = static_cast<MotionSetsWindowPlugin*>(motionSetBasePlugin);
connect(m_motionSetPlugin->GetMotionSetWindow(), &MotionSetWindow::MotionSelectionChanged, this, &TimeViewPlugin::MotionSelectionChanged, Qt::UniqueConnection); // UniqueConnection as we could connect multiple times.
}
EMStudioPlugin* motionEventsBasePlugin = pluginManager->FindActivePlugin(MotionEventsPlugin::CLASS_ID);
if (motionEventsBasePlugin)
{
m_motionEventsPlugin = static_cast<MotionEventsPlugin*>(motionEventsBasePlugin);
m_motionEventsPlugin->ValidatePluginLinks();
}
}
void TimeViewPlugin::MotionSelectionChanged()
{
ValidatePluginLinks();
if (m_motionSetPlugin && m_motionSetPlugin->GetMotionSetWindow() &&
m_motionSetPlugin->GetMotionSetWindow()->isVisible())
{
SetMode(TimeViewMode::Motion);
}
}
void TimeViewPlugin::UpdateSelection()
{
m_selectedEvents.clear();
if (!m_motion)
{
return;
}
// get the motion event table
const EMotionFX::MotionEventTable* eventTable = m_motion->GetEventTable();
// get the number of tracks in the time view and iterate through them
const size_t numTracks = GetNumTracks();
for (size_t trackIndex = 0; trackIndex < numTracks; ++trackIndex)
{
// get the current time view track
const TimeTrack* track = GetTrack(trackIndex);
if (track->GetIsVisible() == false)
{
continue;
}
const AZ::Outcome<size_t> trackNr = eventTable->FindTrackIndexByName(track->GetName());
if (!trackNr.IsSuccess())
{
continue;
}
// get the number of elements in the track and iterate through them
const size_t numTrackElements = track->GetNumElements();
for (size_t elementIndex = 0; elementIndex < numTrackElements; ++elementIndex)
{
TimeTrackElement* element = track->GetElement(elementIndex);
if (element->GetIsVisible() == false)
{
continue;
}
if (element->GetIsSelected())
{
EventSelectionItem selectionItem;
selectionItem.m_motion = m_motion;
selectionItem.m_trackNr = trackNr.GetValue();
selectionItem.m_eventNr = element->GetElementNumber();
m_selectedEvents.emplace_back(selectionItem);
}
}
}
}
void TimeViewPlugin::ReInit()
{
if (EMotionFX::GetMotionManager().FindMotionIndex(m_motion) == InvalidIndex)
{
// set the motion first back to nullptr
m_motion = nullptr;
}
// update the selection and save it
UpdateSelection();
ValidatePluginLinks();
// If we are in anim graph mode and have a recording, don't init for the motions.
if ((m_mode == TimeViewMode::AnimGraph) &&
(EMotionFX::GetRecorder().GetIsRecording() || EMotionFX::GetRecorder().GetRecordTime() > MCore::Math::epsilon || EMotionFX::GetRecorder().GetIsInPlayMode()))
{
SetScrollX(0);
m_trackHeaderWidget->ReInit();
return;
}
if (m_motion)
{
size_t trackIndex;
AZStd::string text;
const EMotionFX::MotionEventTable* eventTable = m_motion->GetEventTable();
RemoveAllTracks();
// get the number of motion event tracks and iterate through them
const size_t numEventTracks = eventTable->GetNumTracks();
for (trackIndex = 0; trackIndex < numEventTracks; ++trackIndex)
{
const EMotionFX::MotionEventTrack* eventTrack = eventTable->GetTrack(trackIndex);
TimeTrack* timeTrack = new TimeTrack(this);
AddTrack(timeTrack);
timeTrack->SetName(eventTrack->GetName());
timeTrack->SetIsEnabled(eventTrack->GetIsEnabled());
timeTrack->SetIsVisible(true);
timeTrack->SetIsDeletable(eventTrack->GetIsDeletable());
// get the number of motion events and iterate through them
size_t eventIndex;
const size_t numMotionEvents = eventTrack->GetNumEvents();
if (numMotionEvents == 0)
{
timeTrack->RemoveAllElements();
}
else
{
for (eventIndex = 0; eventIndex < numMotionEvents; ++eventIndex)
{
const EMotionFX::MotionEvent& motionEvent = eventTrack->GetEvent(eventIndex);
TimeTrackElement* element = nullptr;
if (eventIndex < timeTrack->GetNumElements())
{
element = timeTrack->GetElement(eventIndex);
}
else
{
element = new TimeTrackElement("", timeTrack);
timeTrack->AddElement(element);
}
// Select the element if in m_selectedEvents.
for (const EventSelectionItem& selectionItem : m_selectedEvents)
{
if (m_motion != selectionItem.m_motion)
{
continue;
}
if (selectionItem.m_trackNr == trackIndex && selectionItem.m_eventNr == eventIndex)
{
element->SetIsSelected(true);
break;
}
}
text = '{';
AZStd::string delimiter;
const EMotionFX::EventDataSet& eventDatas = motionEvent.GetEventDatas();
for (const EMotionFX::EventDataPtr& data : eventDatas)
{
if (data)
{
text += delimiter + data->ToString() + "}";
}
else
{
text += "<null>}";
}
delimiter = ", {";
}
uint32 color = GetEventPresetManager()->GetEventColor(motionEvent.GetEventDatas());
QColor qColor = QColor(MCore::ExtractRed(color), MCore::ExtractGreen(color), MCore::ExtractBlue(color));
element->SetIsVisible(true);
element->SetName(text.c_str());
element->SetColor(qColor);
element->SetElementNumber(eventIndex);
element->SetStartTime(motionEvent.GetStartTime());
element->SetEndTime(motionEvent.GetEndTime());
// tooltip
AZStd::string tooltip;
AZStd::string rowName;
tooltip.reserve(16384);
tooltip = "<table border=\"0\">";
if (motionEvent.GetIsTickEvent())
{
// time
rowName = "Time";
tooltip += AZStd::string::format("<tr><td><p style=\"color:rgb(%i,%i,%i)\"><b>%s: </b></p></td>", qColor.red(), qColor.green(), qColor.blue(), rowName.c_str());
tooltip += AZStd::string::format("<td><p style=\"color:rgb(115, 115, 115)\">%.3f s</p></td></tr>", motionEvent.GetStartTime());
}
else // range event
{
// start time
rowName = "Start Time";
tooltip += AZStd::string::format("<tr><td><p style=\"color:rgb(%i,%i,%i)\"><b>%s: </b></p></td>", qColor.red(), qColor.green(), qColor.blue(), rowName.c_str());
tooltip += AZStd::string::format("<td><p style=\"color:rgb(115, 115, 115)\">%.3f s</p></td></tr>", motionEvent.GetStartTime());
// end time
rowName = "End Time";
tooltip += AZStd::string::format("<tr><td><p style=\"color:rgb(%i,%i,%i)\"><b>%s: </b></p></td>", qColor.red(), qColor.green(), qColor.blue(), rowName.c_str());
tooltip += AZStd::string::format("<td><p style=\"color:rgb(115, 115, 115)\">%.3f s</p></td></tr>", motionEvent.GetEndTime());
}
for (const EMotionFX::EventDataPtr& eventData : eventDatas)
{
if (!eventData.get())
{
continue;
}
const auto& motionDataProperties = MCore::ReflectionSerializer::SerializeIntoMap(eventData.get());
if (motionDataProperties.IsSuccess())
{
for (const AZStd::pair<AZStd::string, AZStd::string>& keyValuePair : motionDataProperties.GetValue())
{
tooltip += AZStd::string::format(
"<tr><td><p style=\"color:rgb(%i,%i,%i)\"><b>%s: </b></p></td>" // no comma, concat these 2 string literals
"<td><p style=\"color:rgb(115, 115, 115)\">%s</p></td></tr>",
qColor.red(),
qColor.green(),
qColor.blue(),
keyValuePair.first.c_str(),
keyValuePair.second.c_str()
);
}
}
}
tooltip += "</table>";
// set tooltip
element->SetToolTip(tooltip.c_str());
}
}
timeTrack->SetElementCount(numMotionEvents);
}
}
else // m_motion == nullptr
{
const size_t numEventTracks = GetNumTracks();
for (size_t trackIndex = 0; trackIndex < numEventTracks; ++trackIndex)
{
TimeTrack* timeTrack = GetTrack(trackIndex);
timeTrack->SetIsVisible(false);
const size_t numMotionEvents = timeTrack->GetNumElements();
for (size_t j = 0; j < numMotionEvents; ++j)
{
TimeTrackElement* element = timeTrack->GetElement(j);
element->SetIsVisible(false);
}
}
}
// update the time view plugin
m_trackHeaderWidget->ReInit();
if (m_motion)
{
MotionInfo* motionInfo = FindMotionInfo(m_motion->GetID());
// if we already selected before, set the remembered settings
if (motionInfo->m_initialized)
{
const int32 tempScroll = aznumeric_cast<int32>(motionInfo->m_scrollX);
SetScale(motionInfo->m_scale);
SetScrollX(tempScroll);
}
else
{
// selected the animation the first time
motionInfo->m_initialized = true;
m_targetTimeScale = CalcFitScale(m_minScale, m_maxScale) * 0.8;
motionInfo->m_scale = m_targetTimeScale;
motionInfo->m_scrollX = 0.0;
}
}
UpdateVisualData();
}
// find the motion info for the given motion id
TimeViewPlugin::MotionInfo* TimeViewPlugin::FindMotionInfo(uint32 motionID)
{
const auto foundMotionInfo = AZStd::find_if(begin(m_motionInfos), end(m_motionInfos), [motionID](const MotionInfo* motionInfo)
{
return motionInfo->m_motionId == motionID;
});
if (foundMotionInfo != end(m_motionInfos))
{
return *foundMotionInfo;
}
// we haven't found a motion info for the given id yet, so create a new one
MotionInfo* motionInfo = new MotionInfo();
motionInfo->m_motionId = motionID;
motionInfo->m_initialized = false;
m_motionInfos.emplace_back(motionInfo);
return motionInfo;
}
void TimeViewPlugin::Select(const AZStd::vector<EventSelectionItem>& selection)
{
m_selectedEvents = selection;
// get the number of tracks in the time view and iterate through them
const size_t numTracks = GetNumTracks();
for (size_t i = 0; i < numTracks; ++i)
{
TimeTrack* track = GetTrack(i);
// get the number of elements in the track and iterate through them
const size_t numTrackElements = track->GetNumElements();
for (size_t j = 0; j < numTrackElements; ++j)
{
TimeTrackElement* element = track->GetElement(j);
element->SetIsSelected(false);
}
}
for (const EventSelectionItem& selectionItem : selection)
{
TimeTrack* track = GetTrack(selectionItem.m_trackNr);
TimeTrackElement* element = track->GetElement(selectionItem.m_eventNr);
element->SetIsSelected(true);
}
}
EMotionFX::MotionEvent* EventSelectionItem::GetMotionEvent()
{
EMotionFX::MotionEventTrack* eventTrack = GetEventTrack();
if (eventTrack == nullptr)
{
return nullptr;
}
if (m_eventNr >= eventTrack->GetNumEvents())
{
return nullptr;
}
return &(eventTrack->GetEvent(m_eventNr));
}
EMotionFX::MotionEventTrack* EventSelectionItem::GetEventTrack()
{
if (m_trackNr >= m_motion->GetEventTable()->GetNumTracks())
{
return nullptr;
}
EMotionFX::MotionEventTrack* eventTrack = m_motion->GetEventTable()->GetTrack(m_trackNr);
return eventTrack;
}
void TimeViewPlugin::AddMotionEvent(int32 x, int32 y)
{
if (m_motion == nullptr)
{
return;
}
SetRedrawFlag();
// calculate the start time for the motion event
double dropTimeInSeconds = PixelToTime(x);
//CalcTime( x, &dropTimeInSeconds, nullptr, nullptr, nullptr, nullptr );
// get the time track on which we dropped the preset
TimeTrack* timeTrack = GetTrackAt(y);
if (timeTrack == nullptr)
{
return;
}
CommandSystem::CommandHelperAddMotionEvent(timeTrack->GetName(), aznumeric_cast<float>(dropTimeInSeconds), aznumeric_cast<float>(dropTimeInSeconds));
}
void TimeViewPlugin::RemoveMotionEvent(int32 x, int32 y)
{
// get the time track on which we dropped the preset
TimeTrack* timeTrack = GetTrackAt(y);
if (timeTrack == nullptr)
{
return;
}
// get the time track on which we dropped the preset
TimeTrackElement* element = GetElementAt(x, y);
if (element == nullptr)
{
return;
}
CommandSystem::CommandHelperRemoveMotionEvent(timeTrack->GetName(), element->GetElementNumber());
}
void TimeViewPlugin::MotionEventChanged(TimeTrackElement* element, double startTime, double endTime)
{
if (element == nullptr)
{
return;
}
// get the motion event number by getting the time track element number
size_t motionEventNr = element->GetElementNumber();
if (motionEventNr == InvalidIndex)
{
return;
}
// find the corresponding time track for the element
TimeTrack* timeTrack = FindTrackByElement(element);
if (timeTrack == nullptr)
{
return;
}
// get the corresponding motion event track
EMotionFX::MotionEventTable* eventTable = m_motion->GetEventTable();
EMotionFX::MotionEventTrack* eventTrack = eventTable->FindTrackByName(timeTrack->GetName());
if (eventTrack == nullptr)
{
return;
}
// check if the motion event number is valid and return in case it is not
if (motionEventNr >= eventTrack->GetNumEvents())
{
return;
}
// adjust the motion event
AZStd::string outResult, command;
command = AZStd::string::format("AdjustMotionEvent -motionID %i -eventTrackName \"%s\" -eventNr %zu -startTime %f -endTime %f", m_motion->GetID(), eventTrack->GetName(), motionEventNr, startTime, endTime);
if (EMStudio::GetCommandManager()->ExecuteCommand(command.c_str(), outResult) == false)
{
MCore::LogError(outResult.c_str());
}
}
void TimeViewPlugin::RemoveSelectedMotionEvents()
{
// create the command group
AZStd::string result;
MCore::CommandGroup commandGroup("Remove motion events");
if (m_trackDataWidget)
{
m_trackDataWidget->ClearState();
}
if (m_motion == nullptr)
{
return;
}
if (EMotionFX::GetMotionManager().FindMotionIndex(m_motion) == InvalidIndex)
{
return;
}
// get the motion event table
// MotionEventTable& eventTable = m_motion->GetEventTable();
AZStd::vector<size_t> eventNumbers;
// get the number of tracks in the time view and iterate through them
const size_t numTracks = GetNumTracks();
for (size_t i = 0; i < numTracks; ++i)
{
// get the current time view track
TimeTrack* track = GetTrack(i);
if (track->GetIsVisible() == false)
{
continue;
}
eventNumbers.clear();
// get the number of elements in the track and iterate through them
const size_t numTrackElements = track->GetNumElements();
for (size_t j = 0; j < numTrackElements; ++j)
{
TimeTrackElement* element = track->GetElement(j);
if (element->GetIsSelected() && element->GetIsVisible())
{
eventNumbers.emplace_back(j);
}
}
// remove selected motion events
CommandSystem::CommandHelperRemoveMotionEvents(track->GetName(), eventNumbers, &commandGroup);
}
// execute the command group
if (EMStudio::GetCommandManager()->ExecuteCommandGroup(commandGroup, result) == false)
{
MCore::LogError(result.c_str());
}
UnselectAllElements();
}
void TimeViewPlugin::RemoveAllMotionEvents()
{
// create the command group
AZStd::string result;
MCore::CommandGroup commandGroup("Remove motion events");
if (m_motion == nullptr)
{
return;
}
if (EMotionFX::GetMotionManager().FindMotionIndex(m_motion) == InvalidIndex)
{
return;
}
// get the motion event table
AZStd::vector<size_t> eventNumbers;
// get the number of tracks in the time view and iterate through them
const size_t numTracks = GetNumTracks();
for (size_t i = 0; i < numTracks; ++i)
{
// get the current time view track
TimeTrack* track = GetTrack(i);
if (track->GetIsVisible() == false)
{
continue;
}
eventNumbers.clear();
// get the number of elements in the track and iterate through them
const size_t numTrackElements = track->GetNumElements();
for (size_t j = 0; j < numTrackElements; ++j)
{
TimeTrackElement* element = track->GetElement(j);
if (element->GetIsVisible())
{
eventNumbers.emplace_back(j);
}
}
// remove selected motion events
CommandSystem::CommandHelperRemoveMotionEvents(track->GetName(), eventNumbers, &commandGroup);
}
// execute the command group
if (EMStudio::GetCommandManager()->ExecuteCommandGroup(commandGroup, result) == false)
{
MCore::LogError(result.c_str());
}
UnselectAllElements();
}
// get the data times
void TimeViewPlugin::GetDataTimes(double* outMaxTime, double* outClipStart, double* outClipEnd) const
{
if (outMaxTime)
{
*outMaxTime = 0.0;
}
if (outClipStart)
{
*outClipStart = 0.0;
}
if (outClipEnd)
{
*outClipEnd = 0.0;
}
switch (m_mode)
{
case TimeViewMode::Motion:
{
EMotionFX::Motion* motion = GetMotion();
if (motion)
{
EMotionFX::PlayBackInfo* playbackInfo = motion->GetDefaultPlayBackInfo();
if (outClipStart)
{
*outClipStart = playbackInfo->m_clipStartTime;
}
if (outClipEnd)
{
*outClipEnd = playbackInfo->m_clipEndTime;
}
if (outMaxTime)
{
*outMaxTime = motion->GetDuration();
}
}
break;
}
case TimeViewMode::AnimGraph:
{
EMotionFX::Recorder& recorder = EMotionFX::GetRecorder();
if (recorder.GetRecordTime() > MCore::Math::epsilon)
{
if (outClipEnd)
{
*outClipEnd = recorder.GetRecordTime();
}
if (outMaxTime)
{
*outMaxTime = recorder.GetRecordTime();
}
}
break;
}
}
}
// zoom to fit
void TimeViewPlugin::ZoomToFit()
{
m_targetScrollX = 0.0;
m_targetTimeScale = CalcFitScale(m_minScale, m_maxScale);
}
// calculate the scale needed to fit exactly
double TimeViewPlugin::CalcFitScale(double minScale, double maxScale) const
{
// get the duration
double maxTime;
GetDataTimes(&maxTime, nullptr, nullptr);
// calculate the right scale to fit it
double scale = 1.0;
if (maxTime > 0.0)
{
double width = m_trackDataWidget->geometry().width();
scale = (width / m_pixelsPerSecond) / maxTime;
}
if (scale < minScale)
{
scale = minScale;
}
if (scale > maxScale)
{
scale = maxScale;
}
return scale;
}
// is the given time value visible?
bool TimeViewPlugin::GetIsTimeVisible(double timeValue) const
{
const double pixel = TimeToPixel(timeValue);
return (pixel >= 0.0 && pixel < m_trackDataWidget->geometry().width());
}
// make a given time value visible
void TimeViewPlugin::MakeTimeVisible(double timeValue, double offsetFactor, bool animate)
{
SetRedrawFlag();
const double pixel = TimeToPixel(timeValue, false);
// if we need to scroll to the right
double width = m_trackDataWidget->geometry().width() / m_timeScale;
m_targetScrollX += (pixel - width) + width * (1.0 - offsetFactor);
if (m_targetScrollX < 0)
{
m_targetScrollX = 0;
}
if (animate == false)
{
m_scrollX = m_targetScrollX;
}
}
// update the maximum height
void TimeViewPlugin::UpdateMaxHeight()
{
m_maxHeight = 0.0;
// find the selected actor instance
EMotionFX::Recorder& recorder = EMotionFX::GetRecorder();
if (recorder.GetRecordTime() > MCore::Math::epsilon)
{
EMotionFX::ActorInstance* actorInstance = GetCommandManager()->GetCurrentSelection().GetSingleActorInstance();
if (actorInstance)
{
// find the actor instance data for this actor instance
const size_t actorInstanceDataIndex = recorder.FindActorInstanceDataIndex(actorInstance);
if (actorInstanceDataIndex != InvalidIndex)
{
RecorderGroup* recorderGroup = m_timeViewToolBar->GetRecorderGroup();
const bool displayNodeActivity = recorderGroup->GetDisplayNodeActivity();
const bool displayEvents = recorderGroup->GetDisplayMotionEvents();
const bool displayRelativeGraph = recorderGroup->GetDisplayRelativeGraph();
bool isTop = true;
const EMotionFX::Recorder::ActorInstanceData& actorInstanceData = recorder.GetActorInstanceData(actorInstanceDataIndex);
if (displayNodeActivity)
{
m_maxHeight += ((recorder.CalcMaxNodeHistoryTrackIndex(actorInstanceData) + 1) * (m_trackDataWidget->m_nodeHistoryItemHeight + 3));
isTop = false;
}
if (displayEvents)
{
if (isTop == false)
{
m_maxHeight += 10 + 10;
}
isTop = false;
m_maxHeight += m_trackDataWidget->m_eventHistoryTotalHeight;
}
if (displayRelativeGraph)
{
if (isTop == false)
{
m_maxHeight += 10;
}
isTop = false;
}
}
}
}
else
{
if (m_motion)
{
for (const TimeTrack* track : m_tracks)
{
if (track->GetIsVisible() == false)
{
continue;
}
m_maxHeight += track->GetHeight();
m_maxHeight += 1;
}
}
}
}
// zoom all
void TimeViewPlugin::OnZoomAll()
{
ZoomToFit();
}
// goto time zero
void TimeViewPlugin::OnGotoTimeZero()
{
m_targetScrollX = 0;
}
// reset timeline
void TimeViewPlugin::OnResetTimeline()
{
m_targetScrollX = 0;
m_targetTimeScale = 1.0;
}
// center on current time
void TimeViewPlugin::OnCenterOnCurTime()
{
MakeTimeVisible(m_curTime, 0.5);
}
// center on current time
void TimeViewPlugin::OnShowNodeHistoryNodeInGraph()
{
if (m_nodeHistoryItem && m_actorInstanceData)
{
emit DoubleClickedRecorderNodeHistoryItem(m_actorInstanceData, m_nodeHistoryItem);
}
}
// center on current time
void TimeViewPlugin::OnClickNodeHistoryNode()
{
if (m_nodeHistoryItem && m_actorInstanceData)
{
emit ClickedRecorderNodeHistoryItem(m_actorInstanceData, m_nodeHistoryItem);
}
}
// zooming on rect
void TimeViewPlugin::ZoomRect(const QRect& rect)
{
m_targetScrollX = m_scrollX + (rect.left() / m_timeScale);
m_targetTimeScale = m_trackDataWidget->geometry().width() / (double)(rect.width() / m_timeScale);
if (m_targetTimeScale < 1.0)
{
m_targetTimeScale = 1.0;
}
if (m_targetTimeScale > m_maxScale)
{
m_targetTimeScale = m_maxScale;
}
}
// callbacks
bool ReInitTimeViewPlugin()
{
EMStudioPlugin* plugin = EMStudio::GetPluginManager()->FindActivePlugin(TimeViewPlugin::CLASS_ID);
if (plugin == nullptr)
{
return false;
}
TimeViewPlugin* timeViewPlugin = (TimeViewPlugin*)plugin;
timeViewPlugin->ReInit();
return true;
}
bool MotionSelectionChangedTimeViewPlugin()
{
EMStudioPlugin* plugin = EMStudio::GetPluginManager()->FindActivePlugin(TimeViewPlugin::CLASS_ID);
if (plugin == nullptr)
{
return false;
}
TimeViewPlugin* timeViewPlugin = (TimeViewPlugin*)plugin;
timeViewPlugin->MotionSelectionChanged();
return true;
}
bool UpdateInterfaceTimeViewPlugin()
{
EMStudioPlugin* plugin = EMStudio::GetPluginManager()->FindActivePlugin(TimeViewPlugin::CLASS_ID);
if (plugin == nullptr)
{
return false;
}
static_cast<TimeViewPlugin*>(plugin)->GetTimeViewToolBar()->UpdateInterface();
return true;
}
bool TimeViewPlugin::CommandAdjustMotionCallback::Execute(MCore::Command* command, const MCore::CommandLine& commandLine) { MCORE_UNUSED(command); MCORE_UNUSED(commandLine); return ReInitTimeViewPlugin(); }
bool TimeViewPlugin::CommandAdjustMotionCallback::Undo(MCore::Command* command, const MCore::CommandLine& commandLine) { MCORE_UNUSED(command); MCORE_UNUSED(commandLine); return ReInitTimeViewPlugin(); }
bool TimeViewPlugin::CommandSelectCallback::Execute(MCore::Command* command, const MCore::CommandLine& commandLine)
{
MCORE_UNUSED(command);
if (CommandSystem::CheckIfHasMotionSelectionParameter(commandLine) == false)
{
UpdateInterfaceTimeViewPlugin();
return true;
}
return MotionSelectionChangedTimeViewPlugin();
}
bool TimeViewPlugin::CommandSelectCallback::Undo(MCore::Command* command, const MCore::CommandLine& commandLine)
{
MCORE_UNUSED(command);
if (CommandSystem::CheckIfHasMotionSelectionParameter(commandLine) == false)
{
UpdateInterfaceTimeViewPlugin();
return true;
}
return MotionSelectionChangedTimeViewPlugin();
}
bool TimeViewPlugin::CommandUnselectCallback::Execute(MCore::Command* command, const MCore::CommandLine& commandLine)
{
MCORE_UNUSED(command);
if (CommandSystem::CheckIfHasMotionSelectionParameter(commandLine) == false)
{
return true;
}
return MotionSelectionChangedTimeViewPlugin();
}
bool TimeViewPlugin::CommandUnselectCallback::Undo(MCore::Command* command, const MCore::CommandLine& commandLine)
{
MCORE_UNUSED(command);
if (CommandSystem::CheckIfHasMotionSelectionParameter(commandLine) == false)
{
return true;
}
return MotionSelectionChangedTimeViewPlugin();
}
bool TimeViewPlugin::CommandClearSelectionCallback::Execute(MCore::Command* command, const MCore::CommandLine& commandLine) { MCORE_UNUSED(command); MCORE_UNUSED(commandLine); return MotionSelectionChangedTimeViewPlugin(); }
bool TimeViewPlugin::CommandClearSelectionCallback::Undo(MCore::Command* command, const MCore::CommandLine& commandLine) { MCORE_UNUSED(command); MCORE_UNUSED(commandLine); return MotionSelectionChangedTimeViewPlugin(); }
bool TimeViewPlugin::CommandRecorderClearCallback::Execute(MCore::Command* command, const MCore::CommandLine& commandLine) { MCORE_UNUSED(command); MCORE_UNUSED(commandLine); return ReInitTimeViewPlugin(); }
bool TimeViewPlugin::CommandRecorderClearCallback::Undo(MCore::Command* command, const MCore::CommandLine& commandLine) { MCORE_UNUSED(command); MCORE_UNUSED(commandLine); return ReInitTimeViewPlugin(); }
bool TimeViewPlugin::UpdateInterfaceCallback::Execute(MCore::Command* command, const MCore::CommandLine& commandLine) { MCORE_UNUSED(command); MCORE_UNUSED(commandLine); return UpdateInterfaceTimeViewPlugin(); }
bool TimeViewPlugin::UpdateInterfaceCallback::Undo(MCore::Command* command, const MCore::CommandLine& commandLine) { MCORE_UNUSED(command); MCORE_UNUSED(commandLine); return UpdateInterfaceTimeViewPlugin(); }
// calculate the content heights
uint32 TimeViewPlugin::CalcContentHeight() const
{
RecorderGroup* recorderGroup = m_timeViewToolBar->GetRecorderGroup();
const bool displayNodeActivity = recorderGroup->GetDisplayNodeActivity();
const bool displayEvents = recorderGroup->GetDisplayMotionEvents();
const bool displayRelativeGraph = recorderGroup->GetDisplayRelativeGraph();
uint32 result = 0;
if (displayNodeActivity)
{
result += m_trackDataWidget->m_nodeHistoryRect.bottom();
}
if (displayEvents)
{
result += m_trackDataWidget->m_eventHistoryTotalHeight;
}
if (displayRelativeGraph)
{
}
// MCore::LogInfo("maxHeight = %d", result);
return result;
}
void TimeViewPlugin::OnManualTimeChange(float timeValue)
{
MCORE_UNUSED(timeValue);
GetMainWindow()->OnUpdateRenderPlugins();
}
void TimeViewPlugin::OnFocusIn()
{
SetMode(TimeViewMode::AnimGraph);
}
void TimeViewPlugin::OnShow()
{
SetMode(TimeViewMode::AnimGraph);
}
void TimeViewPlugin::SetMode(TimeViewMode mode)
{
const bool modeChanged = (m_mode != mode);
m_mode = mode;
switch (mode)
{
case TimeViewMode::Motion:
{
EMotionFX::Motion* motion = GetCommandManager()->GetCurrentSelection().GetSingleMotion();
if ((m_motion != motion) || modeChanged)
{
m_motion = motion;
ReInit();
}
if (m_trackHeaderWidget)
{
m_trackHeaderWidget->GetAddTrackWidget()->setEnabled(motion != nullptr);
}
break;
}
default:
{
m_motion = nullptr;
ReInit();
OnZoomAll();
SetCurrentTime(0.0f);
}
}
m_timeViewToolBar->UpdateInterface();
}
} // namespace EMStudio
| 32.996163 | 232 | 0.545271 | [
"geometry",
"render",
"vector",
"3d"
] |
606736ad5ea2f07d1d0dbc42904b2e580176721a | 3,729 | hpp | C++ | SubtaskSingularTask.hpp | iarebwan/TaskScheduler | f21a7c1823f9dfe1e495596666d072ca08b234b7 | [
"MIT"
] | null | null | null | SubtaskSingularTask.hpp | iarebwan/TaskScheduler | f21a7c1823f9dfe1e495596666d072ca08b234b7 | [
"MIT"
] | null | null | null | SubtaskSingularTask.hpp | iarebwan/TaskScheduler | f21a7c1823f9dfe1e495596666d072ca08b234b7 | [
"MIT"
] | 1 | 2022-01-27T05:15:36.000Z | 2022-01-27T05:15:36.000Z | #ifndef __SUBTASK_SINGULAR_TASK_HPP__
#define __SUBTASK_SINGULAR_TASK_HPP__
#include "Task.hpp"
#include <string>
#include <iostream>
#include <fstream>
using namespace std;
class Task;
class SingularSubtask : public Task {
public:
SingularSubtask(string taskTitle, string taskPriority, string taskDescription, string taskDueDate, string taskType) {
title = taskTitle;
priority = taskPriority;
description = taskDescription;
dueDate = taskDueDate;
classification = taskType;
}
void displayTask() {
if(firstLayerDirectorySubtaskDisplayFlag == 0) {
cout << "TASK TITLE: " << getTaskTitle() << endl;
cout << "TASK PRIORITY: " << getTaskPriority() << endl;
cout << "TASK DESCRIPTION: " << getTaskDescription() << endl;
cout << "TASK DUE DATE: " << getTaskDueDate() << endl;
cout << "TASK TYPE: " << getTaskType() << endl << endl;
}
else {
for (int i = 0; i < numberOfIndents; i++) {
cout << "\t";
}
cout << "TASK TITLE: " << getTaskTitle() << endl;
for (int i = 0; i < numberOfIndents; i++) {
cout << "\t";
}
cout << "TASK PRIORITY: " << getTaskPriority() << endl;
for (int i = 0; i < numberOfIndents; i++) {
cout << "\t";
}
cout << "TASK DESCRIPTION: " << getTaskDescription() << endl;
for (int i = 0; i < numberOfIndents; i++) {
cout << "\t";
}
cout << "TASK DUE DATE: " << getTaskDueDate() << endl;
for(int i = 0; i < numberOfIndents; i++) {
cout << "\t";
}
cout << "TASK TYPE: " << getTaskType() << endl;
}
}
void setTaskTitle(string taskTitle) {
title = taskTitle;
}
string getTaskTitle() {
return title;
}
void setTaskPriority(string taskPriority) {
priority = taskPriority;
}
string getTaskPriority() {
return priority;
}
void setTaskDescription(string taskDescription) {
description = taskDescription;
}
string getTaskDescription() {
return description;
}
void setTaskDueDate(string taskDueDate) {
dueDate = taskDueDate;
}
string getTaskDueDate() {
return dueDate;
}
void setTaskType(string taskType) {
classification = taskType;
}
string getTaskType() {
return classification;
}
string checkTaskType() {
return "Singular Task";
}
vector<Task*> getEmbeddedListOfTasks() {}
void renameTaskFile(string oldTaskTitleStr) {
const char* oldTaskTitle = oldTaskTitleStr.c_str();
string newTaskTitleStr = getTaskTitle() + ".txt";
const char* newTaskTitle = newTaskTitleStr.c_str();
rename(oldTaskTitle, newTaskTitle);
}
void saveTaskInformation() {
fstream writeToFile;
string fileName = getTaskTitle() + ".txt";
writeToFile.open(fileName, ios::out | ios::trunc);
string theTaskDescription = getTaskDescription();
string theTaskPriority = getTaskPriority();
string theTaskDueDate = getTaskDueDate();
string theTaskType = getTaskType();
writeToFile << "TASK DESCRIPTION: " << theTaskDescription << endl << endl;
writeToFile << "TASK PRIORITY: " << theTaskPriority << endl << endl;
writeToFile << "TASK DUE DATE: " << theTaskDueDate << endl << endl;
writeToFile << "TASK CLASSIFICATION: " << theTaskType << endl << endl;
writeToFile.close();
}
};
#endif __SUBTASK_SINGULAR_TASK_HPP__ | 29.832 | 121 | 0.56959 | [
"vector"
] |
606a6cb5cbbb66cd02f2193183a8614257d16239 | 15,619 | cpp | C++ | src/SpaceTimeCubeGridArrayManipulator.cpp | nimachm81/YEEFDTD | b6a757d574ad5475193c24c0bf83af445568a3fa | [
"MIT"
] | null | null | null | src/SpaceTimeCubeGridArrayManipulator.cpp | nimachm81/YEEFDTD | b6a757d574ad5475193c24c0bf83af445568a3fa | [
"MIT"
] | null | null | null | src/SpaceTimeCubeGridArrayManipulator.cpp | nimachm81/YEEFDTD | b6a757d574ad5475193c24c0bf83af445568a3fa | [
"MIT"
] | null | null | null |
#include <cassert>
#include <cmath>
#include "SpaceTimeCubeGridArrayManipulator.h"
void SpaceTimeCubeGridArrayManipulator::SetCubeCorners(std::array<FPNumber, 4>& cube_r0, std::array<FPNumber, 4>& cube_r1) {
assert(std::real(cube_r0[0]) <= std::real(cube_r1[0]) &&
std::real(cube_r0[1]) <= std::real(cube_r1[1]) &&
std::real(cube_r0[2]) <= std::real(cube_r1[2]) &&
std::real(cube_r0[3]) <= std::real(cube_r1[3]));
cubeR0 = cube_r0;
cubeR1 = cube_r1;
}
void SpaceTimeCubeGridArrayManipulator::SetEdgeThickness(std::array<FPNumber, 4>& thickness) {
assert(std::real(thickness[0]) >= 0.0 &&
std::real(thickness[1]) >= 0.0 &&
std::real(thickness[2]) >= 0.0 &&
std::real(thickness[3]) >= 0.0);
smoothEdgeThickness = thickness;
}
void SpaceTimeCubeGridArrayManipulator::SetInsideValue(FPNumber value) {
insideValue = value;
}
void SpaceTimeCubeGridArrayManipulator::SetOutsideValue(FPNumber value) {
outsideValue = value;
}
void SpaceTimeCubeGridArrayManipulator::SetTimeOffsetFraction(const FPNumber offsetFraction) {
timeOffsetFraction = offsetFraction;
}
std::pair<std::array<std::size_t, 3>, std::array<std::size_t, 3>>
SpaceTimeCubeGridArrayManipulator::GetArrayIndicesBetweenTwoCorners(std::array<FPNumber, 3>& cornerR0,
std::array<FPNumber, 3>& cornerR1) {
std::array<std::size_t, 3> shape = gridArray.GetShape();
FPNumber dx = dr[0];
FPNumber dy = dr[1];
FPNumber dz = dr[2];
std::array<std::size_t, 3> indStart = {(std::size_t)std::ceil(std::real((cornerR0[0] - r0[0])/dx)),
(std::size_t)std::ceil(std::real((cornerR0[1] - r0[1])/dy)),
(std::size_t)std::ceil(std::real((cornerR0[2] - r0[2])/dz))};
if(std::real(cornerR0[0]) <= std::real(r0[0])) {indStart[0] = 0;}
if(std::real(cornerR0[1]) <= std::real(r0[1])) {indStart[1] = 0;}
if(std::real(cornerR0[2]) <= std::real(r0[2])) {indStart[2] = 0;}
std::array<std::size_t, 3> indEnd = {(std::size_t)std::floor(std::real((cornerR1[0] - r0[0])/dx)),
(std::size_t)std::floor(std::real((cornerR1[1] - r0[1])/dy)),
(std::size_t)std::floor(std::real((cornerR1[2] - r0[2])/dz))};
if(indEnd[0] > shape[0]) {indEnd[0] = shape[0];}
if(indEnd[1] > shape[1]) {indEnd[1] = shape[1];}
if(indEnd[2] > shape[2]) {indEnd[2] = shape[2];}
if(std::real(cornerR1[0]) <= std::real(r0[0])) {indEnd[0] = 0;}
if(std::real(cornerR1[1]) <= std::real(r0[1])) {indEnd[1] = 0;}
if(std::real(cornerR1[2]) <= std::real(r0[2])) {indEnd[2] = 0;}
std::pair<std::array<std::size_t, 3>, std::array<std::size_t, 3>> indexPair(indStart, indEnd);
return indexPair;
}
void SpaceTimeCubeGridArrayManipulator::UpdateArray(const FPNumber t, GAManipulatorInstructionCode instruction) {
FPNumber t0_m = cubeR0[3] - smoothEdgeThickness[3]/(FPNumber)2.0;
FPNumber t0_p = cubeR0[3] + smoothEdgeThickness[3]/(FPNumber)2.0;
FPNumber t1_m = cubeR1[3] - smoothEdgeThickness[3]/(FPNumber)2.0;
FPNumber t1_p = cubeR1[3] + smoothEdgeThickness[3]/(FPNumber)2.0;
assert(std::real(t0_p) <= std::real(t1_m)); // otherwise array recalculation conditions may lead to unpredicted results
/* If array is modified elsewhere everything has to be recalculated
if(t < t0_m && temporalState == 0) {
return; // the array has already the correct value. No need to recalculate.
} else if(t > t1_p && temporalState == 4) {
return;
} else if(t > t0_p && t < t1_m && temporalState == 2) {
return;
}*/
NumberArray3D<FPNumber> rhsArray;
std::array<std::size_t, 3> shape = gridArray.GetShape();
FPNumber dx = dr[0];
FPNumber dy = dr[1];
FPNumber dz = dr[2];
if(instruction == GAManipulatorInstructionCode::Equal) {
rhsArray.MakeThisASliceOf(gridArray);
rhsArray = (FPNumber)0.0;
} else {
rhsArray.ReInitialize(shape, (FPNumber)0.0);
}
// get an slice on the cube and set its value to insideValue
std::array<FPNumber, 3> cubeR0_p{cubeR0[0] + smoothEdgeThickness[0]/(FPNumber)2,
cubeR0[1] + smoothEdgeThickness[1]/(FPNumber)2,
cubeR0[2] + smoothEdgeThickness[2]/(FPNumber)2};
std::array<FPNumber, 3> cubeR0_m{cubeR0[0] - smoothEdgeThickness[0]/(FPNumber)2,
cubeR0[1] - smoothEdgeThickness[1]/(FPNumber)2,
cubeR0[2] - smoothEdgeThickness[2]/(FPNumber)2};
std::array<FPNumber, 3> cubeR1_p{cubeR1[0] + smoothEdgeThickness[0]/(FPNumber)2,
cubeR1[1] + smoothEdgeThickness[1]/(FPNumber)2,
cubeR1[2] + smoothEdgeThickness[2]/(FPNumber)2};
std::array<FPNumber, 3> cubeR1_m{cubeR1[0] - smoothEdgeThickness[0]/(FPNumber)2,
cubeR1[1] - smoothEdgeThickness[1]/(FPNumber)2,
cubeR1[2] - smoothEdgeThickness[2]/(FPNumber)2};
std::pair<std::array<std::size_t, 3>, std::array<std::size_t, 3>> indexPair_mp =
GetArrayIndicesBetweenTwoCorners(cubeR0_m, cubeR1_p);
std::pair<std::array<std::size_t, 3>, std::array<std::size_t, 3>> indexPair_pm =
GetArrayIndicesBetweenTwoCorners(cubeR0_p, cubeR1_m);
std::array<std::size_t, 3>& indStart_p = indexPair_pm.first;
std::array<std::size_t, 3>& indStart_m = indexPair_mp.first;
std::array<std::size_t, 3>& indEnd_p = indexPair_mp.second;
std::array<std::size_t, 3>& indEnd_m = indexPair_pm.second;
assert(indStart_m[0] <= indEnd_p[0] && indStart_m[1] <= indEnd_p[1] && indStart_m[2] <= indEnd_p[2]);
assert(indStart_m[0] < indEnd_p[0] || indStart_m[1] < indEnd_p[1] || indStart_m[2] < indEnd_p[2]);
NumberArray3D slice = rhsArray.GetSlice(indStart_p, indEnd_m);
slice = (FPNumber)1.0;
// set the edge frames to 1.0
if(std::real(smoothEdgeThickness[0]) > 0.0) {
// get an slice for the cube face with normal along +x or -x
std::array<std::size_t, 3> indStart_xm{indStart_m[0], indStart_m[1], indStart_m[2]};
std::array<std::size_t, 3> indEnd_xm{indStart_p[0], indEnd_p[1], indEnd_p[2]};
std::array<std::size_t, 3> indStart_xp{indEnd_m[0], indStart_m[1], indStart_m[2]};
std::array<std::size_t, 3> indEnd_xp{indEnd_p[0], indEnd_p[1], indEnd_p[2]};
NumberArray3D slice_xm = rhsArray.GetSlice(indStart_xm, indEnd_xm);
slice_xm = 1.0;
NumberArray3D slice_xp = rhsArray.GetSlice(indStart_xp, indEnd_xp);
slice_xp = (FPNumber)1.0;
}
if(std::real(smoothEdgeThickness[1]) > 0.0) {
// get an slice for the cube face with normal along +y or -y
std::array<std::size_t, 3> indStart_ym{indStart_m[0], indStart_m[1], indStart_m[2]};
std::array<std::size_t, 3> indEnd_ym{indEnd_p[0], indStart_p[1], indEnd_p[2]};
std::array<std::size_t, 3> indStart_yp{indStart_m[0], indEnd_m[1], indStart_m[2]};
std::array<std::size_t, 3> indEnd_yp{indEnd_p[0], indEnd_p[1], indEnd_p[2]};
NumberArray3D slice_ym = rhsArray.GetSlice(indStart_ym, indEnd_ym);
slice_ym = (FPNumber)1.0;
NumberArray3D slice_yp = rhsArray.GetSlice(indStart_yp, indEnd_yp);
slice_yp = (FPNumber)1.0;
}
if(std::real(smoothEdgeThickness[2]) > 0.0) {
// get an slice for the cube face with normal along +z or -z
std::array<std::size_t, 3> indStart_zm{indStart_m[0], indStart_m[1], indStart_m[2]};
std::array<std::size_t, 3> indEnd_zm{indEnd_p[0], indEnd_p[1], indStart_p[2]};
std::array<std::size_t, 3> indStart_zp{indStart_m[0], indStart_m[1], indEnd_m[2]};
std::array<std::size_t, 3> indEnd_zp{indEnd_p[0], indEnd_p[1], indEnd_p[2]};
NumberArray3D slice_zm = rhsArray.GetSlice(indStart_zm, indEnd_zm);
slice_zm = (FPNumber)1.0;
NumberArray3D slice_zp = rhsArray.GetSlice(indStart_zp, indEnd_zp);
slice_zp = (FPNumber)1.0;
}
// smoothen the edges
if(std::real(smoothEdgeThickness[0]) > 0.0) {
// get an slice for the cube face with normal along +x or -x
std::array<std::size_t, 3> indStart_xm{indStart_m[0], indStart_m[1], indStart_m[2]};
std::array<std::size_t, 3> indEnd_xm{indStart_p[0], indEnd_p[1], indEnd_p[2]};
std::array<std::size_t, 3> indStart_xp{indEnd_m[0], indStart_m[1], indStart_m[2]};
std::array<std::size_t, 3> indEnd_xp{indEnd_p[0], indEnd_p[1], indEnd_p[2]};
NumberArray3D slice_xm = rhsArray.GetSlice(indStart_xm, indEnd_xm);
NumberArray3D slice_xp = rhsArray.GetSlice(indStart_xp, indEnd_xp);
// create meshgrid
std::array<FPNumber, 3> r0_xm{(FPNumber)(indStart_xm[0])*dx,
(FPNumber)(indStart_xm[1])*dy,
(FPNumber)(indStart_xm[2])*dz};
std::array<FPNumber, 3> r1_xm{(FPNumber)(indEnd_xm[0])*dx,
(FPNumber)(indEnd_xm[1])*dy,
(FPNumber)(indEnd_xm[2])*dz};
NumberArray3D<FPNumber> xm = NumberArray3D<FPNumber>::GetMeshGrid(slice_xm.GetShape(), r0_xm, r1_xm, 0);
slice_xm *= 0.5*NumberArray3D<FPNumber>::sin((xm - r0_xm[0])*M_PI/(r1_xm[0] - r0_xm[0]) - M_PI/2) + 0.5;
std::array<FPNumber, 3> r0_xp{r0[0] + (FPNumber)(indStart_xp[0])*dx,
r0[1] + (FPNumber)(indStart_xp[1])*dy,
r0[2] + (FPNumber)(indStart_xp[2])*dz};
std::array<FPNumber, 3> r1_xp{r0[0] + (FPNumber)(indEnd_xp[0])*dx,
r0[1] + (FPNumber)(indEnd_xp[1])*dy,
r0[2] + (FPNumber)(indEnd_xp[2])*dz};
NumberArray3D<FPNumber> xp = NumberArray3D<FPNumber>::GetMeshGrid(slice_xp.GetShape(), r0_xp, r1_xp, 0);
slice_xp *= 0.5*NumberArray3D<FPNumber>::cos((xp - r0_xp[0])*M_PI/(r1_xp[0] - r0_xp[0])) + 0.5;
}
if(std::real(smoothEdgeThickness[1]) > 0.0) {
// get an slice for the cube face with normal along +y or -y
std::array<std::size_t, 3> indStart_ym{indStart_m[0], indStart_m[1], indStart_m[2]};
std::array<std::size_t, 3> indEnd_ym{indEnd_p[0], indStart_p[1], indEnd_p[2]};
std::array<std::size_t, 3> indStart_yp{indStart_m[0], indEnd_m[1], indStart_m[2]};
std::array<std::size_t, 3> indEnd_yp{indEnd_p[0], indEnd_p[1], indEnd_p[2]};
NumberArray3D slice_ym = rhsArray.GetSlice(indStart_ym, indEnd_ym);
NumberArray3D slice_yp = rhsArray.GetSlice(indStart_yp, indEnd_yp);
// create meshgrid
std::array<FPNumber, 3> r0_ym{(FPNumber)(indStart_ym[0])*dx,
(FPNumber)(indStart_ym[1])*dy,
(FPNumber)(indStart_ym[2])*dz};
std::array<FPNumber, 3> r1_ym{(FPNumber)(indEnd_ym[0])*dx,
(FPNumber)(indEnd_ym[1])*dy,
(FPNumber)(indEnd_ym[2])*dz};
NumberArray3D<FPNumber> ym = NumberArray3D<FPNumber>::GetMeshGrid(slice_ym.GetShape(), r0_ym, r1_ym, 1);
slice_ym *= 0.5*NumberArray3D<FPNumber>::sin((ym - r0_ym[1])*M_PI/(r1_ym[1] - r0_ym[1]) - M_PI/2) + 0.5;
std::array<FPNumber, 3> r0_yp{r0[0] + (FPNumber)(indStart_yp[0])*dx,
r0[1] + (FPNumber)(indStart_yp[1])*dy,
r0[2] + (FPNumber)(indStart_yp[2])*dz};
std::array<FPNumber, 3> r1_yp{r0[0] + (FPNumber)(indEnd_yp[0])*dx,
r0[1] + (FPNumber)(indEnd_yp[1])*dy,
r0[2] + (FPNumber)(indEnd_yp[2])*dz};
NumberArray3D<FPNumber> yp = NumberArray3D<FPNumber>::GetMeshGrid(slice_yp.GetShape(), r0_yp, r1_yp, 1);
slice_yp *= 0.5*NumberArray3D<FPNumber>::cos((yp - r0_yp[1])*M_PI/(r1_yp[1] - r0_yp[1])) + 0.5;
}
if(std::real(smoothEdgeThickness[2]) > 0.0) {
// get an slice for the cube face with normal along +z or -z
std::array<std::size_t, 3> indStart_zm{indStart_m[0], indStart_m[1], indStart_m[2]};
std::array<std::size_t, 3> indEnd_zm{indEnd_p[0], indEnd_p[1], indStart_p[2]};
std::array<std::size_t, 3> indStart_zp{indStart_m[0], indStart_m[1], indEnd_m[2]};
std::array<std::size_t, 3> indEnd_zp{indEnd_p[0], indEnd_p[1], indEnd_p[2]};
NumberArray3D slice_zm = rhsArray.GetSlice(indStart_zm, indEnd_zm);
NumberArray3D slice_zp = rhsArray.GetSlice(indStart_zp, indEnd_zp);
// create meshgrid
std::array<FPNumber, 3> r0_zm{(FPNumber)(indStart_zm[0])*dx,
(FPNumber)(indStart_zm[1])*dy,
(FPNumber)(indStart_zm[2])*dz};
std::array<FPNumber, 3> r1_zm{(FPNumber)(indEnd_zm[0])*dx,
(FPNumber)(indEnd_zm[1])*dy,
(FPNumber)(indEnd_zm[2])*dz};
NumberArray3D<FPNumber> zm = NumberArray3D<FPNumber>::GetMeshGrid(slice_zm.GetShape(), r0_zm, r1_zm, 2);
slice_zm *= 0.5*NumberArray3D<FPNumber>::sin((zm - r0_zm[2])*M_PI/(r1_zm[2] - r0_zm[2]) - M_PI/2) + 0.5;
std::array<FPNumber, 3> r0_zp{r0[0] + (FPNumber)(indStart_zp[0])*dx,
r0[1] + (FPNumber)(indStart_zp[1])*dy,
r0[2] + (FPNumber)(indStart_zp[2])*dz};
std::array<FPNumber, 3> r1_zp{r0[0] + (FPNumber)(indEnd_zp[0])*dx,
r0[1] + (FPNumber)(indEnd_zp[1])*dy,
r0[2] + (FPNumber)(indEnd_zp[2])*dz};
NumberArray3D<FPNumber> zp = NumberArray3D<FPNumber>::GetMeshGrid(slice_zp.GetShape(), r0_zp, r1_zp, 2);
slice_zp *= 0.5*NumberArray3D<FPNumber>::cos((zp - r0_zp[2])*M_PI/(r1_zp[2] - r0_zp[2])) + 0.5;
}
//std::cout << temporalState << " ";
temporalState = 2;
if(std::real(t) <= std::real(t0_m) || std::real(t) >= std::real(t1_p)) {
rhsArray *= (FPNumber)0.0;
if(std::real(t) <= std::real(t0_m)) {
temporalState = 0;
} else if(std::real(t) >= std::real(t1_p)) {
temporalState = 4;
}
} else if(std::real(t) > std::real(t0_m) && std::real(t) < std::real(t0_p)) {
rhsArray *= (FPNumber)0.5*std::sin((t - t0_m)*(FPNumber)(M_PI)/(t0_p - t0_m) - (FPNumber)(M_PI/2)) + (FPNumber)0.5;
temporalState = 1;
} else if(std::real(t) > std::real(t1_m) && std::real(t) < std::real(t1_p)) {
rhsArray *= (FPNumber)0.5*std::cos((t - t1_m)*(FPNumber)(M_PI)/(t1_p - t1_m)) + (FPNumber)0.5;
temporalState = 3;
}
//std::cout << temporalState << std::endl;
rhsArray *= (insideValue - outsideValue);
rhsArray += outsideValue;
if(instruction == GAManipulatorInstructionCode::PlusEqual) {
gridArray += rhsArray;
} else if(instruction == GAManipulatorInstructionCode::MultiplyEqual) {
gridArray *= rhsArray;
} else {
std::cout << "Not implemented!!!" << std::endl;
assert(false);
}
}
FPNumber SpaceTimeCubeGridArrayManipulator::CalculateTime(const FPNumber dt, const std::size_t timeIndex) {
return ((FPNumber)timeIndex + timeOffsetFraction) * dt;
}
| 51.209836 | 125 | 0.584544 | [
"shape"
] |
606b76293d88002e91491dcdf81896473140607e | 3,484 | hpp | C++ | Peli.hpp | WhiteDeathFIN/Labyrinttipeli | f89b62d17f6b4bddd5a5df4729c157649b8f64b4 | [
"Apache-2.0"
] | null | null | null | Peli.hpp | WhiteDeathFIN/Labyrinttipeli | f89b62d17f6b4bddd5a5df4729c157649b8f64b4 | [
"Apache-2.0"
] | null | null | null | Peli.hpp | WhiteDeathFIN/Labyrinttipeli | f89b62d17f6b4bddd5a5df4729c157649b8f64b4 | [
"Apache-2.0"
] | null | null | null | #ifndef PELI_HPP
#define PELI_HPP
/**
* \version $Id: Peli.hpp 2660 2015-12-08 12:47:00Z bitti $
* \file Peli.hpp
* \brief Peli-luokan esittely.
* \author ©2015 Santeri Hetekivi <santeri.hetekivi@eng.tamk.fi>
*/
// Rajapinta
#include "pelirajapinta.hh"
// Nayttö
#include "valmiiden_toteutus\include\naytto.hh"
// Julkisen rajapinnan kirjastot:
#include "vaittama.hh"
#include "toimintovirhe.hh"
// Luomani luokat
#include "PelaajaToiminto.hpp"
#include "PelinNaytto.hpp"
#include "Data.hpp"
// STL:n kirjastot:
#include <map>
/**
* \brief Labyrintti-pelin pelin toimintojen suorittava luokka.
*/
class Peli : public Julkinen::Pelirajapinta
{
public:
Peli();
~Peli();
/**
* \copydoc Julkinen::Pelirajapinta::onkoAlustustilassa() const
*/
virtual bool onkoAlustustilassa() const;
/**
* \copydoc Julkinen::Pelirajapinta::lisaaNaytto(Nayttorajapinta* naytto)
*/
virtual void lisaaNaytto(Julkinen::Nayttorajapinta* naytto);
/**
* \copydoc Julkinen::Pelirajapinta::maaritaPelialueenKoko(Julkinen::Koordinaatti const& koko)
*/
virtual void maaritaPelialueenKoko(Julkinen::Koordinaatti const& koko);
/**
* \copydoc Julkinen::Pelirajapinta::lisaaPelaaja(PelaajaTyyppi tyyppi, std::string const& nimi, char lyhenne, Julkinen::Koordinaatti const& sijainti)
*/
virtual void lisaaPelaaja(Julkinen::PelaajaTyyppi tyyppi, std::string const& nimi, char lyhenne, Julkinen::Koordinaatti const& sijainti);
/**
* \copydoc Julkinen::Pelirajapinta::lisaaPala(Julkinen::PalaTyyppi pala, unsigned int rotaatio, Julkinen::Koordinaatti const& sijainti)
*/
virtual void lisaaPala(Julkinen::PalaTyyppi pala, unsigned int rotaatio, Julkinen::Koordinaatti const& sijainti);
/**
* \copydoc Julkinen::Pelirajapinta::lisaaEsine(char merkki, Julkinen::Koordinaatti const& sijainti, std::string const& pelaaja)
*/
virtual void lisaaEsine(char merkki, Julkinen::Koordinaatti const& sijainti, std::string const& pelaaja);
/**
* \copydoc Julkinen::Pelirajapinta::asetaPalanTyyppi(Julkinen::ErikoispalaTyyppi tyyppi, Julkinen::Koordinaatti const& sijainti, Julkinen::Koordinaatti const& kohde = Julkinen::Koordinaatti())
*/
virtual void asetaPalanTyyppi(Julkinen::ErikoispalaTyyppi tyyppi, Julkinen::Koordinaatti const& sijainti, Julkinen::Koordinaatti const& kohde = Julkinen::Koordinaatti());
/**
* \copydoc Julkinen::Pelirajapinta::alustusLopeta()
*/
virtual void alustusLopeta();
/**
* \copydoc Julkinen::Pelirajapinta::onkoPelitilassa() const
*/
virtual bool onkoPelitilassa() const;
/**
* \copydoc Julkinen::Pelirajapinta::komentoTyonna(Julkinen::Reuna reuna, unsigned int paikka, unsigned int rotaatio)
*/
virtual void komentoTyonna(Julkinen::Reuna reuna, unsigned int paikka, unsigned int rotaatio);
/**
* \copydoc Julkinen::Pelirajapinta::komentoLiiku(Julkinen::Suunta suunta, unsigned int maara = 0)
*/
virtual void komentoLiiku(Julkinen::Suunta suunta, unsigned int maara = 0);
/**
* \copydoc Julkinen::Pelirajapinta::vaihdaVuoro()
*/
virtual bool vaihdaVuoro();
/**
* \copydoc Julkinen::Pelirajapinta::haeVuorossa()
*/
virtual Julkinen::PelaajaTyyppi haeVuorossa();
private:
void paivitaNaytto();
enum Tila
{
ALUSTUS,
PELI
};
Tila _tila;
PelinNaytto * _naytto = NULL;
PelaajaToiminto * _toiminto = NULL;
std::vector<Pelaaja *>::iterator vuorossa;
Julkinen::Koordinaatti _koko;
std::vector<Pelaaja *> _pelaajat;
Data * _data = new Data();
};
#endif | 32.867925 | 195 | 0.73163 | [
"vector"
] |
606d4b0c41ba82a0fb62d1899975d65c19775701 | 12,223 | cpp | C++ | modules/cpp-core-mmciflib-wrapper-gen/src/wrapCifFile.cpp | epeisach/py-mmcif | f44cb8e4a1699c1f254f873fadced1f4461763f6 | [
"Apache-2.0"
] | 9 | 2019-08-29T09:43:02.000Z | 2022-01-11T01:00:39.000Z | modules/cpp-core-mmciflib-wrapper-gen/src/wrapCifFile.cpp | epeisach/py-mmcif | f44cb8e4a1699c1f254f873fadced1f4461763f6 | [
"Apache-2.0"
] | 7 | 2018-07-03T16:04:38.000Z | 2022-03-23T05:54:37.000Z | modules/cpp-core-mmciflib-wrapper-gen/src/wrapCifFile.cpp | epeisach/py-mmcif | f44cb8e4a1699c1f254f873fadced1f4461763f6 | [
"Apache-2.0"
] | 10 | 2019-03-05T18:06:59.000Z | 2022-01-27T03:32:19.000Z | // File: ./src/wrapCifFile.cpp
// Date: 2018-01-10
//
#include <pybind11/pybind11.h>
#include <pybind11/stl.h>
#include <string>
#include <vector>
#include <map>
#include <iostream>
#include <sstream>
#include "GenString.h"
#include "CifString.h"
#include "TableFile.h"
#include "CifParentChild.h"
#include "CifFile.h"
namespace py = pybind11;
using namespace pybind11::literals;
#ifndef BINDER_PYBIND11_TYPE_CASTER
#define BINDER_PYBIND11_TYPE_CASTER
PYBIND11_DECLARE_HOLDER_TYPE(T, std::shared_ptr<T>);
PYBIND11_DECLARE_HOLDER_TYPE(T, T*);
PYBIND11_MAKE_OPAQUE(std::shared_ptr<void>);
#endif
void wrapCifFile(py::module &m) {
m.doc() = "Wrapper for header file CifFile.h";
{
py::class_<CifFile, std::shared_ptr<CifFile>, TableFile> cls(m, "CifFile", "Wrapper for class CifFile");
py::enum_<CifFile::eQuoting>(cls, "eQuoting")
.value("eSINGLE", CifFile::eQuoting::eSINGLE)
.value("eDOUBLE", CifFile::eQuoting::eDOUBLE)
.export_values();
cls.def(py::init<const eFileMode, const std::string &, const bool, const Char::eCompareType, const unsigned int, const std::string &>(), py::arg("fileMode"), py::arg("fileName"), py::arg("verbose"), py::arg("caseSense"), py::arg("maxLineLength"), py::arg("nullValue"));
cls.def(py::init([](const eFileMode fileMode,const std::string & fileName){ return new CifFile(fileMode,fileName); }), "Generated constructor");
cls.def(py::init([](const eFileMode fileMode,const std::string & fileName,const bool verbose){ return new CifFile(fileMode,fileName,verbose); }), "Generated constructor");
cls.def(py::init([](const eFileMode fileMode,const std::string & fileName,const bool verbose,const Char::eCompareType caseSense){ return new CifFile(fileMode,fileName,verbose,caseSense); }), "Generated constructor");
cls.def(py::init([](const eFileMode fileMode,const std::string & fileName,const bool verbose,const Char::eCompareType caseSense,const unsigned int maxLineLength){ return new CifFile(fileMode,fileName,verbose,caseSense,maxLineLength); }), "Generated constructor");
cls.def(py::init<const bool, const Char::eCompareType, const unsigned int, const std::string &>(), py::arg("verbose"), py::arg("caseSense"), py::arg("maxLineLength"), py::arg("nullValue"));
cls.def(py::init([](){ return new CifFile(); }), "Generated constructor");
cls.def(py::init([](const bool verbose){ return new CifFile(verbose); }), "Generated constructor");
cls.def(py::init([](const bool verbose,const Char::eCompareType caseSense){ return new CifFile(verbose,caseSense); }), "Generated constructor");
cls.def(py::init([](const bool verbose,const Char::eCompareType caseSense,const unsigned int maxLineLength){ return new CifFile(verbose,caseSense,maxLineLength); }), "Generated constructor");
cls.def(py::init<const bool, const bool, const unsigned int, const unsigned int, const std::string &>(), py::arg("fake"), py::arg("verbose"), py::arg("intCaseSense"), py::arg("maxLineLength"), py::arg("nullValue"));
cls.def(py::init([](const bool fake,const bool verbose){ return new CifFile(fake,verbose); }), "Generated constructor");
cls.def(py::init([](const bool fake,const bool verbose,const unsigned int intCaseSense){ return new CifFile(fake,verbose,intCaseSense); }), "Generated constructor");
cls.def(py::init([](const bool fake,const bool verbose,const unsigned int intCaseSense,const unsigned int maxLineLength){ return new CifFile(fake,verbose,intCaseSense,maxLineLength); }), "Generated constructor");
cls.def("SetSrcFileName", &CifFile::SetSrcFileName,"",py::arg("srcFileName"));
cls.def("GetSrcFileName", &CifFile::GetSrcFileName,"",py::return_value_policy::reference_internal);
cls.def("GetVerbose", (bool (CifFile::*)()) &CifFile::GetVerbose,"GetVerbose with arguments ");
cls.def("SetSmartPrint", (void (CifFile::*)(bool)) &CifFile::SetSmartPrint,"SetSmartPrint with arguments bool",py::arg("smartPrint"));
cls.def("SetSmartPrint", [](CifFile &o ) -> void { return o.SetSmartPrint(); },"doc");
cls.def("IsSmartPrint", (bool (CifFile::*)()) &CifFile::IsSmartPrint,"IsSmartPrint with arguments ");
cls.def("SetQuoting", &CifFile::SetQuoting,"",py::arg("quoting"));
cls.def("GetQuoting", &CifFile::GetQuoting,"");
cls.def("SetLooping", (void (CifFile::*)(const std::string &, bool)) &CifFile::SetLooping,"SetLooping with arguments const std::string &, bool",py::arg("catName"), py::arg("looping"));
cls.def("SetLooping", [](CifFile &o, const std::string & catName) -> void { return o.SetLooping(catName); },"doc");
cls.def("GetLooping", (bool (CifFile::*)(const std::string &)) &CifFile::GetLooping,"GetLooping with arguments const std::string &",py::arg("catName"));
cls.def("Write", (void (CifFile::*)(const std::string &, const bool, const bool)) &CifFile::Write,"Write with arguments const std::string &, const bool, const bool",py::arg("cifFileName"), py::arg("sortTables"), py::arg("writeEmptyTables"));
cls.def("Write", [](CifFile &o, const std::string & cifFileName) -> void { return o.Write(cifFileName); },"doc");
cls.def("Write", [](CifFile &o, const std::string & cifFileName,const bool sortTables) -> void { return o.Write(cifFileName,sortTables); },"doc");
cls.def("Write", (void (CifFile::*)(const std::string &, const std::vector<std::string> &, const bool)) &CifFile::Write,"Write with arguments const std::string &, const std::vector<std::string> &, const bool",py::arg("cifFileName"), py::arg("tableOrder"), py::arg("writeEmptyTables"));
cls.def("Write", [](CifFile &o, const std::string & cifFileName,const std::vector<std::string> & tableOrder) -> void { return o.Write(cifFileName,tableOrder); },"doc");
cls.def("WriteNmrStar", (void (CifFile::*)(const std::string &, const std::string &, const bool, const bool)) &CifFile::WriteNmrStar,"WriteNmrStar with arguments const std::string &, const std::string &, const bool, const bool",py::arg("nmrStarFileName"), py::arg("globalBlockName"), py::arg("sortTables"), py::arg("writeEmptyTables"));
cls.def("WriteNmrStar", [](CifFile &o, const std::string & nmrStarFileName,const std::string & globalBlockName) -> void { return o.WriteNmrStar(nmrStarFileName,globalBlockName); },"doc");
cls.def("WriteNmrStar", [](CifFile &o, const std::string & nmrStarFileName,const std::string & globalBlockName,const bool sortTables) -> void { return o.WriteNmrStar(nmrStarFileName,globalBlockName,sortTables); },"doc");
cls.def("DataChecking", [](CifFile &o , CifFile & dicRef, const std::string & diagFileName, const bool extraDictChecks, const bool extraCifChecks) {
int _retVal = o.DataChecking(dicRef, diagFileName, extraDictChecks, extraCifChecks);
return std::make_tuple(_retVal, dicRef);
},"DataChecking with arguments dicRef, diagFileName, extraDictChecks, extraCifChecks",py::return_value_policy::reference_internal , py::arg("dicRef"), py::arg("diagFileName"), py::arg("extraDictChecks"), py::arg("extraCifChecks"));
cls.def("SetEnumCheck", (void (CifFile::*)(bool)) &CifFile::SetEnumCheck,"SetEnumCheck with arguments bool",py::arg("caseSense"));
cls.def("SetEnumCheck", [](CifFile &o ) -> void { return o.SetEnumCheck(); },"doc");
cls.def("GetEnumCheck", (bool (CifFile::*)()) &CifFile::GetEnumCheck,"GetEnumCheck with arguments ");
cls.def("GetParsingDiags", &CifFile::GetParsingDiags,"",py::return_value_policy::reference_internal);
cls.def("FindCifNullRows", [](CifFile &o , std::vector<unsigned int> & nullRowsIndices, const ISTable & isTable) {
o.FindCifNullRows(nullRowsIndices, isTable);
return nullRowsIndices;
},"FindCifNullRows with arguments nullRowsIndices, isTable",py::return_value_policy::reference_internal , py::arg("nullRowsIndices"), py::arg("isTable"));
cls.def("GetAttributeValue", [](CifFile &o , std::string & attribVal, const std::string & blockId, const std::string & category, const std::string & attribute) {
o.GetAttributeValue(attribVal, blockId, category, attribute);
return attribVal;
},"GetAttributeValue with arguments attribVal, blockId, category, attribute",py::return_value_policy::reference_internal , py::arg("attribVal"), py::arg("blockId"), py::arg("category"), py::arg("attribute"));
cls.def("GetAttributeValueIf", [](CifFile &o , std::string & attribVal, const std::string & blockId, const std::string & category, const std::string & attributeA, const std::string & attributeB, const std::string & valB) {
o.GetAttributeValueIf(attribVal, blockId, category, attributeA, attributeB, valB);
return attribVal;
},"GetAttributeValueIf with arguments attribVal, blockId, category, attributeA, attributeB, valB",py::return_value_policy::reference_internal , py::arg("attribVal"), py::arg("blockId"), py::arg("category"), py::arg("attributeA"), py::arg("attributeB"), py::arg("valB"));
cls.def("IsAttributeValueDefined", (bool (CifFile::*)(const std::string &, const std::string &, const std::string &)) &CifFile::IsAttributeValueDefined,"IsAttributeValueDefined with arguments const std::string &, const std::string &, const std::string &",py::arg("blockId"), py::arg("category"), py::arg("attribute"));
cls.def("SetAttributeValue", (void (CifFile::*)(const std::string &, const std::string &, const std::string &, const std::string &, const bool)) &CifFile::SetAttributeValue,"SetAttributeValue with arguments const std::string &, const std::string &, const std::string &, const std::string &, const bool",py::arg("blockId"), py::arg("category"), py::arg("attribute"), py::arg("value"), py::arg("create"));
cls.def("SetAttributeValue", [](CifFile &o, const std::string & blockId,const std::string & category,const std::string & attribute,const std::string & value) -> void { return o.SetAttributeValue(blockId,category,attribute,value); },"doc");
cls.def("SetAttributeValueIf", (void (CifFile::*)(const std::string &, const std::string &, const std::string &, const std::string &, const std::string &, const std::string &, const bool)) &CifFile::SetAttributeValueIf,"SetAttributeValueIf with arguments const std::string &, const std::string &, const std::string &, const std::string &, const std::string &, const std::string &, const bool",py::arg("blockId"), py::arg("category"), py::arg("attributeA"), py::arg("valA"), py::arg("attributeB"), py::arg("valB"), py::arg("create"));
cls.def("SetAttributeValueIf", [](CifFile &o, const std::string & blockId,const std::string & category,const std::string & attributeA,const std::string & valA,const std::string & attributeB,const std::string & valB) -> void { return o.SetAttributeValueIf(blockId,category,attributeA,valA,attributeB,valB); },"doc");
cls.def("SetAttributeValueIfNull", &CifFile::SetAttributeValueIfNull,"",py::arg("blockId"), py::arg("category"), py::arg("attribute"), py::arg("value"));
cls.def("GetAttributeValues", [](CifFile &o , std::vector<std::string> & strings, const std::string & blockId, const std::string & category, const std::string & attribute) {
o.GetAttributeValues(strings, blockId, category, attribute);
return strings;
},"GetAttributeValues with arguments strings, blockId, category, attribute",py::return_value_policy::reference_internal , py::arg("strings"), py::arg("blockId"), py::arg("category"), py::arg("attribute"));
cls.def("GetAttributeValuesIf", [](CifFile &o , std::vector<std::string> & strings, const std::string & blockId, const std::string & category, const std::string & attributeA, const std::string & attributeB, const std::string & valB) {
o.GetAttributeValuesIf(strings, blockId, category, attributeA, attributeB, valB);
return strings;
},"GetAttributeValuesIf with arguments strings, blockId, category, attributeA, attributeB, valB",py::return_value_policy::reference_internal , py::arg("strings"), py::arg("blockId"), py::arg("category"), py::arg("attributeA"), py::arg("attributeB"), py::arg("valB"));
cls.def("SetAttributeValues", &CifFile::SetAttributeValues,"",py::arg("blockId"), py::arg("category"), py::arg("attribute"), py::arg("values"));
}
} | 113.175926 | 538 | 0.702201 | [
"vector"
] |
6076f7b06231bb7f94499d92dee6a17f3d3043be | 9,908 | cpp | C++ | sample/SimpleController/UniversalRobotPickupController.cpp | kindsenior/choreonoid | 1962dc53d67c8c4d17e0b92802ee4e4684239f08 | [
"MIT"
] | 1 | 2020-05-27T15:49:54.000Z | 2020-05-27T15:49:54.000Z | sample/SimpleController/UniversalRobotPickupController.cpp | kindsenior/choreonoid | 1962dc53d67c8c4d17e0b92802ee4e4684239f08 | [
"MIT"
] | 2 | 2018-09-05T05:01:23.000Z | 2019-08-19T21:03:15.000Z | sample/SimpleController/UniversalRobotPickupController.cpp | kindsenior/choreonoid | 1962dc53d67c8c4d17e0b92802ee4e4684239f08 | [
"MIT"
] | 3 | 2019-12-21T17:54:10.000Z | 2019-12-27T13:03:29.000Z | /**
Sample picking up motion controller for UniversalRobot-2F85.
@author Shizuko Hattori
*/
#include <cnoid/SimpleController>
#include <cnoid/JointPath>
#include <cnoid/EigenUtil>
#include "Interpolator.h"
#include <fmt/format.h>
using namespace std;
using namespace cnoid;
namespace {
struct JointSpec {
string name;
double kp_torque;
double kd_torque;
};
enum ARM_MODEL {
UR3,
UR5,
UR10,
_2F_85,
NUM_ROBOTS
} ;
const int NUM_JOINTS=6;
const int NUM_HAND_JOINTS = 2;
const int MAX_NUM_JOINTS = NUM_JOINTS;
JointSpec specs[NUM_ROBOTS][MAX_NUM_JOINTS] = {
{ { "Shoulder", 500.0, 50.0 }, //UR3
{ "Upper_arm", 500.0, 50.0 },
{ "Forearm", 200.0, 20.0 },
{ "Wrist_1", 30.0, 3.0 },
{ "Wrist_2", 30.0, 3.0 },
{ "Wrist_3", 30.0, 3.0 }
},
{ { "Shoulder", 5000.0, 500.0 }, //UR5
{ "Upper_arm", 5000.0, 500.0 },
{ "Forearm", 2000.0, 200.0 },
{ "Wrist_1", 300.0, 30.0 },
{ "Wrist_2", 300.0, 30.0 },
{ "Wrist_3", 300.0, 30.0 }
},
{ { "Shoulder", 5000.0, 500.0 }, //UR10
{ "Upper_arm", 5000.0, 500.0 },
{ "Forearm", 2000.0, 200.0 },
{ "Wrist_1", 300.0, 30.0 },
{ "Wrist_2", 300.0, 30.0 },
{ "Wrist_3", 300.0, 30.0 }
},
{ { "Finger1_knuckle", 30.0, 3.0 }, //2F-85
{ "Finger2_knuckle", 30.0, 3.0 },
{ "", 0.0, 0.0 },
{ "", 0.0, 0.0 },
{ "", 0.0, 0.0 },
{ "", 0.0, 0.0 }
},
};
Vector3 position[NUM_ROBOTS-1][6][2] = {
{ { {0.4, 0.0, 0.35}, {-90.0, -25.0, 0.0} },
{ {0.5, 0.0, 0.35}, {-90.0, 0.0, 0.0} },
{ {0.0, 0.24, 0.6}, {-90.0, -45.0, 90.0} },
{ {0.0, 0.4, 0.4}, {-90.0, 0.0, 90.0} },
{ {0.0, 0.4, 0.45}, {-90.0, 0.0, 90.0} },
{ {0.23, 0.1, 0.6}, {-45.0, 41.0, -45.0} }
},
{ { {0.6, 0.0, 0.5}, {-90.0, -20.0, 0.0} },
{ {0.8, 0.0, 0.33}, {-90.0, 0.0, 0.0} },
{ {0.0, 0.5, 0.75}, {-90.0, -45.0, 90.0} },
{ {0.0, 0.5, 0.63}, {-90.0, 0.0, 90.0} },
{ {0.0, 0.5, 0.75}, {-90.0, 0.0, 90.0} },
{ {0.35, 0.1, 0.75},{-133.0, 53.0, -116.0} }
},
{ { {0.9, 0.0, 0.35}, {-90.0, 45.0, 0.0} },
{ {0.9, 0.0, 0.35}, {-90.0, 0.0, 0.0} },
{ {0.0, 0.5, 1.0 }, {-90.0, -45.0, 90.0} },
{ {0.0, 0.7, 0.65}, {-90.0, 0.0, 90.0} },
{ {0.05, 0.7, 0.75},{-90.0, 0.0, 90.0} },
{ {0.5, 0.16, 1.1}, {-133.0, 53.0, -116.0} }
}
};
}
class URobotPickupController : public SimpleController
{
Body* ioBody;
double dt;
Link::ActuationMode mainActuationMode;
ARM_MODEL arm_model;
struct JointInfo {
Link* joint;
double q_ref;
double q_old;
double kp;
double kd;
};
vector<JointInfo> jointInfos;
BodyPtr ikBody;
Link* ikWrist;
shared_ptr<JointPath> baseToWrist;
Interpolator<VectorXd> wristInterpolator;
Link* ioFinger1;
Link* ioFinger2;
int phase;
double time;
double timeStep;
double dq_Finger;
public:
Vector3 toRadianVector3(Vector3& v)
{
return Vector3(radian(v.x()), radian(v.y()), radian(v.z()));
}
bool initializeJoints(SimpleControllerIO* io, JointSpec* specs)
{
for(int i=0; i<MAX_NUM_JOINTS; i++){
JointInfo info;
if(specs[i].name!=""){
auto joint = ioBody->link(specs[i].name);
if(!joint){
io->os() << fmt::format("{0} of {1} is not found", specs[i].name, ioBody->name()) << endl;
return false;
} else {
joint->setActuationMode(mainActuationMode);
io->enableIO(joint);
info.joint = joint;
info.q_ref = info.q_old = joint->q();
if(mainActuationMode == Link::JOINT_TORQUE){
info.kp = specs[i].kp_torque;
info.kd = specs[i].kd_torque;
}
}
jointInfos.push_back(info);
}
}
return true;
};
virtual bool initialize(SimpleControllerIO* io) override
{
ioBody = io->body();
dt = io->timeStep();
mainActuationMode = Link::JOINT_TORQUE;
jointInfos.clear();
const string& BodyName = ioBody->name();
if(BodyName.find("UR3")!=string::npos){
initializeJoints( io, specs[UR3] );
arm_model = UR3;
}else if (BodyName.find("UR5")!=string::npos){
initializeJoints( io, specs[UR5] );
arm_model = UR5;
}else if (BodyName.find("UR10")!=string::npos){
initializeJoints( io, specs[UR10] );
arm_model = UR10;
}
initializeJoints( io, specs[_2F_85] );
ioFinger1 = ioBody->link("Finger1_knuckle");
ioFinger2 = ioBody->link("Finger2_knuckle");
ikBody = ioBody->clone();
ikWrist = ikBody->link("Wrist_3");
Link* base = ikBody->rootLink();
baseToWrist = JointPath::getCustomPath(ikBody, base, ikWrist);
base->p().setZero();
base->R().setIdentity();
baseToWrist->calcForwardKinematics();
VectorXd p0(6);
p0.head<3>() = ikWrist->p();
p0.tail<3>() = rpyFromRot(ikWrist->attitude());
VectorXd p1(6);
p1.head<3>() = position[arm_model][0][0];
p1.tail<3>() = toRadianVector3(position[arm_model][0][1]);
wristInterpolator.clear();
wristInterpolator.appendSample(0.0, p0);
wristInterpolator.appendSample(1.0, p1);
p1.head<3>() = position[arm_model][1][0];
p1.tail<3>() = toRadianVector3(position[arm_model][1][1]);
wristInterpolator.appendSample(1.2, p1);
wristInterpolator.update();
phase = 0;
time = 0.0;
timeStep = io->timeStep();
dq_Finger = 0.0;
return true;
}
virtual bool control() override
{
bool isActive = true;
VectorXd p(6);
if(phase <= 4){
p = wristInterpolator.interpolate(time);
if(baseToWrist->calcInverseKinematics(
Vector3(p.head<3>()), ikWrist->calcRfromAttitude(rotFromRpy(Vector3(p.tail<3>()))))){
for(int i=0; i < baseToWrist->numJoints(); ++i){
Link* joint = baseToWrist->joint(i);
jointInfos[i].q_ref = joint->q();
}
}
}
if(phase == 0){
if(time > wristInterpolator.domainUpper()){
phase = 1;
}
} else if(phase == 1){
if(fabs(ioFinger1->u()) < 40.0 || fabs(ioFinger2->u()) < 40.0){
dq_Finger = std::min(dq_Finger + 0.001, 0.1);
jointInfos[NUM_JOINTS].q_ref += radian(dq_Finger);
jointInfos[NUM_JOINTS+1].q_ref = jointInfos[NUM_JOINTS].q_ref;
} else {
VectorXd p2(6);
p2.head<3>() = position[arm_model][2][0];
p2.tail<3>() = toRadianVector3(position[arm_model][2][1]);
VectorXd p3(6);
p3.head<3>() = position[arm_model][3][0];
p3.tail<3>() = toRadianVector3(position[arm_model][3][1]);
wristInterpolator.clear();
wristInterpolator.appendSample(time, p);
wristInterpolator.appendSample(time + 1.0, p2);
wristInterpolator.appendSample(time + 1.7, p3);
wristInterpolator.update();
phase = 2;
}
} else if(phase == 2){
if(time > wristInterpolator.domainUpper()){
phase = 3;
dq_Finger = 0.0;
}
} else if(phase == 3){
if(jointInfos[NUM_JOINTS].q_ref > 0.2 || jointInfos[NUM_JOINTS+1].q_ref > 0.2){
dq_Finger = std::min(dq_Finger + 0.001, 0.03);
jointInfos[NUM_JOINTS].q_ref -= radian(dq_Finger);
jointInfos[NUM_JOINTS+1].q_ref = jointInfos[NUM_JOINTS].q_ref;
} else {
VectorXd p1(6);
p1.head<3>() = position[arm_model][4][0];
p1.tail<3>() = toRadianVector3(position[arm_model][4][1]);
VectorXd p2(6);
p2.head<3>() = position[arm_model][5][0];
p2.tail<3>() = toRadianVector3(position[arm_model][5][1]);
wristInterpolator.clear();
wristInterpolator.appendSample(time, p);
wristInterpolator.appendSample(time + 0.5, p1);
wristInterpolator.appendSample(time + 1.5, p2);
wristInterpolator.update();
phase = 4;
}
} else if(phase == 4){
if(time > wristInterpolator.domainUpper()){
isActive = false;
}
}
time += timeStep;
controlJointsWithTorque();
return isActive;
}
void controlJointsWithTorque()
{
for(auto& info : jointInfos){
auto joint = info.joint;
double q = joint->q();
double dq = (q - info.q_old) / dt;
joint->u() = info.kp * (info.q_ref - q) + info.kd * (0.0 - dq);
info.q_old = q;
}
}
};
CNOID_IMPLEMENT_SIMPLE_CONTROLLER_FACTORY(URobotPickupController)
| 31.858521 | 110 | 0.4674 | [
"vector"
] |
607cc0576de262a8758a490f1c6f90920396719a | 18,119 | cpp | C++ | Source/ALSV4_CPP/Private/Components/ALSMantleComponent.cpp | kostenickj/ALS-Community | 579453e7d06ed52160887fc9ae5ba0cf383b8153 | [
"MIT"
] | null | null | null | Source/ALSV4_CPP/Private/Components/ALSMantleComponent.cpp | kostenickj/ALS-Community | 579453e7d06ed52160887fc9ae5ba0cf383b8153 | [
"MIT"
] | null | null | null | Source/ALSV4_CPP/Private/Components/ALSMantleComponent.cpp | kostenickj/ALS-Community | 579453e7d06ed52160887fc9ae5ba0cf383b8153 | [
"MIT"
] | null | null | null | // Copyright: Copyright (C) 2022 Doğa Can Yanıkoğlu
// Source Code: https://github.com/dyanikoglu/ALS-Community
#include "Components/ALSMantleComponent.h"
#include "Character/ALSCharacter.h"
#include "Character/Animation/ALSCharacterAnimInstance.h"
#include "Components/ALSDebugComponent.h"
#include "Curves/CurveVector.h"
#include "GameFramework/CharacterMovementComponent.h"
#include "Kismet/KismetMathLibrary.h"
#include "Library/ALSMathLibrary.h"
const FName NAME_MantleEnd(TEXT("MantleEnd"));
const FName NAME_MantleUpdate(TEXT("MantleUpdate"));
const FName NAME_MantleTimeline(TEXT("MantleTimeline"));
FName UALSMantleComponent::NAME_IgnoreOnlyPawn(TEXT("IgnoreOnlyPawn"));
UALSMantleComponent::UALSMantleComponent()
{
PrimaryComponentTick.bCanEverTick = true;
PrimaryComponentTick.bStartWithTickEnabled = true;
MantleTimeline = CreateDefaultSubobject<UTimelineComponent>(NAME_MantleTimeline);
}
void UALSMantleComponent::BeginPlay()
{
Super::BeginPlay();
if (GetOwner())
{
OwnerCharacter = Cast<AALSBaseCharacter>(GetOwner());
if (OwnerCharacter)
{
ALSDebugComponent = OwnerCharacter->FindComponentByClass<UALSDebugComponent>();
AddTickPrerequisiteActor(OwnerCharacter); // Always tick after owner, so we'll use updated values
// Bindings
FOnTimelineFloat TimelineUpdated;
FOnTimelineEvent TimelineFinished;
TimelineUpdated.BindUFunction(this, NAME_MantleUpdate);
TimelineFinished.BindUFunction(this, NAME_MantleEnd);
MantleTimeline->SetTimelineFinishedFunc(TimelineFinished);
MantleTimeline->SetLooping(false);
MantleTimeline->SetTimelineLengthMode(TL_TimelineLength);
MantleTimeline->AddInterpFloat(MantleTimelineCurve, TimelineUpdated);
OwnerCharacter->JumpPressedDelegate.AddUniqueDynamic(this, &UALSMantleComponent::OnOwnerJumpInput);
OwnerCharacter->RagdollStateChangedDelegate.AddUniqueDynamic(
this, &UALSMantleComponent::OnOwnerRagdollStateChanged);
}
}
}
void UALSMantleComponent::TickComponent(float DeltaTime, ELevelTick TickType,
FActorComponentTickFunction* ThisTickFunction)
{
Super::TickComponent(DeltaTime, TickType, ThisTickFunction);
if (OwnerCharacter && OwnerCharacter->GetMovementState() == EALSMovementState::InAir)
{
// Perform a mantle check if falling while movement input is pressed.
if (OwnerCharacter->HasMovementInput())
{
MantleCheck(FallingTraceSettings, EDrawDebugTrace::Type::ForOneFrame);
}
}
}
void UALSMantleComponent::MantleStart(float MantleHeight, const FALSComponentAndTransform& MantleLedgeWS,
EALSMantleType MantleType)
{
if (OwnerCharacter == nullptr || !IsValid(MantleLedgeWS.Component) || !IsValid(MantleTimeline))
{
return;
}
if (MantleType != EALSMantleType::LowMantle && OwnerCharacter->IsA(AALSCharacter::StaticClass()))
{
Cast<AALSCharacter>(OwnerCharacter)->ClearHeldObject();
}
// Disable ticking during mantle
SetComponentTickEnabledAsync(false);
// Step 1: Get the Mantle Asset and use it to set the new Mantle Params.
const FALSMantleAsset MantleAsset = GetMantleAsset(MantleType, OwnerCharacter->GetOverlayState());
check(MantleAsset.PositionCorrectionCurve)
MantleParams.AnimMontage = MantleAsset.AnimMontage;
MantleParams.PositionCorrectionCurve = MantleAsset.PositionCorrectionCurve;
MantleParams.StartingOffset = MantleAsset.StartingOffset;
MantleParams.StartingPosition = FMath::GetMappedRangeValueClamped<float, float>({MantleAsset.LowHeight, MantleAsset.HighHeight},
{
MantleAsset.LowStartPosition,
MantleAsset.HighStartPosition
},
MantleHeight);
MantleParams.PlayRate = FMath::GetMappedRangeValueClamped<float, float>({MantleAsset.LowHeight, MantleAsset.HighHeight},
{MantleAsset.LowPlayRate, MantleAsset.HighPlayRate},
MantleHeight);
// Step 2: Convert the world space target to the mantle component's local space for use in moving objects.
MantleLedgeLS.Component = MantleLedgeWS.Component;
MantleLedgeLS.Transform = MantleLedgeWS.Transform * MantleLedgeWS.Component->GetComponentToWorld().Inverse();
// Step 3: Set the Mantle Target and calculate the Starting Offset
// (offset amount between the actor and target transform).
MantleTarget = MantleLedgeWS.Transform;
MantleActualStartOffset = UALSMathLibrary::TransformSub(OwnerCharacter->GetActorTransform(), MantleTarget);
// Step 4: Calculate the Animated Start Offset from the Target Location.
// This would be the location the actual animation starts at relative to the Target Transform.
FVector RotatedVector = MantleTarget.GetRotation().Vector() * MantleParams.StartingOffset.Y;
RotatedVector.Z = MantleParams.StartingOffset.Z;
const FTransform StartOffset(MantleTarget.Rotator(), MantleTarget.GetLocation() - RotatedVector,
FVector::OneVector);
MantleAnimatedStartOffset = UALSMathLibrary::TransformSub(StartOffset, MantleTarget);
// Step 5: Clear the Character Movement Mode and set the Movement State to Mantling
OwnerCharacter->GetCharacterMovement()->SetMovementMode(MOVE_None);
OwnerCharacter->SetMovementState(EALSMovementState::Mantling);
// Step 6: Configure the Mantle Timeline so that it is the same length as the
// Lerp/Correction curve minus the starting position, and plays at the same speed as the animation.
// Then start the timeline.
float MinTime = 0.0f;
float MaxTime = 0.0f;
MantleParams.PositionCorrectionCurve->GetTimeRange(MinTime, MaxTime);
MantleTimeline->SetTimelineLength(MaxTime - MantleParams.StartingPosition);
MantleTimeline->SetPlayRate(MantleParams.PlayRate);
MantleTimeline->PlayFromStart();
// Step 7: Play the Anim Montage if valid.
if (MantleParams.AnimMontage && OwnerCharacter->GetMesh()->GetAnimInstance())
{
OwnerCharacter->GetMesh()->GetAnimInstance()->Montage_Play(MantleParams.AnimMontage, MantleParams.PlayRate,
EMontagePlayReturnType::MontageLength,
MantleParams.StartingPosition, false);
}
}
bool UALSMantleComponent::MantleCheck(const FALSMantleTraceSettings& TraceSettings, EDrawDebugTrace::Type DebugType)
{
if (!OwnerCharacter)
{
return false;
}
// Step 1: Trace forward to find a wall / object the character cannot walk on.
const FVector& TraceDirection = OwnerCharacter->GetActorForwardVector();
const FVector& CapsuleBaseLocation = UALSMathLibrary::GetCapsuleBaseLocation(
2.0f, OwnerCharacter->GetCapsuleComponent());
FVector TraceStart = CapsuleBaseLocation + TraceDirection * -30.0f;
TraceStart.Z += (TraceSettings.MaxLedgeHeight + TraceSettings.MinLedgeHeight) / 2.0f;
const FVector TraceEnd = TraceStart + TraceDirection * TraceSettings.ReachDistance;
const float HalfHeight = 1.0f + (TraceSettings.MaxLedgeHeight - TraceSettings.MinLedgeHeight) / 2.0f;
UWorld* World = GetWorld();
check(World);
FCollisionQueryParams Params;
Params.AddIgnoredActor(OwnerCharacter);
FHitResult HitResult;
{
const FCollisionShape CapsuleCollisionShape = FCollisionShape::MakeCapsule(TraceSettings.ForwardTraceRadius, HalfHeight);
const bool bHit = World->SweepSingleByProfile(HitResult, TraceStart, TraceEnd, FQuat::Identity, MantleObjectDetectionProfile,
CapsuleCollisionShape, Params);
if (ALSDebugComponent && ALSDebugComponent->GetShowTraces())
{
UALSDebugComponent::DrawDebugCapsuleTraceSingle(World,
TraceStart,
TraceEnd,
CapsuleCollisionShape,
DebugType,
bHit,
HitResult,
FLinearColor::Black,
FLinearColor::Black,
1.0f);
}
}
if (!HitResult.IsValidBlockingHit() || OwnerCharacter->GetCharacterMovement()->IsWalkable(HitResult))
{
// Not a valid surface to mantle
return false;
}
if (HitResult.GetComponent() != nullptr)
{
UPrimitiveComponent* PrimitiveComponent = HitResult.GetComponent();
if (PrimitiveComponent && PrimitiveComponent->GetComponentVelocity().Size() > AcceptableVelocityWhileMantling)
{
// The surface to mantle moves too fast
return false;
}
}
const FVector InitialTraceImpactPoint = HitResult.ImpactPoint;
const FVector InitialTraceNormal = HitResult.ImpactNormal;
// Step 2: Trace downward from the first trace's Impact Point and determine if the hit location is walkable.
FVector DownwardTraceEnd = InitialTraceImpactPoint;
DownwardTraceEnd.Z = CapsuleBaseLocation.Z;
DownwardTraceEnd += InitialTraceNormal * -15.0f;
FVector DownwardTraceStart = DownwardTraceEnd;
DownwardTraceStart.Z += TraceSettings.MaxLedgeHeight + TraceSettings.DownwardTraceRadius + 1.0f;
{
const FCollisionShape SphereCollisionShape = FCollisionShape::MakeSphere(TraceSettings.DownwardTraceRadius);
const bool bHit = World->SweepSingleByChannel(HitResult, DownwardTraceStart, DownwardTraceEnd, FQuat::Identity,
WalkableSurfaceDetectionChannel, SphereCollisionShape,
Params);
if (ALSDebugComponent && ALSDebugComponent->GetShowTraces())
{
UALSDebugComponent::DrawDebugSphereTraceSingle(World,
TraceStart,
TraceEnd,
SphereCollisionShape,
DebugType,
bHit,
HitResult,
FLinearColor::Black,
FLinearColor::Black,
1.0f);
}
}
if (!OwnerCharacter->GetCharacterMovement()->IsWalkable(HitResult))
{
// Not a valid surface to mantle
return false;
}
const FVector DownTraceLocation(HitResult.Location.X, HitResult.Location.Y, HitResult.ImpactPoint.Z);
UPrimitiveComponent* HitComponent = HitResult.GetComponent();
// Step 3: Check if the capsule has room to stand at the downward trace's location.
// If so, set that location as the Target Transform and calculate the mantle height.
const FVector& CapsuleLocationFBase = UALSMathLibrary::GetCapsuleLocationFromBase(
DownTraceLocation, 2.0f, OwnerCharacter->GetCapsuleComponent());
const bool bCapsuleHasRoom = UALSMathLibrary::CapsuleHasRoomCheck(OwnerCharacter->GetCapsuleComponent(),
CapsuleLocationFBase, 0.0f,
0.0f, DebugType, ALSDebugComponent && ALSDebugComponent->GetShowTraces());
if (!bCapsuleHasRoom)
{
// Capsule doesn't have enough room to mantle
return false;
}
const FTransform TargetTransform(
(InitialTraceNormal * FVector(-1.0f, -1.0f, 0.0f)).ToOrientationRotator(),
CapsuleLocationFBase,
FVector::OneVector);
const float MantleHeight = (CapsuleLocationFBase - OwnerCharacter->GetActorLocation()).Z;
// Step 4: Determine the Mantle Type by checking the movement mode and Mantle Height.
EALSMantleType MantleType;
if (OwnerCharacter->GetMovementState() == EALSMovementState::InAir)
{
MantleType = EALSMantleType::FallingCatch;
}
else
{
MantleType = MantleHeight > 125.0f ? EALSMantleType::HighMantle : EALSMantleType::LowMantle;
}
// Step 5: If everything checks out, start the Mantle
FALSComponentAndTransform MantleWS;
MantleWS.Component = HitComponent;
MantleWS.Transform = TargetTransform;
MantleStart(MantleHeight, MantleWS, MantleType);
Server_MantleStart(MantleHeight, MantleWS, MantleType);
return true;
}
void UALSMantleComponent::Server_MantleStart_Implementation(float MantleHeight,
const FALSComponentAndTransform& MantleLedgeWS,
EALSMantleType MantleType)
{
Multicast_MantleStart(MantleHeight, MantleLedgeWS, MantleType);
}
void UALSMantleComponent::Multicast_MantleStart_Implementation(float MantleHeight,
const FALSComponentAndTransform& MantleLedgeWS,
EALSMantleType MantleType)
{
if (OwnerCharacter && !OwnerCharacter->IsLocallyControlled())
{
MantleStart(MantleHeight, MantleLedgeWS, MantleType);
}
}
// This function is called by "MantleTimeline" using BindUFunction in UALSMantleComponent::BeginPlay during the default settings initialization.
void UALSMantleComponent::MantleUpdate(float BlendIn)
{
if (!OwnerCharacter)
{
return;
}
// Step 1: Continually update the mantle target from the stored local transform to follow along with moving objects
MantleTarget = UALSMathLibrary::MantleComponentLocalToWorld(MantleLedgeLS);
// Step 2: Update the Position and Correction Alphas using the Position/Correction curve set for each Mantle.
const FVector CurveVec = MantleParams.PositionCorrectionCurve
->GetVectorValue(
MantleParams.StartingPosition + MantleTimeline->GetPlaybackPosition());
const float PositionAlpha = CurveVec.X;
const float XYCorrectionAlpha = CurveVec.Y;
const float ZCorrectionAlpha = CurveVec.Z;
// Step 3: Lerp multiple transforms together for independent control over the horizontal
// and vertical blend to the animated start position, as well as the target position.
// Blend into the animated horizontal and rotation offset using the Y value of the Position/Correction Curve.
const FTransform TargetHzTransform(MantleAnimatedStartOffset.GetRotation(),
{
MantleAnimatedStartOffset.GetLocation().X,
MantleAnimatedStartOffset.GetLocation().Y,
MantleActualStartOffset.GetLocation().Z
},
FVector::OneVector);
const FTransform& HzLerpResult =
UKismetMathLibrary::TLerp(MantleActualStartOffset, TargetHzTransform, XYCorrectionAlpha);
// Blend into the animated vertical offset using the Z value of the Position/Correction Curve.
const FTransform TargetVtTransform(MantleActualStartOffset.GetRotation(),
{
MantleActualStartOffset.GetLocation().X,
MantleActualStartOffset.GetLocation().Y,
MantleAnimatedStartOffset.GetLocation().Z
},
FVector::OneVector);
const FTransform& VtLerpResult =
UKismetMathLibrary::TLerp(MantleActualStartOffset, TargetVtTransform, ZCorrectionAlpha);
const FTransform ResultTransform(HzLerpResult.GetRotation(),
{
HzLerpResult.GetLocation().X, HzLerpResult.GetLocation().Y,
VtLerpResult.GetLocation().Z
},
FVector::OneVector);
// Blend from the currently blending transforms into the final mantle target using the X
// value of the Position/Correction Curve.
const FTransform& ResultLerp = UKismetMathLibrary::TLerp(
UALSMathLibrary::TransformAdd(MantleTarget, ResultTransform), MantleTarget,
PositionAlpha);
// Initial Blend In (controlled in the timeline curve) to allow the actor to blend into the Position/Correction
// curve at the midpoint. This prevents pops when mantling an object lower than the animated mantle.
const FTransform& LerpedTarget =
UKismetMathLibrary::TLerp(UALSMathLibrary::TransformAdd(MantleTarget, MantleActualStartOffset), ResultLerp,
BlendIn);
// Step 4: Set the actors location and rotation to the Lerped Target.
OwnerCharacter->SetActorLocationAndTargetRotation(LerpedTarget.GetLocation(), LerpedTarget.GetRotation().Rotator());
}
void UALSMantleComponent::MantleEnd()
{
// Set the Character Movement Mode to Walking
if (OwnerCharacter)
{
OwnerCharacter->GetCharacterMovement()->SetMovementMode(MOVE_Walking);
if (OwnerCharacter->IsA(AALSCharacter::StaticClass()))
{
Cast<AALSCharacter>(OwnerCharacter)->UpdateHeldObject();
}
}
// Enable ticking back after mantle ends
SetComponentTickEnabledAsync(true);
}
void UALSMantleComponent::OnOwnerJumpInput()
{
// Check if character is able to do one of the special mantling
if (OwnerCharacter && OwnerCharacter->GetMovementAction() == EALSMovementAction::None)
{
if (OwnerCharacter->GetMovementState() == EALSMovementState::Grounded)
{
if (OwnerCharacter->HasMovementInput())
{
MantleCheck(GroundedTraceSettings, EDrawDebugTrace::Type::ForDuration);
}
}
else if (OwnerCharacter->GetMovementState() == EALSMovementState::InAir)
{
MantleCheck(FallingTraceSettings, EDrawDebugTrace::Type::ForDuration);
}
}
}
void UALSMantleComponent::OnOwnerRagdollStateChanged(bool bRagdollState)
{
// If owner is going into ragdoll state, stop mantling immediately
if (bRagdollState)
{
MantleTimeline->Stop();
}
}
| 42.936019 | 144 | 0.672443 | [
"object",
"vector",
"transform"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.