text
stringlengths 5
1.04M
|
|---|
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you 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 "arrow/type.h"
#include <algorithm>
#include <climits>
#include <cstddef>
#include <limits>
#include <mutex>
#include <ostream>
#include <sstream> // IWYU pragma: keep
#include <string>
#include <unordered_map>
#include <unordered_set>
#include <utility>
#include <vector>
#include "arrow/array.h"
#include "arrow/compare.h"
#include "arrow/record_batch.h"
#include "arrow/result.h"
#include "arrow/status.h"
#include "arrow/util/checked_cast.h"
#include "arrow/util/hash_util.h"
#include "arrow/util/hashing.h"
#include "arrow/util/key_value_metadata.h"
#include "arrow/util/logging.h"
#include "arrow/util/make_unique.h"
#include "arrow/util/range.h"
#include "arrow/util/vector.h"
#include "arrow/visitor_inline.h"
namespace arrow {
constexpr Type::type NullType::type_id;
constexpr Type::type ListType::type_id;
constexpr Type::type LargeListType::type_id;
constexpr Type::type MapType::type_id;
constexpr Type::type FixedSizeListType::type_id;
constexpr Type::type BinaryType::type_id;
constexpr Type::type LargeBinaryType::type_id;
constexpr Type::type StringType::type_id;
constexpr Type::type LargeStringType::type_id;
constexpr Type::type FixedSizeBinaryType::type_id;
constexpr Type::type StructType::type_id;
constexpr Type::type Decimal128Type::type_id;
constexpr Type::type Decimal256Type::type_id;
constexpr Type::type SparseUnionType::type_id;
constexpr Type::type DenseUnionType::type_id;
constexpr Type::type Date32Type::type_id;
constexpr Type::type Date64Type::type_id;
constexpr Type::type Time32Type::type_id;
constexpr Type::type Time64Type::type_id;
constexpr Type::type TimestampType::type_id;
constexpr Type::type MonthIntervalType::type_id;
constexpr Type::type DayTimeIntervalType::type_id;
constexpr Type::type MonthDayNanoIntervalType::type_id;
constexpr Type::type DurationType::type_id;
constexpr Type::type DictionaryType::type_id;
namespace internal {
struct TypeIdToTypeNameVisitor {
std::string out;
template <typename ArrowType>
Status Visit(const ArrowType*) {
out = ArrowType::type_name();
return Status::OK();
}
};
std::string ToTypeName(Type::type id) {
TypeIdToTypeNameVisitor visitor;
ARROW_CHECK_OK(VisitTypeIdInline(id, &visitor));
return std::move(visitor.out);
}
std::string ToString(Type::type id) {
switch (id) {
#define TO_STRING_CASE(_id) \
case Type::_id: \
return ARROW_STRINGIFY(_id);
TO_STRING_CASE(NA)
TO_STRING_CASE(BOOL)
TO_STRING_CASE(INT8)
TO_STRING_CASE(INT16)
TO_STRING_CASE(INT32)
TO_STRING_CASE(INT64)
TO_STRING_CASE(UINT8)
TO_STRING_CASE(UINT16)
TO_STRING_CASE(UINT32)
TO_STRING_CASE(UINT64)
TO_STRING_CASE(HALF_FLOAT)
TO_STRING_CASE(FLOAT)
TO_STRING_CASE(DOUBLE)
TO_STRING_CASE(DECIMAL128)
TO_STRING_CASE(DECIMAL256)
TO_STRING_CASE(DATE32)
TO_STRING_CASE(DATE64)
TO_STRING_CASE(TIME32)
TO_STRING_CASE(TIME64)
TO_STRING_CASE(TIMESTAMP)
TO_STRING_CASE(INTERVAL_DAY_TIME)
TO_STRING_CASE(INTERVAL_MONTH_DAY_NANO)
TO_STRING_CASE(INTERVAL_MONTHS)
TO_STRING_CASE(DURATION)
TO_STRING_CASE(STRING)
TO_STRING_CASE(BINARY)
TO_STRING_CASE(LARGE_STRING)
TO_STRING_CASE(LARGE_BINARY)
TO_STRING_CASE(FIXED_SIZE_BINARY)
TO_STRING_CASE(STRUCT)
TO_STRING_CASE(LIST)
TO_STRING_CASE(LARGE_LIST)
TO_STRING_CASE(FIXED_SIZE_LIST)
TO_STRING_CASE(MAP)
TO_STRING_CASE(DENSE_UNION)
TO_STRING_CASE(SPARSE_UNION)
TO_STRING_CASE(DICTIONARY)
TO_STRING_CASE(EXTENSION)
#undef TO_STRING_CASE
default:
ARROW_LOG(FATAL) << "Unhandled type id: " << id;
return "";
}
}
std::string ToString(TimeUnit::type unit) {
switch (unit) {
case TimeUnit::SECOND:
return "s";
case TimeUnit::MILLI:
return "ms";
case TimeUnit::MICRO:
return "us";
case TimeUnit::NANO:
return "ns";
default:
DCHECK(false);
return "";
}
}
int GetByteWidth(const DataType& type) {
const auto& fw_type = checked_cast<const FixedWidthType&>(type);
return fw_type.bit_width() / CHAR_BIT;
}
} // namespace internal
namespace {
struct PhysicalTypeVisitor {
const std::shared_ptr<DataType>& real_type;
std::shared_ptr<DataType> result;
Status Visit(const DataType&) {
result = real_type;
return Status::OK();
}
template <typename Type, typename PhysicalType = typename Type::PhysicalType>
Status Visit(const Type&) {
result = TypeTraits<PhysicalType>::type_singleton();
return Status::OK();
}
};
} // namespace
std::shared_ptr<DataType> GetPhysicalType(const std::shared_ptr<DataType>& real_type) {
PhysicalTypeVisitor visitor{real_type, {}};
ARROW_CHECK_OK(VisitTypeInline(*real_type, &visitor));
return std::move(visitor.result);
}
namespace {
using internal::checked_cast;
// Merges `existing` and `other` if one of them is of NullType, otherwise
// returns nullptr.
// - if `other` if of NullType or is nullable, the unified field will be nullable.
// - if `existing` is of NullType but other is not, the unified field will
// have `other`'s type and will be nullable
std::shared_ptr<Field> MaybePromoteNullTypes(const Field& existing, const Field& other) {
if (existing.type()->id() != Type::NA && other.type()->id() != Type::NA) {
return nullptr;
}
if (existing.type()->id() == Type::NA) {
return other.WithNullable(true)->WithMetadata(existing.metadata());
}
// `other` must be null.
return existing.WithNullable(true);
}
} // namespace
Field::~Field() {}
bool Field::HasMetadata() const {
return (metadata_ != nullptr) && (metadata_->size() > 0);
}
std::shared_ptr<Field> Field::WithMetadata(
const std::shared_ptr<const KeyValueMetadata>& metadata) const {
return std::make_shared<Field>(name_, type_, nullable_, metadata);
}
std::shared_ptr<Field> Field::WithMergedMetadata(
const std::shared_ptr<const KeyValueMetadata>& metadata) const {
std::shared_ptr<const KeyValueMetadata> merged_metadata;
if (metadata_) {
merged_metadata = metadata_->Merge(*metadata);
} else {
merged_metadata = metadata;
}
return std::make_shared<Field>(name_, type_, nullable_, merged_metadata);
}
std::shared_ptr<Field> Field::RemoveMetadata() const {
return std::make_shared<Field>(name_, type_, nullable_);
}
std::shared_ptr<Field> Field::WithType(const std::shared_ptr<DataType>& type) const {
return std::make_shared<Field>(name_, type, nullable_, metadata_);
}
std::shared_ptr<Field> Field::WithName(const std::string& name) const {
return std::make_shared<Field>(name, type_, nullable_, metadata_);
}
std::shared_ptr<Field> Field::WithNullable(const bool nullable) const {
return std::make_shared<Field>(name_, type_, nullable, metadata_);
}
Result<std::shared_ptr<Field>> Field::MergeWith(const Field& other,
MergeOptions options) const {
if (name() != other.name()) {
return Status::Invalid("Field ", name(), " doesn't have the same name as ",
other.name());
}
if (Equals(other, /*check_metadata=*/false)) {
return Copy();
}
if (options.promote_nullability) {
if (type()->Equals(other.type())) {
return Copy()->WithNullable(nullable() || other.nullable());
}
std::shared_ptr<Field> promoted = MaybePromoteNullTypes(*this, other);
if (promoted) return promoted;
}
return Status::Invalid("Unable to merge: Field ", name(),
" has incompatible types: ", type()->ToString(), " vs ",
other.type()->ToString());
}
Result<std::shared_ptr<Field>> Field::MergeWith(const std::shared_ptr<Field>& other,
MergeOptions options) const {
DCHECK_NE(other, nullptr);
return MergeWith(*other, options);
}
std::vector<std::shared_ptr<Field>> Field::Flatten() const {
std::vector<std::shared_ptr<Field>> flattened;
if (type_->id() == Type::STRUCT) {
for (const auto& child : type_->fields()) {
auto flattened_child = child->Copy();
flattened.push_back(flattened_child);
flattened_child->name_.insert(0, name() + ".");
flattened_child->nullable_ |= nullable_;
}
} else {
flattened.push_back(this->Copy());
}
return flattened;
}
std::shared_ptr<Field> Field::Copy() const {
return ::arrow::field(name_, type_, nullable_, metadata_);
}
bool Field::Equals(const Field& other, bool check_metadata) const {
if (this == &other) {
return true;
}
if (this->name_ == other.name_ && this->nullable_ == other.nullable_ &&
this->type_->Equals(*other.type_.get(), check_metadata)) {
if (!check_metadata) {
return true;
} else if (this->HasMetadata() && other.HasMetadata()) {
return metadata_->Equals(*other.metadata_);
} else if (!this->HasMetadata() && !other.HasMetadata()) {
return true;
} else {
return false;
}
}
return false;
}
bool Field::Equals(const std::shared_ptr<Field>& other, bool check_metadata) const {
return Equals(*other.get(), check_metadata);
}
bool Field::IsCompatibleWith(const Field& other) const { return MergeWith(other).ok(); }
bool Field::IsCompatibleWith(const std::shared_ptr<Field>& other) const {
DCHECK_NE(other, nullptr);
return IsCompatibleWith(*other);
}
std::string Field::ToString(bool show_metadata) const {
std::stringstream ss;
ss << name_ << ": " << type_->ToString();
if (!nullable_) {
ss << " not null";
}
if (show_metadata && metadata_) {
ss << metadata_->ToString();
}
return ss.str();
}
DataType::~DataType() {}
bool DataType::Equals(const DataType& other, bool check_metadata) const {
return TypeEquals(*this, other, check_metadata);
}
bool DataType::Equals(const std::shared_ptr<DataType>& other) const {
if (!other) {
return false;
}
return Equals(*other.get());
}
size_t DataType::Hash() const {
static constexpr size_t kHashSeed = 0;
size_t result = kHashSeed;
internal::hash_combine(result, this->fingerprint());
return result;
}
std::ostream& operator<<(std::ostream& os, const DataType& type) {
os << type.ToString();
return os;
}
FloatingPointType::Precision HalfFloatType::precision() const {
return FloatingPointType::HALF;
}
FloatingPointType::Precision FloatType::precision() const {
return FloatingPointType::SINGLE;
}
FloatingPointType::Precision DoubleType::precision() const {
return FloatingPointType::DOUBLE;
}
std::string ListType::ToString() const {
std::stringstream s;
s << "list<" << value_field()->ToString() << ">";
return s.str();
}
std::string LargeListType::ToString() const {
std::stringstream s;
s << "large_list<" << value_field()->ToString() << ">";
return s.str();
}
MapType::MapType(std::shared_ptr<DataType> key_type, std::shared_ptr<DataType> item_type,
bool keys_sorted)
: MapType(::arrow::field("key", std::move(key_type), false),
::arrow::field("value", std::move(item_type)), keys_sorted) {}
MapType::MapType(std::shared_ptr<DataType> key_type, std::shared_ptr<Field> item_field,
bool keys_sorted)
: MapType(::arrow::field("key", std::move(key_type), false), std::move(item_field),
keys_sorted) {}
MapType::MapType(std::shared_ptr<Field> key_field, std::shared_ptr<Field> item_field,
bool keys_sorted)
: MapType(
::arrow::field("entries",
struct_({std::move(key_field), std::move(item_field)}), false),
keys_sorted) {}
MapType::MapType(std::shared_ptr<Field> value_field, bool keys_sorted)
: ListType(std::move(value_field)), keys_sorted_(keys_sorted) {
id_ = type_id;
}
Result<std::shared_ptr<DataType>> MapType::Make(std::shared_ptr<Field> value_field,
bool keys_sorted) {
const auto& value_type = *value_field->type();
if (value_field->nullable() || value_type.id() != Type::STRUCT) {
return Status::TypeError("Map entry field should be non-nullable struct");
}
const auto& struct_type = checked_cast<const StructType&>(value_type);
if (struct_type.num_fields() != 2) {
return Status::TypeError("Map entry field should have two children (got ",
struct_type.num_fields(), ")");
}
if (struct_type.field(0)->nullable()) {
return Status::TypeError("Map key field should be non-nullable");
}
return std::make_shared<MapType>(std::move(value_field), keys_sorted);
}
std::string MapType::ToString() const {
std::stringstream s;
const auto print_field_name = [](std::ostream& os, const Field& field,
const char* std_name) {
if (field.name() != std_name) {
os << " ('" << field.name() << "')";
}
};
const auto print_field = [&](std::ostream& os, const Field& field,
const char* std_name) {
os << field.type()->ToString();
print_field_name(os, field, std_name);
};
s << "map<";
print_field(s, *key_field(), "key");
s << ", ";
print_field(s, *item_field(), "value");
if (keys_sorted_) {
s << ", keys_sorted";
}
print_field_name(s, *value_field(), "entries");
s << ">";
return s.str();
}
std::string FixedSizeListType::ToString() const {
std::stringstream s;
s << "fixed_size_list<" << value_field()->ToString() << ">[" << list_size_ << "]";
return s.str();
}
std::string BinaryType::ToString() const { return "binary"; }
std::string LargeBinaryType::ToString() const { return "large_binary"; }
std::string StringType::ToString() const { return "string"; }
std::string LargeStringType::ToString() const { return "large_string"; }
int FixedSizeBinaryType::bit_width() const { return CHAR_BIT * byte_width(); }
Result<std::shared_ptr<DataType>> FixedSizeBinaryType::Make(int32_t byte_width) {
if (byte_width < 0) {
return Status::Invalid("Negative FixedSizeBinaryType byte width");
}
if (byte_width > std::numeric_limits<int>::max() / CHAR_BIT) {
// bit_width() would overflow
return Status::Invalid("byte width of FixedSizeBinaryType too large");
}
return std::make_shared<FixedSizeBinaryType>(byte_width);
}
std::string FixedSizeBinaryType::ToString() const {
std::stringstream ss;
ss << "fixed_size_binary[" << byte_width_ << "]";
return ss.str();
}
// ----------------------------------------------------------------------
// Date types
DateType::DateType(Type::type type_id) : TemporalType(type_id) {}
Date32Type::Date32Type() : DateType(Type::DATE32) {}
Date64Type::Date64Type() : DateType(Type::DATE64) {}
std::string Date64Type::ToString() const { return std::string("date64[ms]"); }
std::string Date32Type::ToString() const { return std::string("date32[day]"); }
// ----------------------------------------------------------------------
// Time types
TimeType::TimeType(Type::type type_id, TimeUnit::type unit)
: TemporalType(type_id), unit_(unit) {}
Time32Type::Time32Type(TimeUnit::type unit) : TimeType(Type::TIME32, unit) {
ARROW_CHECK(unit == TimeUnit::SECOND || unit == TimeUnit::MILLI)
<< "Must be seconds or milliseconds";
}
std::string Time32Type::ToString() const {
std::stringstream ss;
ss << "time32[" << this->unit_ << "]";
return ss.str();
}
Time64Type::Time64Type(TimeUnit::type unit) : TimeType(Type::TIME64, unit) {
ARROW_CHECK(unit == TimeUnit::MICRO || unit == TimeUnit::NANO)
<< "Must be microseconds or nanoseconds";
}
std::string Time64Type::ToString() const {
std::stringstream ss;
ss << "time64[" << this->unit_ << "]";
return ss.str();
}
std::ostream& operator<<(std::ostream& os, TimeUnit::type unit) {
switch (unit) {
case TimeUnit::SECOND:
os << "s";
break;
case TimeUnit::MILLI:
os << "ms";
break;
case TimeUnit::MICRO:
os << "us";
break;
case TimeUnit::NANO:
os << "ns";
break;
}
return os;
}
// ----------------------------------------------------------------------
// Timestamp types
std::string TimestampType::ToString() const {
std::stringstream ss;
ss << "timestamp[" << this->unit_;
if (this->timezone_.size() > 0) {
ss << ", tz=" << this->timezone_;
}
ss << "]";
return ss.str();
}
// Duration types
std::string DurationType::ToString() const {
std::stringstream ss;
ss << "duration[" << this->unit_ << "]";
return ss.str();
}
// ----------------------------------------------------------------------
// Union type
constexpr int8_t UnionType::kMaxTypeCode;
constexpr int UnionType::kInvalidChildId;
UnionMode::type UnionType::mode() const {
return id_ == Type::SPARSE_UNION ? UnionMode::SPARSE : UnionMode::DENSE;
}
UnionType::UnionType(std::vector<std::shared_ptr<Field>> fields,
std::vector<int8_t> type_codes, Type::type id)
: NestedType(id),
type_codes_(std::move(type_codes)),
child_ids_(kMaxTypeCode + 1, kInvalidChildId) {
children_ = std::move(fields);
DCHECK_OK(ValidateParameters(children_, type_codes_, mode()));
for (int child_id = 0; child_id < static_cast<int>(type_codes_.size()); ++child_id) {
const auto type_code = type_codes_[child_id];
child_ids_[type_code] = child_id;
}
}
Status UnionType::ValidateParameters(const std::vector<std::shared_ptr<Field>>& fields,
const std::vector<int8_t>& type_codes,
UnionMode::type mode) {
if (fields.size() != type_codes.size()) {
return Status::Invalid("Union should get the same number of fields as type codes");
}
for (const auto type_code : type_codes) {
if (type_code < 0 || type_code > kMaxTypeCode) {
return Status::Invalid("Union type code out of bounds");
}
}
return Status::OK();
}
DataTypeLayout UnionType::layout() const {
if (mode() == UnionMode::SPARSE) {
return DataTypeLayout(
{DataTypeLayout::AlwaysNull(), DataTypeLayout::FixedWidth(sizeof(uint8_t))});
} else {
return DataTypeLayout({DataTypeLayout::AlwaysNull(),
DataTypeLayout::FixedWidth(sizeof(uint8_t)),
DataTypeLayout::FixedWidth(sizeof(int32_t))});
}
}
uint8_t UnionType::max_type_code() const {
return type_codes_.size() == 0
? 0
: *std::max_element(type_codes_.begin(), type_codes_.end());
}
std::string UnionType::ToString() const {
std::stringstream s;
s << name() << "<";
for (size_t i = 0; i < children_.size(); ++i) {
if (i) {
s << ", ";
}
s << children_[i]->ToString() << "=" << static_cast<int>(type_codes_[i]);
}
s << ">";
return s.str();
}
SparseUnionType::SparseUnionType(std::vector<std::shared_ptr<Field>> fields,
std::vector<int8_t> type_codes)
: UnionType(fields, type_codes, Type::SPARSE_UNION) {}
Result<std::shared_ptr<DataType>> SparseUnionType::Make(
std::vector<std::shared_ptr<Field>> fields, std::vector<int8_t> type_codes) {
RETURN_NOT_OK(ValidateParameters(fields, type_codes, UnionMode::SPARSE));
return std::make_shared<SparseUnionType>(fields, type_codes);
}
DenseUnionType::DenseUnionType(std::vector<std::shared_ptr<Field>> fields,
std::vector<int8_t> type_codes)
: UnionType(fields, type_codes, Type::DENSE_UNION) {}
Result<std::shared_ptr<DataType>> DenseUnionType::Make(
std::vector<std::shared_ptr<Field>> fields, std::vector<int8_t> type_codes) {
RETURN_NOT_OK(ValidateParameters(fields, type_codes, UnionMode::DENSE));
return std::make_shared<DenseUnionType>(fields, type_codes);
}
// ----------------------------------------------------------------------
// Struct type
namespace {
std::unordered_multimap<std::string, int> CreateNameToIndexMap(
const std::vector<std::shared_ptr<Field>>& fields) {
std::unordered_multimap<std::string, int> name_to_index;
for (size_t i = 0; i < fields.size(); ++i) {
name_to_index.emplace(fields[i]->name(), static_cast<int>(i));
}
return name_to_index;
}
template <int NotFoundValue = -1, int DuplicateFoundValue = -1>
int LookupNameIndex(const std::unordered_multimap<std::string, int>& name_to_index,
const std::string& name) {
auto p = name_to_index.equal_range(name);
auto it = p.first;
if (it == p.second) {
// Not found
return NotFoundValue;
}
auto index = it->second;
if (++it != p.second) {
// Duplicate field name
return DuplicateFoundValue;
}
return index;
}
} // namespace
class StructType::Impl {
public:
explicit Impl(const std::vector<std::shared_ptr<Field>>& fields)
: name_to_index_(CreateNameToIndexMap(fields)) {}
const std::unordered_multimap<std::string, int> name_to_index_;
};
StructType::StructType(const std::vector<std::shared_ptr<Field>>& fields)
: NestedType(Type::STRUCT), impl_(new Impl(fields)) {
children_ = fields;
}
StructType::~StructType() {}
std::string StructType::ToString() const {
std::stringstream s;
s << "struct<";
for (int i = 0; i < this->num_fields(); ++i) {
if (i > 0) {
s << ", ";
}
std::shared_ptr<Field> field = this->field(i);
s << field->ToString();
}
s << ">";
return s.str();
}
std::shared_ptr<Field> StructType::GetFieldByName(const std::string& name) const {
int i = GetFieldIndex(name);
return i == -1 ? nullptr : children_[i];
}
int StructType::GetFieldIndex(const std::string& name) const {
return LookupNameIndex(impl_->name_to_index_, name);
}
std::vector<int> StructType::GetAllFieldIndices(const std::string& name) const {
std::vector<int> result;
auto p = impl_->name_to_index_.equal_range(name);
for (auto it = p.first; it != p.second; ++it) {
result.push_back(it->second);
}
if (result.size() > 1) {
std::sort(result.begin(), result.end());
}
return result;
}
std::vector<std::shared_ptr<Field>> StructType::GetAllFieldsByName(
const std::string& name) const {
std::vector<std::shared_ptr<Field>> result;
auto p = impl_->name_to_index_.equal_range(name);
for (auto it = p.first; it != p.second; ++it) {
result.push_back(children_[it->second]);
}
return result;
}
Result<std::shared_ptr<DataType>> DecimalType::Make(Type::type type_id, int32_t precision,
int32_t scale) {
if (type_id == Type::DECIMAL128) {
return Decimal128Type::Make(precision, scale);
} else if (type_id == Type::DECIMAL256) {
return Decimal256Type::Make(precision, scale);
} else {
return Status::Invalid("Not a decimal type_id: ", type_id);
}
}
// Taken from the Apache Impala codebase. The comments next
// to the return values are the maximum value that can be represented in 2's
// complement with the returned number of bytes.
int32_t DecimalType::DecimalSize(int32_t precision) {
DCHECK_GE(precision, 1) << "decimal precision must be greater than or equal to 1, got "
<< precision;
// Generated in python with:
// >>> decimal_size = lambda prec: int(math.ceil((prec * math.log2(10) + 1) / 8))
// >>> [-1] + [decimal_size(i) for i in range(1, 77)]
constexpr int32_t kBytes[] = {
-1, 1, 1, 2, 2, 3, 3, 4, 4, 4, 5, 5, 6, 6, 6, 7, 7, 8, 8, 9,
9, 9, 10, 10, 11, 11, 11, 12, 12, 13, 13, 13, 14, 14, 15, 15, 16, 16, 16, 17,
17, 18, 18, 18, 19, 19, 20, 20, 21, 21, 21, 22, 22, 23, 23, 23, 24, 24, 25, 25,
26, 26, 26, 27, 27, 28, 28, 28, 29, 29, 30, 30, 31, 31, 31, 32, 32};
if (precision <= 76) {
return kBytes[precision];
}
return static_cast<int32_t>(std::ceil((precision / 8.0) * std::log2(10) + 1));
}
// ----------------------------------------------------------------------
// Decimal128 type
Decimal128Type::Decimal128Type(int32_t precision, int32_t scale)
: DecimalType(type_id, 16, precision, scale) {
ARROW_CHECK_GE(precision, kMinPrecision);
ARROW_CHECK_LE(precision, kMaxPrecision);
}
Result<std::shared_ptr<DataType>> Decimal128Type::Make(int32_t precision, int32_t scale) {
if (precision < kMinPrecision || precision > kMaxPrecision) {
return Status::Invalid("Decimal precision out of range: ", precision);
}
return std::make_shared<Decimal128Type>(precision, scale);
}
// ----------------------------------------------------------------------
// Decimal256 type
Decimal256Type::Decimal256Type(int32_t precision, int32_t scale)
: DecimalType(type_id, 32, precision, scale) {
ARROW_CHECK_GE(precision, kMinPrecision);
ARROW_CHECK_LE(precision, kMaxPrecision);
}
Result<std::shared_ptr<DataType>> Decimal256Type::Make(int32_t precision, int32_t scale) {
if (precision < kMinPrecision || precision > kMaxPrecision) {
return Status::Invalid("Decimal precision out of range: ", precision);
}
return std::make_shared<Decimal256Type>(precision, scale);
}
// ----------------------------------------------------------------------
// Dictionary-encoded type
Status DictionaryType::ValidateParameters(const DataType& index_type,
const DataType& value_type) {
if (!is_integer(index_type.id())) {
return Status::TypeError("Dictionary index type should be integer, got ",
index_type.ToString());
}
return Status::OK();
}
int DictionaryType::bit_width() const {
return checked_cast<const FixedWidthType&>(*index_type_).bit_width();
}
Result<std::shared_ptr<DataType>> DictionaryType::Make(
const std::shared_ptr<DataType>& index_type,
const std::shared_ptr<DataType>& value_type, bool ordered) {
RETURN_NOT_OK(ValidateParameters(*index_type, *value_type));
return std::make_shared<DictionaryType>(index_type, value_type, ordered);
}
DictionaryType::DictionaryType(const std::shared_ptr<DataType>& index_type,
const std::shared_ptr<DataType>& value_type, bool ordered)
: FixedWidthType(Type::DICTIONARY),
index_type_(index_type),
value_type_(value_type),
ordered_(ordered) {
ARROW_CHECK_OK(ValidateParameters(*index_type_, *value_type_));
}
DataTypeLayout DictionaryType::layout() const {
auto layout = index_type_->layout();
layout.has_dictionary = true;
return layout;
}
std::string DictionaryType::ToString() const {
std::stringstream ss;
ss << this->name() << "<values=" << value_type_->ToString()
<< ", indices=" << index_type_->ToString() << ", ordered=" << ordered_ << ">";
return ss.str();
}
// ----------------------------------------------------------------------
// Null type
std::string NullType::ToString() const { return name(); }
// ----------------------------------------------------------------------
// FieldRef
size_t FieldPath::hash() const {
return internal::ComputeStringHash<0>(indices().data(), indices().size() * sizeof(int));
}
std::string FieldPath::ToString() const {
if (this->indices().empty()) {
return "FieldPath(empty)";
}
std::string repr = "FieldPath(";
for (auto index : this->indices()) {
repr += std::to_string(index) + " ";
}
repr.back() = ')';
return repr;
}
struct FieldPathGetImpl {
static const DataType& GetType(const ArrayData& data) { return *data.type; }
static void Summarize(const FieldVector& fields, std::stringstream* ss) {
*ss << "{ ";
for (const auto& field : fields) {
*ss << field->ToString() << ", ";
}
*ss << "}";
}
template <typename T>
static void Summarize(const std::vector<T>& columns, std::stringstream* ss) {
*ss << "{ ";
for (const auto& column : columns) {
*ss << GetType(*column) << ", ";
}
*ss << "}";
}
template <typename T>
static Status IndexError(const FieldPath* path, int out_of_range_depth,
const std::vector<T>& children) {
std::stringstream ss;
ss << "index out of range. ";
ss << "indices=[ ";
int depth = 0;
for (int i : path->indices()) {
if (depth != out_of_range_depth) {
ss << i << " ";
continue;
}
ss << ">" << i << "< ";
++depth;
}
ss << "] ";
if (std::is_same<T, std::shared_ptr<Field>>::value) {
ss << "fields were: ";
} else {
ss << "columns had types: ";
}
Summarize(children, &ss);
return Status::IndexError(ss.str());
}
template <typename T, typename GetChildren>
static Result<T> Get(const FieldPath* path, const std::vector<T>* children,
GetChildren&& get_children, int* out_of_range_depth) {
if (path->indices().empty()) {
return Status::Invalid("empty indices cannot be traversed");
}
int depth = 0;
const T* out;
for (int index : path->indices()) {
if (children == nullptr) {
return Status::NotImplemented("Get child data of non-struct array");
}
if (index < 0 || static_cast<size_t>(index) >= children->size()) {
*out_of_range_depth = depth;
return nullptr;
}
out = &children->at(index);
children = get_children(*out);
++depth;
}
return *out;
}
template <typename T, typename GetChildren>
static Result<T> Get(const FieldPath* path, const std::vector<T>* children,
GetChildren&& get_children) {
int out_of_range_depth = -1;
ARROW_ASSIGN_OR_RAISE(auto child,
Get(path, children, std::forward<GetChildren>(get_children),
&out_of_range_depth));
if (child != nullptr) {
return std::move(child);
}
return IndexError(path, out_of_range_depth, *children);
}
static Result<std::shared_ptr<Field>> Get(const FieldPath* path,
const FieldVector& fields) {
return FieldPathGetImpl::Get(path, &fields, [](const std::shared_ptr<Field>& field) {
return &field->type()->fields();
});
}
static Result<std::shared_ptr<ArrayData>> Get(const FieldPath* path,
const ArrayDataVector& child_data) {
return FieldPathGetImpl::Get(
path, &child_data,
[](const std::shared_ptr<ArrayData>& data) -> const ArrayDataVector* {
if (data->type->id() != Type::STRUCT) {
return nullptr;
}
return &data->child_data;
});
}
};
Result<std::shared_ptr<Field>> FieldPath::Get(const Schema& schema) const {
return FieldPathGetImpl::Get(this, schema.fields());
}
Result<std::shared_ptr<Field>> FieldPath::Get(const Field& field) const {
return FieldPathGetImpl::Get(this, field.type()->fields());
}
Result<std::shared_ptr<Field>> FieldPath::Get(const DataType& type) const {
return FieldPathGetImpl::Get(this, type.fields());
}
Result<std::shared_ptr<Field>> FieldPath::Get(const FieldVector& fields) const {
return FieldPathGetImpl::Get(this, fields);
}
Result<std::shared_ptr<Array>> FieldPath::Get(const RecordBatch& batch) const {
ARROW_ASSIGN_OR_RAISE(auto data, FieldPathGetImpl::Get(this, batch.column_data()));
return MakeArray(std::move(data));
}
Result<std::shared_ptr<Array>> FieldPath::Get(const Array& array) const {
ARROW_ASSIGN_OR_RAISE(auto data, Get(*array.data()));
return MakeArray(std::move(data));
}
Result<std::shared_ptr<ArrayData>> FieldPath::Get(const ArrayData& data) const {
if (data.type->id() != Type::STRUCT) {
return Status::NotImplemented("Get child data of non-struct array");
}
return FieldPathGetImpl::Get(this, data.child_data);
}
FieldRef::FieldRef(FieldPath indices) : impl_(std::move(indices)) {
DCHECK_GT(util::get<FieldPath>(impl_).indices().size(), 0);
}
void FieldRef::Flatten(std::vector<FieldRef> children) {
// flatten children
struct Visitor {
void operator()(std::string* name) { *out++ = FieldRef(std::move(*name)); }
void operator()(FieldPath* indices) { *out++ = FieldRef(std::move(*indices)); }
void operator()(std::vector<FieldRef>* children) {
for (auto& child : *children) {
util::visit(*this, &child.impl_);
}
}
std::back_insert_iterator<std::vector<FieldRef>> out;
};
std::vector<FieldRef> out;
Visitor visitor{std::back_inserter(out)};
visitor(&children);
DCHECK(!out.empty());
DCHECK(std::none_of(out.begin(), out.end(),
[](const FieldRef& ref) { return ref.IsNested(); }));
if (out.size() == 1) {
impl_ = std::move(out[0].impl_);
} else {
impl_ = std::move(out);
}
}
Result<FieldRef> FieldRef::FromDotPath(const std::string& dot_path_arg) {
if (dot_path_arg.empty()) {
return Status::Invalid("Dot path was empty");
}
std::vector<FieldRef> children;
util::string_view dot_path = dot_path_arg;
auto parse_name = [&] {
std::string name;
for (;;) {
auto segment_end = dot_path.find_first_of("\\[.");
if (segment_end == util::string_view::npos) {
// dot_path doesn't contain any other special characters; consume all
name.append(dot_path.begin(), dot_path.end());
dot_path = "";
break;
}
if (dot_path[segment_end] != '\\') {
// segment_end points to a subscript for a new FieldRef
name.append(dot_path.begin(), segment_end);
dot_path = dot_path.substr(segment_end);
break;
}
if (dot_path.size() == segment_end + 1) {
// dot_path ends with backslash; consume it all
name.append(dot_path.begin(), dot_path.end());
dot_path = "";
break;
}
// append all characters before backslash, then the character which follows it
name.append(dot_path.begin(), segment_end);
name.push_back(dot_path[segment_end + 1]);
dot_path = dot_path.substr(segment_end + 2);
}
return name;
};
while (!dot_path.empty()) {
auto subscript = dot_path[0];
dot_path = dot_path.substr(1);
switch (subscript) {
case '.': {
// next element is a name
children.emplace_back(parse_name());
continue;
}
case '[': {
auto subscript_end = dot_path.find_first_not_of("0123456789");
if (subscript_end == util::string_view::npos || dot_path[subscript_end] != ']') {
return Status::Invalid("Dot path '", dot_path_arg,
"' contained an unterminated index");
}
children.emplace_back(std::atoi(dot_path.data()));
dot_path = dot_path.substr(subscript_end + 1);
continue;
}
default:
return Status::Invalid("Dot path must begin with '[' or '.', got '", dot_path_arg,
"'");
}
}
FieldRef out;
out.Flatten(std::move(children));
return out;
}
size_t FieldRef::hash() const {
struct Visitor : std::hash<std::string> {
using std::hash<std::string>::operator();
size_t operator()(const FieldPath& path) { return path.hash(); }
size_t operator()(const std::vector<FieldRef>& children) {
size_t hash = 0;
for (const FieldRef& child : children) {
hash ^= child.hash();
}
return hash;
}
};
return util::visit(Visitor{}, impl_);
}
std::string FieldRef::ToString() const {
struct Visitor {
std::string operator()(const FieldPath& path) { return path.ToString(); }
std::string operator()(const std::string& name) { return "Name(" + name + ")"; }
std::string operator()(const std::vector<FieldRef>& children) {
std::string repr = "Nested(";
for (const auto& child : children) {
repr += child.ToString() + " ";
}
repr.resize(repr.size() - 1);
repr += ")";
return repr;
}
};
return "FieldRef." + util::visit(Visitor{}, impl_);
}
std::vector<FieldPath> FieldRef::FindAll(const Schema& schema) const {
if (auto name = this->name()) {
return internal::MapVector([](int i) { return FieldPath{i}; },
schema.GetAllFieldIndices(*name));
}
return FindAll(schema.fields());
}
std::vector<FieldPath> FieldRef::FindAll(const Field& field) const {
return FindAll(field.type()->fields());
}
std::vector<FieldPath> FieldRef::FindAll(const DataType& type) const {
return FindAll(type.fields());
}
std::vector<FieldPath> FieldRef::FindAll(const FieldVector& fields) const {
struct Visitor {
std::vector<FieldPath> operator()(const FieldPath& path) {
// skip long IndexError construction if path is out of range
int out_of_range_depth;
auto maybe_field = FieldPathGetImpl::Get(
&path, &fields_,
[](const std::shared_ptr<Field>& field) { return &field->type()->fields(); },
&out_of_range_depth);
DCHECK_OK(maybe_field.status());
if (maybe_field.ValueOrDie() != nullptr) {
return {path};
}
return {};
}
std::vector<FieldPath> operator()(const std::string& name) {
std::vector<FieldPath> out;
for (int i = 0; i < static_cast<int>(fields_.size()); ++i) {
if (fields_[i]->name() == name) {
out.push_back({i});
}
}
return out;
}
struct Matches {
// referents[i] is referenced by prefixes[i]
std::vector<FieldPath> prefixes;
FieldVector referents;
Matches(std::vector<FieldPath> matches, const FieldVector& fields) {
for (auto& match : matches) {
Add({}, std::move(match), fields);
}
}
Matches() = default;
size_t size() const { return referents.size(); }
void Add(const FieldPath& prefix, const FieldPath& suffix,
const FieldVector& fields) {
auto maybe_field = suffix.Get(fields);
DCHECK_OK(maybe_field.status());
referents.push_back(std::move(maybe_field).ValueOrDie());
std::vector<int> concatenated_indices(prefix.indices().size() +
suffix.indices().size());
auto it = concatenated_indices.begin();
for (auto path : {&prefix, &suffix}) {
it = std::copy(path->indices().begin(), path->indices().end(), it);
}
prefixes.emplace_back(std::move(concatenated_indices));
}
};
std::vector<FieldPath> operator()(const std::vector<FieldRef>& refs) {
DCHECK_GE(refs.size(), 1);
Matches matches(refs.front().FindAll(fields_), fields_);
for (auto ref_it = refs.begin() + 1; ref_it != refs.end(); ++ref_it) {
Matches next_matches;
for (size_t i = 0; i < matches.size(); ++i) {
const auto& referent = *matches.referents[i];
for (const FieldPath& match : ref_it->FindAll(referent)) {
next_matches.Add(matches.prefixes[i], match, referent.type()->fields());
}
}
matches = std::move(next_matches);
}
return matches.prefixes;
}
const FieldVector& fields_;
};
return util::visit(Visitor{fields}, impl_);
}
std::vector<FieldPath> FieldRef::FindAll(const ArrayData& array) const {
return FindAll(*array.type);
}
std::vector<FieldPath> FieldRef::FindAll(const Array& array) const {
return FindAll(*array.type());
}
std::vector<FieldPath> FieldRef::FindAll(const RecordBatch& batch) const {
return FindAll(*batch.schema());
}
void PrintTo(const FieldRef& ref, std::ostream* os) { *os << ref.ToString(); }
// ----------------------------------------------------------------------
// Schema implementation
std::string EndiannessToString(Endianness endianness) {
switch (endianness) {
case Endianness::Little:
return "little";
case Endianness::Big:
return "big";
default:
DCHECK(false) << "invalid endianness";
return "???";
}
}
class Schema::Impl {
public:
Impl(std::vector<std::shared_ptr<Field>> fields, Endianness endianness,
std::shared_ptr<const KeyValueMetadata> metadata)
: fields_(std::move(fields)),
endianness_(endianness),
name_to_index_(CreateNameToIndexMap(fields_)),
metadata_(std::move(metadata)) {}
std::vector<std::shared_ptr<Field>> fields_;
Endianness endianness_;
std::unordered_multimap<std::string, int> name_to_index_;
std::shared_ptr<const KeyValueMetadata> metadata_;
};
Schema::Schema(std::vector<std::shared_ptr<Field>> fields, Endianness endianness,
std::shared_ptr<const KeyValueMetadata> metadata)
: detail::Fingerprintable(),
impl_(new Impl(std::move(fields), endianness, std::move(metadata))) {}
Schema::Schema(std::vector<std::shared_ptr<Field>> fields,
std::shared_ptr<const KeyValueMetadata> metadata)
: detail::Fingerprintable(),
impl_(new Impl(std::move(fields), Endianness::Native, std::move(metadata))) {}
Schema::Schema(const Schema& schema)
: detail::Fingerprintable(), impl_(new Impl(*schema.impl_)) {}
Schema::~Schema() = default;
std::shared_ptr<Schema> Schema::WithEndianness(Endianness endianness) const {
return std::make_shared<Schema>(impl_->fields_, endianness, impl_->metadata_);
}
Endianness Schema::endianness() const { return impl_->endianness_; }
bool Schema::is_native_endian() const { return impl_->endianness_ == Endianness::Native; }
int Schema::num_fields() const { return static_cast<int>(impl_->fields_.size()); }
const std::shared_ptr<Field>& Schema::field(int i) const {
DCHECK_GE(i, 0);
DCHECK_LT(i, num_fields());
return impl_->fields_[i];
}
const std::vector<std::shared_ptr<Field>>& Schema::fields() const {
return impl_->fields_;
}
bool Schema::Equals(const Schema& other, bool check_metadata) const {
if (this == &other) {
return true;
}
// checks endianness equality
if (endianness() != other.endianness()) {
return false;
}
// checks field equality
if (num_fields() != other.num_fields()) {
return false;
}
if (check_metadata) {
const auto& metadata_fp = metadata_fingerprint();
const auto& other_metadata_fp = other.metadata_fingerprint();
if (metadata_fp != other_metadata_fp) {
return false;
}
}
// Fast path using fingerprints, if possible
const auto& fp = fingerprint();
const auto& other_fp = other.fingerprint();
if (!fp.empty() && !other_fp.empty()) {
return fp == other_fp;
}
// Fall back on field-by-field comparison
for (int i = 0; i < num_fields(); ++i) {
if (!field(i)->Equals(*other.field(i).get(), check_metadata)) {
return false;
}
}
return true;
}
bool Schema::Equals(const std::shared_ptr<Schema>& other, bool check_metadata) const {
if (other == nullptr) {
return false;
}
return Equals(*other, check_metadata);
}
std::shared_ptr<Field> Schema::GetFieldByName(const std::string& name) const {
int i = GetFieldIndex(name);
return i == -1 ? nullptr : impl_->fields_[i];
}
int Schema::GetFieldIndex(const std::string& name) const {
return LookupNameIndex(impl_->name_to_index_, name);
}
std::vector<int> Schema::GetAllFieldIndices(const std::string& name) const {
std::vector<int> result;
auto p = impl_->name_to_index_.equal_range(name);
for (auto it = p.first; it != p.second; ++it) {
result.push_back(it->second);
}
if (result.size() > 1) {
std::sort(result.begin(), result.end());
}
return result;
}
Status Schema::CanReferenceFieldsByNames(const std::vector<std::string>& names) const {
for (const auto& name : names) {
if (GetFieldByName(name) == nullptr) {
return Status::Invalid("Field named '", name,
"' not found or not unique in the schema.");
}
}
return Status::OK();
}
std::vector<std::shared_ptr<Field>> Schema::GetAllFieldsByName(
const std::string& name) const {
std::vector<std::shared_ptr<Field>> result;
auto p = impl_->name_to_index_.equal_range(name);
for (auto it = p.first; it != p.second; ++it) {
result.push_back(impl_->fields_[it->second]);
}
return result;
}
Result<std::shared_ptr<Schema>> Schema::AddField(
int i, const std::shared_ptr<Field>& field) const {
if (i < 0 || i > this->num_fields()) {
return Status::Invalid("Invalid column index to add field.");
}
return std::make_shared<Schema>(internal::AddVectorElement(impl_->fields_, i, field),
impl_->metadata_);
}
Result<std::shared_ptr<Schema>> Schema::SetField(
int i, const std::shared_ptr<Field>& field) const {
if (i < 0 || i > this->num_fields()) {
return Status::Invalid("Invalid column index to add field.");
}
return std::make_shared<Schema>(
internal::ReplaceVectorElement(impl_->fields_, i, field), impl_->metadata_);
}
Result<std::shared_ptr<Schema>> Schema::RemoveField(int i) const {
if (i < 0 || i >= this->num_fields()) {
return Status::Invalid("Invalid column index to remove field.");
}
return std::make_shared<Schema>(internal::DeleteVectorElement(impl_->fields_, i),
impl_->metadata_);
}
bool Schema::HasMetadata() const {
return (impl_->metadata_ != nullptr) && (impl_->metadata_->size() > 0);
}
bool Schema::HasDistinctFieldNames() const {
auto fields = field_names();
std::unordered_set<std::string> names{fields.cbegin(), fields.cend()};
return names.size() == fields.size();
}
std::shared_ptr<Schema> Schema::WithMetadata(
const std::shared_ptr<const KeyValueMetadata>& metadata) const {
return std::make_shared<Schema>(impl_->fields_, metadata);
}
const std::shared_ptr<const KeyValueMetadata>& Schema::metadata() const {
return impl_->metadata_;
}
std::shared_ptr<Schema> Schema::RemoveMetadata() const {
return std::make_shared<Schema>(impl_->fields_);
}
std::string Schema::ToString(bool show_metadata) const {
std::stringstream buffer;
int i = 0;
for (const auto& field : impl_->fields_) {
if (i > 0) {
buffer << std::endl;
}
buffer << field->ToString(show_metadata);
++i;
}
if (impl_->endianness_ != Endianness::Native) {
buffer << "\n-- endianness: " << EndiannessToString(impl_->endianness_) << " --";
}
if (show_metadata && HasMetadata()) {
buffer << impl_->metadata_->ToString();
}
return buffer.str();
}
std::vector<std::string> Schema::field_names() const {
std::vector<std::string> names;
for (const auto& field : impl_->fields_) {
names.push_back(field->name());
}
return names;
}
class SchemaBuilder::Impl {
public:
friend class SchemaBuilder;
Impl(ConflictPolicy policy, Field::MergeOptions field_merge_options)
: policy_(policy), field_merge_options_(field_merge_options) {}
Impl(std::vector<std::shared_ptr<Field>> fields,
std::shared_ptr<const KeyValueMetadata> metadata, ConflictPolicy conflict_policy,
Field::MergeOptions field_merge_options)
: fields_(std::move(fields)),
name_to_index_(CreateNameToIndexMap(fields_)),
metadata_(std::move(metadata)),
policy_(conflict_policy),
field_merge_options_(field_merge_options) {}
Status AddField(const std::shared_ptr<Field>& field) {
DCHECK_NE(field, nullptr);
// Short-circuit, no lookup needed.
if (policy_ == CONFLICT_APPEND) {
return AppendField(field);
}
auto name = field->name();
constexpr int kNotFound = -1;
constexpr int kDuplicateFound = -2;
auto i = LookupNameIndex<kNotFound, kDuplicateFound>(name_to_index_, name);
if (i == kNotFound) {
return AppendField(field);
}
// From this point, there's one or more field in the builder that exists with
// the same name.
if (policy_ == CONFLICT_IGNORE) {
// The ignore policy is more generous when there's duplicate in the builder.
return Status::OK();
} else if (policy_ == CONFLICT_ERROR) {
return Status::Invalid("Duplicate found, policy dictate to treat as an error");
}
if (i == kDuplicateFound) {
// Cannot merge/replace when there's more than one field in the builder
// because we can't decide which to merge/replace.
return Status::Invalid("Cannot merge field ", name,
" more than one field with same name exists");
}
DCHECK_GE(i, 0);
if (policy_ == CONFLICT_REPLACE) {
fields_[i] = field;
} else if (policy_ == CONFLICT_MERGE) {
ARROW_ASSIGN_OR_RAISE(fields_[i], fields_[i]->MergeWith(field));
}
return Status::OK();
}
Status AppendField(const std::shared_ptr<Field>& field) {
name_to_index_.emplace(field->name(), static_cast<int>(fields_.size()));
fields_.push_back(field);
return Status::OK();
}
void Reset() {
fields_.clear();
name_to_index_.clear();
metadata_.reset();
}
private:
std::vector<std::shared_ptr<Field>> fields_;
std::unordered_multimap<std::string, int> name_to_index_;
std::shared_ptr<const KeyValueMetadata> metadata_;
ConflictPolicy policy_;
Field::MergeOptions field_merge_options_;
};
SchemaBuilder::SchemaBuilder(ConflictPolicy policy,
Field::MergeOptions field_merge_options) {
impl_ = internal::make_unique<Impl>(policy, field_merge_options);
}
SchemaBuilder::SchemaBuilder(std::vector<std::shared_ptr<Field>> fields,
ConflictPolicy policy,
Field::MergeOptions field_merge_options) {
impl_ = internal::make_unique<Impl>(std::move(fields), nullptr, policy,
field_merge_options);
}
SchemaBuilder::SchemaBuilder(const std::shared_ptr<Schema>& schema, ConflictPolicy policy,
Field::MergeOptions field_merge_options) {
std::shared_ptr<const KeyValueMetadata> metadata;
if (schema->HasMetadata()) {
metadata = schema->metadata()->Copy();
}
impl_ = internal::make_unique<Impl>(schema->fields(), std::move(metadata), policy,
field_merge_options);
}
SchemaBuilder::~SchemaBuilder() {}
SchemaBuilder::ConflictPolicy SchemaBuilder::policy() const { return impl_->policy_; }
void SchemaBuilder::SetPolicy(SchemaBuilder::ConflictPolicy resolution) {
impl_->policy_ = resolution;
}
Status SchemaBuilder::AddField(const std::shared_ptr<Field>& field) {
return impl_->AddField(field);
}
Status SchemaBuilder::AddFields(const std::vector<std::shared_ptr<Field>>& fields) {
for (const auto& field : fields) {
RETURN_NOT_OK(AddField(field));
}
return Status::OK();
}
Status SchemaBuilder::AddSchema(const std::shared_ptr<Schema>& schema) {
DCHECK_NE(schema, nullptr);
return AddFields(schema->fields());
}
Status SchemaBuilder::AddSchemas(const std::vector<std::shared_ptr<Schema>>& schemas) {
for (const auto& schema : schemas) {
RETURN_NOT_OK(AddSchema(schema));
}
return Status::OK();
}
Status SchemaBuilder::AddMetadata(const KeyValueMetadata& metadata) {
impl_->metadata_ = metadata.Copy();
return Status::OK();
}
Result<std::shared_ptr<Schema>> SchemaBuilder::Finish() const {
return schema(impl_->fields_, impl_->metadata_);
}
void SchemaBuilder::Reset() { impl_->Reset(); }
Result<std::shared_ptr<Schema>> SchemaBuilder::Merge(
const std::vector<std::shared_ptr<Schema>>& schemas, ConflictPolicy policy) {
SchemaBuilder builder{policy};
RETURN_NOT_OK(builder.AddSchemas(schemas));
return builder.Finish();
}
Status SchemaBuilder::AreCompatible(const std::vector<std::shared_ptr<Schema>>& schemas,
ConflictPolicy policy) {
return Merge(schemas, policy).status();
}
std::shared_ptr<Schema> schema(std::vector<std::shared_ptr<Field>> fields,
std::shared_ptr<const KeyValueMetadata> metadata) {
return std::make_shared<Schema>(std::move(fields), std::move(metadata));
}
std::shared_ptr<Schema> schema(std::vector<std::shared_ptr<Field>> fields,
Endianness endianness,
std::shared_ptr<const KeyValueMetadata> metadata) {
return std::make_shared<Schema>(std::move(fields), endianness, std::move(metadata));
}
Result<std::shared_ptr<Schema>> UnifySchemas(
const std::vector<std::shared_ptr<Schema>>& schemas,
const Field::MergeOptions field_merge_options) {
if (schemas.empty()) {
return Status::Invalid("Must provide at least one schema to unify.");
}
if (!schemas[0]->HasDistinctFieldNames()) {
return Status::Invalid("Can't unify schema with duplicate field names.");
}
SchemaBuilder builder{schemas[0], SchemaBuilder::CONFLICT_MERGE, field_merge_options};
for (size_t i = 1; i < schemas.size(); i++) {
const auto& schema = schemas[i];
if (!schema->HasDistinctFieldNames()) {
return Status::Invalid("Can't unify schema with duplicate field names.");
}
RETURN_NOT_OK(builder.AddSchema(schema));
}
return builder.Finish();
}
// ----------------------------------------------------------------------
// Fingerprint computations
namespace detail {
Fingerprintable::~Fingerprintable() {
delete fingerprint_.load();
delete metadata_fingerprint_.load();
}
template <typename ComputeFingerprint>
static const std::string& LoadFingerprint(std::atomic<std::string*>* fingerprint,
ComputeFingerprint&& compute_fingerprint) {
auto new_p = new std::string(std::forward<ComputeFingerprint>(compute_fingerprint)());
// Since fingerprint() and metadata_fingerprint() return a *reference* to the
// allocated string, the first allocation ever should never be replaced by another
// one. Hence the compare_exchange_strong() against nullptr.
std::string* expected = nullptr;
if (fingerprint->compare_exchange_strong(expected, new_p)) {
return *new_p;
} else {
delete new_p;
DCHECK_NE(expected, nullptr);
return *expected;
}
}
const std::string& Fingerprintable::LoadFingerprintSlow() const {
return LoadFingerprint(&fingerprint_, [this]() { return ComputeFingerprint(); });
}
const std::string& Fingerprintable::LoadMetadataFingerprintSlow() const {
return LoadFingerprint(&metadata_fingerprint_,
[this]() { return ComputeMetadataFingerprint(); });
}
} // namespace detail
static inline std::string TypeIdFingerprint(const DataType& type) {
auto c = static_cast<int>(type.id()) + 'A';
DCHECK_GE(c, 0);
DCHECK_LT(c, 128); // Unlikely to happen any soon
// Prefix with an unusual character in order to disambiguate
std::string s{'@', static_cast<char>(c)};
return s;
}
static char TimeUnitFingerprint(TimeUnit::type unit) {
switch (unit) {
case TimeUnit::SECOND:
return 's';
case TimeUnit::MILLI:
return 'm';
case TimeUnit::MICRO:
return 'u';
case TimeUnit::NANO:
return 'n';
default:
DCHECK(false) << "Unexpected TimeUnit";
return '\0';
}
}
static char IntervalTypeFingerprint(IntervalType::type unit) {
switch (unit) {
case IntervalType::DAY_TIME:
return 'd';
case IntervalType::MONTHS:
return 'M';
case IntervalType::MONTH_DAY_NANO:
return 'N';
default:
DCHECK(false) << "Unexpected IntervalType::type";
return '\0';
}
}
static void AppendMetadataFingerprint(const KeyValueMetadata& metadata,
std::stringstream* ss) {
// Compute metadata fingerprint. KeyValueMetadata is not immutable,
// so we don't cache the result on the metadata instance.
const auto pairs = metadata.sorted_pairs();
if (!pairs.empty()) {
*ss << "!{";
for (const auto& p : pairs) {
const auto& k = p.first;
const auto& v = p.second;
// Since metadata strings can contain arbitrary characters, prefix with
// string length to disambiguate.
*ss << k.length() << ':' << k << ':';
*ss << v.length() << ':' << v << ';';
}
*ss << '}';
}
}
std::string Field::ComputeFingerprint() const {
const auto& type_fingerprint = type_->fingerprint();
if (type_fingerprint.empty()) {
// Underlying DataType doesn't support fingerprinting.
return "";
}
std::stringstream ss;
ss << 'F';
if (nullable_) {
ss << 'n';
} else {
ss << 'N';
}
ss << name_;
ss << '{' << type_fingerprint << '}';
return ss.str();
}
std::string Field::ComputeMetadataFingerprint() const {
std::stringstream ss;
if (metadata_) {
AppendMetadataFingerprint(*metadata_, &ss);
}
const auto& type_fingerprint = type_->metadata_fingerprint();
if (!type_fingerprint.empty()) {
ss << "+{" << type_->metadata_fingerprint() << "}";
}
return ss.str();
}
std::string Schema::ComputeFingerprint() const {
std::stringstream ss;
ss << "S{";
for (const auto& field : fields()) {
const auto& field_fingerprint = field->fingerprint();
if (field_fingerprint.empty()) {
return "";
}
ss << field_fingerprint << ";";
}
ss << (endianness() == Endianness::Little ? "L" : "B");
ss << "}";
return ss.str();
}
std::string Schema::ComputeMetadataFingerprint() const {
std::stringstream ss;
if (HasMetadata()) {
AppendMetadataFingerprint(*metadata(), &ss);
}
ss << "S{";
for (const auto& field : fields()) {
const auto& field_fingerprint = field->metadata_fingerprint();
ss << field_fingerprint << ";";
}
ss << "}";
return ss.str();
}
void PrintTo(const Schema& s, std::ostream* os) { *os << s; }
std::string DataType::ComputeFingerprint() const {
// Default implementation returns empty string, signalling non-implemented
// functionality.
return "";
}
std::string DataType::ComputeMetadataFingerprint() const {
// Whatever the data type, metadata can only be found on child fields
std::string s;
for (const auto& child : children_) {
s += child->metadata_fingerprint() + ";";
}
return s;
}
#define PARAMETER_LESS_FINGERPRINT(TYPE_CLASS) \
std::string TYPE_CLASS##Type::ComputeFingerprint() const { \
return TypeIdFingerprint(*this); \
}
PARAMETER_LESS_FINGERPRINT(Null)
PARAMETER_LESS_FINGERPRINT(Boolean)
PARAMETER_LESS_FINGERPRINT(Int8)
PARAMETER_LESS_FINGERPRINT(Int16)
PARAMETER_LESS_FINGERPRINT(Int32)
PARAMETER_LESS_FINGERPRINT(Int64)
PARAMETER_LESS_FINGERPRINT(UInt8)
PARAMETER_LESS_FINGERPRINT(UInt16)
PARAMETER_LESS_FINGERPRINT(UInt32)
PARAMETER_LESS_FINGERPRINT(UInt64)
PARAMETER_LESS_FINGERPRINT(HalfFloat)
PARAMETER_LESS_FINGERPRINT(Float)
PARAMETER_LESS_FINGERPRINT(Double)
PARAMETER_LESS_FINGERPRINT(Binary)
PARAMETER_LESS_FINGERPRINT(LargeBinary)
PARAMETER_LESS_FINGERPRINT(String)
PARAMETER_LESS_FINGERPRINT(LargeString)
PARAMETER_LESS_FINGERPRINT(Date32)
PARAMETER_LESS_FINGERPRINT(Date64)
#undef PARAMETER_LESS_FINGERPRINT
std::string DictionaryType::ComputeFingerprint() const {
const auto& index_fingerprint = index_type_->fingerprint();
const auto& value_fingerprint = value_type_->fingerprint();
std::string ordered_fingerprint = ordered_ ? "1" : "0";
DCHECK(!index_fingerprint.empty()); // it's an integer type
if (!value_fingerprint.empty()) {
return TypeIdFingerprint(*this) + index_fingerprint + value_fingerprint +
ordered_fingerprint;
}
return ordered_fingerprint;
}
std::string ListType::ComputeFingerprint() const {
const auto& child_fingerprint = children_[0]->fingerprint();
if (!child_fingerprint.empty()) {
return TypeIdFingerprint(*this) + "{" + child_fingerprint + "}";
}
return "";
}
std::string LargeListType::ComputeFingerprint() const {
const auto& child_fingerprint = children_[0]->fingerprint();
if (!child_fingerprint.empty()) {
return TypeIdFingerprint(*this) + "{" + child_fingerprint + "}";
}
return "";
}
std::string MapType::ComputeFingerprint() const {
const auto& key_fingerprint = key_type()->fingerprint();
const auto& item_fingerprint = item_type()->fingerprint();
if (!key_fingerprint.empty() && !item_fingerprint.empty()) {
if (keys_sorted_) {
return TypeIdFingerprint(*this) + "s{" + key_fingerprint + item_fingerprint + "}";
} else {
return TypeIdFingerprint(*this) + "{" + key_fingerprint + item_fingerprint + "}";
}
}
return "";
}
std::string FixedSizeListType::ComputeFingerprint() const {
const auto& child_fingerprint = children_[0]->fingerprint();
if (!child_fingerprint.empty()) {
std::stringstream ss;
ss << TypeIdFingerprint(*this) << "[" << list_size_ << "]"
<< "{" << child_fingerprint << "}";
return ss.str();
}
return "";
}
std::string FixedSizeBinaryType::ComputeFingerprint() const {
std::stringstream ss;
ss << TypeIdFingerprint(*this) << "[" << byte_width_ << "]";
return ss.str();
}
std::string DecimalType::ComputeFingerprint() const {
std::stringstream ss;
ss << TypeIdFingerprint(*this) << "[" << byte_width_ << "," << precision_ << ","
<< scale_ << "]";
return ss.str();
}
std::string StructType::ComputeFingerprint() const {
std::stringstream ss;
ss << TypeIdFingerprint(*this) << "{";
for (const auto& child : children_) {
const auto& child_fingerprint = child->fingerprint();
if (child_fingerprint.empty()) {
return "";
}
ss << child_fingerprint << ";";
}
ss << "}";
return ss.str();
}
std::string UnionType::ComputeFingerprint() const {
std::stringstream ss;
ss << TypeIdFingerprint(*this);
switch (mode()) {
case UnionMode::SPARSE:
ss << "[s";
break;
case UnionMode::DENSE:
ss << "[d";
break;
default:
DCHECK(false) << "Unexpected UnionMode";
}
for (const auto code : type_codes_) {
// Represent code as integer, not raw character
ss << ':' << static_cast<int32_t>(code);
}
ss << "]{";
for (const auto& child : children_) {
const auto& child_fingerprint = child->fingerprint();
if (child_fingerprint.empty()) {
return "";
}
ss << child_fingerprint << ";";
}
ss << "}";
return ss.str();
}
std::string TimeType::ComputeFingerprint() const {
std::stringstream ss;
ss << TypeIdFingerprint(*this) << TimeUnitFingerprint(unit_);
return ss.str();
}
std::string TimestampType::ComputeFingerprint() const {
std::stringstream ss;
ss << TypeIdFingerprint(*this) << TimeUnitFingerprint(unit_) << timezone_.length()
<< ':' << timezone_;
return ss.str();
}
std::string IntervalType::ComputeFingerprint() const {
std::stringstream ss;
ss << TypeIdFingerprint(*this) << IntervalTypeFingerprint(interval_type());
return ss.str();
}
std::string DurationType::ComputeFingerprint() const {
std::stringstream ss;
ss << TypeIdFingerprint(*this) << TimeUnitFingerprint(unit_);
return ss.str();
}
// ----------------------------------------------------------------------
// Visitors and factory functions
Status DataType::Accept(TypeVisitor* visitor) const {
return VisitTypeInline(*this, visitor);
}
#define TYPE_FACTORY(NAME, KLASS) \
std::shared_ptr<DataType> NAME() { \
static std::shared_ptr<DataType> result = std::make_shared<KLASS>(); \
return result; \
}
TYPE_FACTORY(null, NullType)
TYPE_FACTORY(boolean, BooleanType)
TYPE_FACTORY(int8, Int8Type)
TYPE_FACTORY(uint8, UInt8Type)
TYPE_FACTORY(int16, Int16Type)
TYPE_FACTORY(uint16, UInt16Type)
TYPE_FACTORY(int32, Int32Type)
TYPE_FACTORY(uint32, UInt32Type)
TYPE_FACTORY(int64, Int64Type)
TYPE_FACTORY(uint64, UInt64Type)
TYPE_FACTORY(float16, HalfFloatType)
TYPE_FACTORY(float32, FloatType)
TYPE_FACTORY(float64, DoubleType)
TYPE_FACTORY(utf8, StringType)
TYPE_FACTORY(large_utf8, LargeStringType)
TYPE_FACTORY(binary, BinaryType)
TYPE_FACTORY(large_binary, LargeBinaryType)
TYPE_FACTORY(date64, Date64Type)
TYPE_FACTORY(date32, Date32Type)
std::shared_ptr<DataType> fixed_size_binary(int32_t byte_width) {
return std::make_shared<FixedSizeBinaryType>(byte_width);
}
std::shared_ptr<DataType> duration(TimeUnit::type unit) {
return std::make_shared<DurationType>(unit);
}
std::shared_ptr<DataType> day_time_interval() {
return std::make_shared<DayTimeIntervalType>();
}
std::shared_ptr<DataType> month_day_nano_interval() {
return std::make_shared<MonthDayNanoIntervalType>();
}
std::shared_ptr<DataType> month_interval() {
return std::make_shared<MonthIntervalType>();
}
std::shared_ptr<DataType> timestamp(TimeUnit::type unit) {
return std::make_shared<TimestampType>(unit);
}
std::shared_ptr<DataType> timestamp(TimeUnit::type unit, const std::string& timezone) {
return std::make_shared<TimestampType>(unit, timezone);
}
std::shared_ptr<DataType> time32(TimeUnit::type unit) {
return std::make_shared<Time32Type>(unit);
}
std::shared_ptr<DataType> time64(TimeUnit::type unit) {
return std::make_shared<Time64Type>(unit);
}
std::shared_ptr<DataType> list(const std::shared_ptr<DataType>& value_type) {
return std::make_shared<ListType>(value_type);
}
std::shared_ptr<DataType> list(const std::shared_ptr<Field>& value_field) {
return std::make_shared<ListType>(value_field);
}
std::shared_ptr<DataType> large_list(const std::shared_ptr<DataType>& value_type) {
return std::make_shared<LargeListType>(value_type);
}
std::shared_ptr<DataType> large_list(const std::shared_ptr<Field>& value_field) {
return std::make_shared<LargeListType>(value_field);
}
std::shared_ptr<DataType> map(std::shared_ptr<DataType> key_type,
std::shared_ptr<DataType> item_type, bool keys_sorted) {
return std::make_shared<MapType>(std::move(key_type), std::move(item_type),
keys_sorted);
}
std::shared_ptr<DataType> map(std::shared_ptr<DataType> key_type,
std::shared_ptr<Field> item_field, bool keys_sorted) {
return std::make_shared<MapType>(std::move(key_type), std::move(item_field),
keys_sorted);
}
std::shared_ptr<DataType> fixed_size_list(const std::shared_ptr<DataType>& value_type,
int32_t list_size) {
return std::make_shared<FixedSizeListType>(value_type, list_size);
}
std::shared_ptr<DataType> fixed_size_list(const std::shared_ptr<Field>& value_field,
int32_t list_size) {
return std::make_shared<FixedSizeListType>(value_field, list_size);
}
std::shared_ptr<DataType> struct_(const std::vector<std::shared_ptr<Field>>& fields) {
return std::make_shared<StructType>(fields);
}
std::shared_ptr<DataType> sparse_union(FieldVector child_fields,
std::vector<int8_t> type_codes) {
if (type_codes.empty()) {
type_codes = internal::Iota(static_cast<int8_t>(child_fields.size()));
}
return std::make_shared<SparseUnionType>(std::move(child_fields),
std::move(type_codes));
}
std::shared_ptr<DataType> dense_union(FieldVector child_fields,
std::vector<int8_t> type_codes) {
if (type_codes.empty()) {
type_codes = internal::Iota(static_cast<int8_t>(child_fields.size()));
}
return std::make_shared<DenseUnionType>(std::move(child_fields), std::move(type_codes));
}
FieldVector FieldsFromArraysAndNames(std::vector<std::string> names,
const ArrayVector& arrays) {
FieldVector fields(arrays.size());
int i = 0;
if (names.empty()) {
for (const auto& array : arrays) {
fields[i] = field(std::to_string(i), array->type());
++i;
}
} else {
DCHECK_EQ(names.size(), arrays.size());
for (const auto& array : arrays) {
fields[i] = field(std::move(names[i]), array->type());
++i;
}
}
return fields;
}
std::shared_ptr<DataType> sparse_union(const ArrayVector& children,
std::vector<std::string> field_names,
std::vector<int8_t> type_codes) {
if (type_codes.empty()) {
type_codes = internal::Iota(static_cast<int8_t>(children.size()));
}
auto fields = FieldsFromArraysAndNames(std::move(field_names), children);
return sparse_union(std::move(fields), std::move(type_codes));
}
std::shared_ptr<DataType> dense_union(const ArrayVector& children,
std::vector<std::string> field_names,
std::vector<int8_t> type_codes) {
if (type_codes.empty()) {
type_codes = internal::Iota(static_cast<int8_t>(children.size()));
}
auto fields = FieldsFromArraysAndNames(std::move(field_names), children);
return dense_union(std::move(fields), std::move(type_codes));
}
std::shared_ptr<DataType> dictionary(const std::shared_ptr<DataType>& index_type,
const std::shared_ptr<DataType>& dict_type,
bool ordered) {
return std::make_shared<DictionaryType>(index_type, dict_type, ordered);
}
std::shared_ptr<Field> field(std::string name, std::shared_ptr<DataType> type,
bool nullable,
std::shared_ptr<const KeyValueMetadata> metadata) {
return std::make_shared<Field>(std::move(name), std::move(type), nullable,
std::move(metadata));
}
std::shared_ptr<Field> field(std::string name, std::shared_ptr<DataType> type,
std::shared_ptr<const KeyValueMetadata> metadata) {
return std::make_shared<Field>(std::move(name), std::move(type), /*nullable=*/true,
std::move(metadata));
}
std::shared_ptr<DataType> decimal(int32_t precision, int32_t scale) {
return precision <= Decimal128Type::kMaxPrecision ? decimal128(precision, scale)
: decimal256(precision, scale);
}
std::shared_ptr<DataType> decimal128(int32_t precision, int32_t scale) {
return std::make_shared<Decimal128Type>(precision, scale);
}
std::shared_ptr<DataType> decimal256(int32_t precision, int32_t scale) {
return std::make_shared<Decimal256Type>(precision, scale);
}
std::string Decimal128Type::ToString() const {
std::stringstream s;
s << "decimal128(" << precision_ << ", " << scale_ << ")";
return s.str();
}
std::string Decimal256Type::ToString() const {
std::stringstream s;
s << "decimal256(" << precision_ << ", " << scale_ << ")";
return s.str();
}
namespace {
std::vector<std::shared_ptr<DataType>> g_signed_int_types;
std::vector<std::shared_ptr<DataType>> g_unsigned_int_types;
std::vector<std::shared_ptr<DataType>> g_int_types;
std::vector<std::shared_ptr<DataType>> g_floating_types;
std::vector<std::shared_ptr<DataType>> g_numeric_types;
std::vector<std::shared_ptr<DataType>> g_base_binary_types;
std::vector<std::shared_ptr<DataType>> g_temporal_types;
std::vector<std::shared_ptr<DataType>> g_interval_types;
std::vector<std::shared_ptr<DataType>> g_primitive_types;
std::once_flag static_data_initialized;
template <typename T>
void Extend(const std::vector<T>& values, std::vector<T>* out) {
out->insert(out->end(), values.begin(), values.end());
}
void InitStaticData() {
// Signed int types
g_signed_int_types = {int8(), int16(), int32(), int64()};
// Unsigned int types
g_unsigned_int_types = {uint8(), uint16(), uint32(), uint64()};
// All int types
Extend(g_unsigned_int_types, &g_int_types);
Extend(g_signed_int_types, &g_int_types);
// Floating point types
g_floating_types = {float32(), float64()};
// Numeric types
Extend(g_int_types, &g_numeric_types);
Extend(g_floating_types, &g_numeric_types);
// Temporal types
g_temporal_types = {date32(),
date64(),
time32(TimeUnit::SECOND),
time32(TimeUnit::MILLI),
time64(TimeUnit::MICRO),
time64(TimeUnit::NANO),
timestamp(TimeUnit::SECOND),
timestamp(TimeUnit::MILLI),
timestamp(TimeUnit::MICRO),
timestamp(TimeUnit::NANO)};
// Interval types
g_interval_types = {day_time_interval(), month_interval()};
// Base binary types (without FixedSizeBinary)
g_base_binary_types = {binary(), utf8(), large_binary(), large_utf8()};
// Non-parametric, non-nested types. This also DOES NOT include
//
// * Decimal
// * Fixed Size Binary
// * Time32
// * Time64
// * Timestamp
g_primitive_types = {null(), boolean(), date32(), date64()};
Extend(g_numeric_types, &g_primitive_types);
Extend(g_base_binary_types, &g_primitive_types);
}
} // namespace
const std::vector<std::shared_ptr<DataType>>& BaseBinaryTypes() {
std::call_once(static_data_initialized, InitStaticData);
return g_base_binary_types;
}
const std::vector<std::shared_ptr<DataType>>& StringTypes() {
static DataTypeVector types = {utf8(), large_utf8()};
return types;
}
const std::vector<std::shared_ptr<DataType>>& SignedIntTypes() {
std::call_once(static_data_initialized, InitStaticData);
return g_signed_int_types;
}
const std::vector<std::shared_ptr<DataType>>& UnsignedIntTypes() {
std::call_once(static_data_initialized, InitStaticData);
return g_unsigned_int_types;
}
const std::vector<std::shared_ptr<DataType>>& IntTypes() {
std::call_once(static_data_initialized, InitStaticData);
return g_int_types;
}
const std::vector<std::shared_ptr<DataType>>& FloatingPointTypes() {
std::call_once(static_data_initialized, InitStaticData);
return g_floating_types;
}
const std::vector<std::shared_ptr<DataType>>& NumericTypes() {
std::call_once(static_data_initialized, InitStaticData);
return g_numeric_types;
}
const std::vector<std::shared_ptr<DataType>>& TemporalTypes() {
std::call_once(static_data_initialized, InitStaticData);
return g_temporal_types;
}
const std::vector<std::shared_ptr<DataType>>& IntervalTypes() {
std::call_once(static_data_initialized, InitStaticData);
return g_interval_types;
}
const std::vector<std::shared_ptr<DataType>>& PrimitiveTypes() {
std::call_once(static_data_initialized, InitStaticData);
return g_primitive_types;
}
const std::vector<TimeUnit::type>& TimeUnit::values() {
static std::vector<TimeUnit::type> units = {TimeUnit::SECOND, TimeUnit::MILLI,
TimeUnit::MICRO, TimeUnit::NANO};
return units;
}
} // namespace arrow
|
#include "appch.h"
#include "Alpha/Platform/OpenGL/OpenGLRendererAPI.h"
#include "RenderCommand.h"
namespace Alpha
{
RendererAPI* RenderCommand::s_RendererAPI = new OpenGLRendererAPI;
}
|
#ifndef VG_STATISTICS_HPP_INCLUDED
#define VG_STATISTICS_HPP_INCLUDED
/**
* \file statistics.hpp
*
* Defines a range of statistical functions
*
*/
#include <cmath>
#include <algorithm>
#include "utility.hpp"
namespace vg {
using namespace std;
double median(std::vector<int> &v);
// Online mean-variance computation with wellfords algorithm (pass 0's to 1st 3 params to start)
void wellford_update(size_t& count, double& mean, double& M2, double new_val);
pair<double, double> wellford_mean_var(size_t count, double mean, double M2, bool sample_variance = false);
template<typename T>
double stdev(const T& v) {
double sum = std::accumulate(v.begin(), v.end(), 0.0);
double mean = sum / v.size();
std::vector<double> diff(v.size());
std::transform(v.begin(), v.end(), diff.begin(), [mean](double x) { return x - mean; });
double sq_sum = std::inner_product(diff.begin(), diff.end(), diff.begin(), 0.0);
return std::sqrt(sq_sum / v.size());
}
/// The standard normal cumulative distribution function
double Phi(double x);
/// Inverse CDF of a standard normal distribution. Must have 0 < quantile < 1.
double Phi_inv(double quantile);
/// Probability density function or log-normal distribution
double lognormal_pdf(double x, double mu, double sigma);
/*
* Return the log of the sum of two log-transformed values without taking them
* out of log space.
*/
inline double add_log(double log_x, double log_y) {
return log_x > log_y ? log_x + log(1.0 + exp(log_y - log_x)) : log_y + log(1.0 + exp(log_x - log_y));
}
/*
* Return the log of the difference of two log-transformed values without taking
* them out of log space.
*/
inline double subtract_log(double log_x, double log_y) {
return log_x + log(1.0 - exp(log_y - log_x));
}
/**
* Convert a number ln to the same number log 10.
*/
inline double ln_to_log10(double ln) {
return ln / log(10);
}
/**
* Convert a number log 10 to the same number ln.
*/
inline double log10_to_ln(double l10) {
return l10 * log(10);
}
/**
* Given the log10 of a value, retunr the log10 of (that value plus one).
*/
inline double log10_add_one(double x) {
return log10(pow(10, x) + 1);
}
/**
* Return the log of the sum of two log10-transformed values without taking them
* out of log space.
*/
inline double add_log10(double i, double j) {
if (i < j) {
return log10_add_one(j - i) + ((j - i < 10) ? i : j);
}
return log10_add_one(i - j) + ((i - j <= 10) ? j : i);
}
/**
* Assume that we have n independent random events that occur with probability
* p each (p is interpreted as a real number between 0 at 0 and 1 at its
* maximum value). Return an approximate probability for at least one event
* occurring as a phred score.
*
* n must be <= MAX_AT_LEAST_ONE_EVENTS.
*/
double phred_for_at_least_one(size_t p, size_t n);
/**
* Assume that we have n independent random events that occur with probability
* p each (p is interpreted as a real number between 0 at 0 and 1 at its
* maximum value). Return an approximate probability for at least one event
* occurring as a raw probability.
*
* n must be <= MAX_AT_LEAST_ONE_EVENTS.
*/
double prob_for_at_least_one(size_t p, size_t n);
/// How many events should we allow in phred_for_at_least_one and
/// prob_for_at_least_one? Should be >= our longest supported minimizer index.
constexpr static size_t MAX_AT_LEAST_ONE_EVENTS = 32;
/// Use this many bits for approximate probabilities.
constexpr static size_t AT_LEAST_ONE_PRECISION = 8;
// normal pdf, from http://stackoverflow.com/a/10848293/238609
template <typename T>
T normal_pdf(T x, T m = 0.0, T s = 1.0)
{
static const T inv_sqrt_2pi = 0.3989422804014327;
T z = (x - m) / s;
return inv_sqrt_2pi / s * std::exp(T(-0.5) * z * z);
}
/// Convert a probability to a natural log probability.
inline double prob_to_logprob(double prob) {
return log(prob);
}
/// Convert natural log probability to a probability
inline double logprob_to_prob(double logprob) {
return exp(logprob);
}
/// Add two probabilities (expressed as logprobs) together and return the result
/// as a logprob.
inline double logprob_add(double logprob1, double logprob2) {
// Pull out the larger one to avoid underflows
double pulled_out = max(logprob1, logprob2);
return pulled_out + prob_to_logprob(logprob_to_prob(logprob1 - pulled_out) + logprob_to_prob(logprob2 - pulled_out));
}
/// Invert a logprob, and get the probability of its opposite.
inline double logprob_invert(double logprob) {
return prob_to_logprob(1.0 - logprob_to_prob(logprob));
}
/// Convert 8-bit Phred quality score to probability of wrongness, using a lookup table.
double phred_to_prob(uint8_t phred);
/// Convert floating point Phred quality score to probability of wrongness.
inline double phred_to_prob(double phred) {
return pow(10, -phred / 10);
}
/// Convert probability of wrongness to integer Phred quality score.
inline double prob_to_phred(double prob) {
return -10.0 * log10(prob);
}
/// Convert a Phred quality score directly to a natural log probability of wrongness.
inline double phred_to_logprob(int phred) {
return (-((double)phred) / 10) / log10(exp(1.0));
}
/// Convert a natural log probability of wrongness directly to a Phred quality score.
inline double logprob_to_phred(double logprob ) {
return -10.0 * logprob * log10(exp(1.0));
}
/// Take the geometric mean of two logprobs
inline double logprob_geometric_mean(double lnprob1, double lnprob2) {
return log(sqrt(exp(lnprob1 + lnprob2)));
}
/// Take the geometric mean of two phred-encoded probabilities
inline double phred_geometric_mean(double phred1, double phred2) {
return prob_to_phred(sqrt(phred_to_prob(phred1 + phred2)));
}
/// Add two probabilities (expressed as phred scores) together and return the result
/// as a phred score.
inline double phred_add(double phred1, double phred2) {
return logprob_to_phred(logprob_add(phred_to_logprob(phred1), phred_to_logprob(phred2)));
}
/**
* Compute the sum of the values in a collection, where the values are log
* probabilities and the result is the log of the total probability. Items must
* be convertible to/from doubles for math.
*/
template<typename Collection>
typename Collection::value_type logprob_sum(const Collection& collection) {
// Set up an alias
using Item = typename Collection::value_type;
// Pull out the minimum value
auto min_iterator = min_element(begin(collection), end(collection));
if(min_iterator == end(collection)) {
// Nothing there, p = 0
return Item(prob_to_logprob(0));
}
auto check_iterator = begin(collection);
++check_iterator;
if(check_iterator == end(collection)) {
// We only have a single element anyway. We don't want to subtract it
// out because we'll get 0s.
return *min_iterator;
}
// Pull this much out of every logprob.
Item pulled_out = *min_iterator;
if(logprob_to_prob(pulled_out) == 0) {
// Can't divide by 0!
// TODO: fix this in selection
pulled_out = prob_to_logprob(1);
}
Item total(0);
for(auto& to_add : collection) {
// Sum up all the scaled probabilities.
total += logprob_to_prob(to_add - pulled_out);
}
// Re-log and re-scale
return pulled_out + prob_to_logprob(total);
}
/**
* Compute the sum of the values in a collection, represented by an iterator
* range, where the values are Phred scores and the result is the Phred score
* of the total probability. Items must be convertible to/from doubles for
* math.
*/
template<typename Iterator>
typename std::iterator_traits<Iterator>::value_type phred_sum(const Iterator& begin_it, const Iterator& end_it) {
// Set up an alias for the type we're operating on
using Item = typename std::iterator_traits<Iterator>::value_type;
// Pull out the minimum probability
auto min_iterator = max_element(begin_it, end_it);
if (min_iterator == end_it) {
// Nothing there, p = 0
return Item(logprob_to_phred(prob_to_logprob(0)));
}
auto check_iterator = begin_it;
++check_iterator;
if (check_iterator == end_it) {
// We only have a single element anyway. We don't want to subtract it
// out because we'll get 0s.
return *min_iterator;
}
// Pull this much out of every logprob.
double pulled_out = phred_to_logprob(*min_iterator);
if (logprob_to_prob(pulled_out) == 0) {
// Can't divide by 0!
// TODO: fix this in selection
pulled_out = prob_to_logprob(1);
}
double total(0);
for(auto to_add_it = begin_it; to_add_it != end_it; ++to_add_it) {
// Sum up all the scaled probabilities.
total += logprob_to_prob(phred_to_logprob(*to_add_it) - pulled_out);
}
// Re-log and re-scale
return Item(logprob_to_phred(pulled_out + prob_to_logprob(total)));
}
/**
* Compute the sum of the values in a collection, where the values are Phred
* scores and the result is the Phred score of the total probability. Items
* must be convertible to/from doubles for math.
*/
template<typename Collection>
typename Collection::value_type phred_sum(const Collection& collection) {
return phred_sum(begin(collection), end(collection));
}
double slope(const std::vector<double>& x, const std::vector<double>& y);
double fit_zipf(const vector<double>& y);
/// Returns the MLE rate parameter for the distribution of (shape) iid exponential RVs
double fit_fixed_shape_max_exponential(const vector<double>& x, double shape, double tolerance = 1e-8);
/// Returns the MLE estimate for the number of iid exponential RVs the data are maxima of
double fit_fixed_rate_max_exponential(const vector<double>& x, double rate, double tolerance = 1e-8);
/// Returns the MLE rate and shape parameters of a max exponential
pair<double, double> fit_max_exponential(const vector<double>& x, double tolerance = 1e-8);
// TODO: I'm eliminating this algorithm because it is approx non-identifiable for large values of shape
///// Returns the MLE rate, shape, and location parameters of an offset max exponential
//tuple<double, double, double> fit_offset_max_exponential(const vector<double>& x, double tolerance = 1e-8);
/// Return the CDF of a max exponential with the given parameters
inline double max_exponential_cdf(double x, double rate, double shape, double location = 0.0) {
return x > location ? pow(1.0 - exp(-(x - location) * rate), shape) : 0.0;
}
/// The log likelihood of a max exponential with the given parameters on the given data
double max_exponential_log_likelihood(const vector<double>& x, double rate, double shape,
double location = 0.0);
/// Returns an estimate of the rate and shape parameters of a Weibull distribution
pair<double, double> fit_weibull(const vector<double>& x);
/// Returns an estimate of the rate, shape, and location (minimum value) of a 3-parameter Weibull distribution
tuple<double, double, double> fit_offset_weibull(const vector<double>& x,
double tolerance = 1e-8);
/// Return the CDF of a max exponential with the given parameters
inline double weibull_cdf(double x, double scale, double shape, double location = 0.0) {
return x > location ? 1.0 - exp(-pow((x - location) / scale, shape)) : 0.0;
}
/// Returns the log likelihood of some data generated by a Weibull distribution
double weibull_log_likelihood(const vector<double>& x, double scale, double shape,
double location = 0.0);
/// Returns a local maximum of a function within an interval
double golden_section_search(const function<double(double)>& f, double x_min, double x_max,
double tolerance = 1e-8);
/// A shitty set of linear algebra functions
vector<vector<double>> transpose(const vector<vector<double>>& A);
vector<vector<double>> matrix_multiply(const vector<vector<double>>& A,
const vector<vector<double>>& B);
vector<double> matrix_multiply(const vector<vector<double>>& A,
const vector<double>& b);
vector<vector<double>> matrix_invert(const vector<vector<double>>& A);
/// Returns the coefficients of a regression (does not automatically compute constant)
vector<double> regress(const vector<vector<double>>& X, vector<double>& y);
/*
*********************************
* Code ported over from FreeBayes
*********************************
*/
// We use this slightly nonstandard type for our math. We wrap it so it's easy
// to change later.
using real_t = long double;
/**
* Calculate the natural log of the gamma function of the given argument.
*/
inline real_t gamma_ln(real_t x) {
real_t cofactors[] = {76.18009173,
-86.50532033,
24.01409822,
-1.231739516,
0.120858003E-2,
-0.536382E-5};
real_t x1 = x - 1.0;
real_t tmp = x1 + 5.5;
tmp -= (x1 + 0.5) * log(tmp);
real_t ser = 1.0;
for (int j=0; j<=5; j++) {
x1 += 1.0;
ser += cofactors[j]/x1;
}
real_t y = (-1.0 * tmp + log(2.50662827465 * ser));
return y;
}
/**
* Calculate the natural log of the factorial of the given integer. TODO:
* replace with a cache or giant lookup table from Freebayes.
*/
inline real_t factorial_ln(int n) {
if (n < 0) {
return (long double)-1.0;
}
else if (n == 0) {
return (long double)0.0;
}
else {
return gamma_ln(n + 1.0);
}
}
/**
* Raise a log probability to a power
*/
inline real_t pow_ln(real_t m, int n) {
return m * n;
}
/**
* Compute the number of ways to select k items from a collection of n
* distinguishable items, ignoring order. Returns the natural log of the
* (integer) result.
*/
inline real_t choose_ln(int n, int k) {
return factorial_ln(n) - (factorial_ln(k) + factorial_ln(n - k));
}
/**
* Compute the number of ways to select k_1, k_2, ... k_i items into i buckets
* from a collection of n distinguishable items, ignoring order. All of the
* items have to go into the buckets, so all k_i must sum to n. To compute
* choose you have to call this function with a 2-element vector, to represent
* the chosen and not-chosen buckets. Returns the natural log of the (integer)
* result.
*
* TODO: Turns out we don't actually need this for the ambiguous multinomial
* after all.
*/
inline real_t multinomial_choose_ln(int n, vector<int> k) {
// We use the product-of-binomial-coefficients approach from
// <https://en.wikipedia.org/wiki/Multinomial_theorem#Multinomial_coefficients>
real_t product_of_binomials_ln = 0;
// We sum up the bucket sizes as we go
int bucket_sum = 0;
for (auto& bucket_size : k) {
// Increment the size of what we choose from
bucket_sum += bucket_size;
// Choose this many
product_of_binomials_ln += choose_ln(bucket_sum, bucket_size);
}
// Make sure they actually gave us a proper decomposition of the items into
// buckets.
assert(bucket_sum == n);
return product_of_binomials_ln;
}
/**
* Compute the log probability of a Poisson-distributed process: observed events
* in an interval where expected events happen on average.
*/
inline real_t poisson_prob_ln(int observed, real_t expected) {
return log(expected) * (real_t) observed - expected - factorial_ln(observed);
}
/**
* Get the probability for sampling the counts in obs from a set of categories
* weighted by the probabilities in probs. Works for both double and real_t
* probabilities. Also works for binomials.
*/
template <typename ProbIn>
real_t multinomial_sampling_prob_ln(const vector<ProbIn>& probs, const vector<int>& obs) {
vector<real_t> factorials;
vector<real_t> probsPowObs;
factorials.resize(obs.size());
transform(obs.begin(), obs.end(), factorials.begin(), factorial_ln);
typename vector<ProbIn>::const_iterator p = probs.begin();
vector<int>::const_iterator o = obs.begin();
for (; p != probs.end() && o != obs.end(); ++p, ++o) {
probsPowObs.push_back(pow_ln(log(*p), *o));
}
// Use the collection sum defined in utility.hpp
return factorial_ln(sum(obs)) - sum(factorials) + sum(probsPowObs);
}
/**
* Compute the probability of having the given number of successes or fewer in
* the given number of trials, with the given success probability. Returns the
* resulting log probability.
*/
template <typename ProbIn>
real_t binomial_cmf_ln(ProbIn success_logprob, size_t trials, size_t successes) {
// Compute log probabilities for all cases
vector<real_t> case_logprobs;
if(successes > trials) {
return prob_to_logprob(0);
}
for(size_t considered_successes = 0; considered_successes <= successes; considered_successes++) {
// For every number of successes up to this one, add in the probability.
case_logprobs.push_back(choose_ln(trials, considered_successes) +
success_logprob * considered_successes +
logprob_invert(success_logprob) * (trials - considered_successes));
}
// Sum up all those per-case probabilities
return logprob_sum(case_logprobs);
}
/**
* Get the log probability for sampling the given value from a geometric
* distribution with the given success log probability. The geometric
* distribution is the distribution of the number of trials, with a given
* success probability, required to observe a single success.
*/
template <typename ProbIn>
real_t geometric_sampling_prob_ln(ProbIn success_logprob, size_t trials) {
return logprob_invert(success_logprob) * (trials - 1) + success_logprob;
}
/**
* Given a split of items across a certain number of categories, as ints between
* the two given bidirectional iterators, advance to the next split and return
* true. If there is no next split, leave the collection unchanged and return
* false.
*/
template<typename Iter>
bool advance_split(Iter start, Iter end) {
if (start == end) {
// Base case: we hit the end. No more possible splits.
#ifdef debug
cerr << "Not advancing empty split" << endl;
#endif
return false;
} else {
#ifdef debug
cerr << "Trying to advance split with " << *start << " items in first category" << endl;
#endif
// Try advancing what comes after us.
auto next = start;
++next;
if (advance_split(next, end)) {
// It worked.
#ifdef debug
cerr << "Advanced child split" << endl;
#endif
return true;
}
#ifdef debug
cerr << "Could not advance child split" << endl;
#endif
// If that didn't work, try moving an item from here to what comes after us.
// We also need to reset what comes after us to its initial state of everything in the first category.
// This is easy because we know everything in what comes after us has made its way to the end.
if (*start != 0 && next != end) {
// We have something to move
// Do the reset so everything after us is in the first category
// after us.
auto next_to_last = end;
--next_to_last;
#ifdef debug
cerr << "Want to move " << *next_to_last << " items to next which has " << *next << " and also move one from start which has " << *start << endl;
#endif
if (next_to_last != next) {
(*next) += *next_to_last;
*next_to_last = 0;
}
(*start)--;
(*next)++;
#ifdef debug
cerr << "Reset child split to have " << *next << " items vs. our " << *start << endl;
#endif
return true;
}
// If that didn't work, we're out of stuff to do.
#ifdef debug
cerr << "Could not advance or reset child split" << endl;
#endif
return false;
}
}
/**
* Get the log probability for sampling any actual set of category counts that
* is consistent with the constraints specified by obs, using the per-category
* probabilities defined in probs.
*
* Obs maps from a vector of per-category flags (called a "class") to a number
* of items that might be in any of the flagged categories.
*
* For example, if there are two equally likely categories, and one item flagged
* as potentially from either category, the probability of sampling a set of
* category counts consistent with that constraint is 1. If instead there are
* three equally likely categories, and one item flagged as potentially from two
* of the three but not the third, the probability of sampling a set of category
* counts consistent with that constraint is 2/3.
*/
template<typename ProbIn>
real_t multinomial_censored_sampling_prob_ln(const vector<ProbIn>& probs, const unordered_map<vector<bool>, int>& obs) {
// We fill this with logprobs for all the different cases and then sum them
// up.
vector<real_t> case_logprobs;
// We have a state. We advance this state until we can't anymore.
//
// The state is, for each ambiguity class, a vector of length equal to
// the number of set bits in the valence, and sum equal to the number of
// reads int he category.
//
// We start with all the reads in the first spot in each class, and
// advance/reset until we have iterated over all combinations of category
// assignments for all classes.
unordered_map<vector<bool>, vector<int>> splits_by_class;
// Prepare the state
for (auto& kv : obs) {
// For each input class
if (kv.second == 0) {
// No reads are in this class, so we can skip it.
continue;
}
// Work out if it actually matches any categories
bool has_any_categories = false;
for (const auto& bit : kv.first) {
if (bit) {
has_any_categories = true;
break;
}
}
if (!has_any_categories) {
// There are reads and they match nothing.
// So this case is impossible.
return prob_to_logprob(0);
}
// Otherwise there are reads and they match something.
// For each class, find the vector we will use to describe its read-to-
// category assignments.
auto& class_state = splits_by_class[kv.first];
for (const auto& bit : kv.first) {
// Allocate a spot for each set bit
if (bit) {
class_state.push_back(0);
}
}
// Drop all the reads in the first category
class_state.front() = kv.second;
}
if (splits_by_class.empty()) {
// There are no classes with any reads.
// P(nothing happened) = 1.
return prob_to_logprob(1);
}
// Now we loop over all the combinations of class states using a stack thing.
list<decltype(splits_by_class)::iterator> stack;
// And maintain this vector of category counts for the state we are in. We
// incrementally update it so we aren't always looping over all the classes
// to rebuild it.
vector<int> category_counts(probs.size());
// We have a function to add in the contribution of a class's state
auto add_class_state = [&](const pair<vector<bool>, vector<int>>& class_state) {
auto count_it = class_state.second.begin();
for (size_t i = 0; i < category_counts.size(); i++) {
// For each category
if (class_state.first.at(i)) {
// If this ambiguity class touches it
assert(count_it != class_state.second.end());
// Add in the state's count
category_counts.at(i) += *count_it;
// And consume that state entry
++count_it;
}
}
assert(count_it == class_state.second.end());
};
// And a function to back it out again
auto remove_class_state = [&](const pair<vector<bool>, vector<int>>& class_state) {
auto count_it = class_state.second.begin();
for (size_t i = 0; i < category_counts.size(); i++) {
// For each category
if (class_state.first.at(i)) {
// If this ambiguity class touches it
assert(count_it != class_state.second.end());
// Back out the state's count
category_counts.at(i) -= *count_it;
// And consume that state entry
++count_it;
}
}
assert(count_it == class_state.second.end());
};
for (auto it = splits_by_class.begin(); it != splits_by_class.end(); ++it) {
// Populate the stack with everything
stack.push_back(it);
// And make sure the category counts are up to date.
add_class_state(*it);
}
while (!stack.empty()) {
// Emit the current state
#ifdef debug
cerr << "Category counts:" << endl;
for (auto& count : category_counts) {
cerr << count << endl;
}
#endif
auto case_logprob = multinomial_sampling_prob_ln(probs, category_counts);
#ifdef debug
cerr << "Case probability: " << logprob_to_prob(case_logprob) << endl;
#endif
// Put in the logprob for this case.
case_logprobs.push_back(case_logprob);
while (!stack.empty()) {
// See if we can advance what's at the bottom of the stack
// First clear it out of the category counts.
remove_class_state(*stack.back());
if (advance_split(stack.back()->second.begin(), stack.back()->second.end())) {
// We advanced it successfully.
#ifdef debug
cerr << "Advanced class at stack depth " << stack.size() - 1 << endl;
#endif
// Put it back in the category counts
add_class_state(*stack.back());
// We finally found something to advance, so stop ascending the stack.
break;
} else {
#ifdef debug
cerr << "Could not advanced class at stack depth " << stack.size() - 1 << endl;
#endif
// Pop off the back of the stack.
stack.pop_back();
// Keep looking up
}
}
if (!stack.empty()) {
// We found *something* to advance and haven't finished.
// Now fill in the whole stack again with the first split for every category.
auto it = stack.back();
++it;
while (it != splits_by_class.end()) {
// Reset the split to all 0s except for the first entry.
for (auto& entry : it->second) {
entry = 0;
}
it->second.front() = obs.at(it->first);
// Populate the stack with the next class
stack.push_back(it);
// And make sure the category counts are up to date.
add_class_state(*it);
#ifdef debug
cerr << "Reset class at stack depth " << stack.size() - 1 << endl;
#endif
// Look for the next class
++it;
}
}
// Otherwise we have finished looping over everything and so we should leave the stack empty.
}
// Sum up all those per-case probabilities
return logprob_sum(case_logprobs);
}
// These handy sampling distribution implementations (uniform_real_distribution
// and normal_distribution) matching the C++ <random> API are copied and
// adapted from code at https://stackoverflow.com/a/34962942
template<typename T = double>
class uniform_real_distribution {
public:
typedef T result_type;
uniform_real_distribution(T _a = 0.0, T _b = 1.0) : m_a(_a), m_b(_b) {
// Nothing to do!
}
void reset() {
// Also nothing to do!
}
template<class Generator>
T operator()(Generator &_g) {
double dScale = (m_b - m_a) / ((T)(_g.max() - _g.min()) + (T)1);
return (_g() - _g.min()) * dScale + m_a;
}
T a() const {
return m_a;
}
T b() const {
return m_b;
}
protected:
T m_a;
T m_b;
};
template<typename T = double>
class normal_distribution {
public:
typedef T result_type;
normal_distribution(T _mean = 0.0, T _stddev = 1.0) : m_mean(_mean), m_stddev(_stddev) {
// Nothing to do!
}
void reset() {
m_distU1.reset();
}
template<class Generator>
T operator()(Generator &_g) {
// Use Box-Muller algorithm
const double pi = 3.14159265358979323846264338327950288419716939937511;
double u1 = m_distU1(_g);
double u2 = m_distU1(_g);
double r = sqrt(-2.0 * log(u1));
return m_mean + m_stddev * r * sin(2.0 * pi * u2);
}
T mean() const {
return m_mean;
}
T stddev() const {
return m_stddev;
}
protected:
T m_mean;
T m_stddev;
vg::uniform_real_distribution<T> m_distU1;
};
template<typename T = double>
class truncated_normal_distribution {
public:
typedef T result_type;
truncated_normal_distribution(T _mu = 0.0,
T _sigma = 1.0,
T _a = -numeric_limits<double>::max() / 2.0,
T _b = numeric_limits<double>::max() / 2.0)
: m_mu(_mu), m_sigma(_sigma), m_alpha((_a - _mu) / _sigma), m_beta((_b - _mu) / _sigma)
{
assert(m_sigma > 0.0);
assert(m_alpha < m_beta);
}
void reset() {
m_distU1.reset();
}
template<class Generator>
T operator()(Generator &_g) {
T u = m_distU1(_g);
return m_mu + m_sigma * Phi_inv(u * Phi(m_beta) + (1.0 - u) * Phi(m_alpha));
}
T mean() const {
return m_mu + m_sigma * A();
}
T stddev() const {
T b = (m_alpha * normal_pdf(m_alpha) - m_beta * normal_pdf(m_beta)) / Z();
T a = A();
return m_sigma * std::sqrt(1.0 + b - a * a);
}
T density(T x) const {
T z = (x - m_mu) / m_sigma;
if (z >= m_alpha && z <= m_beta) {
return normal_pdf(z) / (m_sigma * Z());
}
else {
return 0.0;
}
}
T cumul(T x) const {
T z = (x - m_mu) / m_sigma;
if (z >= m_alpha && z <= m_beta) {
return (Phi(z) - Phi(m_alpha)) / Z();
}
else if (z > m_beta) {
return 1.0;
}
else {
return 0.0;
}
}
protected:
T Z() const {
return Phi(m_beta) - Phi(m_alpha);
}
T A() const {
return (normal_pdf(m_alpha) - normal_pdf(m_beta)) / Z();
}
T m_mu;
T m_sigma;
T m_alpha;
T m_beta;
vg::uniform_real_distribution<T> m_distU1;
};
/// We use this widerer to widen the output of a PRNG that generates only
/// numbers in a smaller range so they cover a wider int type.
template<typename PRNG, typename OutType>
class WideningPRNG {
public:
using result_type = OutType;
WideningPRNG(PRNG& to_widen) : base(to_widen) {
// Nothing to do
}
OutType min() const {
return numeric_limits<OutType>::min();
}
OutType max() const {
return numeric_limits<OutType>::max();
}
/// Generate a random number filling all OutType's bits with random bits.
OutType operator()() {
static_assert(is_unsigned<OutType>::value, "OutType must be an unsigned int type");
static_assert(numeric_limits<long long unsigned int>::digits >= numeric_limits<OutType>::digits, "OutType is too wide to bit count in");
// Work out how wide the base PRNG range is, in total (counting the inclusive bounds)
// We assume that this will fit in the wider type we are trying to fill.
// Otherwise you don't need this class.
OutType base_range = (OutType) base.max() - (OutType) base.min() + 1;
// The base range must be 1 bit at least. Otherwise we will make no progress.
assert(base_range >= 2);
// Count unset leading bits with this useful compiler builtin.
// Hope your compiler has it.
auto unused_bits = __builtin_clzll(base_range);
auto used_bits = numeric_limits<long long unsigned int>::digits - unused_bits;
// Get just that max used bit
OutType used_bit = 1 << (used_bits - 1);
// If a generated number from the RNG has this bit flag in it, it has
// passed the largest complete power of 2 it can make and needs to be
// rerolled.
OutType reroll_flag = 0;
if (base_range > used_bit) {
// We don't cover a power of 2 exactly.
// If the high bit is set we're going to need to reroll.
reroll_flag = used_bit;
// Lop off a bit for computing how many bits we actually got.
used_bit = used_bit >> 1;
used_bits--;
}
assert(used_bits > 0);
OutType generated = 0;
int generated_bits = 0;
while (generated_bits < numeric_limits<OutType>::digits) {
// Shift what's there up to make room for new bits.
generated = generated << used_bits;
OutType new_bits;
do {
// Generate bits until we're below the largest power of 2 we can generate above, if any.
new_bits = (OutType) base() - (OutType) base.min();
} while (!(new_bits & reroll_flag) && reroll_flag);
// Add in the new bits and record that they are there.
generated |= new_bits;
generated_bits += used_bits;
}
// Now we have a full type full of bits.
return generated;
}
protected:
PRNG& base;
};
/// This uniform_int_distribution implementation is based on the
/// UniformRealDistribution from https://stackoverflow.com/a/34962942
template<typename T = int>
class uniform_int_distribution {
public:
typedef T result_type;
uniform_int_distribution(T _a = 0, T _b = numeric_limits<T>::max()) : m_a(_a), m_b(_b) {
// Make sure inclusive bounds are valid
assert(_b >= _a);
}
void reset() {
// Also nothing to do!
}
template<class Generator>
T operator()(Generator &_g) {
#ifdef debug
cerr << "Source range " << _g.min() << " to " << _g.max() << endl;
cerr << "Dest range " << m_a << " to " << m_b << endl;
#endif
// Define an unsigned widest type to work in
using WorkType = typename make_unsigned<typename common_type<typename Generator::result_type, T>::type>::type;
// How big are the source and destination ranges?
// Since they are so big and inclusive we can't always hold their real sizes, so hold size-1
WorkType source_range_size_minus_1 = (WorkType) _g.max() - (WorkType) _g.min();
WorkType dest_range_size_minus_1 = (WorkType) m_b - (WorkType) m_a;
if (source_range_size_minus_1 >= dest_range_size_minus_1) {
// The generator's result is going to be wide enough
return generate_from_wide_generator(_g);
} else {
// The hard way is generating a bigger range from a smaller range.
// Wrap the generator in something to widen it to our work type
// and recurse.
WideningPRNG<Generator, WorkType> widened(_g);
// Generate with that, which had better be wide enough
return generate_from_wide_generator(widened);
}
}
T a() const {
return m_a;
}
T b() const {
return m_b;
}
protected:
/// Generate a result when we know the generator will produce a result on a
/// range as big as or bigger than ours.
template<class Generator>
T generate_from_wide_generator(Generator &_g) {
// Jordan's strategy: discard anything above the highest multiple of your range, then mod down to your range.
#ifdef debug
cerr << "Source range " << _g.min() << " to " << _g.max() << endl;
cerr << "Dest range " << m_a << " to " << m_b << endl;
#endif
// Define an unsigned widest type to work in
using WorkType = typename make_unsigned<typename common_type<typename Generator::result_type, T>::type>::type;
// How big are the source and destination ranges?
// Since they are so big and inclusive we can't always hold their real sizes, so hold size-1
WorkType source_range_size_minus_1 = (WorkType) _g.max() - (WorkType) _g.min();
WorkType dest_range_size_minus_1 = (WorkType) m_b - (WorkType) m_a;
// We must be generating a smaller range from a bigger rnage here.
assert(source_range_size_minus_1 >= dest_range_size_minus_1);
if (dest_range_size_minus_1 == source_range_size_minus_1) {
// Ranges are the same size. No real work to do.
return (WorkType) _g() - (WorkType) _g.min() + (WorkType) m_a;
}
// Otherwise the ranges differ in size. Which means the dest range must
// be smaller. Which means the dest range's real size is representable.
WorkType dest_range_size = dest_range_size_minus_1 + 1;
// Find how many numbers we have to clip off of the top of the source
// range so the rest can be covered by tiled destination ranges.
WorkType remainder = source_range_size_minus_1 % dest_range_size;
// Change the remainder from source_range_size_minus_1 to the remainder for the actual source range size
remainder = (remainder + 1) % dest_range_size;
if (remainder == 0) {
// We perfectly tiled the source range
return ((WorkType) _g() - (WorkType) _g.min()) % dest_range_size + (WorkType) m_a;
}
// Otherwise there are some values we need to reject
// Sample a value until we get one that isn't too close to the top of the range.
WorkType sampled;
do {
sampled = (WorkType) _g();
} while (_g.max() - sampled < remainder);
// Convert to destination range.
return (sampled - (WorkType) _g.min()) % dest_range_size + m_a;
}
T m_a;
T m_b;
};
/// We provide a partial discrete_distribution implementation that is just the parts we need
template<typename T = int>
class discrete_distribution {
public:
typedef T result_type;
typedef double param_type;
template<class InputIt>
discrete_distribution(InputIt first, InputIt last) : m_weights{first, last} {
// We can't use an empty weights vector
assert(!m_weights.empty());
// Compute partial sums
std::partial_sum(m_weights.begin(), m_weights.end(), std::back_inserter(m_sums));
}
discrete_distribution(initializer_list<double> weights = {1}) : discrete_distribution(weights.begin(), weights.end()) {
// Nothing to do
}
void reset() {
// Also nothing to do!
}
template<class Generator>
T operator()(Generator &_g) {
// Set up to generate a double from 0 to max weight
vg::uniform_real_distribution<double> backing_dist(0, m_sums.back());
// Do it and find which cumumative sum is greater than it
auto winning_iterator = std::lower_bound(m_sums.begin(), m_sums.end(), backing_dist(_g));
// Find its category number and return that.
return winning_iterator - m_sums.begin();
}
protected:
// If we ever want to implement the params stuff we need the weights stored.
vector<double> m_weights;
vector<double> m_sums;
};
// ewen's allele sampling distribution. for use in genotype prior (as in freebayes)
// gives Pr(a1, ...,an;theta) where ai is the number of sampled haplotypes (out of n) that
// have i different alleles at a given locus. theta is the population mutation rate.
// ex: for a single diploid genotype, a={2,0} = heterozygous: 2 alleles occur once.
// a={0,1} = homozygous: 1 allele occurs twice.
//
// https://en.wikipedia.org/wiki/Ewens%27s_sampling_formula
// https://github.com/ekg/freebayes/blob/master/src/Ewens.cpp#L17
inline real_t ewens_af_prob_ln(const vector<int>& a, real_t theta) {
// first term (wrt formula as stated on wikipedia)
// n! / (theta * (theta + 1) * ... (theta + n - 1))
real_t term1_num_ln = factorial_ln(a.size());
real_t term1_denom_ln = 0.;
for (int i = 0; i < a.size(); ++i) {
term1_denom_ln += log(theta + i);
}
real_t term1_ln = term1_num_ln - term1_denom_ln;
// second term
// prod [ (theta^aj) / (j^aj * aj!)
real_t term2_ln = 0.;
for (int j = 0; j < a.size(); ++j) {
real_t num = log(pow(theta, a[j]));
real_t denom = log(pow(1. + j, a[j]) + factorial_ln(a[j]));
term2_ln += num - denom;
}
return term1_ln + term2_ln;
}
}
#endif
|
//=================================================================================================
/*!
// \file src/classic/TDMatDVecMult.cpp
// \brief Source file for the classic transpose dense matrix/dense vector multiplication kernel
//
// Copyright (C) 2012-2020 Klaus Iglberger - All Rights Reserved
//
// This file is part of the Blaze library. You can redistribute it and/or modify it under
// the terms of the New (Revised) BSD License. Redistribution and use in source and binary
// forms, with or without modification, are permitted provided that the following conditions
// are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of
// conditions and the following disclaimer.
// 2. 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.
// 3. Neither the names of the Blaze development group 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.
*/
//=================================================================================================
//*************************************************************************************************
// Includes
//*************************************************************************************************
#include <iostream>
#include <blaze/util/Timing.h>
#include <blazemark/classic/init/Matrix.h>
#include <blazemark/classic/init/Vector.h>
#include <blazemark/classic/TDMatDVecMult.h>
#include <blazemark/classic/Matrix.h>
#include <blazemark/classic/Vector.h>
#include <blazemark/system/Config.h>
namespace blazemark {
namespace classic {
//=================================================================================================
//
// KERNEL FUNCTIONS
//
//=================================================================================================
//*************************************************************************************************
/*!\brief Classic transpose dense matrix/dense vector multiplication kernel.
//
// \param N The number of rows and columns of the matrix and the size of the vector.
// \param steps The number of iteration steps to perform.
// \return Minimum runtime of the kernel function.
//
// This kernel function implements the transpose dense matrix/dense vector multiplication by
// means of classic C++ operator overloading.
*/
double tdmatdvecmult( size_t N, size_t steps )
{
using ::blazemark::element_t;
::blaze::setSeed( seed );
::blazemark::classic::Matrix<element_t,true> A( N, N );
::blazemark::classic::Vector<element_t> a( N ), b( N );
::blaze::timing::WcTimer timer;
init( A );
init( a );
b = A * a;
for( size_t rep=0UL; rep<reps; ++rep )
{
timer.start();
for( size_t step=0UL; step<steps; ++step ) {
b = A * a;
}
timer.end();
if( b.size() != N )
std::cerr << " Line " << __LINE__ << ": ERROR detected!!!\n";
if( timer.last() > maxtime )
break;
}
const double minTime( timer.min() );
const double avgTime( timer.average() );
if( minTime * ( 1.0 + deviation*0.01 ) < avgTime )
std::cerr << " Classic kernel 'tdmatdvecmult': Time deviation too large!!!\n";
return minTime;
}
//*************************************************************************************************
} // namespace classic
} // namespace blazemark
|
//Radix Sort for strings
#include <iostream>
using namespace std;
#include "Sort.h"
void write(string a[],int n)
{
for (int i=0;i<n;i++)
cout <<' '<<a[i];
}
/*void radixS(string a[],int low,int high,int radix,int digits)
{
LinkedQueue<int> q[radix];
int factor = 1;
int digit;
int index;
for (int k=0;k<digits;++k)
{
for (int i=low;i<=high;++i)
{
digit = (a[i]/factor)%radix;
(q[digit]).enqueue(a[i]);
}
index = low;
for (int d=0;d<radix;++d)
while(!(q[d]).empty())
a[index++] = (q[d]).dequeue();
factor = factor*radix;
}
}*/
int main()
{
int n = 25;
string a[] = {"xie","chen","mo","zhao","luo","cheng","xie","hai","lei","zi","mo","pan","sheng","ti","ai","dong","you",
"sun","wei","song","xiang","wen","song","jing","xia"};
write(a,n);
//quickSort(a,0,n-1);
insertionSort(a,0,n-1);
//mergeSort(a,0,n-1);
//bubbleSort(a,0,n-1);
//selectionSort(a,0,n-1);
//radixS(a,0,n-1,26,5);
cout<<endl;
write(a,n);cout<<endl;
return 0;
}
|
// WCCOAJavaConnection.hxx -- WCCOAJava HmiConnection-Class
#ifndef _WCCOAJavaCONNECTION_H_
#define _WCCOAJavaCONNECTION_H_
#include <HmiConnection.hxx>
class WCCOAJavaConnection : public HmiConnection
{
public:
WCCOAJavaConnection(DpIdType id);
~WCCOAJavaConnection();
/** the open connection callback.
* possible state changes are HMI_CS_Failure and HMI_CS_Connected
*/
virtual void open();
/** the close connection callback.
* there are no active state changes possible here
*/
virtual void close();
/** the open server side callback.
* possible state changes are HMI_CS_Failure and HMI_CS_Listening
*/
virtual void openServer();
/** the close server side callback.
* there are no active state changes possible here
*/
virtual void closeServer();
/** the general query callback.
* this callback is triggered whenever a general query should be done.
* the default implementation issues singleQuery calls for all input and IO elements.
*/
virtual void doGeneralQuery();
/** the internal general query callback.
* this callback is triggered whenever an internal general query should be done.
* the default implementation issues write requests calls for all output and IO elements.
*/
virtual void doInternalGeneralQuery();
/** the alert sync callback.
* this callback is triggered whenever a general alert sync should be done.
*/
virtual void doAlertSync();
/** the connection error check callback.
* this callback is triggered periodically to check for connection faults.
* returning true will cause the connection to be closed.
*/
virtual bool isConnError();
/** This function is called for a single data request or when polling data.
* The HWObject contains the PeriphAddress string. Find the corresponding hardware address, ask
* for the data. The objPtr must not be deleted.
* @param objPtr the HWObject to fill with data
* @classification public use, overload
*/
virtual void singleQuery(HWObject *objPtr);
/** This function is called for each fully converted HWObject. The data inside it has
* been processed according to the choosen transformation. All you have to do is to determine the
* corresponding hardware address and to transmit the data packet. The objPtr must not be deleted.
* @param objPtr pointer to HW object
* @classification public use, overload
*/
virtual PVSSboolean writeData(HWObject *objPtr);
/** Working procedure. This function is called repeatedly by the DrvManager mainLoop() to check the
* hardware for any incoming data. when data is ready for accepting you should pack the data into a HWObject and
* use the DrvManager toDp() function to transmit the data to the pvss2 system.
* @warning beware of staying inside this function too long because no messages can go in and
* out of the driver as long as you keep control!
* @classification public use, overload
*/
virtual void workFunc();
};
#endif
|
/**
* Copyright 2011-2015 Quickstep Technologies LLC.
* Copyright 2015 Pivotal Software, 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.
**/
#ifndef QUICKSTEP_THREADING_WINDOWS_THREAD_HPP_
#define QUICKSTEP_THREADING_WINDOWS_THREAD_HPP_
#include "threading/Thread.hpp"
#include "threading/WinThreadsAPI.hpp"
#include "utility/Macros.hpp"
namespace quickstep {
namespace threading_windows_internal {
class WindowsExecHelper {
public:
static DWORD WINAPI executeRunMethodForThread(LPVOID thread_ptr) {
static_cast<ThreadInterface*>(thread_ptr)->run();
return 0;
}
};
} // namespace threading_windows_internal
/** \addtogroup Threading
* @{
*/
/**
* @brief Implementation of Thread using MS Windows threads.
**/
class ThreadImplWindows : public ThreadInterface {
public:
ThreadImplWindows() {
thread_handle_ = CreateThread(nullptr,
0,
threading_windows_internal::WindowsExecHelper::executeRunMethodForThread,
this,
CREATE_SUSPENDED,
nullptr);
}
virtual ~ThreadImplWindows() {
CloseHandle(thread_handle_);
}
inline void start() {
ResumeThread(thread_handle_);
}
inline void join() {
WaitForSingleObject(thread_handle_, INFINITE);
}
private:
HANDLE thread_handle_;
DISALLOW_COPY_AND_ASSIGN(ThreadImplWindows);
};
typedef ThreadImplWindows Thread;
/** @} */
} // namespace quickstep
#endif // QUICKSTEP_THREADING_WINDOWS_THREAD_HPP_
|
// Copyright 2019 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 "content/browser/file_system_access/file_system_access_manager_impl.h"
#include <string>
#include <utility>
#include <vector>
#include "base/callback_helpers.h"
#include "base/files/file_util.h"
#include "base/files/scoped_temp_dir.h"
#include "base/run_loop.h"
#include "base/test/bind.h"
#include "base/test/gmock_callback_support.h"
#include "base/test/task_environment.h"
#include "content/browser/file_system_access/file_system_access_data_transfer_token_impl.h"
#include "content/browser/file_system_access/file_system_access_directory_handle_impl.h"
#include "content/browser/file_system_access/file_system_access_file_handle_impl.h"
#include "content/browser/file_system_access/file_system_access_transfer_token_impl.h"
#include "content/browser/file_system_access/fixed_file_system_access_permission_grant.h"
#include "content/browser/file_system_access/mock_file_system_access_permission_context.h"
#include "content/public/test/browser_task_environment.h"
#include "content/public/test/test_browser_context.h"
#include "content/public/test/test_web_contents_factory.h"
#include "content/test/test_render_frame_host.h"
#include "content/test/test_web_contents.h"
#include "mojo/public/c/system/data_pipe.h"
#include "mojo/public/cpp/bindings/pending_remote.h"
#include "mojo/public/cpp/bindings/remote.h"
#include "mojo/public/cpp/system/data_pipe_drainer.h"
#include "mojo/public/cpp/test_support/test_utils.h"
#include "mojo/public/mojom/base/file_info.mojom.h"
#include "storage/browser/blob/blob_storage_context.h"
#include "storage/browser/file_system/external_mount_points.h"
#include "storage/browser/test/async_file_test_helper.h"
#include "storage/browser/test/test_file_system_context.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/blink/public/mojom/blob/blob.mojom.h"
#include "third_party/blink/public/mojom/blob/serialized_blob.mojom.h"
#include "third_party/blink/public/mojom/file_system_access/file_system_access_data_transfer_token.mojom.h"
#include "third_party/blink/public/mojom/file_system_access/file_system_access_manager.mojom-forward.h"
#include "third_party/blink/public/mojom/file_system_access/file_system_access_manager.mojom-shared.h"
namespace content {
namespace {
// A helper class that can be passed to mojo::DataPipeDrainer to read the
// information coming through a data pipe as a string and call a callback
// on completion.
class StringDataPipeReader : public mojo::DataPipeDrainer::Client {
public:
StringDataPipeReader(std::string* data_out, base::OnceClosure done_callback)
: data_out_(data_out), done_callback_(std::move(done_callback)) {}
void OnDataAvailable(const void* data, size_t num_bytes) override {
data_out_->append(static_cast<const char*>(data), num_bytes);
}
void OnDataComplete() override { std::move(done_callback_).Run(); }
private:
std::string* data_out_;
base::OnceClosure done_callback_;
};
// Reads the incoming data in `pipe` as an `std::string`. Blocks until all the
// data has been read.
std::string ReadDataPipe(mojo::ScopedDataPipeConsumerHandle pipe) {
base::RunLoop loop;
std::string data;
StringDataPipeReader reader(&data, loop.QuitClosure());
mojo::DataPipeDrainer drainer(&reader, std::move(pipe));
loop.Run();
return data;
}
// Returns the contents of the file referred to by `file_remote` as a
// `std::string`.
std::string ReadStringFromFileRemote(
mojo::Remote<blink::mojom::FileSystemAccessFileHandle> file_remote) {
base::RunLoop await_get_blob;
mojo::Remote<blink::mojom::Blob> blob;
file_remote->AsBlob(base::BindLambdaForTesting(
[&](blink::mojom::FileSystemAccessErrorPtr result,
const base::File::Info& info,
blink::mojom::SerializedBlobPtr received_blob) {
EXPECT_EQ(result->status, blink::mojom::FileSystemAccessStatus::kOk);
EXPECT_FALSE(received_blob.is_null());
blob.Bind(std::move(received_blob->blob));
await_get_blob.Quit();
}));
await_get_blob.Run();
if (!blob) {
return "";
}
mojo::ScopedDataPipeConsumerHandle consumer_handle;
mojo::ScopedDataPipeProducerHandle producer_handle;
CHECK_EQ(mojo::CreateDataPipe(nullptr, producer_handle, consumer_handle),
MOJO_RESULT_OK);
blob->ReadAll(std::move(producer_handle), mojo::NullRemote());
return ReadDataPipe(std::move(consumer_handle));
}
constexpr char kTestMountPoint[] = "testfs";
} // namespace
using base::test::RunOnceCallback;
using blink::mojom::PermissionStatus;
using HandleType = content::FileSystemAccessPermissionContext::HandleType;
using PathType = content::FileSystemAccessPermissionContext::PathType;
using PathInfo = content::FileSystemAccessPermissionContext::PathInfo;
class FileSystemAccessManagerImplTest : public testing::Test {
public:
FileSystemAccessManagerImplTest()
: task_environment_(base::test::TaskEnvironment::MainThreadType::IO) {}
void SetUp() override {
ASSERT_TRUE(dir_.CreateUniqueTempDir());
ASSERT_TRUE(dir_.GetPath().IsAbsolute());
file_system_context_ = storage::CreateFileSystemContextForTesting(
/*quota_manager_proxy=*/nullptr, dir_.GetPath());
// Register an external mount point to test support for virtual paths.
// This maps the virtual path a native local path to make sure an external
// path round trips as an external path, even if the path resolves to a
// local path.
storage::ExternalMountPoints::GetSystemInstance()->RegisterFileSystem(
kTestMountPoint, storage::kFileSystemTypeLocal,
storage::FileSystemMountOption(), dir_.GetPath());
chrome_blob_context_ = base::MakeRefCounted<ChromeBlobStorageContext>();
chrome_blob_context_->InitializeOnIOThread(base::FilePath(),
base::FilePath(), nullptr);
manager_ = base::MakeRefCounted<FileSystemAccessManagerImpl>(
file_system_context_, chrome_blob_context_, &permission_context_,
/*off_the_record=*/false);
web_contents_ = web_contents_factory_.CreateWebContents(&browser_context_);
static_cast<TestWebContents*>(web_contents_)->NavigateAndCommit(kTestURL);
manager_->BindReceiver(kBindingContext,
manager_remote_.BindNewPipeAndPassReceiver());
}
void TearDown() override {
storage::ExternalMountPoints::GetSystemInstance()->RevokeFileSystem(
kTestMountPoint);
// TODO(mek): Figure out what code is leaking open files, and uncomment this
// to prevent further regressions.
// ASSERT_TRUE(dir_.Delete());
}
template <typename HandleType>
PermissionStatus GetPermissionStatusSync(bool writable, HandleType* handle) {
PermissionStatus result;
base::RunLoop loop;
handle->GetPermissionStatus(
writable, base::BindLambdaForTesting([&](PermissionStatus status) {
result = status;
loop.Quit();
}));
loop.Run();
return result;
}
mojo::Remote<blink::mojom::FileSystemAccessDirectoryHandle>
GetHandleForDirectory(const base::FilePath& path) {
auto grant = base::MakeRefCounted<FixedFileSystemAccessPermissionGrant>(
FixedFileSystemAccessPermissionGrant::PermissionStatus::GRANTED, path);
EXPECT_CALL(permission_context_,
GetReadPermissionGrant(
kTestOrigin, path, HandleType::kDirectory,
FileSystemAccessPermissionContext::UserAction::kOpen))
.WillOnce(testing::Return(grant));
EXPECT_CALL(permission_context_,
GetWritePermissionGrant(
kTestOrigin, path, HandleType::kDirectory,
FileSystemAccessPermissionContext::UserAction::kOpen))
.WillOnce(testing::Return(grant));
blink::mojom::FileSystemAccessEntryPtr entry =
manager_->CreateDirectoryEntryFromPath(
kBindingContext, FileSystemAccessEntryFactory::PathType::kLocal,
path, FileSystemAccessPermissionContext::UserAction::kOpen);
return mojo::Remote<blink::mojom::FileSystemAccessDirectoryHandle>(
std::move(entry->entry_handle->get_directory()));
}
FileSystemAccessTransferTokenImpl* SerializeAndDeserializeToken(
mojo::PendingRemote<blink::mojom::FileSystemAccessTransferToken>
token_remote) {
std::vector<uint8_t> serialized;
base::RunLoop serialize_loop;
manager_->SerializeHandle(
std::move(token_remote),
base::BindLambdaForTesting([&](const std::vector<uint8_t>& bits) {
EXPECT_FALSE(bits.empty());
serialized = bits;
serialize_loop.Quit();
}));
serialize_loop.Run();
manager_->DeserializeHandle(kTestOrigin, serialized,
token_remote.InitWithNewPipeAndPassReceiver());
base::RunLoop resolve_loop;
FileSystemAccessTransferTokenImpl* result;
manager_->ResolveTransferToken(
std::move(token_remote),
base::BindLambdaForTesting(
[&](FileSystemAccessTransferTokenImpl* token) {
result = token;
resolve_loop.Quit();
}));
resolve_loop.Run();
return result;
}
void GetEntryFromDataTransferTokenFileTest(
const base::FilePath& file_path,
FileSystemAccessEntryFactory::PathType path_type,
const std::string& expected_file_contents) {
// Create a token representing a dropped file at `file_path`.
mojo::PendingRemote<blink::mojom::FileSystemAccessDataTransferToken>
token_remote;
manager_->CreateFileSystemAccessDataTransferToken(
path_type, file_path, kBindingContext.process_id(),
token_remote.InitWithNewPipeAndPassReceiver());
// Expect permission requests when the token is sent to be redeemed.
EXPECT_CALL(
permission_context_,
GetReadPermissionGrant(
kTestOrigin, file_path, HandleType::kFile,
FileSystemAccessPermissionContext::UserAction::kDragAndDrop))
.WillOnce(testing::Return(allow_grant_));
EXPECT_CALL(
permission_context_,
GetWritePermissionGrant(
kTestOrigin, file_path, HandleType::kFile,
FileSystemAccessPermissionContext::UserAction::kDragAndDrop))
.WillOnce(testing::Return(allow_grant_));
// Attempt to resolve `token_remote` and store the resulting
// FileSystemAccessFileHandle in `file_remote`.
base::RunLoop await_token_resolution;
blink::mojom::FileSystemAccessEntryPtr file_system_access_entry;
manager_remote_->GetEntryFromDataTransferToken(
std::move(token_remote),
base::BindLambdaForTesting([&](blink::mojom::FileSystemAccessEntryPtr
returned_file_system_access_entry) {
file_system_access_entry =
std::move(returned_file_system_access_entry);
await_token_resolution.Quit();
}));
await_token_resolution.Run();
ASSERT_FALSE(file_system_access_entry.is_null());
ASSERT_TRUE(file_system_access_entry->entry_handle->is_file());
mojo::Remote<blink::mojom::FileSystemAccessFileHandle> file_handle(
std::move(file_system_access_entry->entry_handle->get_file()));
// Check to see if the resulting FileSystemAccessFileHandle can read the
// contents of the file at `file_path`.
EXPECT_EQ(ReadStringFromFileRemote(std::move(file_handle)),
expected_file_contents);
}
void GetEntryFromDataTransferTokenDirectoryTest(
const base::FilePath& dir_path,
FileSystemAccessEntryFactory::PathType path_type,
const std::string& expected_child_file_name) {
mojo::PendingRemote<blink::mojom::FileSystemAccessDataTransferToken>
token_remote;
manager_->CreateFileSystemAccessDataTransferToken(
path_type, dir_path, kBindingContext.process_id(),
token_remote.InitWithNewPipeAndPassReceiver());
// Expect permission requests when the token is sent to be redeemed.
EXPECT_CALL(
permission_context_,
GetReadPermissionGrant(
kTestOrigin, dir_path, HandleType::kDirectory,
FileSystemAccessPermissionContext::UserAction::kDragAndDrop))
.WillOnce(testing::Return(allow_grant_));
EXPECT_CALL(
permission_context_,
GetWritePermissionGrant(
kTestOrigin, dir_path, HandleType::kDirectory,
FileSystemAccessPermissionContext::UserAction::kDragAndDrop))
.WillOnce(testing::Return(allow_grant_));
// Attempt to resolve `token_remote` and store the resulting
// FileSystemAccessDirectoryHandle in `dir_remote`.
base::RunLoop await_token_resolution;
blink::mojom::FileSystemAccessEntryPtr file_system_access_entry;
manager_remote_->GetEntryFromDataTransferToken(
std::move(token_remote),
base::BindLambdaForTesting([&](blink::mojom::FileSystemAccessEntryPtr
returned_file_system_access_entry) {
file_system_access_entry =
std::move(returned_file_system_access_entry);
await_token_resolution.Quit();
}));
await_token_resolution.Run();
ASSERT_FALSE(file_system_access_entry.is_null());
ASSERT_TRUE(file_system_access_entry->entry_handle->is_directory());
mojo::Remote<blink::mojom::FileSystemAccessDirectoryHandle> dir_remote(
std::move(file_system_access_entry->entry_handle->get_directory()));
// Use `dir_remote` to verify that dir_path contains a child called
// expected_child_file_name.
base::RunLoop await_get_file;
dir_remote->GetFile(
expected_child_file_name, /*create=*/false,
base::BindLambdaForTesting(
[&](blink::mojom::FileSystemAccessErrorPtr result,
mojo::PendingRemote<blink::mojom::FileSystemAccessFileHandle>
file_handle) {
await_get_file.Quit();
ASSERT_EQ(blink::mojom::FileSystemAccessStatus::kOk,
result->status);
}));
await_get_file.Run();
}
protected:
const GURL kTestURL = GURL("https://example.com/test");
const url::Origin kTestOrigin = url::Origin::Create(kTestURL);
const int kProcessId = 1;
const int kFrameRoutingId = 2;
const GlobalFrameRoutingId kFrameId{kProcessId, kFrameRoutingId};
const FileSystemAccessManagerImpl::BindingContext kBindingContext = {
kTestOrigin, kTestURL, kFrameId};
BrowserTaskEnvironment task_environment_;
TestBrowserContext browser_context_;
TestWebContentsFactory web_contents_factory_;
base::ScopedTempDir dir_;
scoped_refptr<storage::FileSystemContext> file_system_context_;
scoped_refptr<ChromeBlobStorageContext> chrome_blob_context_;
WebContents* web_contents_;
testing::StrictMock<MockFileSystemAccessPermissionContext>
permission_context_;
scoped_refptr<FileSystemAccessManagerImpl> manager_;
mojo::Remote<blink::mojom::FileSystemAccessManager> manager_remote_;
scoped_refptr<FixedFileSystemAccessPermissionGrant> ask_grant_ =
base::MakeRefCounted<FixedFileSystemAccessPermissionGrant>(
FixedFileSystemAccessPermissionGrant::PermissionStatus::ASK,
base::FilePath());
scoped_refptr<FixedFileSystemAccessPermissionGrant> ask_grant2_ =
base::MakeRefCounted<FixedFileSystemAccessPermissionGrant>(
FixedFileSystemAccessPermissionGrant::PermissionStatus::ASK,
base::FilePath());
scoped_refptr<FixedFileSystemAccessPermissionGrant> allow_grant_ =
base::MakeRefCounted<FixedFileSystemAccessPermissionGrant>(
FixedFileSystemAccessPermissionGrant::PermissionStatus::GRANTED,
base::FilePath());
};
TEST_F(FileSystemAccessManagerImplTest, GetSandboxedFileSystem_Permissions) {
mojo::PendingRemote<blink::mojom::FileSystemAccessDirectoryHandle>
directory_remote;
base::RunLoop loop;
manager_remote_->GetSandboxedFileSystem(base::BindLambdaForTesting(
[&](blink::mojom::FileSystemAccessErrorPtr result,
mojo::PendingRemote<blink::mojom::FileSystemAccessDirectoryHandle>
handle) {
EXPECT_EQ(blink::mojom::FileSystemAccessStatus::kOk, result->status);
directory_remote = std::move(handle);
loop.Quit();
}));
loop.Run();
mojo::Remote<blink::mojom::FileSystemAccessDirectoryHandle> root(
std::move(directory_remote));
ASSERT_TRUE(root);
EXPECT_EQ(PermissionStatus::GRANTED,
GetPermissionStatusSync(/*writable=*/false, root.get()));
EXPECT_EQ(PermissionStatus::GRANTED,
GetPermissionStatusSync(/*writable=*/true, root.get()));
}
TEST_F(FileSystemAccessManagerImplTest, CreateFileEntryFromPath_Permissions) {
const base::FilePath kTestPath(dir_.GetPath().AppendASCII("foo"));
EXPECT_CALL(permission_context_,
GetReadPermissionGrant(
kTestOrigin, kTestPath, HandleType::kFile,
FileSystemAccessPermissionContext::UserAction::kOpen))
.WillOnce(testing::Return(allow_grant_));
EXPECT_CALL(permission_context_,
GetWritePermissionGrant(
kTestOrigin, kTestPath, HandleType::kFile,
FileSystemAccessPermissionContext::UserAction::kOpen))
.WillOnce(testing::Return(ask_grant_));
blink::mojom::FileSystemAccessEntryPtr entry =
manager_->CreateFileEntryFromPath(
kBindingContext, FileSystemAccessEntryFactory::PathType::kLocal,
kTestPath, FileSystemAccessPermissionContext::UserAction::kOpen);
mojo::Remote<blink::mojom::FileSystemAccessFileHandle> handle(
std::move(entry->entry_handle->get_file()));
EXPECT_EQ(PermissionStatus::GRANTED,
GetPermissionStatusSync(/*writable=*/false, handle.get()));
EXPECT_EQ(PermissionStatus::ASK,
GetPermissionStatusSync(/*writable=*/true, handle.get()));
}
TEST_F(FileSystemAccessManagerImplTest,
CreateWritableFileEntryFromPath_Permissions) {
const base::FilePath kTestPath(dir_.GetPath().AppendASCII("foo"));
EXPECT_CALL(permission_context_,
GetReadPermissionGrant(
kTestOrigin, kTestPath, HandleType::kFile,
FileSystemAccessPermissionContext::UserAction::kSave))
.WillOnce(testing::Return(allow_grant_));
EXPECT_CALL(permission_context_,
GetWritePermissionGrant(
kTestOrigin, kTestPath, HandleType::kFile,
FileSystemAccessPermissionContext::UserAction::kSave))
.WillOnce(testing::Return(allow_grant_));
blink::mojom::FileSystemAccessEntryPtr entry =
manager_->CreateFileEntryFromPath(
kBindingContext, FileSystemAccessEntryFactory::PathType::kLocal,
kTestPath, FileSystemAccessPermissionContext::UserAction::kSave);
mojo::Remote<blink::mojom::FileSystemAccessFileHandle> handle(
std::move(entry->entry_handle->get_file()));
EXPECT_EQ(PermissionStatus::GRANTED,
GetPermissionStatusSync(/*writable=*/false, handle.get()));
EXPECT_EQ(PermissionStatus::GRANTED,
GetPermissionStatusSync(/*writable=*/true, handle.get()));
}
TEST_F(FileSystemAccessManagerImplTest,
CreateDirectoryEntryFromPath_Permissions) {
const base::FilePath kTestPath(dir_.GetPath().AppendASCII("foo"));
EXPECT_CALL(permission_context_,
GetReadPermissionGrant(
kTestOrigin, kTestPath, HandleType::kDirectory,
FileSystemAccessPermissionContext::UserAction::kOpen))
.WillOnce(testing::Return(allow_grant_));
EXPECT_CALL(permission_context_,
GetWritePermissionGrant(
kTestOrigin, kTestPath, HandleType::kDirectory,
FileSystemAccessPermissionContext::UserAction::kOpen))
.WillOnce(testing::Return(ask_grant_));
blink::mojom::FileSystemAccessEntryPtr entry =
manager_->CreateDirectoryEntryFromPath(
kBindingContext, FileSystemAccessEntryFactory::PathType::kLocal,
kTestPath, FileSystemAccessPermissionContext::UserAction::kOpen);
mojo::Remote<blink::mojom::FileSystemAccessDirectoryHandle> handle(
std::move(entry->entry_handle->get_directory()));
EXPECT_EQ(PermissionStatus::GRANTED,
GetPermissionStatusSync(/*writable=*/false, handle.get()));
EXPECT_EQ(PermissionStatus::ASK,
GetPermissionStatusSync(/*writable=*/true, handle.get()));
}
TEST_F(FileSystemAccessManagerImplTest,
FileWriterSwapDeletedOnConnectionClose) {
auto test_file_url = file_system_context_->CreateCrackedFileSystemURL(
kTestOrigin, storage::kFileSystemTypeTest,
base::FilePath::FromUTF8Unsafe("test"));
auto test_swap_url = file_system_context_->CreateCrackedFileSystemURL(
kTestOrigin, storage::kFileSystemTypeTest,
base::FilePath::FromUTF8Unsafe("test.crswap"));
ASSERT_EQ(base::File::FILE_OK,
storage::AsyncFileTestHelper::CreateFile(file_system_context_.get(),
test_file_url));
ASSERT_EQ(base::File::FILE_OK,
storage::AsyncFileTestHelper::CreateFile(file_system_context_.get(),
test_swap_url));
mojo::Remote<blink::mojom::FileSystemAccessFileWriter> writer_remote(
manager_->CreateFileWriter(kBindingContext, test_file_url, test_swap_url,
FileSystemAccessManagerImpl::SharedHandleState(
allow_grant_, allow_grant_, {}),
/*auto_close=*/false));
ASSERT_TRUE(writer_remote.is_bound());
ASSERT_TRUE(storage::AsyncFileTestHelper::FileExists(
file_system_context_.get(), test_swap_url,
storage::AsyncFileTestHelper::kDontCheckSize));
// Severs the mojo pipe, causing the writer to be destroyed.
writer_remote.reset();
base::RunLoop().RunUntilIdle();
ASSERT_FALSE(storage::AsyncFileTestHelper::FileExists(
file_system_context_.get(), test_swap_url,
storage::AsyncFileTestHelper::kDontCheckSize));
}
TEST_F(FileSystemAccessManagerImplTest, FileWriterCloseDoesNotAbortOnDestruct) {
auto test_file_url = file_system_context_->CreateCrackedFileSystemURL(
kTestOrigin, storage::kFileSystemTypeTest,
base::FilePath::FromUTF8Unsafe("test"));
auto test_swap_url = file_system_context_->CreateCrackedFileSystemURL(
kTestOrigin, storage::kFileSystemTypeTest,
base::FilePath::FromUTF8Unsafe("test.crswap"));
ASSERT_EQ(base::File::FILE_OK,
storage::AsyncFileTestHelper::CreateFileWithData(
file_system_context_.get(), test_swap_url, "foo", 3));
mojo::Remote<blink::mojom::FileSystemAccessFileWriter> writer_remote(
manager_->CreateFileWriter(kBindingContext, test_file_url, test_swap_url,
FileSystemAccessManagerImpl::SharedHandleState(
allow_grant_, allow_grant_, {}),
/*auto_close=*/false));
ASSERT_TRUE(writer_remote.is_bound());
ASSERT_FALSE(storage::AsyncFileTestHelper::FileExists(
file_system_context_.get(), test_file_url,
storage::AsyncFileTestHelper::kDontCheckSize));
writer_remote->Close(base::DoNothing());
EXPECT_CALL(permission_context_,
PerformAfterWriteChecks_(testing::_, kFrameId, testing::_))
.WillOnce(base::test::RunOnceCallback<2>(
FileSystemAccessPermissionContext::AfterWriteCheckResult::kAllow));
// Severs the mojo pipe, but the writer should not be destroyed.
writer_remote.reset();
base::RunLoop().RunUntilIdle();
// Since the close should complete, the swap file should have been destroyed
// and the write should be reflected in the target file.
ASSERT_FALSE(storage::AsyncFileTestHelper::FileExists(
file_system_context_.get(), test_swap_url,
storage::AsyncFileTestHelper::kDontCheckSize));
ASSERT_TRUE(storage::AsyncFileTestHelper::FileExists(
file_system_context_.get(), test_file_url, 3));
}
TEST_F(FileSystemAccessManagerImplTest,
FileWriterNoWritesIfConnectionLostBeforeClose) {
auto test_file_url = file_system_context_->CreateCrackedFileSystemURL(
kTestOrigin, storage::kFileSystemTypeTest,
base::FilePath::FromUTF8Unsafe("test"));
auto test_swap_url = file_system_context_->CreateCrackedFileSystemURL(
kTestOrigin, storage::kFileSystemTypeTest,
base::FilePath::FromUTF8Unsafe("test.crswap"));
ASSERT_EQ(base::File::FILE_OK,
storage::AsyncFileTestHelper::CreateFileWithData(
file_system_context_.get(), test_swap_url, "foo", 3));
mojo::Remote<blink::mojom::FileSystemAccessFileWriter> writer_remote(
manager_->CreateFileWriter(kBindingContext, test_file_url, test_swap_url,
FileSystemAccessManagerImpl::SharedHandleState(
allow_grant_, allow_grant_, {}),
/*auto_close=*/false));
// Severs the mojo pipe. The writer should be destroyed.
writer_remote.reset();
base::RunLoop().RunUntilIdle();
// Neither the target file nor the swap file should exist.
ASSERT_FALSE(storage::AsyncFileTestHelper::FileExists(
file_system_context_.get(), test_file_url,
storage::AsyncFileTestHelper::kDontCheckSize));
ASSERT_FALSE(storage::AsyncFileTestHelper::FileExists(
file_system_context_.get(), test_swap_url,
storage::AsyncFileTestHelper::kDontCheckSize));
}
TEST_F(FileSystemAccessManagerImplTest,
FileWriterAutoCloseIfConnectionLostBeforeClose) {
auto test_file_url = file_system_context_->CreateCrackedFileSystemURL(
kTestOrigin, storage::kFileSystemTypeTest,
base::FilePath::FromUTF8Unsafe("test"));
auto test_swap_url = file_system_context_->CreateCrackedFileSystemURL(
kTestOrigin, storage::kFileSystemTypeTest,
base::FilePath::FromUTF8Unsafe("test.crswap"));
ASSERT_EQ(base::File::FILE_OK,
storage::AsyncFileTestHelper::CreateFileWithData(
file_system_context_.get(), test_swap_url, "foo", 3));
mojo::Remote<blink::mojom::FileSystemAccessFileWriter> writer_remote(
manager_->CreateFileWriter(kBindingContext, test_file_url, test_swap_url,
FileSystemAccessManagerImpl::SharedHandleState(
allow_grant_, allow_grant_, {}),
/*auto_close=*/true));
ASSERT_TRUE(writer_remote.is_bound());
ASSERT_FALSE(storage::AsyncFileTestHelper::FileExists(
file_system_context_.get(), test_file_url,
storage::AsyncFileTestHelper::kDontCheckSize));
EXPECT_CALL(permission_context_,
PerformAfterWriteChecks_(testing::_, kFrameId, testing::_))
.WillOnce(base::test::RunOnceCallback<2>(
FileSystemAccessPermissionContext::AfterWriteCheckResult::kAllow));
// Severs the mojo pipe. Since autoClose was specified, the Writer will not be
// destroyed until the file is written out.
writer_remote.reset();
base::RunLoop().RunUntilIdle();
// Since the close should complete, the swap file should have been destroyed
// and the write should be reflected in the target file.
EXPECT_FALSE(storage::AsyncFileTestHelper::FileExists(
file_system_context_.get(), test_swap_url,
storage::AsyncFileTestHelper::kDontCheckSize));
ASSERT_TRUE(storage::AsyncFileTestHelper::FileExists(
file_system_context_.get(), test_file_url, 3));
}
TEST_F(FileSystemAccessManagerImplTest, SerializeHandle_SandboxedFile) {
auto test_file_url = file_system_context_->CreateCrackedFileSystemURL(
kTestOrigin, storage::kFileSystemTypeTemporary,
base::FilePath::FromUTF8Unsafe("test/foo/bar"));
FileSystemAccessFileHandleImpl file(manager_.get(), kBindingContext,
test_file_url,
{ask_grant_, ask_grant_, {}});
mojo::PendingRemote<blink::mojom::FileSystemAccessTransferToken> token_remote;
manager_->CreateTransferToken(file,
token_remote.InitWithNewPipeAndPassReceiver());
FileSystemAccessTransferTokenImpl* token =
SerializeAndDeserializeToken(std::move(token_remote));
ASSERT_TRUE(token);
EXPECT_EQ(test_file_url, token->url());
EXPECT_EQ(HandleType::kFile, token->type());
// Deserialized sandboxed filesystem handles should always be readable and
// writable.
ASSERT_TRUE(token->GetReadGrant());
EXPECT_EQ(PermissionStatus::GRANTED, token->GetReadGrant()->GetStatus());
ASSERT_TRUE(token->GetWriteGrant());
EXPECT_EQ(PermissionStatus::GRANTED, token->GetWriteGrant()->GetStatus());
}
TEST_F(FileSystemAccessManagerImplTest, SerializeHandle_SandboxedDirectory) {
auto test_file_url = file_system_context_->CreateCrackedFileSystemURL(
kTestOrigin, storage::kFileSystemTypeTemporary,
base::FilePath::FromUTF8Unsafe("hello/world/"));
FileSystemAccessDirectoryHandleImpl directory(manager_.get(), kBindingContext,
test_file_url,
{ask_grant_, ask_grant_, {}});
mojo::PendingRemote<blink::mojom::FileSystemAccessTransferToken> token_remote;
manager_->CreateTransferToken(directory,
token_remote.InitWithNewPipeAndPassReceiver());
FileSystemAccessTransferTokenImpl* token =
SerializeAndDeserializeToken(std::move(token_remote));
ASSERT_TRUE(token);
EXPECT_EQ(test_file_url, token->url());
EXPECT_EQ(HandleType::kDirectory, token->type());
// Deserialized sandboxed filesystem handles should always be readable and
// writable.
ASSERT_TRUE(token->GetReadGrant());
EXPECT_EQ(PermissionStatus::GRANTED, token->GetReadGrant()->GetStatus());
ASSERT_TRUE(token->GetWriteGrant());
EXPECT_EQ(PermissionStatus::GRANTED, token->GetWriteGrant()->GetStatus());
}
TEST_F(FileSystemAccessManagerImplTest, SerializeHandle_Native_SingleFile) {
const base::FilePath kTestPath(dir_.GetPath().AppendASCII("foo"));
auto grant = base::MakeRefCounted<FixedFileSystemAccessPermissionGrant>(
FixedFileSystemAccessPermissionGrant::PermissionStatus::GRANTED,
kTestPath);
// Expect calls to get grants when creating the initial handle.
EXPECT_CALL(permission_context_,
GetReadPermissionGrant(
kTestOrigin, kTestPath, HandleType::kFile,
FileSystemAccessPermissionContext::UserAction::kOpen))
.WillOnce(testing::Return(grant));
EXPECT_CALL(permission_context_,
GetWritePermissionGrant(
kTestOrigin, kTestPath, HandleType::kFile,
FileSystemAccessPermissionContext::UserAction::kOpen))
.WillOnce(testing::Return(grant));
blink::mojom::FileSystemAccessEntryPtr entry =
manager_->CreateFileEntryFromPath(
kBindingContext, FileSystemAccessEntryFactory::PathType::kLocal,
kTestPath, FileSystemAccessPermissionContext::UserAction::kOpen);
mojo::Remote<blink::mojom::FileSystemAccessFileHandle> handle(
std::move(entry->entry_handle->get_file()));
mojo::PendingRemote<blink::mojom::FileSystemAccessTransferToken> token_remote;
handle->Transfer(token_remote.InitWithNewPipeAndPassReceiver());
// Deserializing tokens should re-request grants, with correct user action.
EXPECT_CALL(
permission_context_,
GetReadPermissionGrant(
kTestOrigin, kTestPath, HandleType::kFile,
FileSystemAccessPermissionContext::UserAction::kLoadFromStorage))
.WillOnce(testing::Return(ask_grant_));
EXPECT_CALL(
permission_context_,
GetWritePermissionGrant(
kTestOrigin, kTestPath, HandleType::kFile,
FileSystemAccessPermissionContext::UserAction::kLoadFromStorage))
.WillOnce(testing::Return(ask_grant2_));
FileSystemAccessTransferTokenImpl* token =
SerializeAndDeserializeToken(std::move(token_remote));
ASSERT_TRUE(token);
const storage::FileSystemURL& url = token->url();
EXPECT_EQ(kTestOrigin, url.origin());
EXPECT_EQ(kTestPath, url.path());
EXPECT_EQ(storage::kFileSystemTypeLocal, url.type());
EXPECT_EQ(storage::kFileSystemTypeIsolated, url.mount_type());
EXPECT_EQ(HandleType::kFile, token->type());
EXPECT_EQ(ask_grant_, token->GetReadGrant());
EXPECT_EQ(ask_grant2_, token->GetWriteGrant());
}
TEST_F(FileSystemAccessManagerImplTest,
SerializeHandle_Native_SingleDirectory) {
const base::FilePath kTestPath(dir_.GetPath().AppendASCII("foobar"));
mojo::Remote<blink::mojom::FileSystemAccessDirectoryHandle> handle =
GetHandleForDirectory(kTestPath);
mojo::PendingRemote<blink::mojom::FileSystemAccessTransferToken> token_remote;
handle->Transfer(token_remote.InitWithNewPipeAndPassReceiver());
// Deserializing tokens should re-request grants, with correct user action.
EXPECT_CALL(
permission_context_,
GetReadPermissionGrant(
kTestOrigin, kTestPath, HandleType::kDirectory,
FileSystemAccessPermissionContext::UserAction::kLoadFromStorage))
.WillOnce(testing::Return(ask_grant_));
EXPECT_CALL(
permission_context_,
GetWritePermissionGrant(
kTestOrigin, kTestPath, HandleType::kDirectory,
FileSystemAccessPermissionContext::UserAction::kLoadFromStorage))
.WillOnce(testing::Return(ask_grant2_));
FileSystemAccessTransferTokenImpl* token =
SerializeAndDeserializeToken(std::move(token_remote));
ASSERT_TRUE(token);
const storage::FileSystemURL& url = token->url();
EXPECT_EQ(kTestOrigin, url.origin());
EXPECT_EQ(kTestPath, url.path());
EXPECT_EQ(storage::kFileSystemTypeLocal, url.type());
EXPECT_EQ(storage::kFileSystemTypeIsolated, url.mount_type());
EXPECT_EQ(HandleType::kDirectory, token->type());
EXPECT_EQ(ask_grant_, token->GetReadGrant());
EXPECT_EQ(ask_grant2_, token->GetWriteGrant());
}
TEST_F(FileSystemAccessManagerImplTest,
SerializeHandle_Native_FileInsideDirectory) {
const base::FilePath kDirectoryPath(dir_.GetPath().AppendASCII("foo"));
const std::string kTestName = "test file name ☺";
base::CreateDirectory(kDirectoryPath);
mojo::Remote<blink::mojom::FileSystemAccessDirectoryHandle> directory_handle =
GetHandleForDirectory(kDirectoryPath);
mojo::Remote<blink::mojom::FileSystemAccessFileHandle> file_handle;
base::RunLoop get_file_loop;
directory_handle->GetFile(
kTestName, /*create=*/true,
base::BindLambdaForTesting(
[&](blink::mojom::FileSystemAccessErrorPtr result,
mojo::PendingRemote<blink::mojom::FileSystemAccessFileHandle>
handle) {
get_file_loop.Quit();
ASSERT_EQ(blink::mojom::FileSystemAccessStatus::kOk,
result->status);
file_handle.Bind(std::move(handle));
}));
get_file_loop.Run();
ASSERT_TRUE(file_handle.is_bound());
mojo::PendingRemote<blink::mojom::FileSystemAccessTransferToken> token_remote;
file_handle->Transfer(token_remote.InitWithNewPipeAndPassReceiver());
// Deserializing tokens should re-request grants, with correct user action.
EXPECT_CALL(
permission_context_,
GetReadPermissionGrant(
kTestOrigin, kDirectoryPath, HandleType::kDirectory,
FileSystemAccessPermissionContext::UserAction::kLoadFromStorage))
.WillOnce(testing::Return(ask_grant_));
EXPECT_CALL(
permission_context_,
GetWritePermissionGrant(
kTestOrigin, kDirectoryPath, HandleType::kDirectory,
FileSystemAccessPermissionContext::UserAction::kLoadFromStorage))
.WillOnce(testing::Return(ask_grant2_));
FileSystemAccessTransferTokenImpl* token =
SerializeAndDeserializeToken(std::move(token_remote));
ASSERT_TRUE(token);
const storage::FileSystemURL& url = token->url();
EXPECT_EQ(kTestOrigin, url.origin());
EXPECT_EQ(kDirectoryPath.Append(base::FilePath::FromUTF8Unsafe(kTestName)),
url.path());
EXPECT_EQ(storage::kFileSystemTypeLocal, url.type());
EXPECT_EQ(storage::kFileSystemTypeIsolated, url.mount_type());
EXPECT_EQ(HandleType::kFile, token->type());
EXPECT_EQ(ask_grant_, token->GetReadGrant());
EXPECT_EQ(ask_grant2_, token->GetWriteGrant());
}
TEST_F(FileSystemAccessManagerImplTest,
SerializeHandle_Native_DirectoryInsideDirectory) {
const base::FilePath kDirectoryPath(dir_.GetPath().AppendASCII("foo"));
const std::string kTestName = "test dir name";
base::CreateDirectory(kDirectoryPath);
mojo::Remote<blink::mojom::FileSystemAccessDirectoryHandle> directory_handle =
GetHandleForDirectory(kDirectoryPath);
mojo::Remote<blink::mojom::FileSystemAccessDirectoryHandle> child_handle;
base::RunLoop get_directory_loop;
directory_handle->GetDirectory(
kTestName, /*create=*/true,
base::BindLambdaForTesting(
[&](blink::mojom::FileSystemAccessErrorPtr result,
mojo::PendingRemote<blink::mojom::FileSystemAccessDirectoryHandle>
handle) {
get_directory_loop.Quit();
ASSERT_EQ(blink::mojom::FileSystemAccessStatus::kOk,
result->status);
child_handle.Bind(std::move(handle));
}));
get_directory_loop.Run();
ASSERT_TRUE(child_handle.is_bound());
mojo::PendingRemote<blink::mojom::FileSystemAccessTransferToken> token_remote;
child_handle->Transfer(token_remote.InitWithNewPipeAndPassReceiver());
// Deserializing tokens should re-request grants, with correct user action.
EXPECT_CALL(
permission_context_,
GetReadPermissionGrant(
kTestOrigin, kDirectoryPath, HandleType::kDirectory,
FileSystemAccessPermissionContext::UserAction::kLoadFromStorage))
.WillOnce(testing::Return(ask_grant_));
EXPECT_CALL(
permission_context_,
GetWritePermissionGrant(
kTestOrigin, kDirectoryPath, HandleType::kDirectory,
FileSystemAccessPermissionContext::UserAction::kLoadFromStorage))
.WillOnce(testing::Return(ask_grant2_));
FileSystemAccessTransferTokenImpl* token =
SerializeAndDeserializeToken(std::move(token_remote));
ASSERT_TRUE(token);
const storage::FileSystemURL& url = token->url();
EXPECT_EQ(kTestOrigin, url.origin());
EXPECT_EQ(kDirectoryPath.AppendASCII(kTestName), url.path());
EXPECT_EQ(storage::kFileSystemTypeLocal, url.type());
EXPECT_EQ(storage::kFileSystemTypeIsolated, url.mount_type());
EXPECT_EQ(HandleType::kDirectory, token->type());
EXPECT_EQ(ask_grant_, token->GetReadGrant());
EXPECT_EQ(ask_grant2_, token->GetWriteGrant());
}
TEST_F(FileSystemAccessManagerImplTest, SerializeHandle_ExternalFile) {
const base::FilePath kTestPath =
base::FilePath::FromUTF8Unsafe(kTestMountPoint).AppendASCII("foo");
auto grant = base::MakeRefCounted<FixedFileSystemAccessPermissionGrant>(
FixedFileSystemAccessPermissionGrant::PermissionStatus::GRANTED,
kTestPath);
// Expect calls to get grants when creating the initial handle.
EXPECT_CALL(permission_context_,
GetReadPermissionGrant(
kTestOrigin, kTestPath, HandleType::kFile,
FileSystemAccessPermissionContext::UserAction::kOpen))
.WillOnce(testing::Return(grant));
EXPECT_CALL(permission_context_,
GetWritePermissionGrant(
kTestOrigin, kTestPath, HandleType::kFile,
FileSystemAccessPermissionContext::UserAction::kOpen))
.WillOnce(testing::Return(grant));
blink::mojom::FileSystemAccessEntryPtr entry =
manager_->CreateFileEntryFromPath(
kBindingContext, FileSystemAccessEntryFactory::PathType::kExternal,
kTestPath, FileSystemAccessPermissionContext::UserAction::kOpen);
mojo::Remote<blink::mojom::FileSystemAccessFileHandle> handle(
std::move(entry->entry_handle->get_file()));
mojo::PendingRemote<blink::mojom::FileSystemAccessTransferToken> token_remote;
handle->Transfer(token_remote.InitWithNewPipeAndPassReceiver());
// Deserializing tokens should re-request grants, with correct user action.
EXPECT_CALL(
permission_context_,
GetReadPermissionGrant(
kTestOrigin, kTestPath, HandleType::kFile,
FileSystemAccessPermissionContext::UserAction::kLoadFromStorage))
.WillOnce(testing::Return(ask_grant_));
EXPECT_CALL(
permission_context_,
GetWritePermissionGrant(
kTestOrigin, kTestPath, HandleType::kFile,
FileSystemAccessPermissionContext::UserAction::kLoadFromStorage))
.WillOnce(testing::Return(ask_grant2_));
FileSystemAccessTransferTokenImpl* token =
SerializeAndDeserializeToken(std::move(token_remote));
ASSERT_TRUE(token);
const storage::FileSystemURL& url = token->url();
EXPECT_TRUE(url.origin().opaque());
EXPECT_EQ(kTestPath, url.virtual_path());
EXPECT_EQ(storage::kFileSystemTypeExternal, url.mount_type());
EXPECT_EQ(HandleType::kFile, token->type());
EXPECT_EQ(ask_grant_, token->GetReadGrant());
EXPECT_EQ(ask_grant2_, token->GetWriteGrant());
}
// FileSystemAccessManager should successfully resolve a
// FileSystemAccessDataTransferToken representing a file in the user's file
// system into a valid Remote<blink::mojom::FileSystemAccessFileHandle>, given
// that the PID is valid.
TEST_F(FileSystemAccessManagerImplTest,
GetEntryFromDataTransferToken_File_ValidPID) {
// Create a file and write some text into it.
const base::FilePath file_path = dir_.GetPath().AppendASCII("mr_file");
const std::string file_contents = "Deleted code is debugged code.";
ASSERT_TRUE(base::WriteFile(file_path, file_contents));
GetEntryFromDataTransferTokenFileTest(
file_path, FileSystemAccessEntryFactory::PathType::kLocal, file_contents);
}
// FileSystemAccessManager should successfully resolve a
// FileSystemAccessDataTransferToken representing a
// FileSystemAccessDirectoryEntry into a valid
// Remote<blink::mojom::FileSystemAccessDirectoryHandle>, given that the PID is
// valid.
TEST_F(FileSystemAccessManagerImplTest,
GetEntryFromDataTransferToken_Directory_ValidPID) {
// Create a directory and create a FileSystemAccessDataTransferToken
// representing the new directory.
const base::FilePath dir_path = dir_.GetPath().AppendASCII("mr_dir");
ASSERT_TRUE(base::CreateDirectory(dir_path));
const std::string child_file_name = "child-file-name.txt";
ASSERT_TRUE(base::WriteFile(dir_path.AppendASCII(child_file_name), ""));
GetEntryFromDataTransferTokenDirectoryTest(
dir_path, FileSystemAccessEntryFactory::PathType::kLocal,
child_file_name);
}
// FileSystemAccessManager should successfully resolve a
// FileSystemAccessDataTransferToken representing a file in the user's file
// system into a valid Remote<blink::mojom::FileSystemAccessFileHandle>, given
// that the PID is valid.
TEST_F(FileSystemAccessManagerImplTest,
GetEntryFromDataTransferToken_File_ExternalPath) {
// Create a file and write some text into it.
const base::FilePath file_path = dir_.GetPath().AppendASCII("mr_file");
const std::string file_contents = "Deleted code is debugged code.";
ASSERT_TRUE(base::WriteFile(file_path, file_contents));
const base::FilePath virtual_file_path =
base::FilePath::FromUTF8Unsafe(kTestMountPoint)
.Append(file_path.BaseName());
GetEntryFromDataTransferTokenFileTest(
virtual_file_path, FileSystemAccessEntryFactory::PathType::kExternal,
file_contents);
}
// FileSystemAccessManager should successfully resolve a
// FileSystemAccessDataTransferToken representing a
// FileSystemAccessDirectoryEntry into a valid
// Remote<blink::mojom::FileSystemAccessDirectoryHandle>, given that the PID is
// valid.
TEST_F(FileSystemAccessManagerImplTest,
GetEntryFromDataTransferToken_Directory_ExternalPath) {
// Create a directory and create a FileSystemAccessDataTransferToken
// representing the new directory.
const base::FilePath dir_path = dir_.GetPath().AppendASCII("mr_dir");
ASSERT_TRUE(base::CreateDirectory(dir_path));
const std::string child_file_name = "child-file-name.txt";
ASSERT_TRUE(base::WriteFile(dir_path.AppendASCII(child_file_name), ""));
const base::FilePath virtual_dir_path =
base::FilePath::FromUTF8Unsafe(kTestMountPoint)
.Append(dir_path.BaseName());
GetEntryFromDataTransferTokenDirectoryTest(
virtual_dir_path, FileSystemAccessEntryFactory::PathType::kExternal,
child_file_name);
}
// FileSystemAccessManager should refuse to resolve a
// FileSystemAccessDataTransferToken representing a file on the user's file
// system if the PID of the redeeming process doesn't match the one assigned at
// creation.
TEST_F(FileSystemAccessManagerImplTest,
GetEntryFromDataTransferToken_File_InvalidPID) {
base::FilePath file_path = dir_.GetPath().AppendASCII("mr_file");
ASSERT_TRUE(base::CreateTemporaryFile(&file_path));
// Create a FileSystemAccessDataTransferToken with a PID different than the
// process attempting to redeem to the token.
mojo::PendingRemote<blink::mojom::FileSystemAccessDataTransferToken>
token_remote;
manager_->CreateFileSystemAccessDataTransferToken(
FileSystemAccessEntryFactory::PathType::kLocal, file_path,
/*renderer_id=*/kBindingContext.process_id() - 1,
token_remote.InitWithNewPipeAndPassReceiver());
// Try to redeem the FileSystemAccessDataTransferToken for a
// FileSystemAccessFileHandle, expecting `bad_message_observer` to intercept
// a bad message callback.
mojo::test::BadMessageObserver bad_message_observer;
manager_remote_->GetEntryFromDataTransferToken(std::move(token_remote),
base::DoNothing());
EXPECT_EQ("Invalid renderer ID.", bad_message_observer.WaitForBadMessage());
}
// FileSystemAccessManager should refuse to resolve a
// FileSystemAccessDataTransferToken representing a directory on the user's file
// system if the PID of the redeeming process doesn't match the one assigned at
// creation.
TEST_F(FileSystemAccessManagerImplTest,
GetEntryFromDataTransferToken_Directory_InvalidPID) {
const base::FilePath& kDirPath = dir_.GetPath().AppendASCII("mr_directory");
ASSERT_TRUE(base::CreateDirectory(kDirPath));
// Create a FileSystemAccessDataTransferToken with an PID different than the
// process attempting to redeem to the token.
mojo::PendingRemote<blink::mojom::FileSystemAccessDataTransferToken>
token_remote;
manager_->CreateFileSystemAccessDataTransferToken(
FileSystemAccessEntryFactory::PathType::kLocal, kDirPath,
/*renderer_id=*/kBindingContext.process_id() - 1,
token_remote.InitWithNewPipeAndPassReceiver());
// Try to redeem the FileSystemAccessDataTransferToken for a
// FileSystemAccessFileHandle, expecting `bad_message_observer` to intercept
// a bad message callback.
mojo::test::BadMessageObserver bad_message_observer;
manager_remote_->GetEntryFromDataTransferToken(std::move(token_remote),
base::DoNothing());
EXPECT_EQ("Invalid renderer ID.", bad_message_observer.WaitForBadMessage());
}
// FileSystemAccessManager should refuse to resolve a
// FileSystemAccessDataTransferToken if the value of the token was not
// recognized by the FileSystemAccessManager.
TEST_F(FileSystemAccessManagerImplTest,
GetEntryFromDataTransferToken_UnrecognizedToken) {
const base::FilePath& kDirPath = dir_.GetPath().AppendASCII("mr_directory");
ASSERT_TRUE(base::CreateDirectory(kDirPath));
// Create a FileSystemAccessDataTransferToken without registering it to the
// FileSystemAccessManager.
mojo::PendingRemote<blink::mojom::FileSystemAccessDataTransferToken>
token_remote;
auto drag_drop_token_impl =
std::make_unique<FileSystemAccessDataTransferTokenImpl>(
manager_.get(), FileSystemAccessEntryFactory::PathType::kLocal,
kDirPath, kBindingContext.process_id(),
token_remote.InitWithNewPipeAndPassReceiver());
// Try to redeem the FileSystemAccessDataTransferToken for a
// FileSystemAccessFileHandle, expecting `bad_message_observer` to intercept
// a bad message callback.
mojo::test::BadMessageObserver bad_message_observer;
manager_remote_->GetEntryFromDataTransferToken(std::move(token_remote),
base::DoNothing());
EXPECT_EQ("Unrecognized drag drop token.",
bad_message_observer.WaitForBadMessage());
}
TEST_F(FileSystemAccessManagerImplTest, ChooseEntries_OpenFile) {
base::FilePath test_file = dir_.GetPath().AppendASCII("foo");
ASSERT_TRUE(base::CreateTemporaryFile(&test_file));
FileSystemChooser::ResultEntry entry;
entry.type = PathType::kLocal;
entry.path = test_file;
manager_->SetFilePickerResultForTesting(std::move(entry));
static_cast<TestRenderFrameHost*>(web_contents_->GetMainFrame())
->SimulateUserActivation();
mojo::Remote<blink::mojom::FileSystemAccessManager> manager_remote;
FileSystemAccessManagerImpl::BindingContext binding_context = {
kTestOrigin, kTestURL,
web_contents_->GetMainFrame()->GetGlobalFrameRoutingId()};
manager_->BindReceiver(binding_context,
manager_remote.BindNewPipeAndPassReceiver());
EXPECT_CALL(permission_context_, CanObtainReadPermission(kTestOrigin))
.WillOnce(testing::Return(true));
EXPECT_CALL(
permission_context_,
GetWellKnownDirectoryPath(blink::mojom::WellKnownDirectory::kDefault))
.WillOnce(testing::Return(base::FilePath()));
EXPECT_CALL(permission_context_,
GetLastPickedDirectory(kTestOrigin, std::string()))
.WillOnce(testing::Return(PathInfo()));
EXPECT_CALL(permission_context_,
SetLastPickedDirectory(kTestOrigin, std::string(),
test_file.DirName(), PathType::kLocal));
EXPECT_CALL(
permission_context_,
ConfirmSensitiveDirectoryAccess_(
kTestOrigin, FileSystemAccessPermissionContext::PathType::kLocal,
test_file, FileSystemAccessPermissionContext::HandleType::kFile,
web_contents_->GetMainFrame()->GetGlobalFrameRoutingId(), testing::_))
.WillOnce(RunOnceCallback<5>(FileSystemAccessPermissionContext::
SensitiveDirectoryResult::kAllowed));
EXPECT_CALL(permission_context_,
GetReadPermissionGrant(
kTestOrigin, test_file,
FileSystemAccessPermissionContext::HandleType::kFile,
FileSystemAccessPermissionContext::UserAction::kOpen))
.WillOnce(testing::Return(allow_grant_));
EXPECT_CALL(permission_context_,
GetWritePermissionGrant(
kTestOrigin, test_file,
FileSystemAccessPermissionContext::HandleType::kFile,
FileSystemAccessPermissionContext::UserAction::kOpen))
.WillOnce(testing::Return(allow_grant_));
auto open_file_picker_options = blink::mojom::OpenFilePickerOptions::New(
blink::mojom::AcceptsTypesInfo::New(
std::vector<blink::mojom::ChooseFileSystemEntryAcceptsOptionPtr>(),
/*include_accepts_all=*/true),
/*can_select_multiple_files=*/false);
auto common_file_picker_options = blink::mojom::CommonFilePickerOptions::New(
/*starting_directory_id=*/std::string(),
blink::mojom::WellKnownDirectory::kDefault,
/*starting_directory_token=*/mojo::NullRemote());
base::RunLoop loop;
manager_remote->ChooseEntries(
blink::mojom::FilePickerOptions::NewOpenFilePickerOptions(
std::move(open_file_picker_options)),
std::move(common_file_picker_options),
base::BindLambdaForTesting(
[&](blink::mojom::FileSystemAccessErrorPtr result,
std::vector<blink::mojom::FileSystemAccessEntryPtr> entries) {
loop.Quit();
}));
loop.Run();
}
TEST_F(FileSystemAccessManagerImplTest, ChooseEntries_SaveFile) {
base::FilePath test_file = dir_.GetPath().AppendASCII("foo");
ASSERT_TRUE(base::CreateTemporaryFile(&test_file));
FileSystemChooser::ResultEntry entry;
entry.type = PathType::kLocal;
entry.path = test_file;
manager_->SetFilePickerResultForTesting(std::move(entry));
static_cast<TestRenderFrameHost*>(web_contents_->GetMainFrame())
->SimulateUserActivation();
mojo::Remote<blink::mojom::FileSystemAccessManager> manager_remote;
FileSystemAccessManagerImpl::BindingContext binding_context = {
kTestOrigin, kTestURL,
web_contents_->GetMainFrame()->GetGlobalFrameRoutingId()};
manager_->BindReceiver(binding_context,
manager_remote.BindNewPipeAndPassReceiver());
EXPECT_CALL(permission_context_, CanObtainReadPermission(kTestOrigin))
.WillOnce(testing::Return(true));
EXPECT_CALL(permission_context_, CanObtainWritePermission(kTestOrigin))
.WillOnce(testing::Return(true));
EXPECT_CALL(
permission_context_,
GetWellKnownDirectoryPath(blink::mojom::WellKnownDirectory::kDefault))
.WillOnce(testing::Return(base::FilePath()));
EXPECT_CALL(permission_context_,
GetLastPickedDirectory(kTestOrigin, std::string()))
.WillOnce(testing::Return(PathInfo()));
EXPECT_CALL(permission_context_,
SetLastPickedDirectory(kTestOrigin, std::string(),
test_file.DirName(), PathType::kLocal));
EXPECT_CALL(
permission_context_,
ConfirmSensitiveDirectoryAccess_(
kTestOrigin, FileSystemAccessPermissionContext::PathType::kLocal,
test_file, FileSystemAccessPermissionContext::HandleType::kFile,
web_contents_->GetMainFrame()->GetGlobalFrameRoutingId(), testing::_))
.WillOnce(RunOnceCallback<5>(FileSystemAccessPermissionContext::
SensitiveDirectoryResult::kAllowed));
EXPECT_CALL(permission_context_,
GetReadPermissionGrant(
kTestOrigin, test_file,
FileSystemAccessPermissionContext::HandleType::kFile,
FileSystemAccessPermissionContext::UserAction::kSave))
.WillOnce(testing::Return(allow_grant_));
EXPECT_CALL(permission_context_,
GetWritePermissionGrant(
kTestOrigin, test_file,
FileSystemAccessPermissionContext::HandleType::kFile,
FileSystemAccessPermissionContext::UserAction::kSave))
.WillOnce(testing::Return(allow_grant_));
auto save_file_picker_options = blink::mojom::SaveFilePickerOptions::New(
blink::mojom::AcceptsTypesInfo::New(
std::vector<blink::mojom::ChooseFileSystemEntryAcceptsOptionPtr>(),
/*include_accepts_all=*/true),
/*suggested_name=*/std::string());
auto common_file_picker_options = blink::mojom::CommonFilePickerOptions::New(
/*starting_directory_id=*/std::string(),
blink::mojom::WellKnownDirectory::kDefault,
/*starting_directory_token=*/mojo::NullRemote());
base::RunLoop loop;
manager_remote->ChooseEntries(
blink::mojom::FilePickerOptions::NewSaveFilePickerOptions(
std::move(save_file_picker_options)),
std::move(common_file_picker_options),
base::BindLambdaForTesting(
[&](blink::mojom::FileSystemAccessErrorPtr result,
std::vector<blink::mojom::FileSystemAccessEntryPtr> entries) {
loop.Quit();
}));
loop.Run();
}
TEST_F(FileSystemAccessManagerImplTest, ChooseEntries_OpenDirectory) {
base::FilePath test_dir = dir_.GetPath();
FileSystemChooser::ResultEntry entry;
entry.type = PathType::kLocal;
entry.path = test_dir;
manager_->SetFilePickerResultForTesting(std::move(entry));
static_cast<TestRenderFrameHost*>(web_contents_->GetMainFrame())
->SimulateUserActivation();
mojo::Remote<blink::mojom::FileSystemAccessManager> manager_remote;
FileSystemAccessManagerImpl::BindingContext binding_context = {
kTestOrigin, kTestURL,
web_contents_->GetMainFrame()->GetGlobalFrameRoutingId()};
manager_->BindReceiver(binding_context,
manager_remote.BindNewPipeAndPassReceiver());
EXPECT_CALL(permission_context_, CanObtainReadPermission(kTestOrigin))
.WillOnce(testing::Return(true));
EXPECT_CALL(
permission_context_,
GetWellKnownDirectoryPath(blink::mojom::WellKnownDirectory::kDefault))
.WillOnce(testing::Return(base::FilePath()));
EXPECT_CALL(permission_context_,
GetLastPickedDirectory(kTestOrigin, std::string()))
.WillOnce(testing::Return(PathInfo()));
EXPECT_CALL(permission_context_,
SetLastPickedDirectory(kTestOrigin, std::string(), test_dir,
PathType::kLocal));
EXPECT_CALL(
permission_context_,
ConfirmSensitiveDirectoryAccess_(
kTestOrigin, FileSystemAccessPermissionContext::PathType::kLocal,
test_dir, FileSystemAccessPermissionContext::HandleType::kDirectory,
web_contents_->GetMainFrame()->GetGlobalFrameRoutingId(), testing::_))
.WillOnce(RunOnceCallback<5>(FileSystemAccessPermissionContext::
SensitiveDirectoryResult::kAllowed));
EXPECT_CALL(permission_context_,
GetReadPermissionGrant(
kTestOrigin, test_dir,
FileSystemAccessPermissionContext::HandleType::kDirectory,
FileSystemAccessPermissionContext::UserAction::kOpen))
.WillOnce(testing::Return(allow_grant_));
EXPECT_CALL(permission_context_,
GetWritePermissionGrant(
kTestOrigin, test_dir,
FileSystemAccessPermissionContext::HandleType::kDirectory,
FileSystemAccessPermissionContext::UserAction::kOpen))
.WillOnce(testing::Return(allow_grant_));
auto directory_picker_options = blink::mojom::DirectoryPickerOptions::New();
auto common_file_picker_options = blink::mojom::CommonFilePickerOptions::New(
/*starting_directory_id=*/std::string(),
blink::mojom::WellKnownDirectory::kDefault,
/*starting_directory_token=*/mojo::NullRemote());
base::RunLoop loop;
manager_remote->ChooseEntries(
blink::mojom::FilePickerOptions::NewDirectoryPickerOptions(
std::move(directory_picker_options)),
std::move(common_file_picker_options),
base::BindLambdaForTesting(
[&](blink::mojom::FileSystemAccessErrorPtr result,
std::vector<blink::mojom::FileSystemAccessEntryPtr> entries) {
loop.Quit();
}));
loop.Run();
}
TEST_F(FileSystemAccessManagerImplTest, ChooseEntries_InvalidStartInID) {
base::FilePath test_dir = dir_.GetPath();
FileSystemChooser::ResultEntry entry;
entry.type = PathType::kLocal;
entry.path = test_dir;
manager_->SetFilePickerResultForTesting(std::move(entry));
static_cast<TestRenderFrameHost*>(web_contents_->GetMainFrame())
->SimulateUserActivation();
mojo::Remote<blink::mojom::FileSystemAccessManager> manager_remote;
FileSystemAccessManagerImpl::BindingContext binding_context = {
kTestOrigin, kTestURL,
web_contents_->GetMainFrame()->GetGlobalFrameRoutingId()};
manager_->BindReceiver(binding_context,
manager_remote.BindNewPipeAndPassReceiver());
// Specifying a `starting_directory_id` with invalid characters should trigger
// a bad message callback.
auto directory_picker_options = blink::mojom::DirectoryPickerOptions::New();
auto common_file_picker_options = blink::mojom::CommonFilePickerOptions::New(
/*starting_directory_id=*/"inv*l!d <hars",
blink::mojom::WellKnownDirectory::kDefault,
/*starting_directory_token=*/mojo::NullRemote());
mojo::test::BadMessageObserver bad_message_observer;
manager_remote->ChooseEntries(
blink::mojom::FilePickerOptions::NewDirectoryPickerOptions(
std::move(directory_picker_options)),
std::move(common_file_picker_options), base::DoNothing());
EXPECT_EQ("Invalid starting directory ID in browser",
bad_message_observer.WaitForBadMessage());
}
} // namespace content
|
/*******************************************************************************
* This file was auto-generated using the AutoGemm.py python script.
* DO NOT modify this file! Instead, make changes to scripts in
* clBLAS/src/library/blas/AutoGemm/ then re-generate files
* (otherwise local changes will be lost after re-generation).
******************************************************************************/
#ifndef KERNEL_CGEMM_COL_CT_B0_MX016_NL016_KX08_SRC_H
#define KERNEL_CGEMM_COL_CT_B0_MX016_NL016_KX08_SRC_H
const unsigned int cgemm_Col_CT_B0_MX016_NL016_KX08_workGroupNumRows = 16;
const unsigned int cgemm_Col_CT_B0_MX016_NL016_KX08_workGroupNumCols = 16;
const unsigned int cgemm_Col_CT_B0_MX016_NL016_KX08_microTileNumRows = 1;
const unsigned int cgemm_Col_CT_B0_MX016_NL016_KX08_microTileNumCols = 1;
const unsigned int cgemm_Col_CT_B0_MX016_NL016_KX08_unroll = 8;
const char * const cgemm_Col_CT_B0_MX016_NL016_KX08_src ="\n"
"/* cgemm_Col_CT_B0_MX016_NL016_KX08 */\n"
"\n"
"/* kernel parameters */\n"
"#define WG_NUM_ROWS 16\n"
"#define WG_NUM_COLS 16\n"
"#define MICRO_TILE_NUM_ROWS 1\n"
"#define MICRO_TILE_NUM_COLS 1\n"
"#define MACRO_TILE_NUM_ROWS 16\n"
"#define MACRO_TILE_NUM_COLS 16\n"
"#define NUM_UNROLL_ITER 8\n"
"\n"
"#define LOCAL_ROW_PAD 0\n"
"#define LOCAL_COL_PAD 0\n"
"\n"
"/* global memory indices */\n"
"#define GET_GLOBAL_INDEX_A(ROW,COL) ((ROW)*lda+(COL))\n"
"#define GET_GLOBAL_INDEX_B(ROW,COL) ((ROW)*ldb+(COL))\n"
"#define GET_GLOBAL_INDEX_C(ROW,COL) ((COL)*ldc+(ROW))\n"
"\n"
"/* local memory indices */\n"
"#define GET_LOCAL_INDEX_A(ROW,COL) ((ROW) + (COL)*((MACRO_TILE_NUM_ROWS)+(LOCAL_COL_PAD)) )\n"
"#define GET_LOCAL_INDEX_B(ROW,COL) ((COL) + (ROW)*((MACRO_TILE_NUM_COLS)+(LOCAL_ROW_PAD)) )\n"
"\n"
"/* data types */\n"
"#define DATA_TYPE_STR float2\n"
"#define TYPE_MAD(MULA,MULB,DST) \\\n"
" DST.s0 = mad( MULA.s0, MULB.s0, DST.s0 ); \\\n"
" DST.s0 = mad( MULA.s1, MULB.s1, DST.s0 ); \\\n"
" DST.s1 = mad( MULA.s0, MULB.s1, DST.s1 ); \\\n"
" DST.s1 = mad( -MULA.s1, MULB.s0, DST.s1 );\n"
"#define TYPE_MAD_WRITE( DST, ALPHA, REG, BETA ) \\\n"
" /* (1) */ \\\n"
" type_mad_tmp = REG.s0; \\\n"
" REG.s0 *= ALPHA.s0; \\\n"
" REG.s0 = mad( -ALPHA.s1, REG.s1, REG.s0 ); \\\n"
" REG.s1 *= ALPHA.s0; \\\n"
" REG.s1 = mad( ALPHA.s1, type_mad_tmp, REG.s1 ); \\\n"
" DST = REG;\n"
"\n"
"/* 1x1 micro-tile */\n"
"#define MICRO_TILE \\\n"
" rA[0] = localA[offA + 0*WG_NUM_ROWS]; \\\n"
" rB[0] = localB[offB + 0*WG_NUM_COLS]; \\\n"
" offA += (MACRO_TILE_NUM_ROWS+LOCAL_COL_PAD); \\\n"
" offB += (MACRO_TILE_NUM_COLS+LOCAL_ROW_PAD); \\\n"
" TYPE_MAD(rA[0],rB[0],rC[0][0]); \\\n"
" mem_fence(CLK_LOCAL_MEM_FENCE);\n"
"\n"
"__attribute__((reqd_work_group_size(WG_NUM_COLS,WG_NUM_ROWS,1)))\n"
"__kernel void cgemm_Col_CT_B0_MX016_NL016_KX08(\n"
" __global DATA_TYPE_STR const * restrict A,\n"
" __global DATA_TYPE_STR const * restrict B,\n"
" __global DATA_TYPE_STR * C,\n"
" DATA_TYPE_STR const alpha,\n"
" DATA_TYPE_STR const beta,\n"
" uint const M,\n"
" uint const N,\n"
" uint const K,\n"
" uint const lda,\n"
" uint const ldb,\n"
" uint const ldc,\n"
" uint const offsetA,\n"
" uint const offsetB,\n"
" uint const offsetC\n"
") {\n"
"\n"
" /* apply offsets */\n"
" A += offsetA;\n"
" B += offsetB;\n"
" C += offsetC;\n"
"\n"
" /* allocate registers */\n"
" DATA_TYPE_STR rC[MICRO_TILE_NUM_ROWS][MICRO_TILE_NUM_COLS] = { {0} };\n"
" DATA_TYPE_STR rA[MICRO_TILE_NUM_ROWS];\n"
" DATA_TYPE_STR rB[MICRO_TILE_NUM_COLS];\n"
"\n"
" /* allocate local memory */\n"
" __local DATA_TYPE_STR localA[NUM_UNROLL_ITER*(MACRO_TILE_NUM_ROWS+LOCAL_COL_PAD)];\n"
" __local DATA_TYPE_STR localB[NUM_UNROLL_ITER*(MACRO_TILE_NUM_COLS+LOCAL_ROW_PAD)];\n"
"\n"
" /* work item indices */\n"
" uint groupRow = get_group_id(0);\n"
" uint groupCol = N / 16; // last column\n"
" uint localRow = get_local_id(0);\n"
" uint localCol = get_local_id(1);\n"
" uint localSerial = localRow + localCol*WG_NUM_ROWS;\n"
"\n"
" /* global indices being loaded */\n"
"#define globalARow(LID) (groupRow*MACRO_TILE_NUM_ROWS + (localSerial+(LID)*WG_NUM_ROWS*WG_NUM_COLS)/NUM_UNROLL_ITER)\n"
"#define globalACol(LID) ((localSerial+(LID)*WG_NUM_ROWS*WG_NUM_COLS)%NUM_UNROLL_ITER)\n"
"#define globalBRow(LID) ((localSerial+(LID)*WG_NUM_ROWS*WG_NUM_COLS)/MACRO_TILE_NUM_COLS)\n"
"#define globalBCol(LID) (groupCol*MACRO_TILE_NUM_COLS + (localSerial+(LID)*WG_NUM_ROWS*WG_NUM_COLS)%MACRO_TILE_NUM_COLS)\n"
"\n"
" /* loop over k */\n"
" uint block_k = K / NUM_UNROLL_ITER;\n"
" do {\n"
"\n"
" /* local indices being written */\n"
"#define localARow (localSerial / NUM_UNROLL_ITER)\n"
"#define localACol (localSerial % NUM_UNROLL_ITER)\n"
"#define localAStride (WG_NUM_ROWS*WG_NUM_COLS/NUM_UNROLL_ITER)\n"
"#define localBRow ( localSerial / MACRO_TILE_NUM_COLS )\n"
"#define localBCol ( localSerial % MACRO_TILE_NUM_COLS )\n"
"#define localBStride (WG_NUM_ROWS*WG_NUM_COLS)\n"
" __local DATA_TYPE_STR *lA = localA + GET_LOCAL_INDEX_A(localARow, localACol);\n"
" __local DATA_TYPE_STR *lB = localB + GET_LOCAL_INDEX_B(localBRow, localBCol);\n"
" barrier(CLK_LOCAL_MEM_FENCE);\n"
"\n"
" /* load global -> local */\n"
" if ( localSerial + 0*WG_NUM_ROWS*WG_NUM_COLS < (WG_NUM_ROWS*MICRO_TILE_NUM_ROWS*NUM_UNROLL_ITER) ) {\n"
" lA[ 0*localAStride ] = A[ GET_GLOBAL_INDEX_A( globalARow(0), globalACol(0) ) ];\n"
" }\n"
" if ( localSerial + 0*WG_NUM_ROWS*WG_NUM_COLS < (WG_NUM_COLS*MICRO_TILE_NUM_COLS*NUM_UNROLL_ITER) ) {\n"
" lB[ 0*localBStride ] = (globalBCol(0) >= N) ? (float2)(0.f, 0.f) : B[ GET_GLOBAL_INDEX_B( globalBRow(0), globalBCol(0) ) ];\n"
" }\n"
" barrier(CLK_LOCAL_MEM_FENCE);\n"
" uint offA = localRow;\n"
" uint offB = localCol;\n"
"\n"
" /* do mads */\n"
" MICRO_TILE\n"
" MICRO_TILE\n"
" MICRO_TILE\n"
" MICRO_TILE\n"
" MICRO_TILE\n"
" MICRO_TILE\n"
" MICRO_TILE\n"
" MICRO_TILE\n"
"\n"
" /* shift to next k block */\n"
" A += NUM_UNROLL_ITER;\n"
" B += ldb*NUM_UNROLL_ITER;\n"
"\n"
" } while (--block_k > 0);\n"
"\n"
"\n"
" /* which global Cij index */\n"
" uint globalCRow = groupRow * MACRO_TILE_NUM_ROWS + localRow;\n"
" uint globalCCol = groupCol * MACRO_TILE_NUM_COLS + localCol;\n"
"\n"
" /* write global Cij */\n"
" float type_mad_tmp;\n"
" if (globalCCol+0*WG_NUM_COLS < N){ TYPE_MAD_WRITE( C[ GET_GLOBAL_INDEX_C( globalCRow+0*WG_NUM_ROWS, globalCCol+0*WG_NUM_COLS) ], alpha, rC[0][0], beta )}\n"
"\n"
"}\n"
"";
#else
#endif
|
/*
* Copyright (C) 2018 Apple Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. 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 APPLE INC. ``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 APPLE INC. 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 "PerThread.h"
#include "BExport.h"
#include "Cache.h"
#include "Heap.h"
namespace bmalloc {
#if !HAVE_PTHREAD_MACHDEP_H
template<> BEXPORT bool PerThreadStorage<PerHeapKind<Cache>>::s_didInitialize = false;
template<> BEXPORT pthread_key_t PerThreadStorage<PerHeapKind<Cache>>::s_key = 0;
template<> BEXPORT std::once_flag PerThreadStorage<PerHeapKind<Cache>>::s_onceFlag = { };
template<> BEXPORT bool PerThreadStorage<PerHeapKind<Heap>>::s_didInitialize = false;
template<> BEXPORT pthread_key_t PerThreadStorage<PerHeapKind<Heap>>::s_key = 0;
template<> BEXPORT std::once_flag PerThreadStorage<PerHeapKind<Heap>>::s_onceFlag = { };
#endif
} // namespace bmalloc
|
/*
* Copyright 2019-2020 Diligent Graphics LLC
* Copyright 2015-2019 Egor Yusov
*
* 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.
*
* In no event and under no legal theory, whether in tort (including negligence),
* contract, or otherwise, unless required by applicable law (such as deliberate
* and grossly negligent acts) or agreed to in writing, shall any Contributor be
* liable for any damages, including any direct, indirect, special, incidental,
* or consequential damages of any character arising as a result of this License or
* out of the use or inability to use the software (including but not limited to damages
* for loss of goodwill, work stoppage, computer failure or malfunction, or any and
* all other commercial damages or losses), even if such Contributor has been advised
* of the possibility of such damages.
*/
#pragma once
#include <memory>
#include <chrono>
#include "ImGuiImplDiligent.hpp"
struct _XCBKeySymbols;
namespace Diligent
{
class ImGuiImplLinuxXCB final : public ImGuiImplDiligent
{
public:
ImGuiImplLinuxXCB(xcb_connection_t* connection,
IRenderDevice* pDevice,
TEXTURE_FORMAT BackBufferFmt,
TEXTURE_FORMAT DepthBufferFmt,
Uint32 DisplayWidht,
Uint32 DisplayHeight,
Uint32 InitialVertexBufferSize = ImGuiImplDiligent::DefaultInitialVBSize,
Uint32 InitialIndexBufferSize = ImGuiImplDiligent::DefaultInitialIBSize);
~ImGuiImplLinuxXCB();
// clang-format off
ImGuiImplLinuxXCB (const ImGuiImplLinuxXCB&) = delete;
ImGuiImplLinuxXCB ( ImGuiImplLinuxXCB&&) = delete;
ImGuiImplLinuxXCB& operator = (const ImGuiImplLinuxXCB&) = delete;
ImGuiImplLinuxXCB& operator = ( ImGuiImplLinuxXCB&&) = delete;
// clang-format on
bool HandleXCBEvent(xcb_generic_event_t* event);
virtual void NewFrame(Uint32 RenderSurfaceWidth,
Uint32 RenderSurfaceHeight,
SURFACE_TRANSFORM SurfacePreTransform) override final;
private:
void HandleKeyEvent(xcb_key_release_event_t* event);
_XCBKeySymbols* m_syms = nullptr;
std::chrono::time_point<std::chrono::high_resolution_clock> m_LastTimestamp = {};
};
} // namespace Diligent
|
// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2014 The Bitcoin developers
// Copyright (c) 2014-2015 The Dash developers
// Copyright (c) 2015-2017 The PIVX developers
// Copyright (c) 2018 The IoTHome developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "main.h"
#include "accumulators.h"
#include "addrman.h"
#include "alert.h"
#include "chainparams.h"
#include "checkpoints.h"
#include "checkqueue.h"
#include "init.h"
#include "kernel.h"
#include "masternode-budget.h"
#include "masternode-payments.h"
#include "masternodeman.h"
#include "merkleblock.h"
#include "net.h"
#include "obfuscation.h"
#include "pow.h"
#include "spork.h"
#include "sporkdb.h"
#include "swifttx.h"
#include "txdb.h"
#include "txmempool.h"
#include "ui_interface.h"
#include "util.h"
#include "utilmoneystr.h"
#include "primitives/zerocoin.h"
#include "libzerocoin/Denominations.h"
#include <sstream>
#include <boost/algorithm/string/replace.hpp>
#include <boost/filesystem.hpp>
#include <boost/filesystem/fstream.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/thread.hpp>
using namespace boost;
using namespace std;
using namespace libzerocoin;
#if defined(NDEBUG)
#error "IoTHome cannot be compiled without assertions."
#endif
// 6 comes from OPCODE (1) + vch.size() (1) + BIGNUM size (4)
#define SCRIPT_OFFSET 6
// For Script size (BIGNUM/Uint256 size)
#define BIGNUM_SIZE 4
/**
* Global state
*/
CCriticalSection cs_main;
BlockMap mapBlockIndex;
map<uint256, uint256> mapProofOfStake;
set<pair<COutPoint, unsigned int> > setStakeSeen;
map<unsigned int, unsigned int> mapHashedBlocks;
CChain chainActive;
CBlockIndex* pindexBestHeader = NULL;
int64_t nTimeBestReceived = 0;
CWaitableCriticalSection csBestBlock;
CConditionVariable cvBlockChange;
int nScriptCheckThreads = 0;
bool fImporting = false;
bool fReindex = false;
bool fTxIndex = true;
bool fIsBareMultisigStd = true;
bool fCheckBlockIndex = false;
bool fVerifyingBlocks = false;
unsigned int nCoinCacheSize = 5000;
bool fAlerts = DEFAULT_ALERTS;
//unsigned int nStakeMinAge = 6 * 60 * 60; //6 hours
static unsigned int nStakeMinAgeV1 = 1 * 60 * 60; // 6 hours
static unsigned int nStakeMinAgeV2 = nStakeMinAgeV1; //1 hr
const int targetReadjustment_forkBlockHeight = 700; //retargeting since 700 block
const int targetFork1 = 200790; //fork since block 200,790
int64_t nReserveBalance = 0;
bool IsProtocolMaturityV2(int nHeight)
{
return(nHeight >= targetReadjustment_forkBlockHeight);
}
unsigned int GetStakeMinAge(int nHeight)
{
if(IsProtocolMaturityV2(nHeight))
return nStakeMinAgeV2;
else
return nStakeMinAgeV1;
}
int GetMinPeerProtoVersion(int nHeight)
{
return PROTOCOL_VERSION; //2.2.0
}
/** Fees smaller than this (in duffs) are considered zero fee (for relaying and mining)
* We are ~100 times smaller then bitcoin now (2015-06-23), set minRelayTxFee only 10 times higher
* so it's still 10 times lower comparing to bitcoin.
*/
CFeeRate minRelayTxFee = CFeeRate(10000);
CTxMemPool mempool(::minRelayTxFee);
struct COrphanTx {
CTransaction tx;
NodeId fromPeer;
};
map<uint256, COrphanTx> mapOrphanTransactions;
map<uint256, set<uint256> > mapOrphanTransactionsByPrev;
map<uint256, int64_t> mapRejectedBlocks;
void EraseOrphansFor(NodeId peer);
static void CheckBlockIndex();
/** Constant stuff for coinbase transactions we create: */
CScript COINBASE_FLAGS;
const string strMessageMagic = "DarkNet Signed Message:\n";
// Internal stuff
namespace
{
struct CBlockIndexWorkComparator {
bool operator()(CBlockIndex* pa, CBlockIndex* pb) const
{
// First sort by most total work, ...
if (pa->nChainWork > pb->nChainWork) return false;
if (pa->nChainWork < pb->nChainWork) return true;
// ... then by earliest time received, ...
if (pa->nSequenceId < pb->nSequenceId) return false;
if (pa->nSequenceId > pb->nSequenceId) return true;
// Use pointer address as tie breaker (should only happen with blocks
// loaded from disk, as those all have id 0).
if (pa < pb) return false;
if (pa > pb) return true;
// Identical blocks.
return false;
}
};
CBlockIndex* pindexBestInvalid;
/**
* The set of all CBlockIndex entries with BLOCK_VALID_TRANSACTIONS (for itself and all ancestors) and
* as good as our current tip or better. Entries may be failed, though.
*/
set<CBlockIndex*, CBlockIndexWorkComparator> setBlockIndexCandidates;
/** Number of nodes with fSyncStarted. */
int nSyncStarted = 0;
/** All pairs A->B, where A (or one if its ancestors) misses transactions, but B has transactions. */
multimap<CBlockIndex*, CBlockIndex*> mapBlocksUnlinked;
CCriticalSection cs_LastBlockFile;
std::vector<CBlockFileInfo> vinfoBlockFile;
int nLastBlockFile = 0;
/**
* Every received block is assigned a unique and increasing identifier, so we
* know which one to give priority in case of a fork.
*/
CCriticalSection cs_nBlockSequenceId;
/** Blocks loaded from disk are assigned id 0, so start the counter at 1. */
uint32_t nBlockSequenceId = 1;
/**
* Sources of received blocks, to be able to send them reject messages or ban
* them, if processing happens afterwards. Protected by cs_main.
*/
map<uint256, NodeId> mapBlockSource;
/** Blocks that are in flight, and that are in the queue to be downloaded. Protected by cs_main. */
struct QueuedBlock {
uint256 hash;
CBlockIndex* pindex; //! Optional.
int64_t nTime; //! Time of "getdata" request in microseconds.
int nValidatedQueuedBefore; //! Number of blocks queued with validated headers (globally) at the time this one is requested.
bool fValidatedHeaders; //! Whether this block has validated headers at the time of request.
};
map<uint256, pair<NodeId, list<QueuedBlock>::iterator> > mapBlocksInFlight;
/** Number of blocks in flight with validated headers. */
int nQueuedValidatedHeaders = 0;
/** Number of preferable block download peers. */
int nPreferredDownload = 0;
/** Dirty block index entries. */
set<CBlockIndex*> setDirtyBlockIndex;
/** Dirty block file entries. */
set<int> setDirtyFileInfo;
} // anon namespace
//////////////////////////////////////////////////////////////////////////////
//
// dispatching functions
//
// These functions dispatch to one or all registered wallets
namespace
{
struct CMainSignals {
/** Notifies listeners of updated transaction data (transaction, and optionally the block it is found in. */
boost::signals2::signal<void(const CTransaction&, const CBlock*)> SyncTransaction;
/** Notifies listeners of an erased transaction (currently disabled, requires transaction replacement). */
// XX42 boost::signals2::signal<void(const uint256&)> EraseTransaction;
/** Notifies listeners of an updated transaction without new data (for now: a coinbase potentially becoming visible). */
boost::signals2::signal<void(const uint256&)> UpdatedTransaction;
/** Notifies listeners of a new active block chain. */
boost::signals2::signal<void(const CBlockLocator&)> SetBestChain;
/** Notifies listeners about an inventory item being seen on the network. */
boost::signals2::signal<void(const uint256&)> Inventory;
/** Tells listeners to broadcast their data. */
boost::signals2::signal<void()> Broadcast;
/** Notifies listeners of a block validation result */
boost::signals2::signal<void(const CBlock&, const CValidationState&)> BlockChecked;
} g_signals;
} // anon namespace
void RegisterValidationInterface(CValidationInterface* pwalletIn)
{
g_signals.SyncTransaction.connect(boost::bind(&CValidationInterface::SyncTransaction, pwalletIn, _1, _2));
// XX42 g_signals.EraseTransaction.connect(boost::bind(&CValidationInterface::EraseFromWallet, pwalletIn, _1));
g_signals.UpdatedTransaction.connect(boost::bind(&CValidationInterface::UpdatedTransaction, pwalletIn, _1));
g_signals.SetBestChain.connect(boost::bind(&CValidationInterface::SetBestChain, pwalletIn, _1));
g_signals.Inventory.connect(boost::bind(&CValidationInterface::Inventory, pwalletIn, _1));
g_signals.Broadcast.connect(boost::bind(&CValidationInterface::ResendWalletTransactions, pwalletIn));
g_signals.BlockChecked.connect(boost::bind(&CValidationInterface::BlockChecked, pwalletIn, _1, _2));
}
void UnregisterValidationInterface(CValidationInterface* pwalletIn)
{
g_signals.BlockChecked.disconnect(boost::bind(&CValidationInterface::BlockChecked, pwalletIn, _1, _2));
g_signals.Broadcast.disconnect(boost::bind(&CValidationInterface::ResendWalletTransactions, pwalletIn));
g_signals.Inventory.disconnect(boost::bind(&CValidationInterface::Inventory, pwalletIn, _1));
g_signals.SetBestChain.disconnect(boost::bind(&CValidationInterface::SetBestChain, pwalletIn, _1));
g_signals.UpdatedTransaction.disconnect(boost::bind(&CValidationInterface::UpdatedTransaction, pwalletIn, _1));
// XX42 g_signals.EraseTransaction.disconnect(boost::bind(&CValidationInterface::EraseFromWallet, pwalletIn, _1));
g_signals.SyncTransaction.disconnect(boost::bind(&CValidationInterface::SyncTransaction, pwalletIn, _1, _2));
}
void UnregisterAllValidationInterfaces()
{
g_signals.BlockChecked.disconnect_all_slots();
g_signals.Broadcast.disconnect_all_slots();
g_signals.Inventory.disconnect_all_slots();
g_signals.SetBestChain.disconnect_all_slots();
g_signals.UpdatedTransaction.disconnect_all_slots();
// XX42 g_signals.EraseTransaction.disconnect_all_slots();
g_signals.SyncTransaction.disconnect_all_slots();
}
void SyncWithWallets(const CTransaction& tx, const CBlock* pblock)
{
g_signals.SyncTransaction(tx, pblock);
}
//////////////////////////////////////////////////////////////////////////////
//
// Registration of network node signals.
//
namespace
{
struct CBlockReject {
unsigned char chRejectCode;
string strRejectReason;
uint256 hashBlock;
};
/**
* Maintain validation-specific state about nodes, protected by cs_main, instead
* by CNode's own locks. This simplifies asynchronous operation, where
* processing of incoming data is done after the ProcessMessage call returns,
* and we're no longer holding the node's locks.
*/
struct CNodeState {
//! The peer's address
CService address;
//! Whether we have a fully established connection.
bool fCurrentlyConnected;
//! Accumulated misbehaviour score for this peer.
int nMisbehavior;
//! Whether this peer should be disconnected and banned (unless whitelisted).
bool fShouldBan;
//! String name of this peer (debugging/logging purposes).
std::string name;
//! List of asynchronously-determined block rejections to notify this peer about.
std::vector<CBlockReject> rejects;
//! The best known block we know this peer has announced.
CBlockIndex* pindexBestKnownBlock;
//! The hash of the last unknown block this peer has announced.
uint256 hashLastUnknownBlock;
//! The last full block we both have.
CBlockIndex* pindexLastCommonBlock;
//! Whether we've started headers synchronization with this peer.
bool fSyncStarted;
//! Since when we're stalling block download progress (in microseconds), or 0.
int64_t nStallingSince;
list<QueuedBlock> vBlocksInFlight;
int nBlocksInFlight;
//! Whether we consider this a preferred download peer.
bool fPreferredDownload;
CNodeState()
{
fCurrentlyConnected = false;
nMisbehavior = 0;
fShouldBan = false;
pindexBestKnownBlock = NULL;
hashLastUnknownBlock = uint256(0);
pindexLastCommonBlock = NULL;
fSyncStarted = false;
nStallingSince = 0;
nBlocksInFlight = 0;
fPreferredDownload = false;
}
};
/** Map maintaining per-node state. Requires cs_main. */
map<NodeId, CNodeState> mapNodeState;
// Requires cs_main.
CNodeState* State(NodeId pnode)
{
map<NodeId, CNodeState>::iterator it = mapNodeState.find(pnode);
if (it == mapNodeState.end())
return NULL;
return &it->second;
}
int GetHeight()
{
while (true) {
TRY_LOCK(cs_main, lockMain);
if (!lockMain) {
MilliSleep(50);
continue;
}
return chainActive.Height();
}
}
void UpdatePreferredDownload(CNode* node, CNodeState* state)
{
nPreferredDownload -= state->fPreferredDownload;
// Whether this node should be marked as a preferred download node.
state->fPreferredDownload = (!node->fInbound || node->fWhitelisted) && !node->fOneShot && !node->fClient;
nPreferredDownload += state->fPreferredDownload;
}
void InitializeNode(NodeId nodeid, const CNode* pnode)
{
LOCK(cs_main);
CNodeState& state = mapNodeState.insert(std::make_pair(nodeid, CNodeState())).first->second;
state.name = pnode->addrName;
state.address = pnode->addr;
}
void FinalizeNode(NodeId nodeid)
{
LOCK(cs_main);
CNodeState* state = State(nodeid);
if (state->fSyncStarted)
nSyncStarted--;
if (state->nMisbehavior == 0 && state->fCurrentlyConnected) {
AddressCurrentlyConnected(state->address);
}
BOOST_FOREACH (const QueuedBlock& entry, state->vBlocksInFlight)
mapBlocksInFlight.erase(entry.hash);
EraseOrphansFor(nodeid);
nPreferredDownload -= state->fPreferredDownload;
mapNodeState.erase(nodeid);
}
// Requires cs_main.
void MarkBlockAsReceived(const uint256& hash)
{
map<uint256, pair<NodeId, list<QueuedBlock>::iterator> >::iterator itInFlight = mapBlocksInFlight.find(hash);
if (itInFlight != mapBlocksInFlight.end()) {
CNodeState* state = State(itInFlight->second.first);
nQueuedValidatedHeaders -= itInFlight->second.second->fValidatedHeaders;
state->vBlocksInFlight.erase(itInFlight->second.second);
state->nBlocksInFlight--;
state->nStallingSince = 0;
mapBlocksInFlight.erase(itInFlight);
}
}
// Requires cs_main.
void MarkBlockAsInFlight(NodeId nodeid, const uint256& hash, CBlockIndex* pindex = NULL)
{
CNodeState* state = State(nodeid);
assert(state != NULL);
// Make sure it's not listed somewhere already.
MarkBlockAsReceived(hash);
QueuedBlock newentry = {hash, pindex, GetTimeMicros(), nQueuedValidatedHeaders, pindex != NULL};
nQueuedValidatedHeaders += newentry.fValidatedHeaders;
list<QueuedBlock>::iterator it = state->vBlocksInFlight.insert(state->vBlocksInFlight.end(), newentry);
state->nBlocksInFlight++;
mapBlocksInFlight[hash] = std::make_pair(nodeid, it);
}
/** Check whether the last unknown block a peer advertized is not yet known. */
void ProcessBlockAvailability(NodeId nodeid)
{
CNodeState* state = State(nodeid);
assert(state != NULL);
if (state->hashLastUnknownBlock != 0) {
BlockMap::iterator itOld = mapBlockIndex.find(state->hashLastUnknownBlock);
if (itOld != mapBlockIndex.end() && itOld->second->nChainWork > 0) {
if (state->pindexBestKnownBlock == NULL || itOld->second->nChainWork >= state->pindexBestKnownBlock->nChainWork)
state->pindexBestKnownBlock = itOld->second;
state->hashLastUnknownBlock = uint256(0);
}
}
}
/** Update tracking information about which blocks a peer is assumed to have. */
void UpdateBlockAvailability(NodeId nodeid, const uint256& hash)
{
CNodeState* state = State(nodeid);
assert(state != NULL);
ProcessBlockAvailability(nodeid);
BlockMap::iterator it = mapBlockIndex.find(hash);
if (it != mapBlockIndex.end() && it->second->nChainWork > 0) {
// An actually better block was announced.
if (state->pindexBestKnownBlock == NULL || it->second->nChainWork >= state->pindexBestKnownBlock->nChainWork)
state->pindexBestKnownBlock = it->second;
} else {
// An unknown block was announced; just assume that the latest one is the best one.
state->hashLastUnknownBlock = hash;
}
}
/** Find the last common ancestor two blocks have.
* Both pa and pb must be non-NULL. */
CBlockIndex* LastCommonAncestor(CBlockIndex* pa, CBlockIndex* pb)
{
if (pa->nHeight > pb->nHeight) {
pa = pa->GetAncestor(pb->nHeight);
} else if (pb->nHeight > pa->nHeight) {
pb = pb->GetAncestor(pa->nHeight);
}
while (pa != pb && pa && pb) {
pa = pa->pprev;
pb = pb->pprev;
}
// Eventually all chain branches meet at the genesis block.
assert(pa == pb);
return pa;
}
/** Update pindexLastCommonBlock and add not-in-flight missing successors to vBlocks, until it has
* at most count entries. */
void FindNextBlocksToDownload(NodeId nodeid, unsigned int count, std::vector<CBlockIndex*>& vBlocks, NodeId& nodeStaller)
{
if (count == 0)
return;
vBlocks.reserve(vBlocks.size() + count);
CNodeState* state = State(nodeid);
assert(state != NULL);
// Make sure pindexBestKnownBlock is up to date, we'll need it.
ProcessBlockAvailability(nodeid);
if (state->pindexBestKnownBlock == NULL || state->pindexBestKnownBlock->nChainWork < chainActive.Tip()->nChainWork) {
// This peer has nothing interesting.
return;
}
if (state->pindexLastCommonBlock == NULL) {
// Bootstrap quickly by guessing a parent of our best tip is the forking point.
// Guessing wrong in either direction is not a problem.
state->pindexLastCommonBlock = chainActive[std::min(state->pindexBestKnownBlock->nHeight, chainActive.Height())];
}
// If the peer reorganized, our previous pindexLastCommonBlock may not be an ancestor
// of their current tip anymore. Go back enough to fix that.
state->pindexLastCommonBlock = LastCommonAncestor(state->pindexLastCommonBlock, state->pindexBestKnownBlock);
if (state->pindexLastCommonBlock == state->pindexBestKnownBlock)
return;
std::vector<CBlockIndex*> vToFetch;
CBlockIndex* pindexWalk = state->pindexLastCommonBlock;
// Never fetch further than the best block we know the peer has, or more than BLOCK_DOWNLOAD_WINDOW + 1 beyond the last
// linked block we have in common with this peer. The +1 is so we can detect stalling, namely if we would be able to
// download that next block if the window were 1 larger.
int nWindowEnd = state->pindexLastCommonBlock->nHeight + BLOCK_DOWNLOAD_WINDOW;
int nMaxHeight = std::min<int>(state->pindexBestKnownBlock->nHeight, nWindowEnd + 1);
NodeId waitingfor = -1;
while (pindexWalk->nHeight < nMaxHeight) {
// Read up to 128 (or more, if more blocks than that are needed) successors of pindexWalk (towards
// pindexBestKnownBlock) into vToFetch. We fetch 128, because CBlockIndex::GetAncestor may be as expensive
// as iterating over ~100 CBlockIndex* entries anyway.
int nToFetch = std::min(nMaxHeight - pindexWalk->nHeight, std::max<int>(count - vBlocks.size(), 128));
vToFetch.resize(nToFetch);
pindexWalk = state->pindexBestKnownBlock->GetAncestor(pindexWalk->nHeight + nToFetch);
vToFetch[nToFetch - 1] = pindexWalk;
for (unsigned int i = nToFetch - 1; i > 0; i--) {
vToFetch[i - 1] = vToFetch[i]->pprev;
}
// Iterate over those blocks in vToFetch (in forward direction), adding the ones that
// are not yet downloaded and not in flight to vBlocks. In the mean time, update
// pindexLastCommonBlock as long as all ancestors are already downloaded.
BOOST_FOREACH (CBlockIndex* pindex, vToFetch) {
if (!pindex->IsValid(BLOCK_VALID_TREE)) {
// We consider the chain that this peer is on invalid.
return;
}
if (pindex->nStatus & BLOCK_HAVE_DATA) {
if (pindex->nChainTx)
state->pindexLastCommonBlock = pindex;
} else if (mapBlocksInFlight.count(pindex->GetBlockHash()) == 0) {
// The block is not already downloaded, and not yet in flight.
if (pindex->nHeight > nWindowEnd) {
// We reached the end of the window.
if (vBlocks.size() == 0 && waitingfor != nodeid) {
// We aren't able to fetch anything, but we would be if the download window was one larger.
nodeStaller = waitingfor;
}
return;
}
vBlocks.push_back(pindex);
if (vBlocks.size() == count) {
return;
}
} else if (waitingfor == -1) {
// This is the first already-in-flight block.
waitingfor = mapBlocksInFlight[pindex->GetBlockHash()].first;
}
}
}
}
} // anon namespace
bool GetNodeStateStats(NodeId nodeid, CNodeStateStats& stats)
{
LOCK(cs_main);
CNodeState* state = State(nodeid);
if (state == NULL)
return false;
stats.nMisbehavior = state->nMisbehavior;
stats.nSyncHeight = state->pindexBestKnownBlock ? state->pindexBestKnownBlock->nHeight : -1;
stats.nCommonHeight = state->pindexLastCommonBlock ? state->pindexLastCommonBlock->nHeight : -1;
BOOST_FOREACH (const QueuedBlock& queue, state->vBlocksInFlight) {
if (queue.pindex)
stats.vHeightInFlight.push_back(queue.pindex->nHeight);
}
return true;
}
void RegisterNodeSignals(CNodeSignals& nodeSignals)
{
nodeSignals.GetHeight.connect(&GetHeight);
nodeSignals.ProcessMessages.connect(&ProcessMessages);
nodeSignals.SendMessages.connect(&SendMessages);
nodeSignals.InitializeNode.connect(&InitializeNode);
nodeSignals.FinalizeNode.connect(&FinalizeNode);
}
void UnregisterNodeSignals(CNodeSignals& nodeSignals)
{
nodeSignals.GetHeight.disconnect(&GetHeight);
nodeSignals.ProcessMessages.disconnect(&ProcessMessages);
nodeSignals.SendMessages.disconnect(&SendMessages);
nodeSignals.InitializeNode.disconnect(&InitializeNode);
nodeSignals.FinalizeNode.disconnect(&FinalizeNode);
}
CBlockIndex* FindForkInGlobalIndex(const CChain& chain, const CBlockLocator& locator)
{
// Find the first block the caller has in the main chain
BOOST_FOREACH (const uint256& hash, locator.vHave) {
BlockMap::iterator mi = mapBlockIndex.find(hash);
if (mi != mapBlockIndex.end()) {
CBlockIndex* pindex = (*mi).second;
if (chain.Contains(pindex))
return pindex;
}
}
return chain.Genesis();
}
CCoinsViewCache* pcoinsTip = NULL;
CBlockTreeDB* pblocktree = NULL;
CZerocoinDB* zerocoinDB = NULL;
CSporkDB* pSporkDB = NULL;
//////////////////////////////////////////////////////////////////////////////
//
// mapOrphanTransactions
//
bool AddOrphanTx(const CTransaction& tx, NodeId peer)
{
uint256 hash = tx.GetHash();
if (mapOrphanTransactions.count(hash))
return false;
// Ignore big transactions, to avoid a
// send-big-orphans memory exhaustion attack. If a peer has a legitimate
// large transaction with a missing parent then we assume
// it will rebroadcast it later, after the parent transaction(s)
// have been mined or received.
// 10,000 orphans, each of which is at most 5,000 bytes big is
// at most 500 megabytes of orphans:
unsigned int sz = tx.GetSerializeSize(SER_NETWORK, CTransaction::CURRENT_VERSION);
if (sz > 5000) {
LogPrint("mempool", "ignoring large orphan tx (size: %u, hash: %s)\n", sz, hash.ToString());
return false;
}
mapOrphanTransactions[hash].tx = tx;
mapOrphanTransactions[hash].fromPeer = peer;
BOOST_FOREACH (const CTxIn& txin, tx.vin)
mapOrphanTransactionsByPrev[txin.prevout.hash].insert(hash);
LogPrint("mempool", "stored orphan tx %s (mapsz %u prevsz %u)\n", hash.ToString(),
mapOrphanTransactions.size(), mapOrphanTransactionsByPrev.size());
return true;
}
void static EraseOrphanTx(uint256 hash)
{
map<uint256, COrphanTx>::iterator it = mapOrphanTransactions.find(hash);
if (it == mapOrphanTransactions.end())
return;
BOOST_FOREACH (const CTxIn& txin, it->second.tx.vin) {
map<uint256, set<uint256> >::iterator itPrev = mapOrphanTransactionsByPrev.find(txin.prevout.hash);
if (itPrev == mapOrphanTransactionsByPrev.end())
continue;
itPrev->second.erase(hash);
if (itPrev->second.empty())
mapOrphanTransactionsByPrev.erase(itPrev);
}
mapOrphanTransactions.erase(it);
}
void EraseOrphansFor(NodeId peer)
{
int nErased = 0;
map<uint256, COrphanTx>::iterator iter = mapOrphanTransactions.begin();
while (iter != mapOrphanTransactions.end()) {
map<uint256, COrphanTx>::iterator maybeErase = iter++; // increment to avoid iterator becoming invalid
if (maybeErase->second.fromPeer == peer) {
EraseOrphanTx(maybeErase->second.tx.GetHash());
++nErased;
}
}
if (nErased > 0) LogPrint("mempool", "Erased %d orphan tx from peer %d\n", nErased, peer);
}
unsigned int LimitOrphanTxSize(unsigned int nMaxOrphans)
{
unsigned int nEvicted = 0;
while (mapOrphanTransactions.size() > nMaxOrphans) {
// Evict a random orphan:
uint256 randomhash = GetRandHash();
map<uint256, COrphanTx>::iterator it = mapOrphanTransactions.lower_bound(randomhash);
if (it == mapOrphanTransactions.end())
it = mapOrphanTransactions.begin();
EraseOrphanTx(it->first);
++nEvicted;
}
return nEvicted;
}
bool IsStandardTx(const CTransaction& tx, string& reason)
{
AssertLockHeld(cs_main);
if (tx.nVersion > CTransaction::CURRENT_VERSION || tx.nVersion < 1) {
reason = "version";
return false;
}
// Treat non-final transactions as non-standard to prevent a specific type
// of double-spend attack, as well as DoS attacks. (if the transaction
// can't be mined, the attacker isn't expending resources broadcasting it)
// Basically we don't want to propagate transactions that can't be included in
// the next block.
//
// However, IsFinalTx() is confusing... Without arguments, it uses
// chainActive.Height() to evaluate nLockTime; when a block is accepted, chainActive.Height()
// is set to the value of nHeight in the block. However, when IsFinalTx()
// is called within CBlock::AcceptBlock(), the height of the block *being*
// evaluated is what is used. Thus if we want to know if a transaction can
// be part of the *next* block, we need to call IsFinalTx() with one more
// than chainActive.Height().
//
// Timestamps on the other hand don't get any special treatment, because we
// can't know what timestamp the next block will have, and there aren't
// timestamp applications where it matters.
if (!IsFinalTx(tx, chainActive.Height() + 1)) {
reason = "non-final";
return false;
}
// Extremely large transactions with lots of inputs can cost the network
// almost as much to process as they cost the sender in fees, because
// computing signature hashes is O(ninputs*txsize). Limiting transactions
// to MAX_STANDARD_TX_SIZE mitigates CPU exhaustion attacks.
unsigned int sz = tx.GetSerializeSize(SER_NETWORK, CTransaction::CURRENT_VERSION);
unsigned int nMaxSize = tx.ContainsZerocoins() ? MAX_ZEROCOIN_TX_SIZE : MAX_STANDARD_TX_SIZE;
if (sz >= nMaxSize) {
reason = "tx-size";
return false;
}
for (const CTxIn& txin : tx.vin) {
if (txin.scriptSig.IsZerocoinSpend())
continue;
// Biggest 'standard' txin is a 15-of-15 P2SH multisig with compressed
// keys. (remember the 520 byte limit on redeemScript size) That works
// out to a (15*(33+1))+3=513 byte redeemScript, 513+1+15*(73+1)+3=1627
// bytes of scriptSig, which we round off to 1650 bytes for some minor
// future-proofing. That's also enough to spend a 20-of-20
// CHECKMULTISIG scriptPubKey, though such a scriptPubKey is not
// considered standard)
if (txin.scriptSig.size() > 1650) {
reason = "scriptsig-size";
return false;
}
if (!txin.scriptSig.IsPushOnly()) {
reason = "scriptsig-not-pushonly";
return false;
}
}
unsigned int nDataOut = 0;
txnouttype whichType;
BOOST_FOREACH (const CTxOut& txout, tx.vout) {
if (!::IsStandard(txout.scriptPubKey, whichType)) {
reason = "scriptpubkey";
return false;
}
if (whichType == TX_NULL_DATA)
nDataOut++;
else if ((whichType == TX_MULTISIG) && (!fIsBareMultisigStd)) {
reason = "bare-multisig";
return false;
} else if (txout.IsDust(::minRelayTxFee)) {
reason = "dust";
return false;
}
}
// only one OP_RETURN txout is permitted
if (nDataOut > 1) {
reason = "multi-op-return";
return false;
}
return true;
}
bool IsFinalTx(const CTransaction& tx, int nBlockHeight, int64_t nBlockTime)
{
AssertLockHeld(cs_main);
// Time based nLockTime implemented in 0.1.6
if (tx.nLockTime == 0)
return true;
if (nBlockHeight == 0)
nBlockHeight = chainActive.Height();
if (nBlockTime == 0)
nBlockTime = GetAdjustedTime();
if ((int64_t)tx.nLockTime < ((int64_t)tx.nLockTime < LOCKTIME_THRESHOLD ? (int64_t)nBlockHeight : nBlockTime))
return true;
BOOST_FOREACH (const CTxIn& txin, tx.vin)
if (!txin.IsFinal())
return false;
return true;
}
/**
* Check transaction inputs to mitigate two
* potential denial-of-service attacks:
*
* 1. scriptSigs with extra data stuffed into them,
* not consumed by scriptPubKey (or P2SH script)
* 2. P2SH scripts with a crazy number of expensive
* CHECKSIG/CHECKMULTISIG operations
*/
bool AreInputsStandard(const CTransaction& tx, const CCoinsViewCache& mapInputs)
{
if (tx.IsCoinBase() || tx.IsZerocoinSpend())
return true; // coinbase has no inputs and zerocoinspend has a special input
//todo should there be a check for a 'standard' zerocoinspend here?
for (unsigned int i = 0; i < tx.vin.size(); i++) {
const CTxOut& prev = mapInputs.GetOutputFor(tx.vin[i]);
vector<vector<unsigned char> > vSolutions;
txnouttype whichType;
// get the scriptPubKey corresponding to this input:
const CScript& prevScript = prev.scriptPubKey;
if (!Solver(prevScript, whichType, vSolutions))
return false;
int nArgsExpected = ScriptSigArgsExpected(whichType, vSolutions);
if (nArgsExpected < 0)
return false;
// Transactions with extra stuff in their scriptSigs are
// non-standard. Note that this EvalScript() call will
// be quick, because if there are any operations
// beside "push data" in the scriptSig
// IsStandard() will have already returned false
// and this method isn't called.
vector<vector<unsigned char> > stack;
if (!EvalScript(stack, tx.vin[i].scriptSig, false, BaseSignatureChecker()))
return false;
if (whichType == TX_SCRIPTHASH) {
if (stack.empty())
return false;
CScript subscript(stack.back().begin(), stack.back().end());
vector<vector<unsigned char> > vSolutions2;
txnouttype whichType2;
if (Solver(subscript, whichType2, vSolutions2)) {
int tmpExpected = ScriptSigArgsExpected(whichType2, vSolutions2);
if (tmpExpected < 0)
return false;
nArgsExpected += tmpExpected;
} else {
// Any other Script with less than 15 sigops OK:
unsigned int sigops = subscript.GetSigOpCount(true);
// ... extra data left on the stack after execution is OK, too:
return (sigops <= MAX_P2SH_SIGOPS);
}
}
if (stack.size() != (unsigned int)nArgsExpected)
return false;
}
return true;
}
unsigned int GetLegacySigOpCount(const CTransaction& tx)
{
unsigned int nSigOps = 0;
BOOST_FOREACH (const CTxIn& txin, tx.vin) {
nSigOps += txin.scriptSig.GetSigOpCount(false);
}
BOOST_FOREACH (const CTxOut& txout, tx.vout) {
nSigOps += txout.scriptPubKey.GetSigOpCount(false);
}
return nSigOps;
}
unsigned int GetP2SHSigOpCount(const CTransaction& tx, const CCoinsViewCache& inputs)
{
if (tx.IsCoinBase() || tx.IsZerocoinSpend())
return 0;
unsigned int nSigOps = 0;
for (unsigned int i = 0; i < tx.vin.size(); i++) {
const CTxOut& prevout = inputs.GetOutputFor(tx.vin[i]);
if (prevout.scriptPubKey.IsPayToScriptHash())
nSigOps += prevout.scriptPubKey.GetSigOpCount(tx.vin[i].scriptSig);
}
return nSigOps;
}
int GetInputAge(CTxIn& vin)
{
CCoinsView viewDummy;
CCoinsViewCache view(&viewDummy);
{
LOCK(mempool.cs);
CCoinsViewMemPool viewMempool(pcoinsTip, mempool);
view.SetBackend(viewMempool); // temporarily switch cache backend to db+mempool view
const CCoins* coins = view.AccessCoins(vin.prevout.hash);
if (coins) {
if (coins->nHeight < 0) return 0;
return (chainActive.Tip()->nHeight + 1) - coins->nHeight;
} else
return -1;
}
}
int GetInputAgeIX(uint256 nTXHash, CTxIn& vin)
{
int sigs = 0;
int nResult = GetInputAge(vin);
if (nResult < 0) nResult = 0;
if (nResult < 6) {
std::map<uint256, CTransactionLock>::iterator i = mapTxLocks.find(nTXHash);
if (i != mapTxLocks.end()) {
sigs = (*i).second.CountSignatures();
}
if (sigs >= SWIFTTX_SIGNATURES_REQUIRED) {
return nSwiftTXDepth + nResult;
}
}
return -1;
}
int GetIXConfirmations(uint256 nTXHash)
{
int sigs = 0;
std::map<uint256, CTransactionLock>::iterator i = mapTxLocks.find(nTXHash);
if (i != mapTxLocks.end()) {
sigs = (*i).second.CountSignatures();
}
if (sigs >= SWIFTTX_SIGNATURES_REQUIRED) {
return nSwiftTXDepth;
}
return 0;
}
bool MoneyRange(CAmount nValueOut)
{
return nValueOut >= 0 && nValueOut <= Params().MaxMoneyOut();
}
int GetZerocoinStartHeight()
{
return Params().Zerocoin_StartHeight();
}
void FindMints(vector<CZerocoinMint> vMintsToFind, vector<CZerocoinMint>& vMintsToUpdate, vector<CZerocoinMint>& vMissingMints, bool fExtendedSearch)
{
// see which mints are in our public zerocoin database. The mint should be here if it exists, unless
// something went wrong
for (CZerocoinMint mint : vMintsToFind) {
uint256 txHash;
if (!zerocoinDB->ReadCoinMint(mint.GetValue(), txHash)) {
vMissingMints.push_back(mint);
continue;
}
// make sure the txhash and block height meta data are correct for this mint
CTransaction tx;
uint256 hashBlock;
if (!GetTransaction(txHash, tx, hashBlock, true)) {
LogPrintf("%s : cannot find tx %s\n", __func__, txHash.GetHex());
vMissingMints.push_back(mint);
continue;
}
if (!mapBlockIndex.count(hashBlock)) {
LogPrintf("%s : cannot find block %s\n", __func__, hashBlock.GetHex());
vMissingMints.push_back(mint);
continue;
}
//see if this mint is spent
uint256 hashTxSpend = 0;
zerocoinDB->ReadCoinSpend(mint.GetSerialNumber(), hashTxSpend);
bool fSpent = hashTxSpend != 0;
//if marked as spent, check that it actually made it into the chain
CTransaction txSpend;
uint256 hashBlockSpend;
if (fSpent && !GetTransaction(hashTxSpend, txSpend, hashBlockSpend, true)) {
LogPrintf("%s : cannot find spend tx %s\n", __func__, hashTxSpend.GetHex());
zerocoinDB->EraseCoinSpend(mint.GetSerialNumber());
mint.SetUsed(false);
vMintsToUpdate.push_back(mint);
continue;
}
//The mint has been incorrectly labelled as spent in zerocoinDB and needs to be undone
int nHeightTx = 0;
if (fSpent && !IsSerialInBlockchain(mint.GetSerialNumber(), nHeightTx)) {
LogPrintf("%s : cannot find block %s. Erasing coinspend from zerocoinDB.\n", __func__, hashBlockSpend.GetHex());
zerocoinDB->EraseCoinSpend(mint.GetSerialNumber());
mint.SetUsed(false);
vMintsToUpdate.push_back(mint);
continue;
}
// if meta data is correct, then no need to update
if (mint.GetTxHash() == txHash && mint.GetHeight() == mapBlockIndex[hashBlock]->nHeight && mint.IsUsed() == fSpent)
continue;
//mark this mint for update
mint.SetTxHash(txHash);
mint.SetHeight(mapBlockIndex[hashBlock]->nHeight);
mint.SetUsed(fSpent);
vMintsToUpdate.push_back(mint);
}
if (fExtendedSearch)
{
// search the blockchain for the meta data on our missing mints
int nZerocoinStartHeight = GetZerocoinStartHeight();
for (int i = nZerocoinStartHeight; i < chainActive.Height(); i++) {
if(i % 1000 == 0)
LogPrintf("%s : scanned %d blocks\n", __func__, i - nZerocoinStartHeight);
if(chainActive[i]->vMintDenominationsInBlock.empty())
continue;
CBlock block;
if(!ReadBlockFromDisk(block, chainActive[i]))
continue;
list<CZerocoinMint> vMints;
if(!BlockToZerocoinMintList(block, vMints))
continue;
// search the blocks mints to see if it contains the mint that is requesting meta data updates
for (CZerocoinMint mintBlockChain : vMints) {
for (CZerocoinMint mintMissing : vMissingMints) {
if (mintMissing.GetValue() == mintBlockChain.GetValue()) {
LogPrintf("%s FOUND %s in block %d\n", __func__, mintMissing.GetValue().GetHex(), i);
mintMissing.SetHeight(i);
mintMissing.SetTxHash(mintBlockChain.GetTxHash());
vMintsToUpdate.push_back(mintMissing);
}
}
}
}
}
//remove any missing mints that were found
for (CZerocoinMint mintMissing : vMissingMints) {
for (CZerocoinMint mintFound : vMintsToUpdate) {
if (mintMissing.GetValue() == mintFound.GetValue())
std::remove(vMissingMints.begin(), vMissingMints.end(), mintMissing);
}
}
}
bool GetZerocoinMint(const CBigNum& bnPubcoin, uint256& txHash)
{
txHash = 0;
return zerocoinDB->ReadCoinMint(bnPubcoin, txHash);
}
bool IsSerialKnown(const CBigNum& bnSerial)
{
uint256 txHash = 0;
return zerocoinDB->ReadCoinSpend(bnSerial, txHash);
}
bool IsSerialInBlockchain(const CBigNum& bnSerial, int& nHeightTx)
{
uint256 txHash = 0;
// if not in zerocoinDB then its not in the blockchain
if (!zerocoinDB->ReadCoinSpend(bnSerial, txHash))
return false;
CTransaction tx;
uint256 hashBlock;
if (!GetTransaction(txHash, tx, hashBlock, true))
return false;
bool inChain = mapBlockIndex.count(hashBlock) && chainActive.Contains(mapBlockIndex[hashBlock]);
if (inChain)
nHeightTx = mapBlockIndex.at(hashBlock)->nHeight;
return inChain;
}
bool RemoveSerialFromDB(const CBigNum& bnSerial)
{
return zerocoinDB->EraseCoinSpend(bnSerial);
}
/** zerocoin transaction checks */
bool RecordMintToDB(PublicCoin publicZerocoin, const uint256& txHash)
{
//Check the pubCoinValue didn't already store in the zerocoin database. todo: pubcoin memory map?
//write the zerocoinmint to db if we don't already have it
//note that many of the mint parameters are not set here because those params are private to the minter
CZerocoinMint pubCoinTx;
uint256 hashFromDB;
if (zerocoinDB->ReadCoinMint(publicZerocoin.getValue(), hashFromDB)) {
if(hashFromDB == txHash)
return true;
LogPrintf("RecordMintToDB: failed, we already have this public coin recorded\n");
return false;
}
if (!zerocoinDB->WriteCoinMint(publicZerocoin, txHash)) {
LogPrintf("RecordMintToDB: failed to record public coin to DB\n");
return false;
}
return true;
}
bool TxOutToPublicCoin(const CTxOut txout, PublicCoin& pubCoin, CValidationState& state)
{
CBigNum publicZerocoin;
vector<unsigned char> vchZeroMint;
vchZeroMint.insert(vchZeroMint.end(), txout.scriptPubKey.begin() + SCRIPT_OFFSET,
txout.scriptPubKey.begin() + txout.scriptPubKey.size());
publicZerocoin.setvch(vchZeroMint);
CoinDenomination denomination = AmountToZerocoinDenomination(txout.nValue);
LogPrint("zero", "%s ZCPRINT denomination %d pubcoin %s\n", __func__, denomination, publicZerocoin.GetHex());
if (denomination == ZQ_ERROR)
return state.DoS(100, error("TxOutToPublicCoin : txout.nValue is not correct"));
PublicCoin checkPubCoin(Params().Zerocoin_Params(), publicZerocoin, denomination);
pubCoin = checkPubCoin;
return true;
}
bool BlockToPubcoinList(const CBlock& block, list<PublicCoin>& listPubcoins)
{
for (const CTransaction tx : block.vtx) {
if(!tx.IsZerocoinMint())
continue;
for (unsigned int i = 0; i < tx.vout.size(); i++) {
const CTxOut txOut = tx.vout[i];
if(!txOut.scriptPubKey.IsZerocoinMint())
continue;
CValidationState state;
PublicCoin pubCoin(Params().Zerocoin_Params());
if(!TxOutToPublicCoin(txOut, pubCoin, state))
return false;
listPubcoins.emplace_back(pubCoin);
}
}
return true;
}
//return a list of zerocoin mints contained in a specific block
bool BlockToZerocoinMintList(const CBlock& block, std::list<CZerocoinMint>& vMints)
{
for (const CTransaction tx : block.vtx) {
if(!tx.IsZerocoinMint())
continue;
for (unsigned int i = 0; i < tx.vout.size(); i++) {
const CTxOut txOut = tx.vout[i];
if(!txOut.scriptPubKey.IsZerocoinMint())
continue;
CValidationState state;
PublicCoin pubCoin(Params().Zerocoin_Params());
if(!TxOutToPublicCoin(txOut, pubCoin, state))
return false;
CZerocoinMint mint = CZerocoinMint(pubCoin.getDenomination(), pubCoin.getValue(), 0, 0, false);
mint.SetTxHash(tx.GetHash());
vMints.push_back(mint);
}
}
return true;
}
bool BlockToMintValueVector(const CBlock& block, const CoinDenomination denom, vector<CBigNum>& vValues)
{
for (const CTransaction tx : block.vtx) {
if(!tx.IsZerocoinMint())
continue;
for (const CTxOut txOut : tx.vout) {
if(!txOut.scriptPubKey.IsZerocoinMint())
continue;
CValidationState state;
PublicCoin coin(Params().Zerocoin_Params());
if(!TxOutToPublicCoin(txOut, coin, state))
return false;
if (coin.getDenomination() != denom)
continue;
vValues.push_back(coin.getValue());
}
}
return true;
}
//return a list of zerocoin spends contained in a specific block, list may have many denominations
std::list<libzerocoin::CoinDenomination> ZerocoinSpendListFromBlock(const CBlock& block)
{
std::list<libzerocoin::CoinDenomination> vSpends;
for (const CTransaction tx : block.vtx) {
if (!tx.IsZerocoinSpend())
continue;
for (const CTxIn txin : tx.vin) {
if (!txin.scriptSig.IsZerocoinSpend())
continue;
libzerocoin::CoinDenomination c = libzerocoin::IntToZerocoinDenomination(txin.nSequence);
vSpends.push_back(c);
}
}
return vSpends;
}
bool CheckZerocoinMint(const uint256& txHash, const CTxOut& txout, CValidationState& state, bool fCheckOnly)
{
PublicCoin pubCoin(Params().Zerocoin_Params());
if(!TxOutToPublicCoin(txout, pubCoin, state))
return state.DoS(100, error("CheckZerocoinMint(): TxOutToPublicCoin() failed"));
if (!pubCoin.validate())
return state.DoS(100, error("CheckZerocoinMint() : PubCoin does not validate\n"));
if(!fCheckOnly && !RecordMintToDB(pubCoin, txHash))
return state.DoS(100, error("CheckZerocoinMint(): RecordMintToDB() failed"));
return true;
}
CoinSpend TxInToZerocoinSpend(const CTxIn& txin)
{
// Deserialize the CoinSpend intro a fresh object
std::vector<char, zero_after_free_allocator<char> > dataTxIn;
dataTxIn.insert(dataTxIn.end(), txin.scriptSig.begin() + BIGNUM_SIZE, txin.scriptSig.end());
CDataStream serializedCoinSpend(dataTxIn, SER_NETWORK, PROTOCOL_VERSION);
return CoinSpend(Params().Zerocoin_Params(), serializedCoinSpend);
}
bool IsZerocoinSpendUnknown(CoinSpend coinSpend, uint256 hashTx, CValidationState& state)
{
uint256 hashTxFromDB;
if(zerocoinDB->ReadCoinSpend(coinSpend.getCoinSerialNumber(), hashTxFromDB))
return hashTx == hashTxFromDB;
if(!zerocoinDB->WriteCoinSpend(coinSpend.getCoinSerialNumber(), hashTx))
return state.DoS(100, error("CheckZerocoinSpend(): Failed to write zerocoin mint to database"));
return true;
}
bool CheckZerocoinSpend(const CTransaction tx, bool fVerifySignature, CValidationState& state)
{
//max needed non-mint outputs should be 2 - one for redemption address and a possible 2nd for change
if (tx.vout.size() > 2) {
int outs = 0;
for (const CTxOut out : tx.vout) {
if (out.IsZerocoinMint())
continue;
outs++;
}
if (outs > 2)
return state.DoS(100, error("CheckZerocoinSpend(): over two non-mint outputs in a zerocoinspend transaction"));
}
//compute the txout hash that is used for the zerocoinspend signatures
CMutableTransaction txTemp;
for (const CTxOut out : tx.vout) {
txTemp.vout.push_back(out);
}
uint256 hashTxOut = txTemp.GetHash();
bool fValidated = false;
set<CBigNum> serials;
list<CoinSpend> vSpends;
CAmount nTotalRedeemed = 0;
for (const CTxIn& txin : tx.vin) {
//only check txin that is a zcspend
if (!txin.scriptSig.IsZerocoinSpend())
continue;
CoinSpend newSpend = TxInToZerocoinSpend(txin);
vSpends.push_back(newSpend);
//check that the denomination is valid
if (newSpend.getDenomination() == ZQ_ERROR)
return state.DoS(100, error("Zerocoinspend does not have the correct denomination"));
//check that denomination is what it claims to be in nSequence
if (newSpend.getDenomination() != txin.nSequence)
return state.DoS(100, error("Zerocoinspend nSequence denomination does not match CoinSpend"));
//make sure the txout has not changed
if (newSpend.getTxOutHash() != hashTxOut)
return state.DoS(100, error("Zerocoinspend does not use the same txout that was used in the SoK"));
// Skip signature verification during initial block download
if (fVerifySignature) {
//see if we have record of the accumulator used in the spend tx
CBigNum bnAccumulatorValue = 0;
if(!zerocoinDB->ReadAccumulatorValue(newSpend.getAccumulatorChecksum(), bnAccumulatorValue))
return state.DoS(100, error("Zerocoinspend could not find accumulator associated with checksum"));
Accumulator accumulator(Params().Zerocoin_Params(), newSpend.getDenomination(), bnAccumulatorValue);
//Check that the coin is on the accumulator
if(!newSpend.Verify(accumulator))
return state.DoS(100, error("CheckZerocoinSpend(): zerocoin spend did not verify"));
}
if (serials.count(newSpend.getCoinSerialNumber()))
return state.DoS(100, error("Zerocoinspend serial is used twice in the same tx"));
serials.insert(newSpend.getCoinSerialNumber());
//make sure that there is no over redemption of coins
nTotalRedeemed += ZerocoinDenominationToAmount(newSpend.getDenomination());
fValidated = true;
}
if (nTotalRedeemed < tx.GetValueOut()) {
LogPrintf("redeemed = %s , spend = %s \n", FormatMoney(nTotalRedeemed), FormatMoney(tx.GetValueOut()));
return state.DoS(100, error("Transaction spend more than was redeemed in zerocoins"));
}
// Send signal to wallet if this is ours
if (pwalletMain) {
CWalletDB walletdb(pwalletMain->strWalletFile);
list <CBigNum> listMySerials = walletdb.ListMintedCoinsSerial();
for (const auto& newSpend : vSpends) {
list<CBigNum>::iterator it = find(listMySerials.begin(), listMySerials.end(), newSpend.getCoinSerialNumber());
if (it != listMySerials.end()) {
LogPrintf("%s: %s detected spent zerocoin mint in transaction %s \n", __func__, it->GetHex(), tx.GetHash().GetHex());
pwalletMain->NotifyZerocoinChanged(pwalletMain, it->GetHex(), "Used", CT_UPDATED);
}
}
}
return fValidated;
}
bool CheckTransaction(const CTransaction& tx, bool fZerocoinActive, bool fRejectBadUTXO, CValidationState& state)
{
// Basic checks that don't depend on any context
if (tx.vin.empty())
return state.DoS(10, error("CheckTransaction() : vin empty"),
REJECT_INVALID, "bad-txns-vin-empty");
if (tx.vout.empty())
return state.DoS(10, error("CheckTransaction() : vout empty"),
REJECT_INVALID, "bad-txns-vout-empty");
// Size limits
unsigned int nMaxSize = MAX_ZEROCOIN_TX_SIZE;
if (::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION) > nMaxSize)
return state.DoS(100, error("CheckTransaction() : size limits failed"),
REJECT_INVALID, "bad-txns-oversize");
// Check for negative or overflow output values
CAmount nValueOut = 0;
int nZCSpendCount = 0;
BOOST_FOREACH (const CTxOut& txout, tx.vout) {
if (txout.IsEmpty() && !tx.IsCoinBase() && !tx.IsCoinStake())
return state.DoS(100, error("CheckTransaction(): txout empty for user transaction"));
if (txout.nValue < 0)
return state.DoS(100, error("CheckTransaction() : txout.nValue negative"),
REJECT_INVALID, "bad-txns-vout-negative");
if (txout.nValue > Params().MaxMoneyOut())
return state.DoS(100, error("CheckTransaction() : txout.nValue too high"),
REJECT_INVALID, "bad-txns-vout-toolarge");
nValueOut += txout.nValue;
if (!MoneyRange(nValueOut))
return state.DoS(100, error("CheckTransaction() : txout total out of range"),
REJECT_INVALID, "bad-txns-txouttotal-toolarge");
if (fZerocoinActive && txout.IsZerocoinMint()) {
if(!CheckZerocoinMint(tx.GetHash(), txout, state, false)) {
if (fRejectBadUTXO)
return state.DoS(100, error("CheckTransaction() : invalid zerocoin mint"));
}
}
if (fZerocoinActive && txout.scriptPubKey.IsZerocoinSpend())
nZCSpendCount++;
}
if (fZerocoinActive) {
if (nZCSpendCount > Params().Zerocoin_MaxSpendsPerTransaction())
return state.DoS(100, error("CheckTransaction() : there are more zerocoin spends than are allowed in one transaction"));
if (tx.IsZerocoinSpend()) {
//require that a zerocoinspend only has inputs that are zerocoins
for (const CTxIn in : tx.vin) {
if (!in.scriptSig.IsZerocoinSpend())
return state.DoS(100,
error("CheckTransaction() : zerocoinspend contains inputs that are not zerocoins"));
}
// Do not require signature verification if this is initial sync and a block over 24 hours old
bool fVerifySignature = !IsInitialBlockDownload() && (GetTime() - chainActive.Tip()->GetBlockTime() < (60*60*24));
if (!CheckZerocoinSpend(tx, fVerifySignature, state))
return state.DoS(100, error("CheckTransaction() : invalid zerocoin spend"));
}
}
// Check for duplicate inputs
set<COutPoint> vInOutPoints;
set<CBigNum> vZerocoinSpendSerials;
for (const CTxIn& txin : tx.vin) {
if (vInOutPoints.count(txin.prevout))
return state.DoS(100, error("CheckTransaction() : duplicate inputs"),
REJECT_INVALID, "bad-txns-inputs-duplicate");
//duplicate zcspend serials are checked in CheckZerocoinSpend()
if (!txin.scriptSig.IsZerocoinSpend())
vInOutPoints.insert(txin.prevout);
}
if (tx.IsCoinBase()) {
if (tx.vin[0].scriptSig.size() < 2 || tx.vin[0].scriptSig.size() > 150)
return state.DoS(100, error("CheckTransaction() : coinbase script size=%d", tx.vin[0].scriptSig.size()),
REJECT_INVALID, "bad-cb-length");
} else if (fZerocoinActive && tx.IsZerocoinSpend()) {
if(tx.vin.size() < 1 || static_cast<int>(tx.vin.size()) > Params().Zerocoin_MaxSpendsPerTransaction())
return state.DoS(10, error("CheckTransaction() : Zerocoin Spend has more than allowed txin's"), REJECT_INVALID, "bad-zerocoinspend");
} else {
BOOST_FOREACH (const CTxIn& txin, tx.vin)
if (txin.prevout.IsNull() && (fZerocoinActive && !txin.scriptSig.IsZerocoinSpend()))
return state.DoS(10, error("CheckTransaction() : prevout is null"),
REJECT_INVALID, "bad-txns-prevout-null");
}
return true;
}
bool CheckFinalTx(const CTransaction& tx, int flags)
{
AssertLockHeld(cs_main);
// By convention a negative value for flags indicates that the
// current network-enforced consensus rules should be used. In
// a future soft-fork scenario that would mean checking which
// rules would be enforced for the next block and setting the
// appropriate flags. At the present time no soft-forks are
// scheduled, so no flags are set.
flags = std::max(flags, 0);
// CheckFinalTx() uses chainActive.Height()+1 to evaluate
// nLockTime because when IsFinalTx() is called within
// CBlock::AcceptBlock(), the height of the block *being*
// evaluated is what is used. Thus if we want to know if a
// transaction can be part of the *next* block, we need to call
// IsFinalTx() with one more than chainActive.Height().
const int nBlockHeight = chainActive.Height() + 1;
// BIP113 will require that time-locked transactions have nLockTime set to
// less than the median time of the previous block they're contained in.
// When the next block is created its previous block will be the current
// chain tip, so we use that to calculate the median time passed to
// IsFinalTx() if LOCKTIME_MEDIAN_TIME_PAST is set.
const int64_t nBlockTime = (flags & LOCKTIME_MEDIAN_TIME_PAST) ? chainActive.Tip()->GetMedianTimePast() : GetAdjustedTime();
return IsFinalTx(tx, nBlockHeight, nBlockTime);
}
CAmount GetMinRelayFee(const CTransaction& tx, unsigned int nBytes, bool fAllowFree)
{
{
LOCK(mempool.cs);
uint256 hash = tx.GetHash();
double dPriorityDelta = 0;
CAmount nFeeDelta = 0;
mempool.ApplyDeltas(hash, dPriorityDelta, nFeeDelta);
if (dPriorityDelta > 0 || nFeeDelta > 0)
return 0;
}
CAmount nMinFee = ::minRelayTxFee.GetFee(nBytes);
if (fAllowFree) {
// There is a free transaction area in blocks created by most miners,
// * If we are relaying we allow transactions up to DEFAULT_BLOCK_PRIORITY_SIZE - 1000
// to be considered to fall into this category. We don't want to encourage sending
// multiple transactions instead of one big transaction to avoid fees.
if (nBytes < (DEFAULT_BLOCK_PRIORITY_SIZE - 1000))
nMinFee = 0;
}
if (!MoneyRange(nMinFee))
nMinFee = Params().MaxMoneyOut();
return nMinFee;
}
bool AcceptToMemoryPool(CTxMemPool& pool, CValidationState& state, const CTransaction& tx, bool fLimitFree, bool* pfMissingInputs, bool fRejectInsaneFee, bool ignoreFees)
{
AssertLockHeld(cs_main);
if (pfMissingInputs)
*pfMissingInputs = false;
//Temporarily disable zerocoin for maintenance
if (GetAdjustedTime() > GetSporkValue(SPORK_16_ZEROCOIN_MAINTENANCE_MODE) && tx.ContainsZerocoins())
return state.DoS(10, error("AcceptToMemoryPool : Zerocoin transactions are temporarily disabled for maintenance"), REJECT_INVALID, "bad-tx");
if (!CheckTransaction(tx, chainActive.Height() >= Params().Zerocoin_AccumulatorStartHeight(), true, state))
return state.DoS(100, error("AcceptToMemoryPool: : CheckTransaction failed"), REJECT_INVALID, "bad-tx");
// Coinbase is only valid in a block, not as a loose transaction
if (tx.IsCoinBase())
return state.DoS(100, error("AcceptToMemoryPool: : coinbase as individual tx"),
REJECT_INVALID, "coinbase");
//Coinstake is also only valid in a block, not as a loose transaction
if (tx.IsCoinStake())
return state.DoS(100, error("AcceptToMemoryPool: coinstake as individual tx"),
REJECT_INVALID, "coinstake");
// Rather not work on nonstandard transactions (unless -testnet/-regtest)
string reason;
if (Params().RequireStandard() && !IsStandardTx(tx, reason))
return state.DoS(0,
error("AcceptToMemoryPool : nonstandard transaction: %s", reason),
REJECT_NONSTANDARD, reason);
// is it already in the memory pool?
uint256 hash = tx.GetHash();
if (pool.exists(hash)) {
LogPrintf("%s tx already in mempool\n", __func__);
return false;
}
// ----------- swiftTX transaction scanning -----------
BOOST_FOREACH (const CTxIn& in, tx.vin) {
if (mapLockedInputs.count(in.prevout)) {
if (mapLockedInputs[in.prevout] != tx.GetHash()) {
return state.DoS(0,
error("AcceptToMemoryPool : conflicts with existing transaction lock: %s", reason),
REJECT_INVALID, "tx-lock-conflict");
}
}
}
// Check for conflicts with in-memory transactions
if (!tx.IsZerocoinSpend()) {
LOCK(pool.cs); // protect pool.mapNextTx
for (unsigned int i = 0; i < tx.vin.size(); i++) {
COutPoint outpoint = tx.vin[i].prevout;
if (pool.mapNextTx.count(outpoint)) {
// Disable replacement feature for now
return false;
}
}
}
{
CCoinsView dummy;
CCoinsViewCache view(&dummy);
CAmount nValueIn = 0;
if(tx.IsZerocoinSpend()){
nValueIn = tx.GetZerocoinSpent();
//Check that txid is not already in the chain
int nHeightTx = 0;
if (IsTransactionInChain(tx.GetHash(), nHeightTx))
return state.Invalid(error("AcceptToMemoryPool : zIoTHome spend tx %s already in block %d", tx.GetHash().GetHex(), nHeightTx),
REJECT_DUPLICATE, "bad-txns-inputs-spent");
//Check for double spending of serial #'s
for (const CTxIn& txIn : tx.vin) {
if (!txIn.scriptSig.IsZerocoinSpend())
continue;
CoinSpend spend = TxInToZerocoinSpend(txIn);
int nHeightTx = 0;
if (IsSerialInBlockchain(spend.getCoinSerialNumber(), nHeightTx))
return state.Invalid(error("%s : zIoTHome spend with serial %s is already in block %d\n",
__func__, spend.getCoinSerialNumber().GetHex(), nHeightTx));
//Is serial in the acceptable range
if (!spend.HasValidSerial(Params().Zerocoin_Params()))
return state.Invalid(error("%s : zIoTHome spend with serial %s from tx %s is not in valid range\n",
__func__, spend.getCoinSerialNumber().GetHex(), tx.GetHash().GetHex()));
}
} else {
LOCK(pool.cs);
CCoinsViewMemPool viewMemPool(pcoinsTip, pool);
view.SetBackend(viewMemPool);
// do we already have it?
if (view.HaveCoins(hash))
return false;
// do all inputs exist?
// Note that this does not check for the presence of actual outputs (see the next check for that),
// only helps filling in pfMissingInputs (to determine missing vs spent).
for (const CTxIn txin : tx.vin) {
if (!view.HaveCoins(txin.prevout.hash)) {
if (pfMissingInputs)
*pfMissingInputs = true;
return false;
}
}
// are the actual inputs available?
if (!view.HaveInputs(tx))
return state.Invalid(error("AcceptToMemoryPool : inputs already spent"),
REJECT_DUPLICATE, "bad-txns-inputs-spent");
// Bring the best block into scope
view.GetBestBlock();
nValueIn = view.GetValueIn(tx);
// we have all inputs cached now, so switch back to dummy, so we don't need to keep lock on mempool
view.SetBackend(dummy);
}
// Check for non-standard pay-to-script-hash in inputs
if (Params().RequireStandard() && !AreInputsStandard(tx, view))
return error("AcceptToMemoryPool: : nonstandard transaction input");
// Check that the transaction doesn't have an excessive number of
// sigops, making it impossible to mine. Since the coinbase transaction
// itself can contain sigops MAX_TX_SIGOPS is less than
// MAX_BLOCK_SIGOPS; we still consider this an invalid rather than
// merely non-standard transaction.
if (!tx.IsZerocoinSpend()) {
unsigned int nSigOps = GetLegacySigOpCount(tx);
unsigned int nMaxSigOps = MAX_TX_SIGOPS_CURRENT;
nSigOps += GetP2SHSigOpCount(tx, view);
if(nSigOps > nMaxSigOps)
return state.DoS(0,
error("AcceptToMemoryPool : too many sigops %s, %d > %d",
hash.ToString(), nSigOps, nMaxSigOps),
REJECT_NONSTANDARD, "bad-txns-too-many-sigops");
}
CAmount nValueOut = tx.GetValueOut();
CAmount nFees = nValueIn - nValueOut;
double dPriority = 0;
if (!tx.IsZerocoinSpend())
view.GetPriority(tx, chainActive.Height());
CTxMemPoolEntry entry(tx, nFees, GetTime(), dPriority, chainActive.Height());
unsigned int nSize = entry.GetTxSize();
// Don't accept it if it can't get into a block
// but prioritise dstx and don't check fees for it
if (mapObfuscationBroadcastTxes.count(hash)) {
mempool.PrioritiseTransaction(hash, hash.ToString(), 1000, 0.1 * COIN);
} else if (!ignoreFees) {
CAmount txMinFee = GetMinRelayFee(tx, nSize, true);
if (fLimitFree && nFees < txMinFee && !tx.IsZerocoinSpend())
return state.DoS(0, error("AcceptToMemoryPool : not enough fees %s, %d < %d",
hash.ToString(), nFees, txMinFee),
REJECT_INSUFFICIENTFEE, "insufficient fee");
// Require that free transactions have sufficient priority to be mined in the next block.
if (tx.IsZerocoinMint()) {
if(nFees < Params().Zerocoin_MintFee() * tx.GetZerocoinMintCount())
return state.DoS(0, false, REJECT_INSUFFICIENTFEE, "insufficient fee for zerocoinmint");
} else if (!tx.IsZerocoinSpend() && GetBoolArg("-relaypriority", true) && nFees < ::minRelayTxFee.GetFee(nSize) && !AllowFree(view.GetPriority(tx, chainActive.Height() + 1))) {
return state.DoS(0, false, REJECT_INSUFFICIENTFEE, "insufficient priority");
}
// Continuously rate-limit free (really, very-low-fee) transactions
// This mitigates 'penny-flooding' -- sending thousands of free transactions just to
// be annoying or make others' transactions take longer to confirm.
if (fLimitFree && nFees < ::minRelayTxFee.GetFee(nSize) && !tx.IsZerocoinSpend()) {
static CCriticalSection csFreeLimiter;
static double dFreeCount;
static int64_t nLastTime;
int64_t nNow = GetTime();
LOCK(csFreeLimiter);
// Use an exponentially decaying ~10-minute window:
dFreeCount *= pow(1.0 - 1.0 / 600.0, (double)(nNow - nLastTime));
nLastTime = nNow;
// -limitfreerelay unit is thousand-bytes-per-minute
// At default rate it would take over a month to fill 1GB
if (dFreeCount >= GetArg("-limitfreerelay", 30) * 10 * 1000)
return state.DoS(0, error("AcceptToMemoryPool : free transaction rejected by rate limiter"),
REJECT_INSUFFICIENTFEE, "rate limited free transaction");
LogPrint("mempool", "Rate limit dFreeCount: %g => %g\n", dFreeCount, dFreeCount + nSize);
dFreeCount += nSize;
}
}
if (fRejectInsaneFee && nFees > ::minRelayTxFee.GetFee(nSize) * 10000)
return error("AcceptToMemoryPool: : insane fees %s, %d > %d",
hash.ToString(),
nFees, ::minRelayTxFee.GetFee(nSize) * 10000);
// Check against previous transactions
// This is done last to help prevent CPU exhaustion denial-of-service attacks.
if (!CheckInputs(tx, state, view, true, STANDARD_SCRIPT_VERIFY_FLAGS, true)) {
return error("AcceptToMemoryPool: : ConnectInputs failed %s", hash.ToString());
}
// Check again against just the consensus-critical mandatory script
// verification flags, in case of bugs in the standard flags that cause
// transactions to pass as valid when they're actually invalid. For
// instance the STRICTENC flag was incorrectly allowing certain
// CHECKSIG NOT scripts to pass, even though they were invalid.
//
// There is a similar check in CreateNewBlock() to prevent creating
// invalid blocks, however allowing such transactions into the mempool
// can be exploited as a DoS attack.
if (!CheckInputs(tx, state, view, true, MANDATORY_SCRIPT_VERIFY_FLAGS, true)) {
return error("AcceptToMemoryPool: : BUG! PLEASE REPORT THIS! ConnectInputs failed against MANDATORY but not STANDARD flags %s", hash.ToString());
}
// Store transaction in memory
pool.addUnchecked(hash, entry);
}
SyncWithWallets(tx, NULL);
return true;
}
bool AcceptableInputs(CTxMemPool& pool, CValidationState& state, const CTransaction& tx, bool fLimitFree, bool* pfMissingInputs, bool fRejectInsaneFee, bool isDSTX)
{
AssertLockHeld(cs_main);
if (pfMissingInputs)
*pfMissingInputs = false;
if (!CheckTransaction(tx, chainActive.Height() >= Params().Zerocoin_AccumulatorStartHeight(), true, state))
return error("AcceptableInputs: : CheckTransaction failed");
// Coinbase is only valid in a block, not as a loose transaction
if (tx.IsCoinBase())
return state.DoS(100, error("AcceptableInputs: : coinbase as individual tx"),
REJECT_INVALID, "coinbase");
// Rather not work on nonstandard transactions (unless -testnet/-regtest)
string reason;
// for any real tx this will be checked on AcceptToMemoryPool anyway
// if (Params().RequireStandard() && !IsStandardTx(tx, reason))
// return state.DoS(0,
// error("AcceptableInputs : nonstandard transaction: %s", reason),
// REJECT_NONSTANDARD, reason);
// is it already in the memory pool?
uint256 hash = tx.GetHash();
if (pool.exists(hash))
return false;
// ----------- swiftTX transaction scanning -----------
BOOST_FOREACH (const CTxIn& in, tx.vin) {
if (mapLockedInputs.count(in.prevout)) {
if (mapLockedInputs[in.prevout] != tx.GetHash()) {
return state.DoS(0,
error("AcceptableInputs : conflicts with existing transaction lock: %s", reason),
REJECT_INVALID, "tx-lock-conflict");
}
}
}
// Check for conflicts with in-memory transactions
if (!tx.IsZerocoinSpend()) {
LOCK(pool.cs); // protect pool.mapNextTx
for (unsigned int i = 0; i < tx.vin.size(); i++) {
COutPoint outpoint = tx.vin[i].prevout;
if (pool.mapNextTx.count(outpoint)) {
// Disable replacement feature for now
return false;
}
}
}
{
CCoinsView dummy;
CCoinsViewCache view(&dummy);
CAmount nValueIn = 0;
{
LOCK(pool.cs);
CCoinsViewMemPool viewMemPool(pcoinsTip, pool);
view.SetBackend(viewMemPool);
// do we already have it?
if (view.HaveCoins(hash))
return false;
// do all inputs exist?
// Note that this does not check for the presence of actual outputs (see the next check for that),
// only helps filling in pfMissingInputs (to determine missing vs spent).
for (const CTxIn txin : tx.vin) {
if (!view.HaveCoins(txin.prevout.hash)) {
if (pfMissingInputs)
*pfMissingInputs = true;
return false;
}
}
// are the actual inputs available?
if (!view.HaveInputs(tx))
return state.Invalid(error("AcceptableInputs : inputs already spent"),
REJECT_DUPLICATE, "bad-txns-inputs-spent");
// Bring the best block into scope
view.GetBestBlock();
nValueIn = view.GetValueIn(tx);
// we have all inputs cached now, so switch back to dummy, so we don't need to keep lock on mempool
view.SetBackend(dummy);
}
// Check for non-standard pay-to-script-hash in inputs
// for any real tx this will be checked on AcceptToMemoryPool anyway
// if (Params().RequireStandard() && !AreInputsStandard(tx, view))
// return error("AcceptableInputs: : nonstandard transaction input");
// Check that the transaction doesn't have an excessive number of
// sigops, making it impossible to mine. Since the coinbase transaction
// itself can contain sigops MAX_TX_SIGOPS is less than
// MAX_BLOCK_SIGOPS; we still consider this an invalid rather than
// merely non-standard transaction.
unsigned int nSigOps = GetLegacySigOpCount(tx);
unsigned int nMaxSigOps = MAX_TX_SIGOPS_CURRENT;
nSigOps += GetP2SHSigOpCount(tx, view);
if (nSigOps > nMaxSigOps)
return state.DoS(0,
error("AcceptableInputs : too many sigops %s, %d > %d",
hash.ToString(), nSigOps, nMaxSigOps),
REJECT_NONSTANDARD, "bad-txns-too-many-sigops");
CAmount nValueOut = tx.GetValueOut();
CAmount nFees = nValueIn - nValueOut;
double dPriority = view.GetPriority(tx, chainActive.Height());
CTxMemPoolEntry entry(tx, nFees, GetTime(), dPriority, chainActive.Height());
unsigned int nSize = entry.GetTxSize();
// Don't accept it if it can't get into a block
// but prioritise dstx and don't check fees for it
if (isDSTX) {
mempool.PrioritiseTransaction(hash, hash.ToString(), 1000, 0.1 * COIN);
} else { // same as !ignoreFees for AcceptToMemoryPool
CAmount txMinFee = GetMinRelayFee(tx, nSize, true);
if (fLimitFree && nFees < txMinFee && !tx.IsZerocoinSpend())
return state.DoS(0, error("AcceptableInputs : not enough fees %s, %d < %d",
hash.ToString(), nFees, txMinFee),
REJECT_INSUFFICIENTFEE, "insufficient fee");
// Require that free transactions have sufficient priority to be mined in the next block.
if (GetBoolArg("-relaypriority", true) && nFees < ::minRelayTxFee.GetFee(nSize) && !AllowFree(view.GetPriority(tx, chainActive.Height() + 1))) {
return state.DoS(0, false, REJECT_INSUFFICIENTFEE, "insufficient priority");
}
// Continuously rate-limit free (really, very-low-fee) transactions
// This mitigates 'penny-flooding' -- sending thousands of free transactions just to
// be annoying or make others' transactions take longer to confirm.
if (fLimitFree && nFees < ::minRelayTxFee.GetFee(nSize) && !tx.IsZerocoinSpend()) {
static CCriticalSection csFreeLimiter;
static double dFreeCount;
static int64_t nLastTime;
int64_t nNow = GetTime();
LOCK(csFreeLimiter);
// Use an exponentially decaying ~10-minute window:
dFreeCount *= pow(1.0 - 1.0 / 600.0, (double)(nNow - nLastTime));
nLastTime = nNow;
// -limitfreerelay unit is thousand-bytes-per-minute
// At default rate it would take over a month to fill 1GB
if (dFreeCount >= GetArg("-limitfreerelay", 30) * 10 * 1000)
return state.DoS(0, error("AcceptableInputs : free transaction rejected by rate limiter"),
REJECT_INSUFFICIENTFEE, "rate limited free transaction");
LogPrint("mempool", "Rate limit dFreeCount: %g => %g\n", dFreeCount, dFreeCount + nSize);
dFreeCount += nSize;
}
}
if (fRejectInsaneFee && nFees > ::minRelayTxFee.GetFee(nSize) * 10000)
return error("AcceptableInputs: : insane fees %s, %d > %d",
hash.ToString(),
nFees, ::minRelayTxFee.GetFee(nSize) * 10000);
// Check against previous transactions
// This is done last to help prevent CPU exhaustion denial-of-service attacks.
if (!CheckInputs(tx, state, view, false, STANDARD_SCRIPT_VERIFY_FLAGS, true)) {
return error("AcceptableInputs: : ConnectInputs failed %s", hash.ToString());
}
// Check again against just the consensus-critical mandatory script
// verification flags, in case of bugs in the standard flags that cause
// transactions to pass as valid when they're actually invalid. For
// instance the STRICTENC flag was incorrectly allowing certain
// CHECKSIG NOT scripts to pass, even though they were invalid.
//
// There is a similar check in CreateNewBlock() to prevent creating
// invalid blocks, however allowing such transactions into the mempool
// can be exploited as a DoS attack.
// for any real tx this will be checked on AcceptToMemoryPool anyway
// if (!CheckInputs(tx, state, view, false, MANDATORY_SCRIPT_VERIFY_FLAGS, true))
// {
// return error("AcceptableInputs: : BUG! PLEASE REPORT THIS! ConnectInputs failed against MANDATORY but not STANDARD flags %s", hash.ToString());
// }
// Store transaction in memory
// pool.addUnchecked(hash, entry);
}
// SyncWithWallets(tx, NULL);
return true;
}
/** Return transaction in tx, and if it was found inside a block, its hash is placed in hashBlock */
bool GetTransaction(const uint256& hash, CTransaction& txOut, uint256& hashBlock, bool fAllowSlow)
{
CBlockIndex* pindexSlow = NULL;
{
LOCK(cs_main);
{
if (mempool.lookup(hash, txOut)) {
return true;
}
}
if (fTxIndex) {
CDiskTxPos postx;
if (pblocktree->ReadTxIndex(hash, postx)) {
CAutoFile file(OpenBlockFile(postx, true), SER_DISK, CLIENT_VERSION);
if (file.IsNull())
return error("%s: OpenBlockFile failed", __func__);
CBlockHeader header;
try {
file >> header;
fseek(file.Get(), postx.nTxOffset, SEEK_CUR);
file >> txOut;
} catch (std::exception& e) {
return error("%s : Deserialize or I/O error - %s", __func__, e.what());
}
hashBlock = header.GetHash();
if (txOut.GetHash() != hash)
return error("%s : txid mismatch", __func__);
return true;
}
}
if (fAllowSlow) { // use coin database to locate block that contains transaction, and scan it
int nHeight = -1;
{
CCoinsViewCache& view = *pcoinsTip;
const CCoins* coins = view.AccessCoins(hash);
if (coins)
nHeight = coins->nHeight;
}
if (nHeight > 0)
pindexSlow = chainActive[nHeight];
}
}
if (pindexSlow) {
CBlock block;
if (ReadBlockFromDisk(block, pindexSlow)) {
BOOST_FOREACH (const CTransaction& tx, block.vtx) {
if (tx.GetHash() == hash) {
txOut = tx;
hashBlock = pindexSlow->GetBlockHash();
return true;
}
}
}
}
return false;
}
//////////////////////////////////////////////////////////////////////////////
//
// CBlock and CBlockIndex
//
bool WriteBlockToDisk(CBlock& block, CDiskBlockPos& pos)
{
// Open history file to append
CAutoFile fileout(OpenBlockFile(pos), SER_DISK, CLIENT_VERSION);
if (fileout.IsNull())
return error("WriteBlockToDisk : OpenBlockFile failed");
// Write index header
unsigned int nSize = fileout.GetSerializeSize(block);
fileout << FLATDATA(Params().MessageStart()) << nSize;
// Write block
long fileOutPos = ftell(fileout.Get());
if (fileOutPos < 0)
return error("WriteBlockToDisk : ftell failed");
pos.nPos = (unsigned int)fileOutPos;
fileout << block;
return true;
}
bool ReadBlockFromDisk(CBlock& block, const CDiskBlockPos& pos)
{
block.SetNull();
// Open history file to read
CAutoFile filein(OpenBlockFile(pos, true), SER_DISK, CLIENT_VERSION);
if (filein.IsNull())
return error("ReadBlockFromDisk : OpenBlockFile failed");
// Read block
try {
filein >> block;
} catch (std::exception& e) {
return error("%s : Deserialize or I/O error - %s", __func__, e.what());
}
// Check the header
if (block.IsProofOfWork()) {
if (!CheckProofOfWork(block.GetHash(), block.nBits))
return error("ReadBlockFromDisk : Errors in block header");
}
return true;
}
bool ReadBlockFromDisk(CBlock& block, const CBlockIndex* pindex)
{
if (!ReadBlockFromDisk(block, pindex->GetBlockPos()))
return false;
if (block.GetHash() != pindex->GetBlockHash()) {
LogPrintf("%s : block=%s index=%s\n", __func__, block.GetHash().ToString().c_str(), pindex->GetBlockHash().ToString().c_str());
return error("ReadBlockFromDisk(CBlock&, CBlockIndex*) : GetHash() doesn't match index");
}
return true;
}
double ConvertBitsToDouble(unsigned int nBits)
{
int nShift = (nBits >> 24) & 0xff;
double dDiff =
(double)0x0000ffff / (double)(nBits & 0x00ffffff);
while (nShift < 29) {
dDiff *= 256.0;
nShift++;
}
while (nShift > 29) {
dDiff /= 256.0;
nShift--;
}
return dDiff;
}
int64_t GetBlockValue(int nHeight)
{
int64_t nSubsidy = 0;
if (Params().NetworkID() == CBaseChainParams::TESTNET) {
if (nHeight < 200 && nHeight > 0)
return 10000 * COIN;
}
if(IsTreasuryBlock(nHeight)) {
LogPrintf("GetBlockValue(): this is a treasury block\n");
nSubsidy = GetTreasuryAward(nHeight);
} else {
{
int64_t nSubsidy = 1 * COIN;
if (nHeight == 1) return 650000 * COIN;
if(nHeight > 1 && nHeight <= Params().LAST_POW_BLOCK()) {
nSubsidy = 0* COIN;
} else if (nHeight > Params().LAST_POW_BLOCK() && nHeight <= 15000) {
nSubsidy = 2* COIN;
} else if (nHeight >= 15001 && nHeight <= 150000) {
nSubsidy = 3* COIN;
} else if (nHeight >= 150001 && nHeight <= 300000) {
nSubsidy = 4* COIN;
} else if (nHeight >= 300001 && nHeight <= 450000) {
nSubsidy = 5* COIN;
} else if (nHeight >= 450001 && nHeight <= 600000) {
nSubsidy = 6* COIN;
} else {
nSubsidy = 5* COIN;
}
return nSubsidy;
}
}
return nSubsidy;
}
int64_t GetMasternodePayment(int nHeight, int64_t blockValue, int nMasternodeCount)
{
int64_t ret = 0;
if (Params().NetworkID() == CBaseChainParams::TESTNET) {
if (nHeight < 200)
return 0;
}
// 660 block MN
if (nHeight <= 660) {
ret = blockValue / 100 * 0;
} else if (nHeight > 660) {
ret = blockValue / 100 * 80; //80%
}
return ret;
}
//Treasury blocks start from 70,000 and then each 10,000th block
int nStartTreasuryBlock = INT_MAX;
int nTreasuryBlockStep = 1;
bool IsTreasuryBlock(int nHeight)
{
if(nHeight < nStartTreasuryBlock)
return false;
else
return true;
}
//disabled
int64_t GetTreasuryAward(int nHeight)
{
if(IsTreasuryBlock(nHeight)) {
if(nHeight == nStartTreasuryBlock)
return 400 * COIN; //200 for the first treasury block, 10 - reward to PoS
else{
// int p = 3/100;
// int devreward = GetBlockValue(nHeight) / 100 * 3;
return (GetBlockValue(nHeight) / 100 * 3) * COIN ; //3% of block reward for dev
}
} else
return 0;
}
bool IsInitialBlockDownload()
{
LOCK(cs_main);
if (fImporting || fReindex || chainActive.Height() < Checkpoints::GetTotalBlocksEstimate())
return true;
static bool lockIBDState = false;
if (lockIBDState)
return false;
bool state = (chainActive.Height() < pindexBestHeader->nHeight - 24 * 6 ||
pindexBestHeader->GetBlockTime() < GetTime() - 6 * 60 * 60); // ~144 blocks behind -> 2 x fork detection time
if (!state)
lockIBDState = true;
return state;
}
bool fLargeWorkForkFound = false;
bool fLargeWorkInvalidChainFound = false;
CBlockIndex *pindexBestForkTip = NULL, *pindexBestForkBase = NULL;
void CheckForkWarningConditions()
{
AssertLockHeld(cs_main);
// Before we get past initial download, we cannot reliably alert about forks
// (we assume we don't get stuck on a fork before the last checkpoint)
if (IsInitialBlockDownload())
return;
// If our best fork is no longer within 72 blocks (+/- 3 hours if no one mines it)
// of our head, drop it
if (pindexBestForkTip && chainActive.Height() - pindexBestForkTip->nHeight >= 72)
pindexBestForkTip = NULL;
if (pindexBestForkTip || (pindexBestInvalid && pindexBestInvalid->nChainWork > chainActive.Tip()->nChainWork + (GetBlockProof(*chainActive.Tip()) * 6))) {
if (!fLargeWorkForkFound && pindexBestForkBase) {
if (pindexBestForkBase->phashBlock) {
std::string warning = std::string("'Warning: Large-work fork detected, forking after block ") +
pindexBestForkBase->phashBlock->ToString() + std::string("'");
CAlert::Notify(warning, true);
}
}
if (pindexBestForkTip && pindexBestForkBase) {
if (pindexBestForkBase->phashBlock) {
LogPrintf("CheckForkWarningConditions: Warning: Large valid fork found\n forking the chain at height %d (%s)\n lasting to height %d (%s).\nChain state database corruption likely.\n",
pindexBestForkBase->nHeight, pindexBestForkBase->phashBlock->ToString(),
pindexBestForkTip->nHeight, pindexBestForkTip->phashBlock->ToString());
fLargeWorkForkFound = true;
}
} else {
LogPrintf("CheckForkWarningConditions: Warning: Found invalid chain at least ~6 blocks longer than our best chain.\nChain state database corruption likely.\n");
fLargeWorkInvalidChainFound = true;
}
} else {
fLargeWorkForkFound = false;
fLargeWorkInvalidChainFound = false;
}
}
void CheckForkWarningConditionsOnNewFork(CBlockIndex* pindexNewForkTip)
{
AssertLockHeld(cs_main);
// If we are on a fork that is sufficiently large, set a warning flag
CBlockIndex* pfork = pindexNewForkTip;
CBlockIndex* plonger = chainActive.Tip();
while (pfork && pfork != plonger) {
while (plonger && plonger->nHeight > pfork->nHeight)
plonger = plonger->pprev;
if (pfork == plonger)
break;
pfork = pfork->pprev;
}
// We define a condition which we should warn the user about as a fork of at least 7 blocks
// who's tip is within 72 blocks (+/- 3 hours if no one mines it) of ours
// or a chain that is entirely longer than ours and invalid (note that this should be detected by both)
// We use 7 blocks rather arbitrarily as it represents just under 10% of sustained network
// hash rate operating on the fork.
// We define it this way because it allows us to only store the highest fork tip (+ base) which meets
// the 7-block condition and from this always have the most-likely-to-cause-warning fork
if (pfork && (!pindexBestForkTip || (pindexBestForkTip && pindexNewForkTip->nHeight > pindexBestForkTip->nHeight)) &&
pindexNewForkTip->nChainWork - pfork->nChainWork > (GetBlockProof(*pfork) * 7) &&
chainActive.Height() - pindexNewForkTip->nHeight < 72) {
pindexBestForkTip = pindexNewForkTip;
pindexBestForkBase = pfork;
}
CheckForkWarningConditions();
}
// Requires cs_main.
void Misbehaving(NodeId pnode, int howmuch)
{
if (howmuch == 0)
return;
CNodeState* state = State(pnode);
if (state == NULL)
return;
state->nMisbehavior += howmuch;
int banscore = GetArg("-banscore", 100);
if (state->nMisbehavior >= banscore && state->nMisbehavior - howmuch < banscore) {
LogPrintf("Misbehaving: %s (%d -> %d) BAN THRESHOLD EXCEEDED\n", state->name, state->nMisbehavior - howmuch, state->nMisbehavior);
state->fShouldBan = true;
} else
LogPrintf("Misbehaving: %s (%d -> %d)\n", state->name, state->nMisbehavior - howmuch, state->nMisbehavior);
}
void static InvalidChainFound(CBlockIndex* pindexNew)
{
if (!pindexBestInvalid || pindexNew->nChainWork > pindexBestInvalid->nChainWork)
pindexBestInvalid = pindexNew;
LogPrintf("InvalidChainFound: invalid block=%s height=%d log2_work=%.8g date=%s\n",
pindexNew->GetBlockHash().ToString(), pindexNew->nHeight,
log(pindexNew->nChainWork.getdouble()) / log(2.0), DateTimeStrFormat("%Y-%m-%d %H:%M:%S",
pindexNew->GetBlockTime()));
LogPrintf("InvalidChainFound: current best=%s height=%d log2_work=%.8g date=%s\n",
chainActive.Tip()->GetBlockHash().ToString(), chainActive.Height(), log(chainActive.Tip()->nChainWork.getdouble()) / log(2.0),
DateTimeStrFormat("%Y-%m-%d %H:%M:%S", chainActive.Tip()->GetBlockTime()));
CheckForkWarningConditions();
}
void static InvalidBlockFound(CBlockIndex* pindex, const CValidationState& state)
{
int nDoS = 0;
if (state.IsInvalid(nDoS)) {
std::map<uint256, NodeId>::iterator it = mapBlockSource.find(pindex->GetBlockHash());
if (it != mapBlockSource.end() && State(it->second)) {
CBlockReject reject = {state.GetRejectCode(), state.GetRejectReason().substr(0, MAX_REJECT_MESSAGE_LENGTH), pindex->GetBlockHash()};
State(it->second)->rejects.push_back(reject);
if (nDoS > 0)
Misbehaving(it->second, nDoS);
}
}
if (!state.CorruptionPossible()) {
pindex->nStatus |= BLOCK_FAILED_VALID;
setDirtyBlockIndex.insert(pindex);
setBlockIndexCandidates.erase(pindex);
InvalidChainFound(pindex);
}
}
void UpdateCoins(const CTransaction& tx, CValidationState& state, CCoinsViewCache& inputs, CTxUndo& txundo, int nHeight)
{
// mark inputs spent
if (!tx.IsCoinBase() && !tx.IsZerocoinSpend()) {
txundo.vprevout.reserve(tx.vin.size());
BOOST_FOREACH (const CTxIn& txin, tx.vin) {
txundo.vprevout.push_back(CTxInUndo());
bool ret = inputs.ModifyCoins(txin.prevout.hash)->Spend(txin.prevout, txundo.vprevout.back());
assert(ret);
}
}
// add outputs
inputs.ModifyCoins(tx.GetHash())->FromTx(tx, nHeight);
}
bool CScriptCheck::operator()()
{
const CScript& scriptSig = ptxTo->vin[nIn].scriptSig;
if (!VerifyScript(scriptSig, scriptPubKey, nFlags, CachingTransactionSignatureChecker(ptxTo, nIn, cacheStore), &error)) {
return ::error("CScriptCheck(): %s:%d VerifySignature failed: %s", ptxTo->GetHash().ToString(), nIn, ScriptErrorString(error));
}
return true;
}
bool CheckInputs(const CTransaction& tx, CValidationState& state, const CCoinsViewCache& inputs, bool fScriptChecks, unsigned int flags, bool cacheStore, std::vector<CScriptCheck>* pvChecks)
{
if (!tx.IsCoinBase() && !tx.IsZerocoinSpend()) {
if (pvChecks)
pvChecks->reserve(tx.vin.size());
// This doesn't trigger the DoS code on purpose; if it did, it would make it easier
// for an attacker to attempt to split the network.
if (!inputs.HaveInputs(tx))
return state.Invalid(error("CheckInputs() : %s inputs unavailable", tx.GetHash().ToString()));
// While checking, GetBestBlock() refers to the parent block.
// This is also true for mempool checks.
CBlockIndex* pindexPrev = mapBlockIndex.find(inputs.GetBestBlock())->second;
int nSpendHeight = pindexPrev->nHeight + 1;
CAmount nValueIn = 0;
CAmount nFees = 0;
for (unsigned int i = 0; i < tx.vin.size(); i++) {
const COutPoint& prevout = tx.vin[i].prevout;
const CCoins* coins = inputs.AccessCoins(prevout.hash);
assert(coins);
// If prev is coinbase, check that it's matured
if (coins->IsCoinBase() || coins->IsCoinStake()) {
if (nSpendHeight - coins->nHeight < Params().COINBASE_MATURITY())
return state.Invalid(
error("CheckInputs() : tried to spend coinbase at depth %d, coinstake=%d", nSpendHeight - coins->nHeight, coins->IsCoinStake()),
REJECT_INVALID, "bad-txns-premature-spend-of-coinbase");
}
// Check for negative or overflow input values
nValueIn += coins->vout[prevout.n].nValue;
if (!MoneyRange(coins->vout[prevout.n].nValue) || !MoneyRange(nValueIn))
return state.DoS(100, error("CheckInputs() : txin values out of range"),
REJECT_INVALID, "bad-txns-inputvalues-outofrange");
}
if (!tx.IsCoinStake()) {
if (nValueIn < tx.GetValueOut())
return state.DoS(100, error("CheckInputs() : %s value in (%s) < value out (%s)",
tx.GetHash().ToString(), FormatMoney(nValueIn), FormatMoney(tx.GetValueOut())),
REJECT_INVALID, "bad-txns-in-belowout");
// Tally transaction fees
CAmount nTxFee = nValueIn - tx.GetValueOut();
if (nTxFee < 0)
return state.DoS(100, error("CheckInputs() : %s nTxFee < 0", tx.GetHash().ToString()),
REJECT_INVALID, "bad-txns-fee-negative");
nFees += nTxFee;
if (!MoneyRange(nFees))
return state.DoS(100, error("CheckInputs() : nFees out of range"),
REJECT_INVALID, "bad-txns-fee-outofrange");
}
// The first loop above does all the inexpensive checks.
// Only if ALL inputs pass do we perform expensive ECDSA signature checks.
// Helps prevent CPU exhaustion attacks.
// Skip ECDSA signature verification when connecting blocks
// before the last block chain checkpoint. This is safe because block merkle hashes are
// still computed and checked, and any change will be caught at the next checkpoint.
if (fScriptChecks) {
for (unsigned int i = 0; i < tx.vin.size(); i++) {
const COutPoint& prevout = tx.vin[i].prevout;
const CCoins* coins = inputs.AccessCoins(prevout.hash);
assert(coins);
// Verify signature
CScriptCheck check(*coins, tx, i, flags, cacheStore);
if (pvChecks) {
pvChecks->push_back(CScriptCheck());
check.swap(pvChecks->back());
} else if (!check()) {
if (flags & STANDARD_NOT_MANDATORY_VERIFY_FLAGS) {
// Check whether the failure was caused by a
// non-mandatory script verification check, such as
// non-standard DER encodings or non-null dummy
// arguments; if so, don't trigger DoS protection to
// avoid splitting the network between upgraded and
// non-upgraded nodes.
CScriptCheck check(*coins, tx, i,
flags & ~STANDARD_NOT_MANDATORY_VERIFY_FLAGS, cacheStore);
if (check())
return state.Invalid(false, REJECT_NONSTANDARD, strprintf("non-mandatory-script-verify-flag (%s)", ScriptErrorString(check.GetScriptError())));
}
// Failures of other flags indicate a transaction that is
// invalid in new blocks, e.g. a invalid P2SH. We DoS ban
// such nodes as they are not following the protocol. That
// said during an upgrade careful thought should be taken
// as to the correct behavior - we may want to continue
// peering with non-upgraded nodes even after a soft-fork
// super-majority vote has passed.
return state.DoS(100, false, REJECT_INVALID, strprintf("mandatory-script-verify-flag-failed (%s)", ScriptErrorString(check.GetScriptError())));
}
}
}
}
return true;
}
bool DisconnectBlock(CBlock& block, CValidationState& state, CBlockIndex* pindex, CCoinsViewCache& view, bool* pfClean)
{
assert(pindex->GetBlockHash() == view.GetBestBlock());
if (pfClean)
*pfClean = false;
bool fClean = true;
CBlockUndo blockUndo;
CDiskBlockPos pos = pindex->GetUndoPos();
if (pos.IsNull())
return error("DisconnectBlock() : no undo data available");
if (!blockUndo.ReadFromDisk(pos, pindex->pprev->GetBlockHash()))
return error("DisconnectBlock() : failure reading undo data");
if (blockUndo.vtxundo.size() + 1 != block.vtx.size())
return error("DisconnectBlock() : block and undo data inconsistent");
// undo transactions in reverse order
for (int i = block.vtx.size() - 1; i >= 0; i--) {
const CTransaction& tx = block.vtx[i];
/** UNDO ZEROCOIN DATABASING
* note we only undo zerocoin databasing in the following statement, value to and from IoTHome
* addresses should still be handled by the typical bitcoin based undo code
* */
if (tx.ContainsZerocoins()) {
if (tx.IsZerocoinSpend()) {
//erase all zerocoinspends in this transaction
for (const CTxIn txin : tx.vin) {
if (txin.scriptSig.IsZerocoinSpend()) {
CoinSpend spend = TxInToZerocoinSpend(txin);
if (!zerocoinDB->EraseCoinSpend(spend.getCoinSerialNumber()))
return error("failed to erase spent zerocoin in block");
}
}
}
if (tx.IsZerocoinMint()) {
//erase all zerocoinmints in this transaction
for (const CTxOut txout : tx.vout) {
if (txout.scriptPubKey.empty() || !txout.scriptPubKey.IsZerocoinMint())
continue;
PublicCoin pubCoin(Params().Zerocoin_Params());
if (!TxOutToPublicCoin(txout, pubCoin, state))
return error("DisconnectBlock(): TxOutToPublicCoin() failed");
if(!zerocoinDB->EraseCoinMint(pubCoin.getValue()))
return error("DisconnectBlock(): Failed to erase coin mint");
}
}
}
uint256 hash = tx.GetHash();
// Check that all outputs are available and match the outputs in the block itself
// exactly. Note that transactions with only provably unspendable outputs won't
// have outputs available even in the block itself, so we handle that case
// specially with outsEmpty.
{
CCoins outsEmpty;
CCoinsModifier outs = view.ModifyCoins(hash);
outs->ClearUnspendable();
CCoins outsBlock(tx, pindex->nHeight);
// The CCoins serialization does not serialize negative numbers.
// No network rules currently depend on the version here, so an inconsistency is harmless
// but it must be corrected before txout nversion ever influences a network rule.
if (outsBlock.nVersion < 0)
outs->nVersion = outsBlock.nVersion;
if (*outs != outsBlock)
fClean = fClean && error("DisconnectBlock() : added transaction mismatch? database corrupted");
// remove outputs
outs->Clear();
}
// restore inputs
if (!tx.IsCoinBase() && !tx.IsZerocoinSpend()) { // not coinbases or zerocoinspend because they dont have traditional inputs
const CTxUndo& txundo = blockUndo.vtxundo[i - 1];
if (txundo.vprevout.size() != tx.vin.size())
return error("DisconnectBlock() : transaction and undo data inconsistent - txundo.vprevout.siz=%d tx.vin.siz=%d", txundo.vprevout.size(), tx.vin.size());
for (unsigned int j = tx.vin.size(); j-- > 0;) {
const COutPoint& out = tx.vin[j].prevout;
const CTxInUndo& undo = txundo.vprevout[j];
CCoinsModifier coins = view.ModifyCoins(out.hash);
if (undo.nHeight != 0) {
// undo data contains height: this is the last output of the prevout tx being spent
if (!coins->IsPruned())
fClean = fClean && error("DisconnectBlock() : undo data overwriting existing transaction");
coins->Clear();
coins->fCoinBase = undo.fCoinBase;
coins->nHeight = undo.nHeight;
coins->nVersion = undo.nVersion;
} else {
if (coins->IsPruned())
fClean = fClean && error("DisconnectBlock() : undo data adding output to missing transaction");
}
if (coins->IsAvailable(out.n))
fClean = fClean && error("DisconnectBlock() : undo data overwriting existing output");
if (coins->vout.size() < out.n + 1)
coins->vout.resize(out.n + 1);
coins->vout[out.n] = undo.txout;
}
}
}
// move best block pointer to prevout block
view.SetBestBlock(pindex->pprev->GetBlockHash());
if (!fVerifyingBlocks) {
//if block is an accumulator checkpoint block, remove checkpoint and checksums from db
uint256 nCheckpoint = pindex->nAccumulatorCheckpoint;
if(nCheckpoint != pindex->pprev->nAccumulatorCheckpoint) {
if(!EraseAccumulatorValues(nCheckpoint, pindex->pprev->nAccumulatorCheckpoint))
return error("DisconnectBlock(): failed to erase checkpoint");
}
}
if (pfClean) {
*pfClean = fClean;
return true;
} else {
return fClean;
}
}
void static FlushBlockFile(bool fFinalize = false)
{
LOCK(cs_LastBlockFile);
CDiskBlockPos posOld(nLastBlockFile, 0);
FILE* fileOld = OpenBlockFile(posOld);
if (fileOld) {
if (fFinalize)
TruncateFile(fileOld, vinfoBlockFile[nLastBlockFile].nSize);
FileCommit(fileOld);
fclose(fileOld);
}
fileOld = OpenUndoFile(posOld);
if (fileOld) {
if (fFinalize)
TruncateFile(fileOld, vinfoBlockFile[nLastBlockFile].nUndoSize);
FileCommit(fileOld);
fclose(fileOld);
}
}
bool FindUndoPos(CValidationState& state, int nFile, CDiskBlockPos& pos, unsigned int nAddSize);
static CCheckQueue<CScriptCheck> scriptcheckqueue(128);
void ThreadScriptCheck()
{
RenameThread("iothome-scriptch");
scriptcheckqueue.Thread();
}
void RecalculateZIOTHMinted()
{
CBlockIndex *pindex = chainActive[Params().Zerocoin_AccumulatorStartHeight()];
int nHeightEnd = chainActive.Height();
while (true) {
if (pindex->nHeight % 1000 == 0)
LogPrintf("%s : block %d...\n", __func__, pindex->nHeight);
//overwrite possibly wrong vMintsInBlock data
CBlock block;
assert(ReadBlockFromDisk(block, pindex));
std::list<CZerocoinMint> listMints;
BlockToZerocoinMintList(block, listMints);
vector<libzerocoin::CoinDenomination> vDenomsBefore = pindex->vMintDenominationsInBlock;
pindex->vMintDenominationsInBlock.clear();
for (auto mint : listMints)
pindex->vMintDenominationsInBlock.emplace_back(mint.GetDenomination());
//Record mints to disk
assert(pblocktree->WriteBlockIndex(CDiskBlockIndex(pindex)));
if (pindex->nHeight < nHeightEnd)
pindex = chainActive.Next(pindex);
else
break;
}
pblocktree->Flush();
}
void RecalculateZIOTHSpent()
{
CBlockIndex* pindex = chainActive[Params().Zerocoin_AccumulatorStartHeight()];
while (true) {
if (pindex->nHeight % 1000 == 0)
LogPrintf("%s : block %d...\n", __func__, pindex->nHeight);
//Rewrite zIOTH supply
CBlock block;
assert(ReadBlockFromDisk(block, pindex));
list<libzerocoin::CoinDenomination> listDenomsSpent = ZerocoinSpendListFromBlock(block);
//Reset the supply to previous block
pindex->mapZerocoinSupply = pindex->pprev->mapZerocoinSupply;
//Add mints to zIOTH supply
for (auto denom : libzerocoin::zerocoinDenomList) {
long nDenomAdded = count(pindex->vMintDenominationsInBlock.begin(), pindex->vMintDenominationsInBlock.end(), denom);
pindex->mapZerocoinSupply.at(denom) += nDenomAdded;
}
//Remove spends from zIOTH supply
for (auto denom : listDenomsSpent)
pindex->mapZerocoinSupply.at(denom)--;
//Rewrite money supply
assert(pblocktree->WriteBlockIndex(CDiskBlockIndex(pindex)));
if (pindex->nHeight < chainActive.Height())
pindex = chainActive.Next(pindex);
else
break;
}
pblocktree->Flush();
}
bool RecalculateIOTHSupply(int nHeightStart)
{
if (nHeightStart > chainActive.Height())
return false;
CBlockIndex* pindex = chainActive[nHeightStart];
CAmount nSupplyPrev = pindex->pprev->nMoneySupply;
while (true) {
if (pindex->nHeight % 1000 == 0)
LogPrintf("%s : block %d...\n", __func__, pindex->nHeight);
CBlock block;
assert(ReadBlockFromDisk(block, pindex));
CAmount nValueIn = 0;
CAmount nValueOut = 0;
for (const CTransaction tx : block.vtx) {
for (unsigned int i = 0; i < tx.vin.size(); i++) {
if (tx.IsCoinBase())
break;
if (tx.vin[i].scriptSig.IsZerocoinSpend()) {
nValueIn += tx.vin[i].nSequence * COIN;
continue;
}
COutPoint prevout = tx.vin[i].prevout;
CTransaction txPrev;
uint256 hashBlock;
assert(GetTransaction(prevout.hash, txPrev, hashBlock, true));
nValueIn += txPrev.vout[prevout.n].nValue;
}
for (unsigned int i = 0; i < tx.vout.size(); i++) {
if (i == 0 && tx.IsCoinStake())
continue;
nValueOut += tx.vout[i].nValue;
}
}
// Rewrite money supply
pindex->nMoneySupply = nSupplyPrev + nValueOut - nValueIn;
nSupplyPrev = pindex->nMoneySupply;
assert(pblocktree->WriteBlockIndex(CDiskBlockIndex(pindex)));
if (pindex->nHeight < chainActive.Height())
pindex = chainActive.Next(pindex);
else
break;
}
pblocktree->Flush();
return true;
}
static int64_t nTimeVerify = 0;
static int64_t nTimeConnect = 0;
static int64_t nTimeIndex = 0;
static int64_t nTimeCallbacks = 0;
static int64_t nTimeTotal = 0;
bool ConnectBlock(const CBlock& block, CValidationState& state, CBlockIndex* pindex, CCoinsViewCache& view, bool fJustCheck, bool fAlreadyChecked)
{
AssertLockHeld(cs_main);
// Check it again in case a previous version let a bad block in
if (!fAlreadyChecked && !CheckBlock(block, state, !fJustCheck, !fJustCheck))
return false;
// verify that the view's current state corresponds to the previous block
uint256 hashPrevBlock = pindex->pprev == NULL ? uint256(0) : pindex->pprev->GetBlockHash();
if (hashPrevBlock != view.GetBestBlock())
LogPrintf("%s: hashPrev=%s view=%s\n", __func__, hashPrevBlock.ToString().c_str(), view.GetBestBlock().ToString().c_str());
assert(hashPrevBlock == view.GetBestBlock());
// Special case for the genesis block, skipping connection of its transactions
// (its coinbase is unspendable)
if (block.GetHash() == Params().HashGenesisBlock()) {
view.SetBestBlock(pindex->GetBlockHash());
return true;
}
if (pindex->nHeight <= Params().LAST_POW_BLOCK() && block.IsProofOfStake())
return state.DoS(100, error("ConnectBlock() : PoS period not active"),
REJECT_INVALID, "PoS-early");
if (pindex->nHeight > Params().LAST_POW_BLOCK() && block.IsProofOfWork())
return state.DoS(100, error("ConnectBlock() : PoW period ended"),
REJECT_INVALID, "PoW-ended");
bool fScriptChecks = pindex->nHeight >= Checkpoints::GetTotalBlocksEstimate();
// Do not allow blocks that contain transactions which 'overwrite' older transactions,
// unless those are already completely spent.
// If such overwrites are allowed, coinbases and transactions depending upon those
// can be duplicated to remove the ability to spend the first instance -- even after
// being sent to another address.
// See BIP30 and http://r6.ca/blog/20120206T005236Z.html for more information.
// This logic is not necessary for memory pool transactions, as AcceptToMemoryPool
// already refuses previously-known transaction ids entirely.
// This rule was originally applied all blocks whose timestamp was after March 15, 2012, 0:00 UTC.
// Now that the whole chain is irreversibly beyond that time it is applied to all blocks except the
// two in the chain that violate it. This prevents exploiting the issue against nodes in their
// initial block download.
bool fEnforceBIP30 = (!pindex->phashBlock) || // Enforce on CreateNewBlock invocations which don't have a hash.
!((pindex->nHeight == 91842 && pindex->GetBlockHash() == uint256("0x00000000000a4d0a398161ffc163c503763b1f4360639393e0e4c8e300e0caec")) ||
(pindex->nHeight == 91880 && pindex->GetBlockHash() == uint256("0x00000000000743f190a18c5577a3c2d2a1f610ae9601ac046a38084ccb7cd721")));
if (fEnforceBIP30) {
BOOST_FOREACH (const CTransaction& tx, block.vtx) {
const CCoins* coins = view.AccessCoins(tx.GetHash());
if (coins && !coins->IsPruned())
return state.DoS(100, error("ConnectBlock() : tried to overwrite transaction"),
REJECT_INVALID, "bad-txns-BIP30");
}
}
// BIP16 didn't become active until Apr 1 2012
int64_t nBIP16SwitchTime = 1333238400;
bool fStrictPayToScriptHash = (pindex->GetBlockTime() >= nBIP16SwitchTime);
unsigned int flags = fStrictPayToScriptHash ? SCRIPT_VERIFY_P2SH : SCRIPT_VERIFY_NONE;
// Start enforcing the DERSIG (BIP66) rules, for block.nVersion=3 blocks, when 75% of the network has upgraded:
if (block.nVersion >= 3 && CBlockIndex::IsSuperMajority(3, pindex->pprev, Params().EnforceBlockUpgradeMajority())) {
flags |= SCRIPT_VERIFY_DERSIG;
}
CBlockUndo blockundo;
CCheckQueueControl<CScriptCheck> control(fScriptChecks && nScriptCheckThreads ? &scriptcheckqueue : NULL);
int64_t nTimeStart = GetTimeMicros();
CAmount nFees = 0;
int nInputs = 0;
unsigned int nSigOps = 0;
CDiskTxPos pos(pindex->GetBlockPos(), GetSizeOfCompactSize(block.vtx.size()));
std::vector<std::pair<uint256, CDiskTxPos> > vPos;
vPos.reserve(block.vtx.size());
blockundo.vtxundo.reserve(block.vtx.size() - 1);
CAmount nValueOut = 0;
CAmount nValueIn = 0;
unsigned int nMaxBlockSigOps = MAX_BLOCK_SIGOPS_CURRENT;
for (unsigned int i = 0; i < block.vtx.size(); i++) {
const CTransaction& tx = block.vtx[i];
nInputs += tx.vin.size();
nSigOps += GetLegacySigOpCount(tx);
if (nSigOps > nMaxBlockSigOps)
return state.DoS(100, error("ConnectBlock() : too many sigops"),
REJECT_INVALID, "bad-blk-sigops");
//Temporarily disable zerocoin transactions for maintenance
if (block.nTime > GetSporkValue(SPORK_16_ZEROCOIN_MAINTENANCE_MODE) && !IsInitialBlockDownload() && tx.ContainsZerocoins())
return state.DoS(100, error("ConnectBlock() : zerocoin transactions are currently in maintenance mode"));
if (tx.IsZerocoinSpend()) {
int nHeightTx = 0;
if (IsTransactionInChain(tx.GetHash(), nHeightTx)) {
//when verifying blocks on init, the blocks are scanned without being disconnected - prevent that from causing an error
if (!fVerifyingBlocks || (fVerifyingBlocks && pindex->nHeight > nHeightTx))
return state.DoS(100, error("%s : txid %s already exists in block %d , trying to include it again in block %d", __func__,
tx.GetHash().GetHex(), nHeightTx, pindex->nHeight),
REJECT_INVALID, "bad-txns-inputs-missingorspent");
}
//Check for double spending of serial #'s
for (const CTxIn& txIn : tx.vin) {
if (!txIn.scriptSig.IsZerocoinSpend())
continue;
CoinSpend spend = TxInToZerocoinSpend(txIn);
nValueIn += spend.getDenomination() * COIN;
// Make sure that the serial number is in valid range
if (!spend.HasValidSerial(Params().Zerocoin_Params())) {
string strError = strprintf("%s : txid=%s in block %d contains invalid serial %s\n", __func__, tx.GetHash().GetHex(), pindex->nHeight, spend.getCoinSerialNumber());
if (pindex->nHeight >= Params().Zerocoin_Block_EnforceSerialRange())
return state.DoS(100, error(strError.c_str()));
strError = "NOT ENFORCING : " + strError;
LogPrintf(strError.c_str());
}
//Is the serial already in the blockchain?
uint256 hashTxFromDB;
int nHeightTxSpend = 0;
if (zerocoinDB->ReadCoinSpend(spend.getCoinSerialNumber(), hashTxFromDB)) {
if(IsSerialInBlockchain(spend.getCoinSerialNumber(), nHeightTxSpend)) {
if(!fVerifyingBlocks || (fVerifyingBlocks && pindex->nHeight > nHeightTxSpend))
return state.DoS(100, error("%s : zIoTHome with serial %s is already in the block %d\n",
__func__, spend.getCoinSerialNumber().GetHex(), nHeightTxSpend));
}
}
//record spend to database
if (!zerocoinDB->WriteCoinSpend(spend.getCoinSerialNumber(), tx.GetHash()))
return error("%s : failed to record coin serial to database");
}
} else if (!tx.IsCoinBase()) {
if (!view.HaveInputs(tx))
return state.DoS(100, error("ConnectBlock() : inputs missing/spent"),
REJECT_INVALID, "bad-txns-inputs-missingorspent");
if (fStrictPayToScriptHash) {
// Add in sigops done by pay-to-script-hash inputs;
// this is to prevent a "rogue miner" from creating
// an incredibly-expensive-to-validate block.
nSigOps += GetP2SHSigOpCount(tx, view);
if (nSigOps > nMaxBlockSigOps)
return state.DoS(100, error("ConnectBlock() : too many sigops"),
REJECT_INVALID, "bad-blk-sigops");
}
if (!tx.IsCoinStake())
nFees += view.GetValueIn(tx) - tx.GetValueOut();
nValueIn += view.GetValueIn(tx);
std::vector<CScriptCheck> vChecks;
if (!CheckInputs(tx, state, view, fScriptChecks, flags, false, nScriptCheckThreads ? &vChecks : NULL))
return false;
control.Add(vChecks);
}
nValueOut += tx.GetValueOut();
CTxUndo undoDummy;
if (i > 0) {
blockundo.vtxundo.push_back(CTxUndo());
}
UpdateCoins(tx, state, view, i == 0 ? undoDummy : blockundo.vtxundo.back(), pindex->nHeight);
vPos.push_back(std::make_pair(tx.GetHash(), pos));
pos.nTxOffset += ::GetSerializeSize(tx, SER_DISK, CLIENT_VERSION);
}
std::list<CZerocoinMint> listMints;
BlockToZerocoinMintList(block, listMints);
std::list<libzerocoin::CoinDenomination> listSpends = ZerocoinSpendListFromBlock(block);
if (!fVerifyingBlocks && pindex->nHeight == Params().Zerocoin_StartHeight() + 1) {
RecalculateZIOTHMinted();
RecalculateZIOTHSpent();
RecalculateIOTHSupply(1);
}
// Initialize zerocoin supply to the supply from previous block
if (pindex->pprev && pindex->pprev->GetBlockHeader().nVersion > 3) {
for (auto& denom : zerocoinDenomList) {
pindex->mapZerocoinSupply.at(denom) = pindex->pprev->mapZerocoinSupply.at(denom);
}
}
// Track zerocoin money supply
CAmount nAmountZerocoinSpent = 0;
pindex->vMintDenominationsInBlock.clear();
if (pindex->pprev) {
for (auto& m : listMints) {
libzerocoin::CoinDenomination denom = m.GetDenomination();
pindex->vMintDenominationsInBlock.push_back(m.GetDenomination());
pindex->mapZerocoinSupply.at(denom)++;
}
for (auto& denom : listSpends) {
pindex->mapZerocoinSupply.at(denom)--;
nAmountZerocoinSpent += libzerocoin::ZerocoinDenominationToAmount(denom);
// zerocoin failsafe
if (pindex->mapZerocoinSupply.at(denom) < 0)
return state.DoS(100, error("Block contains zerocoins that spend more than are in the available supply to spend"));
}
}
for (auto& denom : zerocoinDenomList) {
LogPrint("zero" "%s coins for denomination %d pubcoin %s\n", __func__, pindex->mapZerocoinSupply.at(denom), denom);
}
// track money supply and mint amount info
CAmount nMoneySupplyPrev = pindex->pprev ? pindex->pprev->nMoneySupply : 0;
pindex->nMoneySupply = nMoneySupplyPrev + nValueOut - nValueIn;
pindex->nMint = pindex->nMoneySupply - nMoneySupplyPrev + nFees;
// LogPrintf("XX69----------> ConnectBlock(): nValueOut: %s, nValueIn: %s, nFees: %s, nMint: %s zIoTHomeSpent: %s\n",
// FormatMoney(nValueOut), FormatMoney(nValueIn),
// FormatMoney(nFees), FormatMoney(pindex->nMint), FormatMoney(nAmountZerocoinSpent));
if (!pblocktree->WriteBlockIndex(CDiskBlockIndex(pindex)))
return error("Connect() : WriteBlockIndex for pindex failed");
int64_t nTime1 = GetTimeMicros();
nTimeConnect += nTime1 - nTimeStart;
LogPrint("bench", " - Connect %u transactions: %.2fms (%.3fms/tx, %.3fms/txin) [%.2fs]\n", (unsigned)block.vtx.size(), 0.001 * (nTime1 - nTimeStart), 0.001 * (nTime1 - nTimeStart) / block.vtx.size(), nInputs <= 1 ? 0 : 0.001 * (nTime1 - nTimeStart) / (nInputs - 1), nTimeConnect * 0.000001);
//PoW phase redistributed fees to miner. PoS stage destroys fees.
CAmount nExpectedMint = GetBlockValue(pindex->pprev->nHeight);
CAmount nExpectedMintNext = GetBlockValue(pindex->pprev->nHeight+1);
CAmount nExpectedMint2 = nExpectedMint+nExpectedMintNext;
if (block.IsProofOfWork()) {
nExpectedMint2 += nFees;
}
if (!IsBlockValueValid(block, nExpectedMint2, pindex->nMint)) {
return state.DoS(100,
error("ConnectBlock() : reward pays too much (actual=%s vs limit=%s)",
FormatMoney(pindex->nMint), FormatMoney(nExpectedMint2)),
REJECT_INVALID, "bad-cb-amount");
}
// zerocoin accumulator: if a new accumulator checkpoint was generated, check that it is the correct value
if (!fVerifyingBlocks && pindex->nHeight >= Params().Zerocoin_StartHeight() && pindex->nHeight % 10 == 0) {
uint256 nCheckpointCalculated = 0;
if (!CalculateAccumulatorCheckpoint(pindex->nHeight, nCheckpointCalculated))
return state.DoS(100, error("ConnectBlock() : failed to calculate accumulator checkpoint"));
if (nCheckpointCalculated != block.nAccumulatorCheckpoint) {
LogPrintf("%s: block=%d calculated: %s\n block: %s\n", __func__, pindex->nHeight, nCheckpointCalculated.GetHex(), block.nAccumulatorCheckpoint.GetHex());
return state.DoS(100, error("ConnectBlock() : accumulator does not match calculated value"));
}
} else if (!fVerifyingBlocks) {
if (block.nAccumulatorCheckpoint != pindex->pprev->nAccumulatorCheckpoint) {
return state.DoS(100, error("ConnectBlock() : new accumulator checkpoint generated on a block that is not multiple of 10"));
}
}
if (!control.Wait())
return state.DoS(100, false);
int64_t nTime2 = GetTimeMicros();
nTimeVerify += nTime2 - nTimeStart;
LogPrint("bench", " - Verify %u txins: %.2fms (%.3fms/txin) [%.2fs]\n", nInputs - 1, 0.001 * (nTime2 - nTimeStart), nInputs <= 1 ? 0 : 0.001 * (nTime2 - nTimeStart) / (nInputs - 1), nTimeVerify * 0.000001);
if (fJustCheck)
return true;
// Write undo information to disk
if (pindex->GetUndoPos().IsNull() || !pindex->IsValid(BLOCK_VALID_SCRIPTS)) {
if (pindex->GetUndoPos().IsNull()) {
CDiskBlockPos pos;
if (!FindUndoPos(state, pindex->nFile, pos, ::GetSerializeSize(blockundo, SER_DISK, CLIENT_VERSION) + 40))
return error("ConnectBlock() : FindUndoPos failed");
if (!blockundo.WriteToDisk(pos, pindex->pprev->GetBlockHash()))
return state.Abort("Failed to write undo data");
// update nUndoPos in block index
pindex->nUndoPos = pos.nPos;
pindex->nStatus |= BLOCK_HAVE_UNDO;
}
pindex->RaiseValidity(BLOCK_VALID_SCRIPTS);
setDirtyBlockIndex.insert(pindex);
}
if (fTxIndex)
if (!pblocktree->WriteTxIndex(vPos))
return state.Abort("Failed to write transaction index");
// add this block to the view's block chain
view.SetBestBlock(pindex->GetBlockHash());
int64_t nTime3 = GetTimeMicros();
nTimeIndex += nTime3 - nTime2;
LogPrint("bench", " - Index writing: %.2fms [%.2fs]\n", 0.001 * (nTime3 - nTime2), nTimeIndex * 0.000001);
// Watch for changes to the previous coinbase transaction.
static uint256 hashPrevBestCoinBase;
g_signals.UpdatedTransaction(hashPrevBestCoinBase);
hashPrevBestCoinBase = block.vtx[0].GetHash();
int64_t nTime4 = GetTimeMicros();
nTimeCallbacks += nTime4 - nTime3;
LogPrint("bench", " - Callbacks: %.2fms [%.2fs]\n", 0.001 * (nTime4 - nTime3), nTimeCallbacks * 0.000001);
return true;
}
enum FlushStateMode {
FLUSH_STATE_IF_NEEDED,
FLUSH_STATE_PERIODIC,
FLUSH_STATE_ALWAYS
};
/**
* Update the on-disk chain state.
* The caches and indexes are flushed if either they're too large, forceWrite is set, or
* fast is not set and it's been a while since the last write.
*/
bool static FlushStateToDisk(CValidationState& state, FlushStateMode mode)
{
LOCK(cs_main);
static int64_t nLastWrite = 0;
try {
if ((mode == FLUSH_STATE_ALWAYS) ||
((mode == FLUSH_STATE_PERIODIC || mode == FLUSH_STATE_IF_NEEDED) && pcoinsTip->GetCacheSize() > nCoinCacheSize) ||
(mode == FLUSH_STATE_PERIODIC && GetTimeMicros() > nLastWrite + DATABASE_WRITE_INTERVAL * 1000000)) {
// Typical CCoins structures on disk are around 100 bytes in size.
// Pushing a new one to the database can cause it to be written
// twice (once in the log, and once in the tables). This is already
// an overestimation, as most will delete an existing entry or
// overwrite one. Still, use a conservative safety factor of 2.
if (!CheckDiskSpace(100 * 2 * 2 * pcoinsTip->GetCacheSize()))
return state.Error("out of disk space");
// First make sure all block and undo data is flushed to disk.
FlushBlockFile();
// Then update all block file information (which may refer to block and undo files).
bool fileschanged = false;
for (set<int>::iterator it = setDirtyFileInfo.begin(); it != setDirtyFileInfo.end();) {
if (!pblocktree->WriteBlockFileInfo(*it, vinfoBlockFile[*it])) {
return state.Abort("Failed to write to block index");
}
fileschanged = true;
setDirtyFileInfo.erase(it++);
}
if (fileschanged && !pblocktree->WriteLastBlockFile(nLastBlockFile)) {
return state.Abort("Failed to write to block index");
}
for (set<CBlockIndex*>::iterator it = setDirtyBlockIndex.begin(); it != setDirtyBlockIndex.end();) {
if (!pblocktree->WriteBlockIndex(CDiskBlockIndex(*it))) {
return state.Abort("Failed to write to block index");
}
setDirtyBlockIndex.erase(it++);
}
pblocktree->Sync();
// Finally flush the chainstate (which may refer to block index entries).
if (!pcoinsTip->Flush())
return state.Abort("Failed to write to coin database");
// Update best block in wallet (so we can detect restored wallets).
if (mode != FLUSH_STATE_IF_NEEDED) {
g_signals.SetBestChain(chainActive.GetLocator());
}
nLastWrite = GetTimeMicros();
}
} catch (const std::runtime_error& e) {
return state.Abort(std::string("System error while flushing: ") + e.what());
}
return true;
}
void FlushStateToDisk()
{
CValidationState state;
FlushStateToDisk(state, FLUSH_STATE_ALWAYS);
}
/** Update chainActive and related internal data structures. */
void static UpdateTip(CBlockIndex* pindexNew)
{
chainActive.SetTip(pindexNew);
// If turned on AutoZeromint will automatically convert IOTH to zIOTH
if (pwalletMain->isZeromintEnabled ())
pwalletMain->AutoZeromint ();
// New best block
nTimeBestReceived = GetTime();
mempool.AddTransactionsUpdated(1);
LogPrintf("UpdateTip: new best=%s height=%d log2_work=%.8g tx=%lu date=%s progress=%f cache=%u\n",
chainActive.Tip()->GetBlockHash().ToString(), chainActive.Height(), log(chainActive.Tip()->nChainWork.getdouble()) / log(2.0), (unsigned long)chainActive.Tip()->nChainTx,
DateTimeStrFormat("%Y-%m-%d %H:%M:%S", chainActive.Tip()->GetBlockTime()),
Checkpoints::GuessVerificationProgress(chainActive.Tip()), (unsigned int)pcoinsTip->GetCacheSize());
cvBlockChange.notify_all();
// Check the version of the last 100 blocks to see if we need to upgrade:
static bool fWarned = false;
if (!IsInitialBlockDownload() && !fWarned) {
int nUpgraded = 0;
const CBlockIndex* pindex = chainActive.Tip();
for (int i = 0; i < 100 && pindex != NULL; i++) {
if (pindex->nVersion > CBlock::CURRENT_VERSION)
++nUpgraded;
pindex = pindex->pprev;
}
if (nUpgraded > 0)
LogPrintf("SetBestChain: %d of last 100 blocks above version %d\n", nUpgraded, (int)CBlock::CURRENT_VERSION);
if (nUpgraded > 100 / 2) {
// strMiscWarning is read by GetWarnings(), called by Qt and the JSON-RPC code to warn the user:
strMiscWarning = _("Warning: This version is obsolete, upgrade required!");
CAlert::Notify(strMiscWarning, true);
fWarned = true;
}
}
}
/** Disconnect chainActive's tip. */
bool static DisconnectTip(CValidationState& state)
{
CBlockIndex* pindexDelete = chainActive.Tip();
assert(pindexDelete);
mempool.check(pcoinsTip);
// Read block from disk.
CBlock block;
if (!ReadBlockFromDisk(block, pindexDelete))
return state.Abort("Failed to read block");
// Apply the block atomically to the chain state.
int64_t nStart = GetTimeMicros();
{
CCoinsViewCache view(pcoinsTip);
if (!DisconnectBlock(block, state, pindexDelete, view))
return error("DisconnectTip() : DisconnectBlock %s failed", pindexDelete->GetBlockHash().ToString());
assert(view.Flush());
}
LogPrint("bench", "- Disconnect block: %.2fms\n", (GetTimeMicros() - nStart) * 0.001);
// Write the chain state to disk, if necessary.
if (!FlushStateToDisk(state, FLUSH_STATE_ALWAYS))
return false;
// Resurrect mempool transactions from the disconnected block.
BOOST_FOREACH (const CTransaction& tx, block.vtx) {
// ignore validation errors in resurrected transactions
list<CTransaction> removed;
CValidationState stateDummy;
if (tx.IsCoinBase() || tx.IsCoinStake() || !AcceptToMemoryPool(mempool, stateDummy, tx, false, NULL))
mempool.remove(tx, removed, true);
}
mempool.removeCoinbaseSpends(pcoinsTip, pindexDelete->nHeight);
mempool.check(pcoinsTip);
// Update chainActive and related variables.
UpdateTip(pindexDelete->pprev);
// Let wallets know transactions went from 1-confirmed to
// 0-confirmed or conflicted:
BOOST_FOREACH (const CTransaction& tx, block.vtx) {
SyncWithWallets(tx, NULL);
}
return true;
}
static int64_t nTimeReadFromDisk = 0;
static int64_t nTimeConnectTotal = 0;
static int64_t nTimeFlush = 0;
static int64_t nTimeChainState = 0;
static int64_t nTimePostConnect = 0;
/**
* Connect a new block to chainActive. pblock is either NULL or a pointer to a CBlock
* corresponding to pindexNew, to bypass loading it again from disk.
*/
bool static ConnectTip(CValidationState& state, CBlockIndex* pindexNew, CBlock* pblock, bool fAlreadyChecked)
{
assert(pindexNew->pprev == chainActive.Tip());
mempool.check(pcoinsTip);
CCoinsViewCache view(pcoinsTip);
if (pblock == NULL)
fAlreadyChecked = false;
// Read block from disk.
int64_t nTime1 = GetTimeMicros();
CBlock block;
if (!pblock) {
if (!ReadBlockFromDisk(block, pindexNew))
return state.Abort("Failed to read block");
pblock = █
}
// Apply the block atomically to the chain state.
int64_t nTime2 = GetTimeMicros();
nTimeReadFromDisk += nTime2 - nTime1;
int64_t nTime3;
LogPrint("bench", " - Load block from disk: %.2fms [%.2fs]\n", (nTime2 - nTime1) * 0.001, nTimeReadFromDisk * 0.000001);
{
CInv inv(MSG_BLOCK, pindexNew->GetBlockHash());
bool rv = ConnectBlock(*pblock, state, pindexNew, view, false, fAlreadyChecked);
g_signals.BlockChecked(*pblock, state);
if (!rv) {
if (state.IsInvalid())
InvalidBlockFound(pindexNew, state);
return error("ConnectTip() : ConnectBlock %s failed", pindexNew->GetBlockHash().ToString());
}
mapBlockSource.erase(inv.hash);
nTime3 = GetTimeMicros();
nTimeConnectTotal += nTime3 - nTime2;
LogPrint("bench", " - Connect total: %.2fms [%.2fs]\n", (nTime3 - nTime2) * 0.001, nTimeConnectTotal * 0.000001);
assert(view.Flush());
}
int64_t nTime4 = GetTimeMicros();
nTimeFlush += nTime4 - nTime3;
LogPrint("bench", " - Flush: %.2fms [%.2fs]\n", (nTime4 - nTime3) * 0.001, nTimeFlush * 0.000001);
// Write the chain state to disk, if necessary. Always write to disk if this is the first of a new file.
FlushStateMode flushMode = FLUSH_STATE_IF_NEEDED;
if (pindexNew->pprev && (pindexNew->GetBlockPos().nFile != pindexNew->pprev->GetBlockPos().nFile))
flushMode = FLUSH_STATE_ALWAYS;
if (!FlushStateToDisk(state, flushMode))
return false;
int64_t nTime5 = GetTimeMicros();
nTimeChainState += nTime5 - nTime4;
LogPrint("bench", " - Writing chainstate: %.2fms [%.2fs]\n", (nTime5 - nTime4) * 0.001, nTimeChainState * 0.000001);
// Remove conflicting transactions from the mempool.
list<CTransaction> txConflicted;
mempool.removeForBlock(pblock->vtx, pindexNew->nHeight, txConflicted);
mempool.check(pcoinsTip);
// Update chainActive & related variables.
UpdateTip(pindexNew);
// Tell wallet about transactions that went from mempool
// to conflicted:
BOOST_FOREACH (const CTransaction& tx, txConflicted) {
SyncWithWallets(tx, NULL);
}
// ... and about transactions that got confirmed:
BOOST_FOREACH (const CTransaction& tx, pblock->vtx) {
SyncWithWallets(tx, pblock);
}
int64_t nTime6 = GetTimeMicros();
nTimePostConnect += nTime6 - nTime5;
nTimeTotal += nTime6 - nTime1;
LogPrint("bench", " - Connect postprocess: %.2fms [%.2fs]\n", (nTime6 - nTime5) * 0.001, nTimePostConnect * 0.000001);
LogPrint("bench", "- Connect block: %.2fms [%.2fs]\n", (nTime6 - nTime1) * 0.001, nTimeTotal * 0.000001);
return true;
}
bool DisconnectBlocksAndReprocess(int blocks)
{
LOCK(cs_main);
CValidationState state;
LogPrintf("DisconnectBlocksAndReprocess: Got command to replay %d blocks\n", blocks);
for (int i = 0; i <= blocks; i++)
DisconnectTip(state);
return true;
}
/*
DisconnectBlockAndInputs
Remove conflicting blocks for successful SwiftX transaction locks
This should be very rare (Probably will never happen)
*/
// ***TODO*** clean up here
bool DisconnectBlockAndInputs(CValidationState& state, CTransaction txLock)
{
// All modifications to the coin state will be done in this cache.
// Only when all have succeeded, we push it to pcoinsTip.
// CCoinsViewCache view(*pcoinsTip, true);
CBlockIndex* BlockReading = chainActive.Tip();
CBlockIndex* pindexNew = NULL;
bool foundConflictingTx = false;
//remove anything conflicting in the memory pool
list<CTransaction> txConflicted;
mempool.removeConflicts(txLock, txConflicted);
// List of what to disconnect (typically nothing)
vector<CBlockIndex*> vDisconnect;
for (unsigned int i = 1; BlockReading && BlockReading->nHeight > 0 && !foundConflictingTx && i < 6; i++) {
vDisconnect.push_back(BlockReading);
pindexNew = BlockReading->pprev; //new best block
CBlock block;
if (!ReadBlockFromDisk(block, BlockReading))
return state.Abort(_("Failed to read block"));
// Queue memory transactions to resurrect.
// We only do this for blocks after the last checkpoint (reorganisation before that
// point should only happen with -reindex/-loadblock, or a misbehaving peer.
BOOST_FOREACH (const CTransaction& tx, block.vtx) {
if (!tx.IsCoinBase()) {
BOOST_FOREACH (const CTxIn& in1, txLock.vin) {
BOOST_FOREACH (const CTxIn& in2, tx.vin) {
if (in1.prevout == in2.prevout) foundConflictingTx = true;
}
}
}
}
if (BlockReading->pprev == NULL) {
assert(BlockReading);
break;
}
BlockReading = BlockReading->pprev;
}
if (!foundConflictingTx) {
LogPrintf("DisconnectBlockAndInputs: Can't find a conflicting transaction to inputs\n");
return false;
}
if (vDisconnect.size() > 0) {
LogPrintf("REORGANIZE: Disconnect Conflicting Blocks %lli blocks; %s..\n", vDisconnect.size(), pindexNew->GetBlockHash().ToString());
BOOST_FOREACH (CBlockIndex* pindex, vDisconnect) {
LogPrintf(" -- disconnect %s\n", pindex->GetBlockHash().ToString());
DisconnectTip(state);
}
}
return true;
}
/**
* Return the tip of the chain with the most work in it, that isn't
* known to be invalid (it's however far from certain to be valid).
*/
static CBlockIndex* FindMostWorkChain()
{
do {
CBlockIndex* pindexNew = NULL;
// Find the best candidate header.
{
std::set<CBlockIndex*, CBlockIndexWorkComparator>::reverse_iterator it = setBlockIndexCandidates.rbegin();
if (it == setBlockIndexCandidates.rend())
return NULL;
pindexNew = *it;
}
// Check whether all blocks on the path between the currently active chain and the candidate are valid.
// Just going until the active chain is an optimization, as we know all blocks in it are valid already.
CBlockIndex* pindexTest = pindexNew;
bool fInvalidAncestor = false;
while (pindexTest && !chainActive.Contains(pindexTest)) {
assert(pindexTest->nChainTx || pindexTest->nHeight == 0);
// Pruned nodes may have entries in setBlockIndexCandidates for
// which block files have been deleted. Remove those as candidates
// for the most work chain if we come across them; we can't switch
// to a chain unless we have all the non-active-chain parent blocks.
bool fFailedChain = pindexTest->nStatus & BLOCK_FAILED_MASK;
bool fMissingData = !(pindexTest->nStatus & BLOCK_HAVE_DATA);
if (fFailedChain || fMissingData) {
// Candidate chain is not usable (either invalid or missing data)
if (fFailedChain && (pindexBestInvalid == NULL || pindexNew->nChainWork > pindexBestInvalid->nChainWork))
pindexBestInvalid = pindexNew;
CBlockIndex* pindexFailed = pindexNew;
// Remove the entire chain from the set.
while (pindexTest != pindexFailed) {
if (fFailedChain) {
pindexFailed->nStatus |= BLOCK_FAILED_CHILD;
} else if (fMissingData) {
// If we're missing data, then add back to mapBlocksUnlinked,
// so that if the block arrives in the future we can try adding
// to setBlockIndexCandidates again.
mapBlocksUnlinked.insert(std::make_pair(pindexFailed->pprev, pindexFailed));
}
setBlockIndexCandidates.erase(pindexFailed);
pindexFailed = pindexFailed->pprev;
}
setBlockIndexCandidates.erase(pindexTest);
fInvalidAncestor = true;
break;
}
pindexTest = pindexTest->pprev;
}
if (!fInvalidAncestor)
return pindexNew;
} while (true);
}
/** Delete all entries in setBlockIndexCandidates that are worse than the current tip. */
static void PruneBlockIndexCandidates()
{
// Note that we can't delete the current block itself, as we may need to return to it later in case a
// reorganization to a better block fails.
std::set<CBlockIndex*, CBlockIndexWorkComparator>::iterator it = setBlockIndexCandidates.begin();
while (it != setBlockIndexCandidates.end() && setBlockIndexCandidates.value_comp()(*it, chainActive.Tip())) {
setBlockIndexCandidates.erase(it++);
}
// Either the current tip or a successor of it we're working towards is left in setBlockIndexCandidates.
assert(!setBlockIndexCandidates.empty());
}
/**
* Try to make some progress towards making pindexMostWork the active block.
* pblock is either NULL or a pointer to a CBlock corresponding to pindexMostWork.
*/
static bool ActivateBestChainStep(CValidationState& state, CBlockIndex* pindexMostWork, CBlock* pblock, bool fAlreadyChecked)
{
AssertLockHeld(cs_main);
if (pblock == NULL)
fAlreadyChecked = false;
bool fInvalidFound = false;
const CBlockIndex* pindexOldTip = chainActive.Tip();
const CBlockIndex* pindexFork = chainActive.FindFork(pindexMostWork);
// Disconnect active blocks which are no longer in the best chain.
while (chainActive.Tip() && chainActive.Tip() != pindexFork) {
if (!DisconnectTip(state))
return false;
}
// Build list of new blocks to connect.
std::vector<CBlockIndex*> vpindexToConnect;
bool fContinue = true;
int nHeight = pindexFork ? pindexFork->nHeight : -1;
while (fContinue && nHeight != pindexMostWork->nHeight) {
// Don't iterate the entire list of potential improvements toward the best tip, as we likely only need
// a few blocks along the way.
int nTargetHeight = std::min(nHeight + 32, pindexMostWork->nHeight);
vpindexToConnect.clear();
vpindexToConnect.reserve(nTargetHeight - nHeight);
CBlockIndex* pindexIter = pindexMostWork->GetAncestor(nTargetHeight);
while (pindexIter && pindexIter->nHeight != nHeight) {
vpindexToConnect.push_back(pindexIter);
pindexIter = pindexIter->pprev;
}
nHeight = nTargetHeight;
// Connect new blocks.
BOOST_REVERSE_FOREACH (CBlockIndex* pindexConnect, vpindexToConnect) {
if (!ConnectTip(state, pindexConnect, pindexConnect == pindexMostWork ? pblock : NULL, fAlreadyChecked)) {
if (state.IsInvalid()) {
// The block violates a consensus rule.
if (!state.CorruptionPossible())
InvalidChainFound(vpindexToConnect.back());
state = CValidationState();
fInvalidFound = true;
fContinue = false;
break;
} else {
// A system error occurred (disk space, database error, ...).
return false;
}
} else {
PruneBlockIndexCandidates();
if (!pindexOldTip || chainActive.Tip()->nChainWork > pindexOldTip->nChainWork) {
// We're in a better position than we were. Return temporarily to release the lock.
fContinue = false;
break;
}
}
}
}
// Callbacks/notifications for a new best chain.
if (fInvalidFound)
CheckForkWarningConditionsOnNewFork(vpindexToConnect.back());
else
CheckForkWarningConditions();
return true;
}
/**
* Make the best chain active, in multiple steps. The result is either failure
* or an activated best chain. pblock is either NULL or a pointer to a block
* that is already loaded (to avoid loading it again from disk).
*/
bool ActivateBestChain(CValidationState& state, CBlock* pblock, bool fAlreadyChecked)
{
CBlockIndex* pindexNewTip = NULL;
CBlockIndex* pindexMostWork = NULL;
do {
boost::this_thread::interruption_point();
bool fInitialDownload;
while (true) {
TRY_LOCK(cs_main, lockMain);
if (!lockMain) {
MilliSleep(50);
continue;
}
pindexMostWork = FindMostWorkChain();
// Whether we have anything to do at all.
if (pindexMostWork == NULL || pindexMostWork == chainActive.Tip())
return true;
if (!ActivateBestChainStep(state, pindexMostWork, pblock && pblock->GetHash() == pindexMostWork->GetBlockHash() ? pblock : NULL, fAlreadyChecked))
return false;
pindexNewTip = chainActive.Tip();
fInitialDownload = IsInitialBlockDownload();
break;
}
// When we reach this point, we switched to a new tip (stored in pindexNewTip).
// Notifications/callbacks that can run without cs_main
if (!fInitialDownload) {
uint256 hashNewTip = pindexNewTip->GetBlockHash();
// Relay inventory, but don't relay old inventory during initial block download.
int nBlockEstimate = Checkpoints::GetTotalBlocksEstimate();
{
LOCK(cs_vNodes);
BOOST_FOREACH (CNode* pnode, vNodes)
if (chainActive.Height() > (pnode->nStartingHeight != -1 ? pnode->nStartingHeight - 2000 : nBlockEstimate))
pnode->PushInventory(CInv(MSG_BLOCK, hashNewTip));
}
// Notify external listeners about the new tip.
uiInterface.NotifyBlockTip(hashNewTip);
}
} while (pindexMostWork != chainActive.Tip());
CheckBlockIndex();
// Write changes periodically to disk, after relay.
if (!FlushStateToDisk(state, FLUSH_STATE_PERIODIC)) {
return false;
}
return true;
}
bool InvalidateBlock(CValidationState& state, CBlockIndex* pindex)
{
AssertLockHeld(cs_main);
// Mark the block itself as invalid.
pindex->nStatus |= BLOCK_FAILED_VALID;
setDirtyBlockIndex.insert(pindex);
setBlockIndexCandidates.erase(pindex);
while (chainActive.Contains(pindex)) {
CBlockIndex* pindexWalk = chainActive.Tip();
pindexWalk->nStatus |= BLOCK_FAILED_CHILD;
setDirtyBlockIndex.insert(pindexWalk);
setBlockIndexCandidates.erase(pindexWalk);
// ActivateBestChain considers blocks already in chainActive
// unconditionally valid already, so force disconnect away from it.
if (!DisconnectTip(state)) {
return false;
}
}
// The resulting new best tip may not be in setBlockIndexCandidates anymore, so
// add them again.
BlockMap::iterator it = mapBlockIndex.begin();
while (it != mapBlockIndex.end()) {
if (it->second->IsValid(BLOCK_VALID_TRANSACTIONS) && it->second->nChainTx && !setBlockIndexCandidates.value_comp()(it->second, chainActive.Tip())) {
setBlockIndexCandidates.insert(it->second);
}
it++;
}
InvalidChainFound(pindex);
return true;
}
bool ReconsiderBlock(CValidationState& state, CBlockIndex* pindex)
{
AssertLockHeld(cs_main);
int nHeight = pindex->nHeight;
// Remove the invalidity flag from this block and all its descendants.
BlockMap::iterator it = mapBlockIndex.begin();
while (it != mapBlockIndex.end()) {
if (!it->second->IsValid() && it->second->GetAncestor(nHeight) == pindex) {
it->second->nStatus &= ~BLOCK_FAILED_MASK;
setDirtyBlockIndex.insert(it->second);
if (it->second->IsValid(BLOCK_VALID_TRANSACTIONS) && it->second->nChainTx && setBlockIndexCandidates.value_comp()(chainActive.Tip(), it->second)) {
setBlockIndexCandidates.insert(it->second);
}
if (it->second == pindexBestInvalid) {
// Reset invalid block marker if it was pointing to one of those.
pindexBestInvalid = NULL;
}
}
it++;
}
// Remove the invalidity flag from all ancestors too.
while (pindex != NULL) {
if (pindex->nStatus & BLOCK_FAILED_MASK) {
pindex->nStatus &= ~BLOCK_FAILED_MASK;
setDirtyBlockIndex.insert(pindex);
}
pindex = pindex->pprev;
}
return true;
}
CBlockIndex* AddToBlockIndex(const CBlock& block)
{
// Check for duplicate
uint256 hash = block.GetHash();
BlockMap::iterator it = mapBlockIndex.find(hash);
if (it != mapBlockIndex.end())
return it->second;
// Construct new block index object
CBlockIndex* pindexNew = new CBlockIndex(block);
assert(pindexNew);
// We assign the sequence id to blocks only when the full data is available,
// to avoid miners withholding blocks but broadcasting headers, to get a
// competitive advantage.
pindexNew->nSequenceId = 0;
BlockMap::iterator mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
//mark as PoS seen
if (pindexNew->IsProofOfStake())
setStakeSeen.insert(make_pair(pindexNew->prevoutStake, pindexNew->nStakeTime));
pindexNew->phashBlock = &((*mi).first);
BlockMap::iterator miPrev = mapBlockIndex.find(block.hashPrevBlock);
if (miPrev != mapBlockIndex.end()) {
pindexNew->pprev = (*miPrev).second;
pindexNew->nHeight = pindexNew->pprev->nHeight + 1;
pindexNew->BuildSkip();
//update previous block pointer
pindexNew->pprev->pnext = pindexNew;
// ppcoin: compute chain trust score
pindexNew->bnChainTrust = (pindexNew->pprev ? pindexNew->pprev->bnChainTrust : 0) + pindexNew->GetBlockTrust();
// ppcoin: compute stake entropy bit for stake modifier
if (!pindexNew->SetStakeEntropyBit(pindexNew->GetStakeEntropyBit()))
LogPrintf("AddToBlockIndex() : SetStakeEntropyBit() failed \n");
// ppcoin: record proof-of-stake hash value
if (pindexNew->IsProofOfStake()) {
if (!mapProofOfStake.count(hash))
LogPrintf("AddToBlockIndex() : hashProofOfStake not found in map \n");
pindexNew->hashProofOfStake = mapProofOfStake[hash];
}
// ppcoin: compute stake modifier
uint64_t nStakeModifier = 0;
bool fGeneratedStakeModifier = false;
if (!ComputeNextStakeModifier(pindexNew->pprev, nStakeModifier, fGeneratedStakeModifier))
LogPrintf("AddToBlockIndex() : ComputeNextStakeModifier() failed \n");
pindexNew->SetStakeModifier(nStakeModifier, fGeneratedStakeModifier);
pindexNew->nStakeModifierChecksum = GetStakeModifierChecksum(pindexNew);
if (!CheckStakeModifierCheckpoints(pindexNew->nHeight, pindexNew->nStakeModifierChecksum))
LogPrintf("AddToBlockIndex() : Rejected by stake modifier checkpoint height=%d, modifier=%s \n", pindexNew->nHeight, boost::lexical_cast<std::string>(nStakeModifier));
}
pindexNew->nChainWork = (pindexNew->pprev ? pindexNew->pprev->nChainWork : 0) + GetBlockProof(*pindexNew);
pindexNew->RaiseValidity(BLOCK_VALID_TREE);
if (pindexBestHeader == NULL || pindexBestHeader->nChainWork < pindexNew->nChainWork)
pindexBestHeader = pindexNew;
//update previous block pointer
if (pindexNew->nHeight)
pindexNew->pprev->pnext = pindexNew;
setDirtyBlockIndex.insert(pindexNew);
return pindexNew;
}
/** Mark a block as having its data received and checked (up to BLOCK_VALID_TRANSACTIONS). */
bool ReceivedBlockTransactions(const CBlock& block, CValidationState& state, CBlockIndex* pindexNew, const CDiskBlockPos& pos)
{
if (block.IsProofOfStake())
pindexNew->SetProofOfStake();
pindexNew->nTx = block.vtx.size();
pindexNew->nChainTx = 0;
pindexNew->nFile = pos.nFile;
pindexNew->nDataPos = pos.nPos;
pindexNew->nUndoPos = 0;
pindexNew->nStatus |= BLOCK_HAVE_DATA;
pindexNew->RaiseValidity(BLOCK_VALID_TRANSACTIONS);
setDirtyBlockIndex.insert(pindexNew);
if (pindexNew->pprev == NULL || pindexNew->pprev->nChainTx) {
// If pindexNew is the genesis block or all parents are BLOCK_VALID_TRANSACTIONS.
deque<CBlockIndex*> queue;
queue.push_back(pindexNew);
// Recursively process any descendant blocks that now may be eligible to be connected.
while (!queue.empty()) {
CBlockIndex* pindex = queue.front();
queue.pop_front();
pindex->nChainTx = (pindex->pprev ? pindex->pprev->nChainTx : 0) + pindex->nTx;
{
LOCK(cs_nBlockSequenceId);
pindex->nSequenceId = nBlockSequenceId++;
}
if (chainActive.Tip() == NULL || !setBlockIndexCandidates.value_comp()(pindex, chainActive.Tip())) {
setBlockIndexCandidates.insert(pindex);
}
std::pair<std::multimap<CBlockIndex*, CBlockIndex*>::iterator, std::multimap<CBlockIndex*, CBlockIndex*>::iterator> range = mapBlocksUnlinked.equal_range(pindex);
while (range.first != range.second) {
std::multimap<CBlockIndex*, CBlockIndex*>::iterator it = range.first;
queue.push_back(it->second);
range.first++;
mapBlocksUnlinked.erase(it);
}
}
} else {
if (pindexNew->pprev && pindexNew->pprev->IsValid(BLOCK_VALID_TREE)) {
mapBlocksUnlinked.insert(std::make_pair(pindexNew->pprev, pindexNew));
}
}
return true;
}
bool FindBlockPos(CValidationState& state, CDiskBlockPos& pos, unsigned int nAddSize, unsigned int nHeight, uint64_t nTime, bool fKnown = false)
{
LOCK(cs_LastBlockFile);
unsigned int nFile = fKnown ? pos.nFile : nLastBlockFile;
if (vinfoBlockFile.size() <= nFile) {
vinfoBlockFile.resize(nFile + 1);
}
if (!fKnown) {
while (vinfoBlockFile[nFile].nSize + nAddSize >= MAX_BLOCKFILE_SIZE) {
LogPrintf("Leaving block file %i: %s\n", nFile, vinfoBlockFile[nFile].ToString());
FlushBlockFile(true);
nFile++;
if (vinfoBlockFile.size() <= nFile) {
vinfoBlockFile.resize(nFile + 1);
}
}
pos.nFile = nFile;
pos.nPos = vinfoBlockFile[nFile].nSize;
}
nLastBlockFile = nFile;
vinfoBlockFile[nFile].AddBlock(nHeight, nTime);
if (fKnown)
vinfoBlockFile[nFile].nSize = std::max(pos.nPos + nAddSize, vinfoBlockFile[nFile].nSize);
else
vinfoBlockFile[nFile].nSize += nAddSize;
if (!fKnown) {
unsigned int nOldChunks = (pos.nPos + BLOCKFILE_CHUNK_SIZE - 1) / BLOCKFILE_CHUNK_SIZE;
unsigned int nNewChunks = (vinfoBlockFile[nFile].nSize + BLOCKFILE_CHUNK_SIZE - 1) / BLOCKFILE_CHUNK_SIZE;
if (nNewChunks > nOldChunks) {
if (CheckDiskSpace(nNewChunks * BLOCKFILE_CHUNK_SIZE - pos.nPos)) {
FILE* file = OpenBlockFile(pos);
if (file) {
LogPrintf("Pre-allocating up to position 0x%x in blk%05u.dat\n", nNewChunks * BLOCKFILE_CHUNK_SIZE, pos.nFile);
AllocateFileRange(file, pos.nPos, nNewChunks * BLOCKFILE_CHUNK_SIZE - pos.nPos);
fclose(file);
}
} else
return state.Error("out of disk space");
}
}
setDirtyFileInfo.insert(nFile);
return true;
}
bool FindUndoPos(CValidationState& state, int nFile, CDiskBlockPos& pos, unsigned int nAddSize)
{
pos.nFile = nFile;
LOCK(cs_LastBlockFile);
unsigned int nNewSize;
pos.nPos = vinfoBlockFile[nFile].nUndoSize;
nNewSize = vinfoBlockFile[nFile].nUndoSize += nAddSize;
setDirtyFileInfo.insert(nFile);
unsigned int nOldChunks = (pos.nPos + UNDOFILE_CHUNK_SIZE - 1) / UNDOFILE_CHUNK_SIZE;
unsigned int nNewChunks = (nNewSize + UNDOFILE_CHUNK_SIZE - 1) / UNDOFILE_CHUNK_SIZE;
if (nNewChunks > nOldChunks) {
if (CheckDiskSpace(nNewChunks * UNDOFILE_CHUNK_SIZE - pos.nPos)) {
FILE* file = OpenUndoFile(pos);
if (file) {
LogPrintf("Pre-allocating up to position 0x%x in rev%05u.dat\n", nNewChunks * UNDOFILE_CHUNK_SIZE, pos.nFile);
AllocateFileRange(file, pos.nPos, nNewChunks * UNDOFILE_CHUNK_SIZE - pos.nPos);
fclose(file);
}
} else
return state.Error("out of disk space");
}
return true;
}
bool CheckBlockHeader(const CBlockHeader& block, CValidationState& state, bool fCheckPOW)
{
// Check proof of work matches claimed amount
if (fCheckPOW && !CheckProofOfWork(block.GetHash(), block.nBits))
return state.DoS(50, error("CheckBlockHeader() : proof of work failed"),
REJECT_INVALID, "high-hash");
return true;
}
bool CheckBlock(const CBlock& block, CValidationState& state, bool fCheckPOW, bool fCheckMerkleRoot, bool fCheckSig)
{
// These are checks that are independent of context.
// Check that the header is valid (particularly PoW). This is mostly
// redundant with the call in AcceptBlockHeader.
if (!CheckBlockHeader(block, state, fCheckPOW))
return state.DoS(100, error("CheckBlock() : CheckBlockHeader failed"),
REJECT_INVALID, "bad-header", true);
// Check timestamp
LogPrint("debug", "%s: block=%s is proof of stake=%d\n", __func__, block.GetHash().ToString().c_str(), block.IsProofOfStake());
if (block.GetBlockTime() > GetAdjustedTime() + (block.IsProofOfStake() ? 180 : 7200)) // 3 minute future drift for PoS
return state.Invalid(error("CheckBlock() : block timestamp too far in the future"),
REJECT_INVALID, "time-too-new");
// Check the merkle root.
if (fCheckMerkleRoot) {
bool mutated;
uint256 hashMerkleRoot2 = block.BuildMerkleTree(&mutated);
if (block.hashMerkleRoot != hashMerkleRoot2)
return state.DoS(100, error("CheckBlock() : hashMerkleRoot mismatch"),
REJECT_INVALID, "bad-txnmrklroot", true);
// Check for merkle tree malleability (CVE-2012-2459): repeating sequences
// of transactions in a block without affecting the merkle root of a block,
// while still invalidating it.
if (mutated)
return state.DoS(100, error("CheckBlock() : duplicate transaction"),
REJECT_INVALID, "bad-txns-duplicate", true);
}
// All potential-corruption validation must be done before we do any
// transaction validation, as otherwise we may mark the header as invalid
// because we receive the wrong transactions for it.
// Size limits
unsigned int nMaxBlockSize = MAX_BLOCK_SIZE_CURRENT;
if (block.vtx.empty() || block.vtx.size() > nMaxBlockSize || ::GetSerializeSize(block, SER_NETWORK, PROTOCOL_VERSION) > nMaxBlockSize)
return state.DoS(100, error("CheckBlock() : size limits failed"),
REJECT_INVALID, "bad-blk-length");
// First transaction must be coinbase, the rest must not be
if (block.vtx.empty() || !block.vtx[0].IsCoinBase())
return state.DoS(100, error("CheckBlock() : first tx is not coinbase"),
REJECT_INVALID, "bad-cb-missing");
for (unsigned int i = 1; i < block.vtx.size(); i++)
if (block.vtx[i].IsCoinBase())
return state.DoS(100, error("CheckBlock() : more than one coinbase"),
REJECT_INVALID, "bad-cb-multiple");
if (block.IsProofOfStake()) {
// Coinbase output should be empty if proof-of-stake block
if (block.vtx[0].vout.size() != 1 || !block.vtx[0].vout[0].IsEmpty())
return state.DoS(100, error("CheckBlock() : coinbase output not empty for proof-of-stake block"));
// Second transaction must be coinstake, the rest must not be
if (block.vtx.empty() || !block.vtx[1].IsCoinStake())
return state.DoS(100, error("CheckBlock() : second tx is not coinstake"));
for (unsigned int i = 2; i < block.vtx.size(); i++)
if (block.vtx[i].IsCoinStake())
return state.DoS(100, error("CheckBlock() : more than one coinstake"));
}
// ----------- swiftTX transaction scanning -----------
if (IsSporkActive(SPORK_3_SWIFTTX_BLOCK_FILTERING)) {
BOOST_FOREACH (const CTransaction& tx, block.vtx) {
if (!tx.IsCoinBase()) {
//only reject blocks when it's based on complete consensus
BOOST_FOREACH (const CTxIn& in, tx.vin) {
if (mapLockedInputs.count(in.prevout)) {
if (mapLockedInputs[in.prevout] != tx.GetHash()) {
mapRejectedBlocks.insert(make_pair(block.GetHash(), GetTime()));
LogPrintf("CheckBlock() : found conflicting transaction with transaction lock %s %s\n", mapLockedInputs[in.prevout].ToString(), tx.GetHash().ToString());
return state.DoS(0, error("CheckBlock() : found conflicting transaction with transaction lock"),
REJECT_INVALID, "conflicting-tx-ix");
}
}
}
}
}
} else {
LogPrintf("CheckBlock() : skipping transaction locking checks\n");
}
// masternode payments / budgets and zerocoin check
CBlockIndex* pindexPrev = chainActive.Tip();
int nHeight = 0;
if (pindexPrev != NULL) {
if (pindexPrev->GetBlockHash() == block.hashPrevBlock) {
nHeight = pindexPrev->nHeight + 1;
} else { //out of order
BlockMap::iterator mi = mapBlockIndex.find(block.hashPrevBlock);
if (mi != mapBlockIndex.end() && (*mi).second)
nHeight = (*mi).second->nHeight + 1;
}
// Version 4 header must be used after Params().Zerocoin_StartHeight(). And never before.
if (nHeight > Params().Zerocoin_StartHeight()) {
if(block.nVersion < Params().Zerocoin_HeaderVersion())
return state.DoS(50, error("CheckBlockHeader() : block version must be above 4 after ZerocoinStartHeight"),
REJECT_INVALID, "block-version");
}
// IoTHome
// It is entierly possible that we don't have enough data and this could fail
// (i.e. the block could indeed be valid). Store the block for later consideration
// but issue an initial reject message.
// The case also exists that the sending peer could not have enough data to see
// that this block is invalid, so don't issue an outright ban.
if (nHeight != 0 && !IsInitialBlockDownload()) {
if (!IsBlockPayeeValid(block, nHeight)) {
mapRejectedBlocks.insert(make_pair(block.GetHash(), GetTime()));
return state.DoS(0, error("CheckBlock() : Couldn't find masternode/budget payment"),
REJECT_INVALID, "bad-cb-payee");
}
} else {
if (fDebug)
LogPrintf("CheckBlock(): Masternode payment check skipped on sync - skipping IsBlockPayeeValid()\n");
}
}
// Check transactions
bool fZerocoinActive = true;
vector<CBigNum> vBlockSerials;
for (const CTransaction& tx : block.vtx) {
if (!CheckTransaction(tx, fZerocoinActive, chainActive.Height() + 1 >= Params().Zerocoin_StartHeight(), state))
return error("CheckBlock() : CheckTransaction failed");
// double check that there are no double spent zIoTHome spends in this block
if (tx.IsZerocoinSpend()) {
for (const CTxIn txIn : tx.vin) {
if (txIn.scriptSig.IsZerocoinSpend()) {
libzerocoin::CoinSpend spend = TxInToZerocoinSpend(txIn);
if (count(vBlockSerials.begin(), vBlockSerials.end(), spend.getCoinSerialNumber()))
return state.DoS(100, error("%s : Double spending of zIoTHome serial %s in block\n Block: %s",
__func__, spend.getCoinSerialNumber().GetHex(), block.ToString()));
vBlockSerials.emplace_back(spend.getCoinSerialNumber());
}
}
}
}
unsigned int nSigOps = 0;
BOOST_FOREACH (const CTransaction& tx, block.vtx) {
nSigOps += GetLegacySigOpCount(tx);
}
unsigned int nMaxBlockSigOps = fZerocoinActive ? MAX_BLOCK_SIGOPS_CURRENT : MAX_BLOCK_SIGOPS_LEGACY;
if (nSigOps > nMaxBlockSigOps)
return state.DoS(100, error("CheckBlock() : out-of-bounds SigOpCount"),
REJECT_INVALID, "bad-blk-sigops", true);
return true;
}
bool CheckWork(const CBlock block, CBlockIndex* const pindexPrev)
{
if (pindexPrev == NULL)
return error("%s : null pindexPrev for block %s", __func__, block.GetHash().ToString().c_str());
unsigned int nBitsRequired = GetNextWorkRequired(pindexPrev, &block);
if (block.IsProofOfWork() && (pindexPrev->nHeight + 1 <= 68589)) {
double n1 = ConvertBitsToDouble(block.nBits);
double n2 = ConvertBitsToDouble(nBitsRequired);
if (abs(n1 - n2) > n1 * 0.5)
return error("%s : incorrect proof of work (DGW pre-fork) - %f %f %f at %d", __func__, abs(n1 - n2), n1, n2, pindexPrev->nHeight + 1);
return true;
}
if (block.nBits != nBitsRequired)
return error("%s : incorrect proof of work at %d", __func__, pindexPrev->nHeight + 1);
if (block.IsProofOfStake()) {
uint256 hashProofOfStake;
uint256 hash = block.GetHash();
if(!CheckProofOfStake(block, hashProofOfStake)) {
LogPrintf("WARNING: ProcessBlock(): check proof-of-stake failed for block %s\n", hash.ToString().c_str());
// // peershares adapted: ask for missing blocks
// if (chainActive.Height <= )
// pnode->PushGetBlocks(pindexPrev,hash);
return false;
}
if(!mapProofOfStake.count(hash)) // add to mapProofOfStake
mapProofOfStake.insert(make_pair(hash, hashProofOfStake));
}
return true;
}
bool ContextualCheckBlockHeader(const CBlockHeader& block, CValidationState& state, CBlockIndex* const pindexPrev)
{
uint256 hash = block.GetHash();
if (hash == Params().HashGenesisBlock())
return true;
assert(pindexPrev);
int nHeight = pindexPrev->nHeight + 1;
//If this is a reorg, check that it is not too deep
int nMaxReorgDepth = GetArg("-maxreorg", Params().MaxReorganizationDepth());
if (chainActive.Height() - nHeight >= nMaxReorgDepth)
return state.DoS(1, error("%s: forked chain older than max reorganization depth (height %d)", __func__, nHeight));
// Check timestamp against prev
if (block.GetBlockTime() <= pindexPrev->GetMedianTimePast()) {
LogPrintf("Block time = %d , GetMedianTimePast = %d \n", block.GetBlockTime(), pindexPrev->GetMedianTimePast());
return state.Invalid(error("%s : block's timestamp is too early", __func__),
REJECT_INVALID, "time-too-old");
}
// Check that the block chain matches the known block chain up to a checkpoint
if (!Checkpoints::CheckBlock(nHeight, hash))
return state.DoS(100, error("%s : rejected by checkpoint lock-in at %d", __func__, nHeight),
REJECT_CHECKPOINT, "checkpoint mismatch");
// Don't accept any forks from the main chain prior to last checkpoint
CBlockIndex* pcheckpoint = Checkpoints::GetLastCheckpoint();
if (pcheckpoint && nHeight < pcheckpoint->nHeight)
return state.DoS(0, error("%s : forked chain older than last checkpoint (height %d)", __func__, nHeight));
return true;
}
bool IsBlockHashInChain(const uint256& hashBlock)
{
if (hashBlock == 0 || !mapBlockIndex.count(hashBlock))
return false;
return chainActive.Contains(mapBlockIndex[hashBlock]);
}
bool IsTransactionInChain(uint256 txId, int& nHeightTx)
{
uint256 hashBlock;
CTransaction tx;
GetTransaction(txId, tx, hashBlock, true);
if (!IsBlockHashInChain(hashBlock))
return false;
nHeightTx = mapBlockIndex.at(hashBlock)->nHeight;
return true;
}
bool ContextualCheckBlock(const CBlock& block, CValidationState& state, CBlockIndex* const pindexPrev)
{
const int nHeight = pindexPrev == NULL ? 0 : pindexPrev->nHeight + 1;
// Check that all transactions are finalized
BOOST_FOREACH (const CTransaction& tx, block.vtx)
if (!IsFinalTx(tx, nHeight, block.GetBlockTime())) {
return state.DoS(10, error("%s : contains a non-final transaction", __func__), REJECT_INVALID, "bad-txns-nonfinal");
}
return true;
}
bool AcceptBlockHeader(const CBlock& block, CValidationState& state, CBlockIndex** ppindex)
{
AssertLockHeld(cs_main);
// Check for duplicate
uint256 hash = block.GetHash();
BlockMap::iterator miSelf = mapBlockIndex.find(hash);
CBlockIndex* pindex = NULL;
// TODO : ENABLE BLOCK CACHE IN SPECIFIC CASES
if (miSelf != mapBlockIndex.end()) {
// Block header is already known.
pindex = miSelf->second;
if (ppindex)
*ppindex = pindex;
if (pindex->nStatus & BLOCK_FAILED_MASK)
return state.Invalid(error("%s : block is marked invalid", __func__), 0, "duplicate");
return true;
}
if (!CheckBlockHeader(block, state, false)) {
LogPrintf("AcceptBlockHeader(): CheckBlockHeader failed \n");
return false;
}
// Get prev block index
CBlockIndex* pindexPrev = NULL;
if (hash != Params().HashGenesisBlock()) {
BlockMap::iterator mi = mapBlockIndex.find(block.hashPrevBlock);
if (mi == mapBlockIndex.end())
return state.DoS(0, error("%s : prev block %s not found", __func__, block.hashPrevBlock.ToString().c_str()), 0, "bad-prevblk");
pindexPrev = (*mi).second;
if (pindexPrev->nStatus & BLOCK_FAILED_MASK)
return state.DoS(100, error("%s : prev block %s is invalid, unable to add block %s", __func__, block.hashPrevBlock.GetHex(), block.GetHash().GetHex()),
REJECT_INVALID, "bad-prevblk");
}
if (!ContextualCheckBlockHeader(block, state, pindexPrev))
return false;
if (pindex == NULL)
pindex = AddToBlockIndex(block);
if (ppindex)
*ppindex = pindex;
return true;
}
bool AcceptBlock(CBlock& block, CValidationState& state, CBlockIndex** ppindex, CDiskBlockPos* dbp, bool fAlreadyCheckedBlock)
{
AssertLockHeld(cs_main);
CBlockIndex*& pindex = *ppindex;
// Get prev block index
CBlockIndex* pindexPrev = NULL;
if (block.GetHash() != Params().HashGenesisBlock()) {
BlockMap::iterator mi = mapBlockIndex.find(block.hashPrevBlock);
if (mi == mapBlockIndex.end())
return state.DoS(0, error("%s : prev block %s not found", __func__, block.hashPrevBlock.ToString().c_str()), 0, "bad-prevblk");
pindexPrev = (*mi).second;
if (pindexPrev->nStatus & BLOCK_FAILED_MASK)
return state.DoS(100, error("%s : prev block %s is invalid, unable to add block %s", __func__, block.hashPrevBlock.GetHex(), block.GetHash().GetHex()),
REJECT_INVALID, "bad-prevblk");
}
if (block.GetHash() != Params().HashGenesisBlock() && !CheckWork(block, pindexPrev))
return false;
if (!AcceptBlockHeader(block, state, &pindex))
return false;
if (pindex->nStatus & BLOCK_HAVE_DATA) {
// TODO: deal better with duplicate blocks.
// return state.DoS(20, error("AcceptBlock() : already have block %d %s", pindex->nHeight, pindex->GetBlockHash().ToString()), REJECT_DUPLICATE, "duplicate");
return true;
}
if ((!fAlreadyCheckedBlock && !CheckBlock(block, state)) || !ContextualCheckBlock(block, state, pindex->pprev)) {
if (state.IsInvalid() && !state.CorruptionPossible()) {
pindex->nStatus |= BLOCK_FAILED_VALID;
setDirtyBlockIndex.insert(pindex);
}
return false;
}
int nHeight = pindex->nHeight;
// Write block to history file
try {
unsigned int nBlockSize = ::GetSerializeSize(block, SER_DISK, CLIENT_VERSION);
CDiskBlockPos blockPos;
if (dbp != NULL)
blockPos = *dbp;
if (!FindBlockPos(state, blockPos, nBlockSize + 8, nHeight, block.GetBlockTime(), dbp != NULL))
return error("AcceptBlock() : FindBlockPos failed");
if (dbp == NULL)
if (!WriteBlockToDisk(block, blockPos))
return state.Abort("Failed to write block");
if (!ReceivedBlockTransactions(block, state, pindex, blockPos))
return error("AcceptBlock() : ReceivedBlockTransactions failed");
} catch (std::runtime_error& e) {
return state.Abort(std::string("System error: ") + e.what());
}
return true;
}
bool CBlockIndex::IsSuperMajority(int minVersion, const CBlockIndex* pstart, unsigned int nRequired)
{
unsigned int nToCheck = Params().ToCheckBlockUpgradeMajority();
unsigned int nFound = 0;
for (unsigned int i = 0; i < nToCheck && nFound < nRequired && pstart != NULL; i++) {
if (pstart->nVersion >= minVersion)
++nFound;
pstart = pstart->pprev;
}
return (nFound >= nRequired);
}
/** Turn the lowest '1' bit in the binary representation of a number into a '0'. */
int static inline InvertLowestOne(int n) { return n & (n - 1); }
/** Compute what height to jump back to with the CBlockIndex::pskip pointer. */
int static inline GetSkipHeight(int height)
{
if (height < 2)
return 0;
// Determine which height to jump back to. Any number strictly lower than height is acceptable,
// but the following expression seems to perform well in simulations (max 110 steps to go back
// up to 2**18 blocks).
return (height & 1) ? InvertLowestOne(InvertLowestOne(height - 1)) + 1 : InvertLowestOne(height);
}
CBlockIndex* CBlockIndex::GetAncestor(int height)
{
if (height > nHeight || height < 0)
return NULL;
CBlockIndex* pindexWalk = this;
int heightWalk = nHeight;
while (heightWalk > height) {
int heightSkip = GetSkipHeight(heightWalk);
int heightSkipPrev = GetSkipHeight(heightWalk - 1);
if (heightSkip == height ||
(heightSkip > height && !(heightSkipPrev < heightSkip - 2 && heightSkipPrev >= height))) {
// Only follow pskip if pprev->pskip isn't better than pskip->pprev.
pindexWalk = pindexWalk->pskip;
heightWalk = heightSkip;
} else {
pindexWalk = pindexWalk->pprev;
heightWalk--;
}
}
return pindexWalk;
}
const CBlockIndex* CBlockIndex::GetAncestor(int height) const
{
return const_cast<CBlockIndex*>(this)->GetAncestor(height);
}
void CBlockIndex::BuildSkip()
{
if (pprev)
pskip = pprev->GetAncestor(GetSkipHeight(nHeight));
}
bool ProcessNewBlock(CValidationState& state, CNode* pfrom, CBlock* pblock, CDiskBlockPos* dbp)
{
// Preliminary checks
int64_t nStartTime = GetTimeMillis();
bool checked = CheckBlock(*pblock, state);
int nMints = 0;
int nSpends = 0;
for (const CTransaction tx : pblock->vtx) {
if (tx.ContainsZerocoins()) {
for (const CTxIn in : tx.vin) {
if (in.scriptSig.IsZerocoinSpend())
nSpends++;
}
for (const CTxOut out : tx.vout) {
if (out.IsZerocoinMint())
nMints++;
}
}
}
if (nMints || nSpends)
LogPrintf("%s : block contains %d zIoTHome mints and %d zIoTHome spends\n", __func__, nMints, nSpends);
// ppcoin: check proof-of-stake
// Limited duplicity on stake: prevents block flood attack
// Duplicate stake allowed only when there is orphan child block
//if (pblock->IsProofOfStake() && setStakeSeen.count(pblock->GetProofOfStake())/* && !mapOrphanBlocksByPrev.count(hash)*/)
// return error("ProcessNewBlock() : duplicate proof-of-stake (%s, %d) for block %s", pblock->GetProofOfStake().first.ToString().c_str(), pblock->GetProofOfStake().second, pblock->GetHash().ToString().c_str());
// NovaCoin: check proof-of-stake block signature
if (!pblock->CheckBlockSignature())
return error("ProcessNewBlock() : bad proof-of-stake block signature");
if (pblock->GetHash() != Params().HashGenesisBlock() && pfrom != NULL) {
//if we get this far, check if the prev block is our prev block, if not then request sync and return false
BlockMap::iterator mi = mapBlockIndex.find(pblock->hashPrevBlock);
if (mi == mapBlockIndex.end()) {
pfrom->PushMessage("getblocks", chainActive.GetLocator(), uint256(0));
return false;
}
}
{
LOCK(cs_main); // Replaces the former TRY_LOCK loop because busy waiting wastes too much resources
MarkBlockAsReceived (pblock->GetHash ());
if (!checked) {
return error ("%s : CheckBlock FAILED for block %s", __func__, pblock->GetHash().GetHex());
}
// Store to disk
CBlockIndex* pindex = NULL;
bool ret = AcceptBlock (*pblock, state, &pindex, dbp, checked);
if (pindex && pfrom) {
mapBlockSource[pindex->GetBlockHash ()] = pfrom->GetId ();
}
CheckBlockIndex ();
if (!ret)
return error ("%s : AcceptBlock FAILED", __func__);
}
if (!ActivateBestChain(state, pblock, checked))
return error("%s : ActivateBestChain failed", __func__);
if (!fLiteMode) {
if (masternodeSync.RequestedMasternodeAssets > MASTERNODE_SYNC_LIST) {
obfuScationPool.NewBlock();
masternodePayments.ProcessBlock(GetHeight() + 10);
budget.NewBlock();
}
}
if (pwalletMain) {
// If turned on MultiSend will send a transaction (or more) on the after maturity of a stake
if (pwalletMain->isMultiSendEnabled())
pwalletMain->MultiSend();
// If turned on Auto Combine will scan wallet for dust to combine
if (pwalletMain->fCombineDust)
pwalletMain->AutoCombineDust();
}
LogPrintf("%s : ACCEPTED in %ld milliseconds with size=%d\n", __func__, GetTimeMillis() - nStartTime,
pblock->GetSerializeSize(SER_DISK, CLIENT_VERSION));
return true;
}
bool TestBlockValidity(CValidationState& state, const CBlock& block, CBlockIndex* const pindexPrev, bool fCheckPOW, bool fCheckMerkleRoot)
{
AssertLockHeld(cs_main);
assert(pindexPrev == chainActive.Tip());
CCoinsViewCache viewNew(pcoinsTip);
CBlockIndex indexDummy(block);
indexDummy.pprev = pindexPrev;
indexDummy.nHeight = pindexPrev->nHeight + 1;
// NOTE: CheckBlockHeader is called by CheckBlock
if (!ContextualCheckBlockHeader(block, state, pindexPrev))
return false;
if (!CheckBlock(block, state, fCheckPOW, fCheckMerkleRoot))
return false;
if (!ContextualCheckBlock(block, state, pindexPrev))
return false;
if (!ConnectBlock(block, state, &indexDummy, viewNew, true))
return false;
assert(state.IsValid());
return true;
}
bool AbortNode(const std::string& strMessage, const std::string& userMessage)
{
strMiscWarning = strMessage;
LogPrintf("*** %s\n", strMessage);
uiInterface.ThreadSafeMessageBox(
userMessage.empty() ? _("Error: A fatal internal error occured, see debug.log for details") : userMessage,
"", CClientUIInterface::MSG_ERROR);
StartShutdown();
return false;
}
bool CheckDiskSpace(uint64_t nAdditionalBytes)
{
uint64_t nFreeBytesAvailable = filesystem::space(GetDataDir()).available;
// Check for nMinDiskSpace bytes (currently 50MB)
if (nFreeBytesAvailable < nMinDiskSpace + nAdditionalBytes)
return AbortNode("Disk space is low!", _("Error: Disk space is low!"));
return true;
}
FILE* OpenDiskFile(const CDiskBlockPos& pos, const char* prefix, bool fReadOnly)
{
if (pos.IsNull())
return NULL;
boost::filesystem::path path = GetBlockPosFilename(pos, prefix);
boost::filesystem::create_directories(path.parent_path());
FILE* file = fopen(path.string().c_str(), "rb+");
if (!file && !fReadOnly)
file = fopen(path.string().c_str(), "wb+");
if (!file) {
LogPrintf("Unable to open file %s\n", path.string());
return NULL;
}
if (pos.nPos) {
if (fseek(file, pos.nPos, SEEK_SET)) {
LogPrintf("Unable to seek to position %u of %s\n", pos.nPos, path.string());
fclose(file);
return NULL;
}
}
return file;
}
FILE* OpenBlockFile(const CDiskBlockPos& pos, bool fReadOnly)
{
return OpenDiskFile(pos, "blk", fReadOnly);
}
FILE* OpenUndoFile(const CDiskBlockPos& pos, bool fReadOnly)
{
return OpenDiskFile(pos, "rev", fReadOnly);
}
boost::filesystem::path GetBlockPosFilename(const CDiskBlockPos& pos, const char* prefix)
{
return GetDataDir() / "blocks" / strprintf("%s%05u.dat", prefix, pos.nFile);
}
CBlockIndex* InsertBlockIndex(uint256 hash)
{
if (hash == 0)
return NULL;
// Return existing
BlockMap::iterator mi = mapBlockIndex.find(hash);
if (mi != mapBlockIndex.end())
return (*mi).second;
// Create new
CBlockIndex* pindexNew = new CBlockIndex();
if (!pindexNew)
throw runtime_error("LoadBlockIndex() : new CBlockIndex failed");
mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
//mark as PoS seen
if (pindexNew->IsProofOfStake())
setStakeSeen.insert(make_pair(pindexNew->prevoutStake, pindexNew->nStakeTime));
pindexNew->phashBlock = &((*mi).first);
return pindexNew;
}
bool static LoadBlockIndexDB()
{
if (!pblocktree->LoadBlockIndexGuts())
return false;
boost::this_thread::interruption_point();
// Calculate nChainWork
vector<pair<int, CBlockIndex*> > vSortedByHeight;
vSortedByHeight.reserve(mapBlockIndex.size());
BOOST_FOREACH (const PAIRTYPE(uint256, CBlockIndex*) & item, mapBlockIndex) {
CBlockIndex* pindex = item.second;
vSortedByHeight.push_back(make_pair(pindex->nHeight, pindex));
}
sort(vSortedByHeight.begin(), vSortedByHeight.end());
BOOST_FOREACH (const PAIRTYPE(int, CBlockIndex*) & item, vSortedByHeight) {
CBlockIndex* pindex = item.second;
pindex->nChainWork = (pindex->pprev ? pindex->pprev->nChainWork : 0) + GetBlockProof(*pindex);
if (pindex->nStatus & BLOCK_HAVE_DATA) {
if (pindex->pprev) {
if (pindex->pprev->nChainTx) {
pindex->nChainTx = pindex->pprev->nChainTx + pindex->nTx;
} else {
pindex->nChainTx = 0;
mapBlocksUnlinked.insert(std::make_pair(pindex->pprev, pindex));
}
} else {
pindex->nChainTx = pindex->nTx;
}
}
if (pindex->IsValid(BLOCK_VALID_TRANSACTIONS) && (pindex->nChainTx || pindex->pprev == NULL))
setBlockIndexCandidates.insert(pindex);
if (pindex->nStatus & BLOCK_FAILED_MASK && (!pindexBestInvalid || pindex->nChainWork > pindexBestInvalid->nChainWork))
pindexBestInvalid = pindex;
if (pindex->pprev)
pindex->BuildSkip();
if (pindex->IsValid(BLOCK_VALID_TREE) && (pindexBestHeader == NULL || CBlockIndexWorkComparator()(pindexBestHeader, pindex)))
pindexBestHeader = pindex;
}
// Load block file info
pblocktree->ReadLastBlockFile(nLastBlockFile);
vinfoBlockFile.resize(nLastBlockFile + 1);
LogPrintf("%s: last block file = %i\n", __func__, nLastBlockFile);
for (int nFile = 0; nFile <= nLastBlockFile; nFile++) {
pblocktree->ReadBlockFileInfo(nFile, vinfoBlockFile[nFile]);
}
LogPrintf("%s: last block file info: %s\n", __func__, vinfoBlockFile[nLastBlockFile].ToString());
for (int nFile = nLastBlockFile + 1; true; nFile++) {
CBlockFileInfo info;
if (pblocktree->ReadBlockFileInfo(nFile, info)) {
vinfoBlockFile.push_back(info);
} else {
break;
}
}
// Check presence of blk files
LogPrintf("Checking all blk files are present...\n");
set<int> setBlkDataFiles;
BOOST_FOREACH (const PAIRTYPE(uint256, CBlockIndex*) & item, mapBlockIndex) {
CBlockIndex* pindex = item.second;
if (pindex->nStatus & BLOCK_HAVE_DATA) {
setBlkDataFiles.insert(pindex->nFile);
}
}
for (std::set<int>::iterator it = setBlkDataFiles.begin(); it != setBlkDataFiles.end(); it++) {
CDiskBlockPos pos(*it, 0);
if (CAutoFile(OpenBlockFile(pos, true), SER_DISK, CLIENT_VERSION).IsNull()) {
return false;
}
}
//Check if the shutdown procedure was followed on last client exit
bool fLastShutdownWasPrepared = true;
pblocktree->ReadFlag("shutdown", fLastShutdownWasPrepared);
LogPrintf("%s: Last shutdown was prepared: %s\n", __func__, fLastShutdownWasPrepared);
//Check for inconsistency with block file info and internal state
if (!fLastShutdownWasPrepared && !GetBoolArg("-forcestart", false) && !GetBoolArg("-reindex", false) && (vSortedByHeight.size() != vinfoBlockFile[nLastBlockFile].nHeightLast + 1) && (vinfoBlockFile[nLastBlockFile].nHeightLast != 0)) {
//The database is in a state where a block has been accepted and written to disk, but not
//all of the block has perculated through the code. The block and the index should both be
//intact (although assertions are added if they are not), and the block will be reprocessed
//to ensure all data will be accounted for.
LogPrintf("%s: Inconsistent State Detected mapBlockIndex.size()=%d blockFileBlocks=%d\n", __func__, vSortedByHeight.size(), vinfoBlockFile[nLastBlockFile].nHeightLast + 1);
LogPrintf("%s: lastIndexPos=%d blockFileSize=%d\n", __func__, vSortedByHeight[vSortedByHeight.size() - 1].second->GetBlockPos().nPos,
vinfoBlockFile[nLastBlockFile].nSize);
//try reading the block from the last index we have
bool isFixed = true;
string strError = "";
LogPrintf("%s: Attempting to re-add last block that was recorded to disk\n", __func__);
//get the last block that was properly recorded to the block info file
CBlockIndex* pindexLastMeta = vSortedByHeight[vinfoBlockFile[nLastBlockFile].nHeightLast + 1].second;
//fix Assertion `hashPrevBlock == view.GetBestBlock()' failed. By adjusting height to the last recorded by coinsview
CBlockIndex* pindexCoinsView = mapBlockIndex[pcoinsTip->GetBestBlock()];
for(unsigned int i = vinfoBlockFile[nLastBlockFile].nHeightLast + 1; i < vSortedByHeight.size(); i++)
{
pindexLastMeta = vSortedByHeight[i].second;
if(pindexLastMeta->nHeight > pindexCoinsView->nHeight)
break;
}
LogPrintf("%s: Last block properly recorded: #%d %s\n", __func__, pindexLastMeta->nHeight, pindexLastMeta->GetBlockHash().ToString().c_str());
CBlock lastMetaBlock;
if (!ReadBlockFromDisk(lastMetaBlock, pindexLastMeta)) {
isFixed = false;
strError = strprintf("failed to read block %d from disk", pindexLastMeta->nHeight);
}
//set the chain to the block before lastMeta so that the meta block will be seen as new
chainActive.SetTip(pindexLastMeta->pprev);
//Process the lastMetaBlock again, using the known location on disk
CDiskBlockPos blockPos = pindexLastMeta->GetBlockPos();
CValidationState state;
ProcessNewBlock(state, NULL, &lastMetaBlock, &blockPos);
//ensure that everything is as it should be
if (pcoinsTip->GetBestBlock() != vSortedByHeight[vSortedByHeight.size() - 1].second->GetBlockHash()) {
isFixed = false;
strError = "pcoinsTip best block is not correct";
}
//properly account for all of the blocks that were not in the meta data. If this is not done the file
//positioning will be wrong and blocks will be overwritten and later cause serialization errors
CBlockIndex *pindexLast = vSortedByHeight[vSortedByHeight.size() - 1].second;
CBlock lastBlock;
if (!ReadBlockFromDisk(lastBlock, pindexLast)) {
isFixed = false;
strError = strprintf("failed to read block %d from disk", pindexLast->nHeight);
}
vinfoBlockFile[nLastBlockFile].nHeightLast = pindexLast->nHeight;
vinfoBlockFile[nLastBlockFile].nSize = pindexLast->GetBlockPos().nPos + ::GetSerializeSize(lastBlock, SER_DISK, CLIENT_VERSION);;
setDirtyFileInfo.insert(nLastBlockFile);
FlushStateToDisk(state, FLUSH_STATE_ALWAYS);
//Print out file info again
pblocktree->ReadLastBlockFile(nLastBlockFile);
vinfoBlockFile.resize(nLastBlockFile + 1);
LogPrintf("%s: last block file = %i\n", __func__, nLastBlockFile);
for (int nFile = 0; nFile <= nLastBlockFile; nFile++) {
pblocktree->ReadBlockFileInfo(nFile, vinfoBlockFile[nFile]);
}
LogPrintf("%s: last block file info: %s\n", __func__, vinfoBlockFile[nLastBlockFile].ToString());
if (!isFixed) {
strError = "Failed reading from database. " + strError + ". The block database is in an inconsistent state and may cause issues in the future."
"To force start use -forcestart";
uiInterface.ThreadSafeMessageBox(strError, "", CClientUIInterface::MSG_ERROR);
abort();
}
LogPrintf("Passed corruption fix\n");
}
// Check whether we need to continue reindexing
bool fReindexing = false;
pblocktree->ReadReindexing(fReindexing);
fReindex |= fReindexing;
// Check whether we have a transaction index
pblocktree->ReadFlag("txindex", fTxIndex);
LogPrintf("LoadBlockIndexDB(): transaction index %s\n", fTxIndex ? "enabled" : "disabled");
// If this is written true before the next client init, then we know the shutdown process failed
pblocktree->WriteFlag("shutdown", false);
// Load pointer to end of best chain
BlockMap::iterator it = mapBlockIndex.find(pcoinsTip->GetBestBlock());
if (it == mapBlockIndex.end())
return true;
chainActive.SetTip(it->second);
PruneBlockIndexCandidates();
LogPrintf("LoadBlockIndexDB(): hashBestChain=%s height=%d date=%s progress=%f\n",
chainActive.Tip()->GetBlockHash().ToString(), chainActive.Height(),
DateTimeStrFormat("%Y-%m-%d %H:%M:%S", chainActive.Tip()->GetBlockTime()),
Checkpoints::GuessVerificationProgress(chainActive.Tip()));
return true;
}
CVerifyDB::CVerifyDB()
{
uiInterface.ShowProgress(_("Verifying blocks..."), 0);
}
CVerifyDB::~CVerifyDB()
{
uiInterface.ShowProgress("", 100);
}
bool CVerifyDB::VerifyDB(CCoinsView* coinsview, int nCheckLevel, int nCheckDepth)
{
LOCK(cs_main);
if (chainActive.Tip() == NULL || chainActive.Tip()->pprev == NULL)
return true;
// Verify blocks in the best chain
if (nCheckDepth <= 0)
nCheckDepth = 1000000000; // suffices until the year 19000
if (nCheckDepth > chainActive.Height())
nCheckDepth = chainActive.Height();
nCheckLevel = std::max(0, std::min(4, nCheckLevel));
LogPrintf("Verifying last %i blocks at level %i\n", nCheckDepth, nCheckLevel);
CCoinsViewCache coins(coinsview);
CBlockIndex* pindexState = chainActive.Tip();
CBlockIndex* pindexFailure = NULL;
int nGoodTransactions = 0;
CValidationState state;
for (CBlockIndex* pindex = chainActive.Tip(); pindex && pindex->pprev; pindex = pindex->pprev) {
boost::this_thread::interruption_point();
uiInterface.ShowProgress(_("Verifying blocks..."), std::max(1, std::min(99, (int)(((double)(chainActive.Height() - pindex->nHeight)) / (double)nCheckDepth * (nCheckLevel >= 4 ? 50 : 100)))));
if (pindex->nHeight < chainActive.Height() - nCheckDepth)
break;
CBlock block;
// check level 0: read from disk
if (!ReadBlockFromDisk(block, pindex))
return error("VerifyDB() : *** ReadBlockFromDisk failed at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
// check level 1: verify block validity
if (nCheckLevel >= 1 && !CheckBlock(block, state))
return error("VerifyDB() : *** found bad block at %d, hash=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
// check level 2: verify undo validity
if (nCheckLevel >= 2 && pindex) {
CBlockUndo undo;
CDiskBlockPos pos = pindex->GetUndoPos();
if (!pos.IsNull()) {
if (!undo.ReadFromDisk(pos, pindex->pprev->GetBlockHash()))
return error("VerifyDB() : *** found bad undo data at %d, hash=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
}
}
// check level 3: check for inconsistencies during memory-only disconnect of tip blocks
if (nCheckLevel >= 3 && pindex == pindexState && (coins.GetCacheSize() + pcoinsTip->GetCacheSize()) <= nCoinCacheSize) {
bool fClean = true;
if (!DisconnectBlock(block, state, pindex, coins, &fClean))
return error("VerifyDB() : *** irrecoverable inconsistency in block data at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
pindexState = pindex->pprev;
if (!fClean) {
nGoodTransactions = 0;
pindexFailure = pindex;
} else
nGoodTransactions += block.vtx.size();
}
if (ShutdownRequested())
return true;
}
if (pindexFailure)
return error("VerifyDB() : *** coin database inconsistencies found (last %i blocks, %i good transactions before that)\n", chainActive.Height() - pindexFailure->nHeight + 1, nGoodTransactions);
// check level 4: try reconnecting blocks
if (nCheckLevel >= 4) {
CBlockIndex* pindex = pindexState;
while (pindex != chainActive.Tip()) {
boost::this_thread::interruption_point();
uiInterface.ShowProgress(_("Verifying blocks..."), std::max(1, std::min(99, 100 - (int)(((double)(chainActive.Height() - pindex->nHeight)) / (double)nCheckDepth * 50))));
pindex = chainActive.Next(pindex);
CBlock block;
if (!ReadBlockFromDisk(block, pindex))
return error("VerifyDB() : *** ReadBlockFromDisk failed at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
if (!ConnectBlock(block, state, pindex, coins, false))
return error("VerifyDB() : *** found unconnectable block at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
}
}
LogPrintf("No coin database inconsistencies in last %i blocks (%i transactions)\n", chainActive.Height() - pindexState->nHeight, nGoodTransactions);
return true;
}
void UnloadBlockIndex()
{
mapBlockIndex.clear();
setBlockIndexCandidates.clear();
chainActive.SetTip(NULL);
pindexBestInvalid = NULL;
}
bool LoadBlockIndex()
{
// Load block index from databases
if (!fReindex && !LoadBlockIndexDB())
return false;
return true;
}
bool InitBlockIndex()
{
LOCK(cs_main);
// Check whether we're already initialized
if (chainActive.Genesis() != NULL)
return true;
// Use the provided setting for -txindex in the new database
fTxIndex = GetBoolArg("-txindex", true);
pblocktree->WriteFlag("txindex", fTxIndex);
LogPrintf("Initializing databases...\n");
// Only add the genesis block if not reindexing (in which case we reuse the one already on disk)
if (!fReindex) {
try {
CBlock& block = const_cast<CBlock&>(Params().GenesisBlock());
// Start new block file
unsigned int nBlockSize = ::GetSerializeSize(block, SER_DISK, CLIENT_VERSION);
CDiskBlockPos blockPos;
CValidationState state;
if (!FindBlockPos(state, blockPos, nBlockSize + 8, 0, block.GetBlockTime()))
return error("LoadBlockIndex() : FindBlockPos failed");
if (!WriteBlockToDisk(block, blockPos))
return error("LoadBlockIndex() : writing genesis block to disk failed");
CBlockIndex* pindex = AddToBlockIndex(block);
if (!ReceivedBlockTransactions(block, state, pindex, blockPos))
return error("LoadBlockIndex() : genesis block not accepted");
if (!ActivateBestChain(state, &block))
return error("LoadBlockIndex() : genesis block cannot be activated");
// Force a chainstate write so that when we VerifyDB in a moment, it doesnt check stale data
return FlushStateToDisk(state, FLUSH_STATE_ALWAYS);
} catch (std::runtime_error& e) {
return error("LoadBlockIndex() : failed to initialize block database: %s", e.what());
}
}
return true;
}
bool LoadExternalBlockFile(FILE* fileIn, CDiskBlockPos* dbp)
{
// Map of disk positions for blocks with unknown parent (only used for reindex)
static std::multimap<uint256, CDiskBlockPos> mapBlocksUnknownParent;
int64_t nStart = GetTimeMillis();
int nLoaded = 0;
try {
// This takes over fileIn and calls fclose() on it in the CBufferedFile destructor
CBufferedFile blkdat(fileIn, 2 * MAX_BLOCK_SIZE_CURRENT, MAX_BLOCK_SIZE_CURRENT + 8, SER_DISK, CLIENT_VERSION);
uint64_t nRewind = blkdat.GetPos();
while (!blkdat.eof()) {
boost::this_thread::interruption_point();
blkdat.SetPos(nRewind);
nRewind++; // start one byte further next time, in case of failure
blkdat.SetLimit(); // remove former limit
unsigned int nSize = 0;
try {
// locate a header
unsigned char buf[MESSAGE_START_SIZE];
blkdat.FindByte(Params().MessageStart()[0]);
nRewind = blkdat.GetPos() + 1;
blkdat >> FLATDATA(buf);
if (memcmp(buf, Params().MessageStart(), MESSAGE_START_SIZE))
continue;
// read size
blkdat >> nSize;
if (nSize < 80 || nSize > MAX_BLOCK_SIZE_CURRENT)
continue;
} catch (const std::exception&) {
// no valid block header found; don't complain
break;
}
try {
// read block
uint64_t nBlockPos = blkdat.GetPos();
if (dbp)
dbp->nPos = nBlockPos;
blkdat.SetLimit(nBlockPos + nSize);
blkdat.SetPos(nBlockPos);
CBlock block;
blkdat >> block;
nRewind = blkdat.GetPos();
// detect out of order blocks, and store them for later
uint256 hash = block.GetHash();
if (hash != Params().HashGenesisBlock() && mapBlockIndex.find(block.hashPrevBlock) == mapBlockIndex.end()) {
LogPrint("reindex", "%s: Out of order block %s, parent %s not known\n", __func__, hash.ToString(),
block.hashPrevBlock.ToString());
if (dbp)
mapBlocksUnknownParent.insert(std::make_pair(block.hashPrevBlock, *dbp));
continue;
}
// process in case the block isn't known yet
if (mapBlockIndex.count(hash) == 0 || (mapBlockIndex[hash]->nStatus & BLOCK_HAVE_DATA) == 0) {
CValidationState state;
if (ProcessNewBlock(state, NULL, &block, dbp))
nLoaded++;
if (state.IsError())
break;
} else if (hash != Params().HashGenesisBlock() && mapBlockIndex[hash]->nHeight % 1000 == 0) {
LogPrintf("Block Import: already had block %s at height %d\n", hash.ToString(), mapBlockIndex[hash]->nHeight);
}
// Recursively process earlier encountered successors of this block
deque<uint256> queue;
queue.push_back(hash);
while (!queue.empty()) {
uint256 head = queue.front();
queue.pop_front();
std::pair<std::multimap<uint256, CDiskBlockPos>::iterator, std::multimap<uint256, CDiskBlockPos>::iterator> range = mapBlocksUnknownParent.equal_range(head);
while (range.first != range.second) {
std::multimap<uint256, CDiskBlockPos>::iterator it = range.first;
if (ReadBlockFromDisk(block, it->second)) {
LogPrintf("%s: Processing out of order child %s of %s\n", __func__, block.GetHash().ToString(),
head.ToString());
CValidationState dummy;
if (ProcessNewBlock(dummy, NULL, &block, &it->second)) {
nLoaded++;
queue.push_back(block.GetHash());
}
}
range.first++;
mapBlocksUnknownParent.erase(it);
}
}
} catch (std::exception& e) {
LogPrintf("%s : Deserialize or I/O error - %s", __func__, e.what());
}
}
} catch (std::runtime_error& e) {
AbortNode(std::string("System error: ") + e.what());
}
if (nLoaded > 0)
LogPrintf("Loaded %i blocks from external file in %dms\n", nLoaded, GetTimeMillis() - nStart);
return nLoaded > 0;
}
void static CheckBlockIndex()
{
if (!fCheckBlockIndex) {
return;
}
LOCK(cs_main);
// During a reindex, we read the genesis block and call CheckBlockIndex before ActivateBestChain,
// so we have the genesis block in mapBlockIndex but no active chain. (A few of the tests when
// iterating the block tree require that chainActive has been initialized.)
if (chainActive.Height() < 0) {
assert(mapBlockIndex.size() <= 1);
return;
}
// Build forward-pointing map of the entire block tree.
std::multimap<CBlockIndex*, CBlockIndex*> forward;
for (BlockMap::iterator it = mapBlockIndex.begin(); it != mapBlockIndex.end(); it++) {
forward.insert(std::make_pair(it->second->pprev, it->second));
}
assert(forward.size() == mapBlockIndex.size());
std::pair<std::multimap<CBlockIndex*, CBlockIndex*>::iterator, std::multimap<CBlockIndex*, CBlockIndex*>::iterator> rangeGenesis = forward.equal_range(NULL);
CBlockIndex* pindex = rangeGenesis.first->second;
rangeGenesis.first++;
assert(rangeGenesis.first == rangeGenesis.second); // There is only one index entry with parent NULL.
// Iterate over the entire block tree, using depth-first search.
// Along the way, remember whether there are blocks on the path from genesis
// block being explored which are the first to have certain properties.
size_t nNodes = 0;
int nHeight = 0;
CBlockIndex* pindexFirstInvalid = NULL; // Oldest ancestor of pindex which is invalid.
CBlockIndex* pindexFirstMissing = NULL; // Oldest ancestor of pindex which does not have BLOCK_HAVE_DATA.
CBlockIndex* pindexFirstNotTreeValid = NULL; // Oldest ancestor of pindex which does not have BLOCK_VALID_TREE (regardless of being valid or not).
CBlockIndex* pindexFirstNotChainValid = NULL; // Oldest ancestor of pindex which does not have BLOCK_VALID_CHAIN (regardless of being valid or not).
CBlockIndex* pindexFirstNotScriptsValid = NULL; // Oldest ancestor of pindex which does not have BLOCK_VALID_SCRIPTS (regardless of being valid or not).
while (pindex != NULL) {
nNodes++;
if (pindexFirstInvalid == NULL && pindex->nStatus & BLOCK_FAILED_VALID) pindexFirstInvalid = pindex;
if (pindexFirstMissing == NULL && !(pindex->nStatus & BLOCK_HAVE_DATA)) pindexFirstMissing = pindex;
if (pindex->pprev != NULL && pindexFirstNotTreeValid == NULL && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_TREE) pindexFirstNotTreeValid = pindex;
if (pindex->pprev != NULL && pindexFirstNotChainValid == NULL && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_CHAIN) pindexFirstNotChainValid = pindex;
if (pindex->pprev != NULL && pindexFirstNotScriptsValid == NULL && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_SCRIPTS) pindexFirstNotScriptsValid = pindex;
// Begin: actual consistency checks.
if (pindex->pprev == NULL) {
// Genesis block checks.
assert(pindex->GetBlockHash() == Params().HashGenesisBlock()); // Genesis block's hash must match.
assert(pindex == chainActive.Genesis()); // The current active chain's genesis block must be this block.
}
// HAVE_DATA is equivalent to VALID_TRANSACTIONS and equivalent to nTx > 0 (we stored the number of transactions in the block)
assert(!(pindex->nStatus & BLOCK_HAVE_DATA) == (pindex->nTx == 0));
assert(((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_TRANSACTIONS) == (pindex->nTx > 0));
if (pindex->nChainTx == 0) assert(pindex->nSequenceId == 0); // nSequenceId can't be set for blocks that aren't linked
// All parents having data is equivalent to all parents being VALID_TRANSACTIONS, which is equivalent to nChainTx being set.
assert((pindexFirstMissing != NULL) == (pindex->nChainTx == 0)); // nChainTx == 0 is used to signal that all parent block's transaction data is available.
assert(pindex->nHeight == nHeight); // nHeight must be consistent.
assert(pindex->pprev == NULL || pindex->nChainWork >= pindex->pprev->nChainWork); // For every block except the genesis block, the chainwork must be larger than the parent's.
assert(nHeight < 2 || (pindex->pskip && (pindex->pskip->nHeight < nHeight))); // The pskip pointer must point back for all but the first 2 blocks.
assert(pindexFirstNotTreeValid == NULL); // All mapBlockIndex entries must at least be TREE valid
if ((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_TREE) assert(pindexFirstNotTreeValid == NULL); // TREE valid implies all parents are TREE valid
if ((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_CHAIN) assert(pindexFirstNotChainValid == NULL); // CHAIN valid implies all parents are CHAIN valid
if ((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_SCRIPTS) assert(pindexFirstNotScriptsValid == NULL); // SCRIPTS valid implies all parents are SCRIPTS valid
if (pindexFirstInvalid == NULL) {
// Checks for not-invalid blocks.
assert((pindex->nStatus & BLOCK_FAILED_MASK) == 0); // The failed mask cannot be set for blocks without invalid parents.
}
if (!CBlockIndexWorkComparator()(pindex, chainActive.Tip()) && pindexFirstMissing == NULL) {
if (pindexFirstInvalid == NULL) { // If this block sorts at least as good as the current tip and is valid, it must be in setBlockIndexCandidates.
assert(setBlockIndexCandidates.count(pindex));
}
} else { // If this block sorts worse than the current tip, it cannot be in setBlockIndexCandidates.
assert(setBlockIndexCandidates.count(pindex) == 0);
}
// Check whether this block is in mapBlocksUnlinked.
std::pair<std::multimap<CBlockIndex*, CBlockIndex*>::iterator, std::multimap<CBlockIndex*, CBlockIndex*>::iterator> rangeUnlinked = mapBlocksUnlinked.equal_range(pindex->pprev);
bool foundInUnlinked = false;
while (rangeUnlinked.first != rangeUnlinked.second) {
assert(rangeUnlinked.first->first == pindex->pprev);
if (rangeUnlinked.first->second == pindex) {
foundInUnlinked = true;
break;
}
rangeUnlinked.first++;
}
if (pindex->pprev && pindex->nStatus & BLOCK_HAVE_DATA && pindexFirstMissing != NULL) {
if (pindexFirstInvalid == NULL) { // If this block has block data available, some parent doesn't, and has no invalid parents, it must be in mapBlocksUnlinked.
assert(foundInUnlinked);
}
} else { // If this block does not have block data available, or all parents do, it cannot be in mapBlocksUnlinked.
assert(!foundInUnlinked);
}
// assert(pindex->GetBlockHash() == pindex->GetBlockHeader().GetHash()); // Perhaps too slow
// End: actual consistency checks.
// Try descending into the first subnode.
std::pair<std::multimap<CBlockIndex*, CBlockIndex*>::iterator, std::multimap<CBlockIndex*, CBlockIndex*>::iterator> range = forward.equal_range(pindex);
if (range.first != range.second) {
// A subnode was found.
pindex = range.first->second;
nHeight++;
continue;
}
// This is a leaf node.
// Move upwards until we reach a node of which we have not yet visited the last child.
while (pindex) {
// We are going to either move to a parent or a sibling of pindex.
// If pindex was the first with a certain property, unset the corresponding variable.
if (pindex == pindexFirstInvalid) pindexFirstInvalid = NULL;
if (pindex == pindexFirstMissing) pindexFirstMissing = NULL;
if (pindex == pindexFirstNotTreeValid) pindexFirstNotTreeValid = NULL;
if (pindex == pindexFirstNotChainValid) pindexFirstNotChainValid = NULL;
if (pindex == pindexFirstNotScriptsValid) pindexFirstNotScriptsValid = NULL;
// Find our parent.
CBlockIndex* pindexPar = pindex->pprev;
// Find which child we just visited.
std::pair<std::multimap<CBlockIndex*, CBlockIndex*>::iterator, std::multimap<CBlockIndex*, CBlockIndex*>::iterator> rangePar = forward.equal_range(pindexPar);
while (rangePar.first->second != pindex) {
assert(rangePar.first != rangePar.second); // Our parent must have at least the node we're coming from as child.
rangePar.first++;
}
// Proceed to the next one.
rangePar.first++;
if (rangePar.first != rangePar.second) {
// Move to the sibling.
pindex = rangePar.first->second;
break;
} else {
// Move up further.
pindex = pindexPar;
nHeight--;
continue;
}
}
}
// Check that we actually traversed the entire map.
assert(nNodes == forward.size());
}
//////////////////////////////////////////////////////////////////////////////
//
// CAlert
//
string GetWarnings(string strFor)
{
int nPriority = 0;
string strStatusBar;
string strRPC;
if (!CLIENT_VERSION_IS_RELEASE)
strStatusBar = _("This is a pre-release test build - use at your own risk - do not use for staking or merchant applications!");
if (GetBoolArg("-testsafemode", false))
strStatusBar = strRPC = "testsafemode enabled";
// Misc warnings like out of disk space and clock is wrong
if (strMiscWarning != "") {
nPriority = 1000;
strStatusBar = strMiscWarning;
}
if (fLargeWorkForkFound) {
nPriority = 2000;
strStatusBar = strRPC = _("Warning: The network does not appear to fully agree! Some miners appear to be experiencing issues.");
} else if (fLargeWorkInvalidChainFound) {
nPriority = 2000;
strStatusBar = strRPC = _("Warning: We do not appear to fully agree with our peers! You may need to upgrade, or other nodes may need to upgrade.");
}
// Alerts
{
LOCK(cs_mapAlerts);
BOOST_FOREACH (PAIRTYPE(const uint256, CAlert) & item, mapAlerts) {
const CAlert& alert = item.second;
if (alert.AppliesToMe() && alert.nPriority > nPriority) {
nPriority = alert.nPriority;
strStatusBar = alert.strStatusBar;
}
}
}
if (strFor == "statusbar")
return strStatusBar;
else if (strFor == "rpc")
return strRPC;
assert(!"GetWarnings() : invalid parameter");
return "error";
}
//////////////////////////////////////////////////////////////////////////////
//
// Messages
//
bool static AlreadyHave(const CInv& inv)
{
switch (inv.type) {
case MSG_TX: {
bool txInMap = false;
txInMap = mempool.exists(inv.hash);
return txInMap || mapOrphanTransactions.count(inv.hash) ||
pcoinsTip->HaveCoins(inv.hash);
}
case MSG_DSTX:
return mapObfuscationBroadcastTxes.count(inv.hash);
case MSG_BLOCK:
return mapBlockIndex.count(inv.hash);
case MSG_TXLOCK_REQUEST:
return mapTxLockReq.count(inv.hash) ||
mapTxLockReqRejected.count(inv.hash);
case MSG_TXLOCK_VOTE:
return mapTxLockVote.count(inv.hash);
case MSG_SPORK:
return mapSporks.count(inv.hash);
case MSG_MASTERNODE_WINNER:
if (masternodePayments.mapMasternodePayeeVotes.count(inv.hash)) {
masternodeSync.AddedMasternodeWinner(inv.hash);
return true;
}
return false;
case MSG_BUDGET_VOTE:
if (budget.mapSeenMasternodeBudgetVotes.count(inv.hash)) {
masternodeSync.AddedBudgetItem(inv.hash);
return true;
}
return false;
case MSG_BUDGET_PROPOSAL:
if (budget.mapSeenMasternodeBudgetProposals.count(inv.hash)) {
masternodeSync.AddedBudgetItem(inv.hash);
return true;
}
return false;
case MSG_BUDGET_FINALIZED_VOTE:
if (budget.mapSeenFinalizedBudgetVotes.count(inv.hash)) {
masternodeSync.AddedBudgetItem(inv.hash);
return true;
}
return false;
case MSG_BUDGET_FINALIZED:
if (budget.mapSeenFinalizedBudgets.count(inv.hash)) {
masternodeSync.AddedBudgetItem(inv.hash);
return true;
}
return false;
case MSG_MASTERNODE_ANNOUNCE:
if (mnodeman.mapSeenMasternodeBroadcast.count(inv.hash)) {
masternodeSync.AddedMasternodeList(inv.hash);
return true;
}
return false;
case MSG_MASTERNODE_PING:
return mnodeman.mapSeenMasternodePing.count(inv.hash);
}
// Don't know what it is, just say we already got one
return true;
}
void static ProcessGetData(CNode* pfrom)
{
std::deque<CInv>::iterator it = pfrom->vRecvGetData.begin();
vector<CInv> vNotFound;
LOCK(cs_main);
while (it != pfrom->vRecvGetData.end()) {
// Don't bother if send buffer is too full to respond anyway
if (pfrom->nSendSize >= SendBufferSize())
break;
const CInv& inv = *it;
{
boost::this_thread::interruption_point();
it++;
if (inv.type == MSG_BLOCK || inv.type == MSG_FILTERED_BLOCK) {
bool send = false;
BlockMap::iterator mi = mapBlockIndex.find(inv.hash);
if (mi != mapBlockIndex.end()) {
if (chainActive.Contains(mi->second)) {
send = true;
} else {
// To prevent fingerprinting attacks, only send blocks outside of the active
// chain if they are valid, and no more than a max reorg depth than the best header
// chain we know about.
send = mi->second->IsValid(BLOCK_VALID_SCRIPTS) && (pindexBestHeader != NULL) &&
(chainActive.Height() - mi->second->nHeight < Params().MaxReorganizationDepth());
if (!send) {
LogPrintf("ProcessGetData(): ignoring request from peer=%i for old block that isn't in the main chain\n", pfrom->GetId());
}
}
}
// Don't send not-validated blocks
if (send && (mi->second->nStatus & BLOCK_HAVE_DATA)) {
// Send block from disk
CBlock block;
if (!ReadBlockFromDisk(block, (*mi).second))
assert(!"cannot load block from disk");
if (inv.type == MSG_BLOCK)
pfrom->PushMessage("block", block);
else // MSG_FILTERED_BLOCK)
{
LOCK(pfrom->cs_filter);
if (pfrom->pfilter) {
CMerkleBlock merkleBlock(block, *pfrom->pfilter);
pfrom->PushMessage("merkleblock", merkleBlock);
// CMerkleBlock just contains hashes, so also push any transactions in the block the client did not see
// This avoids hurting performance by pointlessly requiring a round-trip
// Note that there is currently no way for a node to request any single transactions we didnt send here -
// they must either disconnect and retry or request the full block.
// Thus, the protocol spec specified allows for us to provide duplicate txn here,
// however we MUST always provide at least what the remote peer needs
typedef std::pair<unsigned int, uint256> PairType;
BOOST_FOREACH (PairType& pair, merkleBlock.vMatchedTxn)
if (!pfrom->setInventoryKnown.count(CInv(MSG_TX, pair.second)))
pfrom->PushMessage("tx", block.vtx[pair.first]);
}
// else
// no response
}
// Trigger them to send a getblocks request for the next batch of inventory
if (inv.hash == pfrom->hashContinue) {
// Bypass PushInventory, this must send even if redundant,
// and we want it right after the last block so they don't
// wait for other stuff first.
// peershares adapted: best block is always the reference block to prevent
// proof-of-stake block from being rejected by stake connection
// check
vector<CInv> vInv;
vInv.push_back(CInv(MSG_BLOCK, chainActive.Tip()->GetBlockHash()));
pfrom->PushMessage("inv", vInv);
pfrom->hashContinue = 0;
}
}
} else if (inv.IsKnownType()) {
// Send stream from relay memory
bool pushed = false;
{
LOCK(cs_mapRelay);
map<CInv, CDataStream>::iterator mi = mapRelay.find(inv);
if (mi != mapRelay.end()) {
pfrom->PushMessage(inv.GetCommand(), (*mi).second);
pushed = true;
}
}
if (!pushed && inv.type == MSG_TX) {
CTransaction tx;
if (mempool.lookup(inv.hash, tx)) {
CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
ss.reserve(1000);
ss << tx;
pfrom->PushMessage("tx", ss);
pushed = true;
}
}
if (!pushed && inv.type == MSG_TXLOCK_VOTE) {
if (mapTxLockVote.count(inv.hash)) {
CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
ss.reserve(1000);
ss << mapTxLockVote[inv.hash];
pfrom->PushMessage("txlvote", ss);
pushed = true;
}
}
if (!pushed && inv.type == MSG_TXLOCK_REQUEST) {
if (mapTxLockReq.count(inv.hash)) {
CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
ss.reserve(1000);
ss << mapTxLockReq[inv.hash];
pfrom->PushMessage("ix", ss);
pushed = true;
}
}
if (!pushed && inv.type == MSG_SPORK) {
if (mapSporks.count(inv.hash)) {
CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
ss.reserve(1000);
ss << mapSporks[inv.hash];
pfrom->PushMessage("spork", ss);
pushed = true;
}
}
if (!pushed && inv.type == MSG_MASTERNODE_WINNER) {
if (masternodePayments.mapMasternodePayeeVotes.count(inv.hash)) {
CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
ss.reserve(1000);
ss << masternodePayments.mapMasternodePayeeVotes[inv.hash];
pfrom->PushMessage("mnw", ss);
pushed = true;
}
}
if (!pushed && inv.type == MSG_BUDGET_VOTE) {
if (budget.mapSeenMasternodeBudgetVotes.count(inv.hash)) {
CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
ss.reserve(1000);
ss << budget.mapSeenMasternodeBudgetVotes[inv.hash];
pfrom->PushMessage("mvote", ss);
pushed = true;
}
}
if (!pushed && inv.type == MSG_BUDGET_PROPOSAL) {
if (budget.mapSeenMasternodeBudgetProposals.count(inv.hash)) {
CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
ss.reserve(1000);
ss << budget.mapSeenMasternodeBudgetProposals[inv.hash];
pfrom->PushMessage("mprop", ss);
pushed = true;
}
}
if (!pushed && inv.type == MSG_BUDGET_FINALIZED_VOTE) {
if (budget.mapSeenFinalizedBudgetVotes.count(inv.hash)) {
CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
ss.reserve(1000);
ss << budget.mapSeenFinalizedBudgetVotes[inv.hash];
pfrom->PushMessage("fbvote", ss);
pushed = true;
}
}
if (!pushed && inv.type == MSG_BUDGET_FINALIZED) {
if (budget.mapSeenFinalizedBudgets.count(inv.hash)) {
CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
ss.reserve(1000);
ss << budget.mapSeenFinalizedBudgets[inv.hash];
pfrom->PushMessage("fbs", ss);
pushed = true;
}
}
if (!pushed && inv.type == MSG_MASTERNODE_ANNOUNCE) {
if (mnodeman.mapSeenMasternodeBroadcast.count(inv.hash)) {
CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
ss.reserve(1000);
ss << mnodeman.mapSeenMasternodeBroadcast[inv.hash];
pfrom->PushMessage("mnb", ss);
pushed = true;
}
}
if (!pushed && inv.type == MSG_MASTERNODE_PING) {
if (mnodeman.mapSeenMasternodePing.count(inv.hash)) {
CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
ss.reserve(1000);
ss << mnodeman.mapSeenMasternodePing[inv.hash];
pfrom->PushMessage("mnp", ss);
pushed = true;
}
}
if (!pushed && inv.type == MSG_DSTX) {
if (mapObfuscationBroadcastTxes.count(inv.hash)) {
CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
ss.reserve(1000);
ss << mapObfuscationBroadcastTxes[inv.hash].tx << mapObfuscationBroadcastTxes[inv.hash].vin << mapObfuscationBroadcastTxes[inv.hash].vchSig << mapObfuscationBroadcastTxes[inv.hash].sigTime;
pfrom->PushMessage("dstx", ss);
pushed = true;
}
}
if (!pushed) {
vNotFound.push_back(inv);
}
}
// Track requests for our stuff.
g_signals.Inventory(inv.hash);
if (inv.type == MSG_BLOCK || inv.type == MSG_FILTERED_BLOCK)
break;
}
}
pfrom->vRecvGetData.erase(pfrom->vRecvGetData.begin(), it);
if (!vNotFound.empty()) {
// Let the peer know that we didn't find what it asked for, so it doesn't
// have to wait around forever. Currently only SPV clients actually care
// about this message: it's needed when they are recursively walking the
// dependencies of relevant unconfirmed transactions. SPV clients want to
// do that because they want to know about (and store and rebroadcast and
// risk analyze) the dependencies of transactions relevant to them, without
// having to download the entire memory pool.
pfrom->PushMessage("notfound", vNotFound);
}
}
bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv, int64_t nTimeReceived)
{
RandAddSeedPerfmon();
if (fDebug)
LogPrintf("received: %s (%u bytes) peer=%d\n", SanitizeString(strCommand), vRecv.size(), pfrom->id);
if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0) {
LogPrintf("dropmessagestest DROPPING RECV MESSAGE\n");
return true;
}
int nCurHeight = GetHeight();
if (strCommand == "version") {
// Each connection can only send one version message
if (pfrom->nVersion != 0) {
pfrom->PushMessage("reject", strCommand, REJECT_DUPLICATE, string("Duplicate version message"));
Misbehaving(pfrom->GetId(), 1);
return false;
}
// IoTHome: We use certain sporks during IBD, so check to see if they are
// available. If not, ask the first peer connected for them.
if (!pSporkDB->SporkExists(SPORK_14_NEW_PROTOCOL_ENFORCEMENT) &&
!pSporkDB->SporkExists(SPORK_15_NEW_PROTOCOL_ENFORCEMENT_2) &&
!pSporkDB->SporkExists(SPORK_11_LOCK_INVALID_UTXO) &&
!pSporkDB->SporkExists(SPORK_16_ZEROCOIN_MAINTENANCE_MODE)) {
LogPrintf("Required sporks not found, asking peer to send them\n");
pfrom->PushMessage("getsporks");
}
int64_t nTime;
CAddress addrMe;
CAddress addrFrom;
uint64_t nNonce = 1;
vRecv >> pfrom->nVersion >> pfrom->nServices >> nTime >> addrMe;
if (pfrom->DisconnectOldProtocol(GetMinPeerProtoVersion(nCurHeight), strCommand))
return false;
if (pfrom->nVersion == 15005)
pfrom->nVersion = 300;
if (!vRecv.empty())
vRecv >> addrFrom >> nNonce;
if (!vRecv.empty()) {
vRecv >> LIMITED_STRING(pfrom->strSubVer, 256);
pfrom->cleanSubVer = SanitizeString(pfrom->strSubVer);
}
if (!vRecv.empty())
vRecv >> pfrom->nStartingHeight;
if (!vRecv.empty())
vRecv >> pfrom->fRelayTxes; // set to true after we get the first filter* message
else
pfrom->fRelayTxes = true;
// Disconnect if we connected to ourself
if (nNonce == nLocalHostNonce && nNonce > 1) {
LogPrintf("connected to self at %s, disconnecting\n", pfrom->addr.ToString());
pfrom->fDisconnect = true;
return true;
}
pfrom->addrLocal = addrMe;
if (pfrom->fInbound && addrMe.IsRoutable()) {
SeenLocal(addrMe);
}
// Be shy and don't send version until we hear
if (pfrom->fInbound)
pfrom->PushVersion();
pfrom->fClient = !(pfrom->nServices & NODE_NETWORK);
// Potentially mark this peer as a preferred download peer.
UpdatePreferredDownload(pfrom, State(pfrom->GetId()));
// Change version
pfrom->PushMessage("verack");
pfrom->ssSend.SetVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
if (!pfrom->fInbound) {
// Advertise our address
if (fListen && !IsInitialBlockDownload()) {
CAddress addr = GetLocalAddress(&pfrom->addr);
if (addr.IsRoutable()) {
LogPrintf("ProcessMessages: advertizing address %s\n", addr.ToString());
pfrom->PushAddress(addr);
} else if (IsPeerAddrLocalGood(pfrom)) {
addr.SetIP(pfrom->addrLocal);
LogPrintf("ProcessMessages: advertizing address %s\n", addr.ToString());
pfrom->PushAddress(addr);
}
}
// Get recent addresses
if (pfrom->fOneShot || pfrom->nVersion >= CADDR_TIME_VERSION || addrman.size() < 1000) {
pfrom->PushMessage("getaddr");
pfrom->fGetAddr = true;
}
addrman.Good(pfrom->addr);
} else {
if (((CNetAddr)pfrom->addr) == (CNetAddr)addrFrom) {
addrman.Add(addrFrom, addrFrom);
addrman.Good(addrFrom);
}
}
// Relay alerts
{
LOCK(cs_mapAlerts);
BOOST_FOREACH (PAIRTYPE(const uint256, CAlert) & item, mapAlerts)
item.second.RelayTo(pfrom);
}
pfrom->fSuccessfullyConnected = true;
string remoteAddr;
if (fLogIPs)
remoteAddr = ", peeraddr=" + pfrom->addr.ToString();
LogPrintf("receive version message: %s: version %d, blocks=%d, us=%s, peer=%d%s\n",
pfrom->cleanSubVer, pfrom->nVersion,
pfrom->nStartingHeight, addrMe.ToString(), pfrom->id,
remoteAddr);
AddTimeData(pfrom->addr, nTime);
}
else if (pfrom->nVersion == 0) {
// Must have a version message before anything else
Misbehaving(pfrom->GetId(), 1);
return false;
}
else if (strCommand == "verack") {
pfrom->SetRecvVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
// Mark this node as currently connected, so we update its timestamp later.
if (pfrom->fNetworkNode) {
LOCK(cs_main);
State(pfrom->GetId())->fCurrentlyConnected = true;
}
}
else if (strCommand == "addr") {
vector<CAddress> vAddr;
vRecv >> vAddr;
// Don't want addr from older versions unless seeding
if (pfrom->nVersion < CADDR_TIME_VERSION && addrman.size() > 1000)
return true;
if (vAddr.size() > 1000) {
Misbehaving(pfrom->GetId(), 20);
return error("message addr size() = %u", vAddr.size());
}
// Store the new addresses
vector<CAddress> vAddrOk;
int64_t nNow = GetAdjustedTime();
int64_t nSince = nNow - 10 * 60;
BOOST_FOREACH (CAddress& addr, vAddr) {
boost::this_thread::interruption_point();
if (addr.nTime <= 100000000 || addr.nTime > nNow + 10 * 60)
addr.nTime = nNow - 5 * 24 * 60 * 60;
pfrom->AddAddressKnown(addr);
bool fReachable = IsReachable(addr);
if (addr.nTime > nSince && !pfrom->fGetAddr && vAddr.size() <= 10 && addr.IsRoutable()) {
// Relay to a limited number of other nodes
{
LOCK(cs_vNodes);
// Use deterministic randomness to send to the same nodes for 24 hours
// at a time so the setAddrKnowns of the chosen nodes prevent repeats
static uint256 hashSalt;
if (hashSalt == 0)
hashSalt = GetRandHash();
uint64_t hashAddr = addr.GetHash();
uint256 hashRand = hashSalt ^ (hashAddr << 32) ^ ((GetTime() + hashAddr) / (24 * 60 * 60));
hashRand = Hash(BEGIN(hashRand), END(hashRand));
multimap<uint256, CNode*> mapMix;
BOOST_FOREACH (CNode* pnode, vNodes) {
if (pnode->nVersion < CADDR_TIME_VERSION)
continue;
unsigned int nPointer;
memcpy(&nPointer, &pnode, sizeof(nPointer));
uint256 hashKey = hashRand ^ nPointer;
hashKey = Hash(BEGIN(hashKey), END(hashKey));
mapMix.insert(make_pair(hashKey, pnode));
}
int nRelayNodes = fReachable ? 2 : 1; // limited relaying of addresses outside our network(s)
for (multimap<uint256, CNode*>::iterator mi = mapMix.begin(); mi != mapMix.end() && nRelayNodes-- > 0; ++mi)
((*mi).second)->PushAddress(addr);
}
}
// Do not store addresses outside our network
if (fReachable)
vAddrOk.push_back(addr);
}
addrman.Add(vAddrOk, pfrom->addr, 2 * 60 * 60);
if (vAddr.size() < 1000)
pfrom->fGetAddr = false;
if (pfrom->fOneShot)
pfrom->fDisconnect = true;
}
else if (strCommand == "inv") {
vector<CInv> vInv;
vRecv >> vInv;
if (vInv.size() > MAX_INV_SZ) {
Misbehaving(pfrom->GetId(), 20);
return error("message inv size() = %u", vInv.size());
}
LOCK(cs_main);
std::vector<CInv> vToFetch;
for (unsigned int nInv = 0; nInv < vInv.size(); nInv++) {
const CInv& inv = vInv[nInv];
boost::this_thread::interruption_point();
pfrom->AddInventoryKnown(inv);
bool fAlreadyHave = AlreadyHave(inv);
LogPrint("net", "got inv: %s %s peer=%d\n", inv.ToString(), fAlreadyHave ? "have" : "new", pfrom->id);
if (!fAlreadyHave && !fImporting && !fReindex && inv.type != MSG_BLOCK)
pfrom->AskFor(inv, IsInitialBlockDownload());
if (inv.type == MSG_BLOCK) {
UpdateBlockAvailability(pfrom->GetId(), inv.hash);
if (!fAlreadyHave && !fImporting && !fReindex && !mapBlocksInFlight.count(inv.hash)) {
// Add this to the list of blocks to request
vToFetch.push_back(inv);
LogPrint("net", "getblocks (%d) %s to peer=%d\n", pindexBestHeader->nHeight, inv.hash.ToString(), pfrom->id);
}
}
// Track requests for our stuff
g_signals.Inventory(inv.hash);
if (pfrom->nSendSize > (SendBufferSize() * 2)) {
Misbehaving(pfrom->GetId(), 50);
return error("send buffer size() = %u", pfrom->nSendSize);
}
}
if (!vToFetch.empty())
pfrom->PushMessage("getdata", vToFetch);
}
else if (strCommand == "getdata") {
vector<CInv> vInv;
vRecv >> vInv;
if (vInv.size() > MAX_INV_SZ) {
Misbehaving(pfrom->GetId(), 20);
return error("message getdata size() = %u", vInv.size());
}
if (fDebug || (vInv.size() != 1))
LogPrint("net", "received getdata (%u invsz) peer=%d\n", vInv.size(), pfrom->id);
if ((fDebug && vInv.size() > 0) || (vInv.size() == 1))
LogPrint("net", "received getdata for: %s peer=%d\n", vInv[0].ToString(), pfrom->id);
pfrom->vRecvGetData.insert(pfrom->vRecvGetData.end(), vInv.begin(), vInv.end());
ProcessGetData(pfrom);
}
else if (strCommand == "getblocks" || strCommand == "getheaders") {
CBlockLocator locator;
uint256 hashStop;
vRecv >> locator >> hashStop;
LOCK(cs_main);
// Find the last block the caller has in the main chain
CBlockIndex* pindex = FindForkInGlobalIndex(chainActive, locator);
// Send the rest of the chain
if (pindex)
pindex = chainActive.Next(pindex);
int nLimit = 500;
LogPrint("net", "getblocks %d to %s limit %d from peer=%d\n", (pindex ? pindex->nHeight : -1), hashStop == uint256(0) ? "end" : hashStop.ToString(), nLimit, pfrom->id);
for (; pindex; pindex = chainActive.Next(pindex)) {
if (pindex->GetBlockHash() == hashStop) {
LogPrint("net", " getblocks stopping at %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
break;
}
pfrom->PushInventory(CInv(MSG_BLOCK, pindex->GetBlockHash()));
if (--nLimit <= 0) {
// When this block is requested, we'll send an inv that'll make them
// getblocks the next batch of inventory.
LogPrint("net", " getblocks stopping at limit %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
pfrom->hashContinue = pindex->GetBlockHash();
break;
}
}
}
else if (strCommand == "headers" && Params().HeadersFirstSyncingActive()) {
CBlockLocator locator;
uint256 hashStop;
vRecv >> locator >> hashStop;
LOCK(cs_main);
if (IsInitialBlockDownload())
return true;
CBlockIndex* pindex = NULL;
if (locator.IsNull()) {
// If locator is null, return the hashStop block
BlockMap::iterator mi = mapBlockIndex.find(hashStop);
if (mi == mapBlockIndex.end())
return true;
pindex = (*mi).second;
} else {
// Find the last block the caller has in the main chain
pindex = FindForkInGlobalIndex(chainActive, locator);
if (pindex)
pindex = chainActive.Next(pindex);
}
// we must use CBlocks, as CBlockHeaders won't include the 0x00 nTx count at the end
vector<CBlock> vHeaders;
int nLimit = MAX_HEADERS_RESULTS;
if (fDebug)
LogPrintf("getheaders %d to %s from peer=%d\n", (pindex ? pindex->nHeight : -1), hashStop.ToString(), pfrom->id);
for (; pindex; pindex = chainActive.Next(pindex)) {
vHeaders.push_back(pindex->GetBlockHeader());
if (--nLimit <= 0 || pindex->GetBlockHash() == hashStop)
break;
}
pfrom->PushMessage("headers", vHeaders);
}
else if (strCommand == "tx" || strCommand == "dstx") {
vector<uint256> vWorkQueue;
vector<uint256> vEraseQueue;
CTransaction tx;
//masternode signed transaction
bool ignoreFees = false;
CTxIn vin;
vector<unsigned char> vchSig;
int64_t sigTime;
if (strCommand == "tx") {
vRecv >> tx;
} else if (strCommand == "dstx") {
//these allow masternodes to publish a limited amount of free transactions
vRecv >> tx >> vin >> vchSig >> sigTime;
CMasternode* pmn = mnodeman.Find(vin);
if (pmn != NULL) {
if (!pmn->allowFreeTx) {
//multiple peers can send us a valid masternode transaction
if (fDebug) LogPrintf("dstx: Masternode sending too many transactions %s\n", tx.GetHash().ToString());
return true;
}
std::string strMessage = tx.GetHash().ToString() + boost::lexical_cast<std::string>(sigTime);
std::string errorMessage = "";
if (!obfuScationSigner.VerifyMessage(pmn->pubKeyMasternode, vchSig, strMessage, errorMessage)) {
LogPrintf("dstx: Got bad masternode address signature %s \n", vin.ToString());
//pfrom->Misbehaving(20);
return false;
}
LogPrintf("dstx: Got Masternode transaction %s\n", tx.GetHash().ToString());
ignoreFees = true;
pmn->allowFreeTx = false;
if (!mapObfuscationBroadcastTxes.count(tx.GetHash())) {
CObfuscationBroadcastTx dstx;
dstx.tx = tx;
dstx.vin = vin;
dstx.vchSig = vchSig;
dstx.sigTime = sigTime;
mapObfuscationBroadcastTxes.insert(make_pair(tx.GetHash(), dstx));
}
}
}
CInv inv(MSG_TX, tx.GetHash());
pfrom->AddInventoryKnown(inv);
LOCK(cs_main);
bool fMissingInputs = false;
bool fMissingZerocoinInputs = false;
CValidationState state;
mapAlreadyAskedFor.erase(inv);
if (!tx.IsZerocoinSpend() && AcceptToMemoryPool(mempool, state, tx, true, &fMissingInputs, false, ignoreFees)) {
mempool.check(pcoinsTip);
RelayTransaction(tx);
vWorkQueue.push_back(inv.hash);
LogPrint("mempool", "AcceptToMemoryPool: peer=%d %s : accepted %s (poolsz %u)\n",
pfrom->id, pfrom->cleanSubVer,
tx.GetHash().ToString(),
mempool.mapTx.size());
// Recursively process any orphan transactions that depended on this one
set<NodeId> setMisbehaving;
for(unsigned int i = 0; i < vWorkQueue.size(); i++) {
map<uint256, set<uint256> >::iterator itByPrev = mapOrphanTransactionsByPrev.find(vWorkQueue[i]);
if(itByPrev == mapOrphanTransactionsByPrev.end())
continue;
for(set<uint256>::iterator mi = itByPrev->second.begin();
mi != itByPrev->second.end();
++mi) {
const uint256 &orphanHash = *mi;
const CTransaction &orphanTx = mapOrphanTransactions[orphanHash].tx;
NodeId fromPeer = mapOrphanTransactions[orphanHash].fromPeer;
bool fMissingInputs2 = false;
// Use a dummy CValidationState so someone can't setup nodes to counter-DoS based on orphan
// resolution (that is, feeding people an invalid transaction based on LegitTxX in order to get
// anyone relaying LegitTxX banned)
CValidationState stateDummy;
if(setMisbehaving.count(fromPeer))
continue;
if(AcceptToMemoryPool(mempool, stateDummy, orphanTx, true, &fMissingInputs2)) {
LogPrint("mempool", " accepted orphan tx %s\n", orphanHash.ToString());
RelayTransaction(orphanTx);
vWorkQueue.push_back(orphanHash);
vEraseQueue.push_back(orphanHash);
} else if(!fMissingInputs2) {
int nDos = 0;
if(stateDummy.IsInvalid(nDos) && nDos > 0) {
// Punish peer that gave us an invalid orphan tx
Misbehaving(fromPeer, nDos);
setMisbehaving.insert(fromPeer);
LogPrint("mempool", " invalid orphan tx %s\n", orphanHash.ToString());
}
// Has inputs but not accepted to mempool
// Probably non-standard or insufficient fee/priority
LogPrint("mempool", " removed orphan tx %s\n", orphanHash.ToString());
vEraseQueue.push_back(orphanHash);
}
mempool.check(pcoinsTip);
}
}
BOOST_FOREACH (uint256 hash, vEraseQueue)EraseOrphanTx(hash);
} else if (tx.IsZerocoinSpend() && AcceptToMemoryPool(mempool, state, tx, true, &fMissingZerocoinInputs, false, ignoreFees)) {
//Presstab: ZCoin has a bunch of code commented out here. Is this something that should have more going on?
//Also there is nothing that handles fMissingZerocoinInputs. Does there need to be?
RelayTransaction(tx);
LogPrint("mempool", "AcceptToMemoryPool: Zerocoinspend peer=%d %s : accepted %s (poolsz %u)\n",
pfrom->id, pfrom->cleanSubVer,
tx.GetHash().ToString(),
mempool.mapTx.size());
} else if (fMissingInputs) {
AddOrphanTx(tx, pfrom->GetId());
// DoS prevention: do not allow mapOrphanTransactions to grow unbounded
unsigned int nMaxOrphanTx = (unsigned int)std::max((int64_t)0, GetArg("-maxorphantx", DEFAULT_MAX_ORPHAN_TRANSACTIONS));
unsigned int nEvicted = LimitOrphanTxSize(nMaxOrphanTx);
if (nEvicted > 0)
LogPrint("mempool", "mapOrphan overflow, removed %u tx\n", nEvicted);
} else if (pfrom->fWhitelisted) {
// Always relay transactions received from whitelisted peers, even
// if they are already in the mempool (allowing the node to function
// as a gateway for nodes hidden behind it).
RelayTransaction(tx);
}
if (strCommand == "dstx") {
CInv inv(MSG_DSTX, tx.GetHash());
RelayInv(inv);
}
int nDoS = 0;
if (state.IsInvalid(nDoS)) {
LogPrint("mempool", "%s from peer=%d %s was not accepted into the memory pool: %s\n", tx.GetHash().ToString(),
pfrom->id, pfrom->cleanSubVer,
state.GetRejectReason());
pfrom->PushMessage("reject", strCommand, state.GetRejectCode(),
state.GetRejectReason().substr(0, MAX_REJECT_MESSAGE_LENGTH), inv.hash);
if (nDoS > 0)
Misbehaving(pfrom->GetId(), nDoS);
}
}
else if (strCommand == "headers" && Params().HeadersFirstSyncingActive() && !fImporting && !fReindex) // Ignore headers received while importing
{
std::vector<CBlockHeader> headers;
// Bypass the normal CBlock deserialization, as we don't want to risk deserializing 2000 full blocks.
unsigned int nCount = ReadCompactSize(vRecv);
if (nCount > MAX_HEADERS_RESULTS) {
Misbehaving(pfrom->GetId(), 20);
return error("headers message size = %u", nCount);
}
headers.resize(nCount);
for (unsigned int n = 0; n < nCount; n++) {
vRecv >> headers[n];
ReadCompactSize(vRecv); // ignore tx count; assume it is 0.
}
LOCK(cs_main);
if (nCount == 0) {
// Nothing interesting. Stop asking this peers for more headers.
return true;
}
CBlockIndex* pindexLast = NULL;
BOOST_FOREACH (const CBlockHeader& header, headers) {
CValidationState state;
if (pindexLast != NULL && header.hashPrevBlock != pindexLast->GetBlockHash()) {
Misbehaving(pfrom->GetId(), 20);
return error("non-continuous headers sequence");
}
/*TODO: this has a CBlock cast on it so that it will compile. There should be a solution for this
* before headers are reimplemented on mainnet
*/
if (!AcceptBlockHeader((CBlock)header, state, &pindexLast)) {
int nDoS;
if (state.IsInvalid(nDoS)) {
if (nDoS > 0)
Misbehaving(pfrom->GetId(), nDoS);
std::string strError = "invalid header received " + header.GetHash().ToString();
return error(strError.c_str());
}
}
}
if (pindexLast)
UpdateBlockAvailability(pfrom->GetId(), pindexLast->GetBlockHash());
if (nCount == MAX_HEADERS_RESULTS && pindexLast) {
// Headers message had its maximum size; the peer may have more headers.
// TODO: optimize: if pindexLast is an ancestor of chainActive.Tip or pindexBestHeader, continue
// from there instead.
LogPrintf("more getheaders (%d) to end to peer=%d (startheight:%d)\n", pindexLast->nHeight, pfrom->id, pfrom->nStartingHeight);
pfrom->PushMessage("getheaders", chainActive.GetLocator(pindexLast), uint256(0));
}
CheckBlockIndex();
}
else if (strCommand == "block" && !fImporting && !fReindex) // Ignore blocks received while importing
{
CBlock block;
vRecv >> block;
uint256 hashBlock = block.GetHash();
CInv inv(MSG_BLOCK, hashBlock);
LogPrint("net", "received block %s peer=%d\n", inv.hash.ToString(), pfrom->id);
//sometimes we will be sent their most recent block and its not the one we want, in that case tell where we are
if (!mapBlockIndex.count(block.hashPrevBlock)) {
if (find(pfrom->vBlockRequested.begin(), pfrom->vBlockRequested.end(), hashBlock) != pfrom->vBlockRequested.end()) {
//we already asked for this block, so lets work backwards and ask for the previous block
pfrom->PushMessage("getblocks", chainActive.GetLocator(), block.hashPrevBlock);
pfrom->vBlockRequested.push_back(block.hashPrevBlock);
} else {
//ask to sync to this block
pfrom->PushMessage("getblocks", chainActive.GetLocator(), hashBlock);
pfrom->vBlockRequested.push_back(hashBlock);
}
} else {
pfrom->AddInventoryKnown(inv);
CValidationState state;
if (!mapBlockIndex.count(block.GetHash())) {
ProcessNewBlock(state, pfrom, &block);
int nDoS;
if(state.IsInvalid(nDoS)) {
pfrom->PushMessage("reject", strCommand, state.GetRejectCode(),
state.GetRejectReason().substr(0, MAX_REJECT_MESSAGE_LENGTH), inv.hash);
if(nDoS > 0) {
TRY_LOCK(cs_main, lockMain);
if(lockMain) Misbehaving(pfrom->GetId(), nDoS);
}
}
//disconnect this node if its old protocol version
pfrom->DisconnectOldProtocol(GetMinPeerProtoVersion(pindexBestHeader->nHeight), strCommand);
} else {
LogPrint("net", "%s : Already processed block %s, skipping ProcessNewBlock()\n", __func__, block.GetHash().GetHex());
}
}
}
// This asymmetric behavior for inbound and outbound connections was introduced
// to prevent a fingerprinting attack: an attacker can send specific fake addresses
// to users' AddrMan and later request them by sending getaddr messages.
// Making users (which are behind NAT and can only make outgoing connections) ignore
// getaddr message mitigates the attack.
else if ((strCommand == "getaddr") && (pfrom->fInbound)) {
pfrom->vAddrToSend.clear();
vector<CAddress> vAddr = addrman.GetAddr();
BOOST_FOREACH (const CAddress& addr, vAddr)
pfrom->PushAddress(addr);
}
else if (strCommand == "mempool") {
LOCK2(cs_main, pfrom->cs_filter);
std::vector<uint256> vtxid;
mempool.queryHashes(vtxid);
vector<CInv> vInv;
BOOST_FOREACH (uint256& hash, vtxid) {
CInv inv(MSG_TX, hash);
CTransaction tx;
bool fInMemPool = mempool.lookup(hash, tx);
if (!fInMemPool) continue; // another thread removed since queryHashes, maybe...
if ((pfrom->pfilter && pfrom->pfilter->IsRelevantAndUpdate(tx)) ||
(!pfrom->pfilter))
vInv.push_back(inv);
if (vInv.size() == MAX_INV_SZ) {
pfrom->PushMessage("inv", vInv);
vInv.clear();
}
}
if (vInv.size() > 0)
pfrom->PushMessage("inv", vInv);
}
else if (strCommand == "ping") {
if (pfrom->nVersion > BIP0031_VERSION) {
uint64_t nonce = 0;
vRecv >> nonce;
// Echo the message back with the nonce. This allows for two useful features:
//
// 1) A remote node can quickly check if the connection is operational
// 2) Remote nodes can measure the latency of the network thread. If this node
// is overloaded it won't respond to pings quickly and the remote node can
// avoid sending us more work, like chain download requests.
//
// The nonce stops the remote getting confused between different pings: without
// it, if the remote node sends a ping once per second and this node takes 5
// seconds to respond to each, the 5th ping the remote sends would appear to
// return very quickly.
pfrom->PushMessage("pong", nonce);
}
}
else if (strCommand == "pong") {
int64_t pingUsecEnd = nTimeReceived;
uint64_t nonce = 0;
size_t nAvail = vRecv.in_avail();
bool bPingFinished = false;
std::string sProblem;
if (nAvail >= sizeof(nonce)) {
vRecv >> nonce;
// Only process pong message if there is an outstanding ping (old ping without nonce should never pong)
if (pfrom->nPingNonceSent != 0) {
if (nonce == pfrom->nPingNonceSent) {
// Matching pong received, this ping is no longer outstanding
bPingFinished = true;
int64_t pingUsecTime = pingUsecEnd - pfrom->nPingUsecStart;
if (pingUsecTime > 0) {
// Successful ping time measurement, replace previous
pfrom->nPingUsecTime = pingUsecTime;
} else {
// This should never happen
sProblem = "Timing mishap";
}
} else {
// Nonce mismatches are normal when pings are overlapping
sProblem = "Nonce mismatch";
if (nonce == 0) {
// This is most likely a bug in another implementation somewhere, cancel this ping
bPingFinished = true;
sProblem = "Nonce zero";
}
}
} else {
sProblem = "Unsolicited pong without ping";
}
} else {
// This is most likely a bug in another implementation somewhere, cancel this ping
bPingFinished = true;
sProblem = "Short payload";
}
if (!(sProblem.empty())) {
LogPrint("net", "pong peer=%d %s: %s, %x expected, %x received, %u bytes\n",
pfrom->id,
pfrom->cleanSubVer,
sProblem,
pfrom->nPingNonceSent,
nonce,
nAvail);
}
if (bPingFinished) {
pfrom->nPingNonceSent = 0;
}
}
else if (fAlerts && strCommand == "alert") {
CAlert alert;
vRecv >> alert;
uint256 alertHash = alert.GetHash();
if (pfrom->setKnown.count(alertHash) == 0) {
if (alert.ProcessAlert()) {
// Relay
pfrom->setKnown.insert(alertHash);
{
LOCK(cs_vNodes);
BOOST_FOREACH (CNode* pnode, vNodes)
alert.RelayTo(pnode);
}
} else {
// Small DoS penalty so peers that send us lots of
// duplicate/expired/invalid-signature/whatever alerts
// eventually get banned.
// This isn't a Misbehaving(100) (immediate ban) because the
// peer might be an older or different implementation with
// a different signature key, etc.
Misbehaving(pfrom->GetId(), 10);
}
}
}
else if (!(nLocalServices & NODE_BLOOM) &&
(strCommand == "filterload" ||
strCommand == "filteradd" ||
strCommand == "filterclear")) {
LogPrintf("bloom message=%s\n", strCommand);
Misbehaving(pfrom->GetId(), 100);
}
else if (strCommand == "filterload") {
CBloomFilter filter;
vRecv >> filter;
if (!filter.IsWithinSizeConstraints())
// There is no excuse for sending a too-large filter
Misbehaving(pfrom->GetId(), 100);
else {
LOCK(pfrom->cs_filter);
delete pfrom->pfilter;
pfrom->pfilter = new CBloomFilter(filter);
pfrom->pfilter->UpdateEmptyFull();
}
pfrom->fRelayTxes = true;
}
else if (strCommand == "filteradd") {
vector<unsigned char> vData;
vRecv >> vData;
// Nodes must NEVER send a data item > 520 bytes (the max size for a script data object,
// and thus, the maximum size any matched object can have) in a filteradd message
if (vData.size() > MAX_SCRIPT_ELEMENT_SIZE) {
Misbehaving(pfrom->GetId(), 100);
} else {
LOCK(pfrom->cs_filter);
if (pfrom->pfilter)
pfrom->pfilter->insert(vData);
else
Misbehaving(pfrom->GetId(), 100);
}
}
else if (strCommand == "filterclear") {
LOCK(pfrom->cs_filter);
delete pfrom->pfilter;
pfrom->pfilter = new CBloomFilter();
pfrom->fRelayTxes = true;
}
else if (strCommand == "reject") {
if (fDebug) {
try {
string strMsg;
unsigned char ccode;
string strReason;
vRecv >> LIMITED_STRING(strMsg, CMessageHeader::COMMAND_SIZE) >> ccode >> LIMITED_STRING(strReason, MAX_REJECT_MESSAGE_LENGTH);
ostringstream ss;
ss << strMsg << " code " << itostr(ccode) << ": " << strReason;
if (strMsg == "block" || strMsg == "tx") {
uint256 hash;
vRecv >> hash;
ss << ": hash " << hash.ToString();
}
LogPrint("net", "Reject %s\n", SanitizeString(ss.str()));
} catch (std::ios_base::failure& e) {
// Avoid feedback loops by preventing reject messages from triggering a new reject message.
LogPrint("net", "Unparseable reject message received\n");
}
}
} else {
//probably one the extensions
obfuScationPool.ProcessMessageObfuscation(pfrom, strCommand, vRecv);
mnodeman.ProcessMessage(pfrom, strCommand, vRecv);
budget.ProcessMessage(pfrom, strCommand, vRecv);
masternodePayments.ProcessMessageMasternodePayments(pfrom, strCommand, vRecv);
ProcessMessageSwiftTX(pfrom, strCommand, vRecv);
ProcessSpork(pfrom, strCommand, vRecv);
masternodeSync.ProcessMessage(pfrom, strCommand, vRecv);
}
return true;
}
// Note: whenever a protocol update is needed toggle between both implementations (comment out the formerly active one)
// so we can leave the existing clients untouched (old SPORK will stay on so they don't see even older clients).
// Those old clients won't react to the changes of the other (new) SPORK because at the time of their implementation
// it was the one which was commented out
int ActiveProtocol()
{
// SPORK_14 was used for 70910. Leave it 'ON' so they don't see > 70910 nodes. They won't react to SPORK_15
// messages because it's not in their code
/* if (IsSporkActive(SPORK_14_NEW_PROTOCOL_ENFORCEMENT))
return MIN_PEER_PROTO_VERSION_AFTER_ENFORCEMENT;
*/
// SPORK_15 is used for 70911. Nodes < 70911 don't see it and still get their protocol version via SPORK_14 and their
// own ModifierUpgradeBlock()
/*
if (IsSporkActive(SPORK_15_NEW_PROTOCOL_ENFORCEMENT_2))
return MIN_PEER_PROTO_VERSION_AFTER_ENFORCEMENT;
return MIN_PEER_PROTO_VERSION_BEFORE_ENFORCEMENT;
* */
return MIN_PEER_PROTO_VERSION_AFTER_ENFORCEMENT;
}
// requires LOCK(cs_vRecvMsg)
bool ProcessMessages(CNode* pfrom)
{
//if (fDebug)
// LogPrintf("ProcessMessages(%u messages)\n", pfrom->vRecvMsg.size());
//
// Message format
// (4) message start
// (12) command
// (4) size
// (4) checksum
// (x) data
//
bool fOk = true;
if (!pfrom->vRecvGetData.empty())
ProcessGetData(pfrom);
// this maintains the order of responses
if (!pfrom->vRecvGetData.empty()) return fOk;
std::deque<CNetMessage>::iterator it = pfrom->vRecvMsg.begin();
while (!pfrom->fDisconnect && it != pfrom->vRecvMsg.end()) {
// Don't bother if send buffer is too full to respond anyway
if (pfrom->nSendSize >= SendBufferSize())
break;
// get next message
CNetMessage& msg = *it;
//if (fDebug)
// LogPrintf("ProcessMessages(message %u msgsz, %u bytes, complete:%s)\n",
// msg.hdr.nMessageSize, msg.vRecv.size(),
// msg.complete() ? "Y" : "N");
// end, if an incomplete message is found
if (!msg.complete())
break;
// at this point, any failure means we can delete the current message
it++;
// Scan for message start
if (memcmp(msg.hdr.pchMessageStart, Params().MessageStart(), MESSAGE_START_SIZE) != 0) {
LogPrintf("PROCESSMESSAGE: INVALID MESSAGESTART %s peer=%d\n", SanitizeString(msg.hdr.GetCommand()), pfrom->id);
fOk = false;
break;
}
// Read header
CMessageHeader& hdr = msg.hdr;
if (!hdr.IsValid()) {
LogPrintf("PROCESSMESSAGE: ERRORS IN HEADER %s peer=%d\n", SanitizeString(hdr.GetCommand()), pfrom->id);
continue;
}
string strCommand = hdr.GetCommand();
// Message size
unsigned int nMessageSize = hdr.nMessageSize;
// Checksum
CDataStream& vRecv = msg.vRecv;
uint256 hash = Hash(vRecv.begin(), vRecv.begin() + nMessageSize);
unsigned int nChecksum = 0;
memcpy(&nChecksum, &hash, sizeof(nChecksum));
if (nChecksum != hdr.nChecksum) {
LogPrintf("ProcessMessages(%s, %u bytes): CHECKSUM ERROR nChecksum=%08x hdr.nChecksum=%08x\n",
SanitizeString(strCommand), nMessageSize, nChecksum, hdr.nChecksum);
continue;
}
// Process message
bool fRet = false;
try {
fRet = ProcessMessage(pfrom, strCommand, vRecv, msg.nTime);
boost::this_thread::interruption_point();
} catch (std::ios_base::failure& e) {
pfrom->PushMessage("reject", strCommand, REJECT_MALFORMED, string("error parsing message"));
if (strstr(e.what(), "end of data")) {
// Allow exceptions from under-length message on vRecv
LogPrintf("ProcessMessages(%s, %u bytes): Exception '%s' caught, normally caused by a message being shorter than its stated length\n", SanitizeString(strCommand), nMessageSize, e.what());
} else if (strstr(e.what(), "size too large")) {
// Allow exceptions from over-long size
LogPrintf("ProcessMessages(%s, %u bytes): Exception '%s' caught\n", SanitizeString(strCommand), nMessageSize, e.what());
} else {
PrintExceptionContinue(&e, "ProcessMessages()");
}
} catch (boost::thread_interrupted) {
throw;
} catch (std::exception& e) {
PrintExceptionContinue(&e, "ProcessMessages()");
} catch (...) {
PrintExceptionContinue(NULL, "ProcessMessages()");
}
if (!fRet)
LogPrintf("ProcessMessage(%s, %u bytes) FAILED peer=%d\n", SanitizeString(strCommand), nMessageSize, pfrom->id);
break;
}
// In case the connection got shut down, its receive buffer was wiped
if (!pfrom->fDisconnect)
pfrom->vRecvMsg.erase(pfrom->vRecvMsg.begin(), it);
return fOk;
}
bool SendMessages(CNode* pto, bool fSendTrickle)
{
{
// Don't send anything until we get their version message
if (pto->nVersion == 0)
return true;
//
// Message: ping
//
bool pingSend = false;
if (pto->fPingQueued) {
// RPC ping request by user
pingSend = true;
}
if (pto->nPingNonceSent == 0 && pto->nPingUsecStart + PING_INTERVAL * 1000000 < GetTimeMicros()) {
// Ping automatically sent as a latency probe & keepalive.
pingSend = true;
}
if (pingSend) {
uint64_t nonce = 0;
while (nonce == 0) {
GetRandBytes((unsigned char*)&nonce, sizeof(nonce));
}
pto->fPingQueued = false;
pto->nPingUsecStart = GetTimeMicros();
if (pto->nVersion > BIP0031_VERSION) {
pto->nPingNonceSent = nonce;
pto->PushMessage("ping", nonce);
} else {
// Peer is too old to support ping command with nonce, pong will never arrive.
pto->nPingNonceSent = 0;
pto->PushMessage("ping");
}
}
TRY_LOCK(cs_main, lockMain); // Acquire cs_main for IsInitialBlockDownload() and CNodeState()
if (!lockMain)
return true;
// Address refresh broadcast
static int64_t nLastRebroadcast;
if (!IsInitialBlockDownload() && (GetTime() - nLastRebroadcast > 24 * 60 * 60)) {
LOCK(cs_vNodes);
BOOST_FOREACH (CNode* pnode, vNodes) {
// Periodically clear setAddrKnown to allow refresh broadcasts
if (nLastRebroadcast)
pnode->setAddrKnown.clear();
// Rebroadcast our address
AdvertizeLocal(pnode);
}
if (!vNodes.empty())
nLastRebroadcast = GetTime();
}
//
// Message: addr
//
if (fSendTrickle) {
vector<CAddress> vAddr;
vAddr.reserve(pto->vAddrToSend.size());
BOOST_FOREACH (const CAddress& addr, pto->vAddrToSend) {
// returns true if wasn't already contained in the set
if (pto->setAddrKnown.insert(addr).second) {
vAddr.push_back(addr);
// receiver rejects addr messages larger than 1000
if (vAddr.size() >= 1000) {
pto->PushMessage("addr", vAddr);
vAddr.clear();
}
}
}
pto->vAddrToSend.clear();
if (!vAddr.empty())
pto->PushMessage("addr", vAddr);
}
CNodeState& state = *State(pto->GetId());
if (state.fShouldBan) {
if (pto->fWhitelisted)
LogPrintf("Warning: not punishing whitelisted peer %s!\n", pto->addr.ToString());
else {
pto->fDisconnect = true;
if (pto->addr.IsLocal())
LogPrintf("Warning: not banning local peer %s!\n", pto->addr.ToString());
else {
CNode::Ban(pto->addr);
}
}
state.fShouldBan = false;
}
BOOST_FOREACH (const CBlockReject& reject, state.rejects)
pto->PushMessage("reject", (string) "block", reject.chRejectCode, reject.strRejectReason, reject.hashBlock);
state.rejects.clear();
// Start block sync
if (pindexBestHeader == NULL)
pindexBestHeader = chainActive.Tip();
bool fFetch = state.fPreferredDownload || (nPreferredDownload == 0 && !pto->fClient && !pto->fOneShot); // Download if this is a nice peer, or we have no nice peers and this one might do.
if (!state.fSyncStarted && !pto->fClient && fFetch /*&& !fImporting*/ && !fReindex) {
// Only actively request headers from a single peer, unless we're close to end of initial download.
if (nSyncStarted == 0 || pindexBestHeader->GetBlockTime() > GetAdjustedTime() - 6 * 60 * 60) { // NOTE: was "close to today" and 24h in Bitcoin
state.fSyncStarted = true;
nSyncStarted++;
//CBlockIndex *pindexStart = pindexBestHeader->pprev ? pindexBestHeader->pprev : pindexBestHeader;
//LogPrint("net", "initial getheaders (%d) to peer=%d (startheight:%d)\n", pindexStart->nHeight, pto->id, pto->nStartingHeight);
//pto->PushMessage("getheaders", chainActive.GetLocator(pindexStart), uint256(0));
pto->PushMessage("getblocks", chainActive.GetLocator(chainActive.Tip()), uint256(0));
}
}
// Resend wallet transactions that haven't gotten in a block yet
// Except during reindex, importing and IBD, when old wallet
// transactions become unconfirmed and spams other nodes.
if (!fReindex /*&& !fImporting && !IsInitialBlockDownload()*/) {
g_signals.Broadcast();
}
//
// Message: inventory
//
vector<CInv> vInv;
vector<CInv> vInvWait;
{
LOCK(pto->cs_inventory);
vInv.reserve(pto->vInventoryToSend.size());
vInvWait.reserve(pto->vInventoryToSend.size());
BOOST_FOREACH (const CInv& inv, pto->vInventoryToSend) {
if (pto->setInventoryKnown.count(inv))
continue;
// trickle out tx inv to protect privacy
if (inv.type == MSG_TX && !fSendTrickle) {
// 1/4 of tx invs blast to all immediately
static uint256 hashSalt;
if (hashSalt == 0)
hashSalt = GetRandHash();
uint256 hashRand = inv.hash ^ hashSalt;
hashRand = Hash(BEGIN(hashRand), END(hashRand));
bool fTrickleWait = ((hashRand & 3) != 0);
if (fTrickleWait) {
vInvWait.push_back(inv);
continue;
}
}
// returns true if wasn't already contained in the set
if (pto->setInventoryKnown.insert(inv).second) {
vInv.push_back(inv);
if (vInv.size() >= 1000) {
pto->PushMessage("inv", vInv);
vInv.clear();
}
}
}
pto->vInventoryToSend = vInvWait;
}
if (!vInv.empty())
pto->PushMessage("inv", vInv);
// Detect whether we're stalling
int64_t nNow = GetTimeMicros();
if (!pto->fDisconnect && state.nStallingSince && state.nStallingSince < nNow - 1000000 * BLOCK_STALLING_TIMEOUT) {
// Stalling only triggers when the block download window cannot move. During normal steady state,
// the download window should be much larger than the to-be-downloaded set of blocks, so disconnection
// should only happen during initial block download.
LogPrintf("Peer=%d is stalling block download, disconnecting\n", pto->id);
pto->fDisconnect = true;
}
// In case there is a block that has been in flight from this peer for (2 + 0.5 * N) times the block interval
// (with N the number of validated blocks that were in flight at the time it was requested), disconnect due to
// timeout. We compensate for in-flight blocks to prevent killing off peers due to our own downstream link
// being saturated. We only count validated in-flight blocks so peers can't advertize nonexisting block hashes
// to unreasonably increase our timeout.
if (!pto->fDisconnect && state.vBlocksInFlight.size() > 0 && state.vBlocksInFlight.front().nTime < nNow - 500000 * Params().TargetSpacing() * (4 + state.vBlocksInFlight.front().nValidatedQueuedBefore)) {
LogPrintf("Timeout downloading block %s from peer=%d, disconnecting\n", state.vBlocksInFlight.front().hash.ToString(), pto->id);
pto->fDisconnect = true;
}
//
// Message: getdata (blocks)
//
vector<CInv> vGetData;
if (!pto->fDisconnect && !pto->fClient && fFetch && state.nBlocksInFlight < MAX_BLOCKS_IN_TRANSIT_PER_PEER) {
vector<CBlockIndex*> vToDownload;
NodeId staller = -1;
FindNextBlocksToDownload(pto->GetId(), MAX_BLOCKS_IN_TRANSIT_PER_PEER - state.nBlocksInFlight, vToDownload, staller);
BOOST_FOREACH (CBlockIndex* pindex, vToDownload) {
vGetData.push_back(CInv(MSG_BLOCK, pindex->GetBlockHash()));
MarkBlockAsInFlight(pto->GetId(), pindex->GetBlockHash(), pindex);
LogPrintf("Requesting block %s (%d) peer=%d\n", pindex->GetBlockHash().ToString(),
pindex->nHeight, pto->id);
}
if (state.nBlocksInFlight == 0 && staller != -1) {
if (State(staller)->nStallingSince == 0) {
State(staller)->nStallingSince = nNow;
LogPrint("net", "Stall started peer=%d\n", staller);
}
}
}
//
// Message: getdata (non-blocks)
//
while (!pto->fDisconnect && !pto->mapAskFor.empty() && (*pto->mapAskFor.begin()).first <= nNow) {
const CInv& inv = (*pto->mapAskFor.begin()).second;
if (!AlreadyHave(inv)) {
if (fDebug)
LogPrint("net", "Requesting %s peer=%d\n", inv.ToString(), pto->id);
vGetData.push_back(inv);
if (vGetData.size() >= 1000) {
pto->PushMessage("getdata", vGetData);
vGetData.clear();
}
}
pto->mapAskFor.erase(pto->mapAskFor.begin());
}
if (!vGetData.empty())
pto->PushMessage("getdata", vGetData);
}
return true;
}
bool CBlockUndo::WriteToDisk(CDiskBlockPos& pos, const uint256& hashBlock)
{
// Open history file to append
CAutoFile fileout(OpenUndoFile(pos), SER_DISK, CLIENT_VERSION);
if (fileout.IsNull())
return error("CBlockUndo::WriteToDisk : OpenUndoFile failed");
// Write index header
unsigned int nSize = fileout.GetSerializeSize(*this);
fileout << FLATDATA(Params().MessageStart()) << nSize;
// Write undo data
long fileOutPos = ftell(fileout.Get());
if (fileOutPos < 0)
return error("CBlockUndo::WriteToDisk : ftell failed");
pos.nPos = (unsigned int)fileOutPos;
fileout << *this;
// calculate & write checksum
CHashWriter hasher(SER_GETHASH, PROTOCOL_VERSION);
hasher << hashBlock;
hasher << *this;
fileout << hasher.GetHash();
return true;
}
bool CBlockUndo::ReadFromDisk(const CDiskBlockPos& pos, const uint256& hashBlock)
{
// Open history file to read
CAutoFile filein(OpenUndoFile(pos, true), SER_DISK, CLIENT_VERSION);
if (filein.IsNull())
return error("CBlockUndo::ReadFromDisk : OpenBlockFile failed");
// Read block
uint256 hashChecksum;
try {
filein >> *this;
filein >> hashChecksum;
} catch (std::exception& e) {
return error("%s : Deserialize or I/O error - %s", __func__, e.what());
}
// Verify checksum
CHashWriter hasher(SER_GETHASH, PROTOCOL_VERSION);
hasher << hashBlock;
hasher << *this;
if (hashChecksum != hasher.GetHash())
return error("CBlockUndo::ReadFromDisk : Checksum mismatch");
return true;
}
std::string CBlockFileInfo::ToString() const
{
return strprintf("CBlockFileInfo(blocks=%u, size=%u, heights=%u...%u, time=%s...%s)", nBlocks, nSize, nHeightFirst, nHeightLast, DateTimeStrFormat("%Y-%m-%d", nTimeFirst), DateTimeStrFormat("%Y-%m-%d", nTimeLast));
}
class CMainCleanup
{
public:
CMainCleanup() {}
~CMainCleanup()
{
// block headers
BlockMap::iterator it1 = mapBlockIndex.begin();
for (; it1 != mapBlockIndex.end(); it1++)
delete (*it1).second;
mapBlockIndex.clear();
// orphan transactions
mapOrphanTransactions.clear();
mapOrphanTransactionsByPrev.clear();
}
} instance_of_cmaincleanup;
|
// Fill out your copyright notice in the Description page of Project Settings.
#include "BBRoomBase.h"
#include "BBGuard.h"
#include "BBPlayerCharacterBase.h"
#include "BBLevel.h"
#include "BBUtilities.h"
#include "BBMainGameMode.h"
#include "Components/StaticMeshComponent.h"
#include "Materials/MaterialInstanceDynamic.h"
#include "BBLootLibrary.h"
#include "BBToolLibrary.h"
#include "BBPlayerCameraManager.h"
#include "BBRoomInfoList.h"
#include "Components/CapsuleComponent.h"
TArray<int32> ABBRoomBase::AmountAlarms;
ABBRoomBase::ABBRoomBase()
{
// Set this actor to call Tick() every frame. You can turn this off to improve performance if you don't need it.
PrimaryActorTick.bCanEverTick = true;
if (Walls.Num() == 0)
{
Walls.Add(EDirection::North, false);
Walls.Add(EDirection::East, false);
Walls.Add(EDirection::South, false);
Walls.Add(EDirection::West, false);
}
SceneRootComponent = CreateDefaultSubobject<USceneComponent>("SceneRoot");
RootComponent = SceneRootComponent;
FloorMesh = CreateDefaultSubobject<UStaticMeshComponent>("FloorMesh");
FloorMesh->SetupAttachment(RootComponent);
NorthWall = CreateDefaultSubobject<UStaticMeshComponent>("NorthWall");
NorthWall->SetupAttachment(RootComponent);
EastWall = CreateDefaultSubobject<UStaticMeshComponent>("EastWall");
EastWall->SetupAttachment(RootComponent);
SouthWall = CreateDefaultSubobject<UStaticMeshComponent>("SouthWall");
SouthWall->SetupAttachment(RootComponent);
WestWall = CreateDefaultSubobject<UStaticMeshComponent>("WestWall");
WestWall->SetupAttachment(RootComponent);
SelectionMesh = CreateDefaultSubobject<UStaticMeshComponent>("SelectionMesh");
SelectionMesh->SetupAttachment(RootComponent);
Player1Position = CreateDefaultSubobject<USceneComponent>("Player1Position");
Player1Position->SetupAttachment(RootComponent);
Player2Position = CreateDefaultSubobject<USceneComponent>("Player2Position");
Player2Position->SetupAttachment(RootComponent);
Player3Position = CreateDefaultSubobject<USceneComponent>("Player3Position");
Player3Position->SetupAttachment(RootComponent);
Player4Position = CreateDefaultSubobject<USceneComponent>("Player4Position");
Player4Position->SetupAttachment(RootComponent);
GuardPosition = CreateDefaultSubobject<USceneComponent>("GuardPosition");
GuardPosition->SetupAttachment(RootComponent);
RoomTypeWidget = CreateDefaultSubobject<UWidgetComponent>("RoomTypeWidget");
RoomTypeWidget->SetupAttachment(RootComponent);
SetWall(EDirection::North, Walls[EDirection::North]);
SetWall(EDirection::East, Walls[EDirection::East]);
SetWall(EDirection::South, Walls[EDirection::South]);
SetWall(EDirection::West, Walls[EDirection::West]);
FloorMesh->SetStaticMesh(DoorMesh);
ItemMarkerMesh = CreateDefaultSubobject<UStaticMeshComponent>("ItemMarkerMesh");
ItemMarkerMesh->SetupAttachment(RootComponent);
ItemMarkerWidget = CreateDefaultSubobject<UWidgetComponent>("ItemMarkerWidget");
ItemMarkerWidget->SetupAttachment(ItemMarkerMesh);
SetPosition(Position);
}
// Called when the game starts or when spawned
void ABBRoomBase::BeginPlay()
{
Super::BeginPlay();
RoomFunction = NewObject<UBBRoomFunctionComponent>(this, RoomFunctionClass, "RoomFunctionComponent");
RoomFunction->RegisterComponent();
UMaterialInterface* Material = NorthWall->GetMaterial(0);
NorthWallMaterialInstance = UMaterialInstanceDynamic::Create(Material, this);
NorthWall->SetMaterial(0, NorthWallMaterialInstance);
Material = EastWall->GetMaterial(0);
EastWallMaterialInstance = UMaterialInstanceDynamic::Create(Material, this);
EastWall->SetMaterial(0, EastWallMaterialInstance);
Material = SouthWall->GetMaterial(0);
SouthWallMaterialInstance = UMaterialInstanceDynamic::Create(Material, this);
SouthWall->SetMaterial(0, SouthWallMaterialInstance);
Material = WestWall->GetMaterial(0);
WestWallMaterialInstance = UMaterialInstanceDynamic::Create(Material, this);
WestWall->SetMaterial(0, WestWallMaterialInstance);
Material = SelectionMesh->GetMaterial(0);
SelectionMeshMaterialInstance = UMaterialInstanceDynamic::Create(Material, this);
SelectionMesh->SetMaterial(0, SelectionMeshMaterialInstance);
if (RoomType != ERoomType::Safe)
{
SafeCombinationNumber = FMath::RandRange(1, 6);
}
if (RoomType == ERoomType::Stairs)
{
bHasStairsUp = true;
}
else if (RoomType == ERoomType::Walkway)
{
bHasStairsDown = true;
}
else if (RoomType == ERoomType::Lavatory)
{
AmountStealthTokens = 3;
}
if (bStartDiscovered)
SetDiscovered();
}
void ABBRoomBase::SetRenderCustomDepth(bool IsEnabled)
{
FloorMesh->SetRenderCustomDepth(IsEnabled);
NorthWall->SetRenderCustomDepth(IsEnabled);
EastWall->SetRenderCustomDepth(IsEnabled);
SouthWall->SetRenderCustomDepth(IsEnabled);
WestWall->SetRenderCustomDepth(IsEnabled);
}
void ABBRoomBase::Tick(float DeltaTime)
{
Super::Tick(DeltaTime);
ABBPlayerCameraManager* CameraManger = UBBUtilities::GetPlayerCameraManager(this, 0);
if (ItemWidgetVisible() && CameraManger)
{
if (!ItemMarkerMesh->IsVisible())
{
ItemMarkerMesh->SetVisibility(true);
}
FRotator CameraRotation = CameraManger->GetCameraRotation();
ItemMarkerWidget->SetWorldRotation((-CameraRotation.Vector()).Rotation());
}
else
{
if (ItemMarkerMesh->IsVisible())
{
ItemMarkerMesh->SetVisibility(false);
}
}
}
void ABBRoomBase::SetWall(EDirection Direction, bool IsWall)
{
Walls[Direction] = IsWall;
switch (Direction)
{
case EDirection::North:
NorthWall->SetStaticMesh(IsWall ? WallMesh : DoorMesh);
break;
case EDirection::East:
EastWall->SetStaticMesh(IsWall ? WallMesh : DoorMesh);
break;
case EDirection::South:
SouthWall->SetStaticMesh(IsWall ? WallMesh : DoorMesh);
break;
case EDirection::West:
WestWall->SetStaticMesh(IsWall ? WallMesh : DoorMesh);
break;
}
UpdateWalls();
}
void ABBRoomBase::SetWallColors()
{
FLinearColor RoomDiscoveredColor;
if (RoomInfoList)
RoomDiscoveredColor = RoomInfoList->GetRoomByType(RoomType)->DiscoveredColor;
if (NorthWallMaterialInstance)
NorthWallMaterialInstance->SetVectorParameterValue("WallColor", bIsDiscovered ? RoomDiscoveredColor : FLinearColor(1, 1, 1, 1));
if (EastWallMaterialInstance)
EastWallMaterialInstance->SetVectorParameterValue("WallColor", bIsDiscovered ? RoomDiscoveredColor : FLinearColor(1, 1, 1, 1));
if (SouthWallMaterialInstance)
SouthWallMaterialInstance->SetVectorParameterValue("WallColor", bIsDiscovered ? RoomDiscoveredColor : FLinearColor(1, 1, 1, 1));
if (WestWallMaterialInstance)
WestWallMaterialInstance->SetVectorParameterValue("WallColor", bIsDiscovered ? RoomDiscoveredColor : FLinearColor(1, 1, 1, 1));
}
void ABBRoomBase::SetPosition(int32 PosX, int32 PosY, int32 Floor)
{
SetPosition(FRoomPosition(PosX, PosY, Floor));
}
void ABBRoomBase::SetPosition(FRoomPosition RoomPosition)
{
Position = RoomPosition;
FText PositionText = FText::FromString(FString::Printf(TEXT("%d | %d"), Position.PosX, Position.PosY));
}
void ABBRoomBase::UpdateWalls()
{
SetWallColors();
}
void ABBRoomBase::SetHidden(bool IsHidden)
{
SetActorHiddenInGame(IsHidden);
ECollisionResponse Response = IsHidden ? ECollisionResponse::ECR_Ignore : ECollisionResponse::ECR_Block;
FloorMesh->SetCollisionResponseToChannel(ECC_Visibility, Response);
NorthWall->SetCollisionResponseToChannel(ECC_Visibility, Response);
EastWall->SetCollisionResponseToChannel(ECC_Visibility, Response);
SouthWall->SetCollisionResponseToChannel(ECC_Visibility, Response);
WestWall->SetCollisionResponseToChannel(ECC_Visibility, Response);
for (ABBCharacterBase* Character : CharactersInRoom)
{
Character->SetCharacterHidden(IsHidden);
Character->GetCapsuleComponent()->SetCollisionResponseToChannel(ECC_Visibility, Response);
}
}
bool ABBRoomBase::IsSameFloor(ABBRoomBase* Other)
{
if (!Other)
return false;
return Position.Floor == Other->Position.Floor;
}
FVector ABBRoomBase::GetFreePlayerPosition()
{
TArray<ABBCharacterBase*> PlayerCharacters = CharactersInRoom.FilterByPredicate([](ABBCharacterBase* Character)
{
return Cast<ABBPlayerCharacterBase>(Character);
});
int32 PlayersPresent = PlayerCharacters.Num();
switch (PlayersPresent)
{
case 0:
return Player1Position->GetComponentLocation();
case 1:
return Player2Position->GetComponentLocation();
case 2:
return Player3Position->GetComponentLocation();
default:
return Player4Position->GetComponentLocation();
}
}
FVector ABBRoomBase::GetGuardPosition()
{
return GuardPosition->GetComponentLocation();
}
void ABBRoomBase::TeleportToRoom(class ABBCharacterBase* Character, bool FocusCameraOnCharacter /*= true*/)
{
FVector Offset(0.f, 0.f, 100.f);
if (Cast<ABBGuard>(Character))
{
Character->SetActorLocation(GetGuardPosition() + Offset);
}
else
{
Character->SetActorLocation(GetFreePlayerPosition() + Offset);
if (FocusCameraOnCharacter)
UBBUtilities::GetPlayerCameraManager(this, 0)->FocusOnViewTarget();
}
}
bool ABBRoomBase::ContainsCharacter(ABBCharacterBase* Character)
{
return CharactersInRoom.Contains(Character);
}
bool ABBRoomBase::ContainsGuard()
{
if (CharactersInRoom.Num() == 0)
return false;
for (ABBCharacterBase* Character : CharactersInRoom)
{
if (Cast<ABBGuard>(Character))
{
return true;
}
}
return false;
}
bool ABBRoomBase::EnterRoom(ABBCharacterBase* Character, bool IgnoreEffects, bool IgnoreCosts)
{
bool IsNotBlocked = OnRoomEntered(Character, IgnoreEffects, IgnoreCosts);
CharactersInRoom.AddUnique(Character);
if (Cast<ABBGuard>(Character))
{
return true;
}
return IsNotBlocked;
}
void ABBRoomBase::LeaveRoom(ABBCharacterBase* Character)
{
OnRoomLeft(Character);
CharactersInRoom.Remove(Character);
}
bool ABBRoomBase::CanEnterRoom(ABBCharacterBase* Character)
{
return RoomFunction->CanEnter(Character);
}
void ABBRoomBase::SetDiscovered()
{
if (!bIsDiscovered)
{
bIsDiscovered = true;
SetWallColors();
ABBMainGameMode* GameMode = UBBUtilities::GetMainGameMode(this);
if (GameMode)
GameMode->UpdateSelectedRoom();
}
}
UBBRoomFunctionComponent* ABBRoomBase::GetRoomFunction() const
{
return RoomFunction;
}
class UBBRoomInfo* ABBRoomBase::GetRoomInfo() const
{
if (RoomInfoList)
{
return RoomInfoList->GetRoomByType(RoomType);
}
return nullptr;
}
bool ABBRoomBase::ItemWidgetVisible()
{
return bHasAlarm
|| (bIsDiscovered && (bHasStairsUp || bHasStairsDown))
|| bContainsRaven
|| bContainsRavenAlt
|| (bIsDiscovered && AmountStealthTokens > 0)
|| ToolsInRoom.Num() > 0
|| LootInRoom.Num() > 0;
}
bool ABBRoomBase::OnRoomEntered(ABBCharacterBase* Character, bool IgnoreEffects, bool IgnoreCosts)
{
bool IsNotBlocked = RoomFunction->OnEnter(Character, IgnoreEffects, IgnoreCosts);
if (Cast<ABBGuard>(Character))
{
OnRoomCharacterEnter.Broadcast(Character);
return true;
}
else
{
SetDiscovered();
if (!CurrentLevel->GetFloor(Position.Floor).bIsRevealed)
{
CurrentLevel->GetFloor(Position.Floor).RevealFloor();
}
if (IsNotBlocked)
{
ABBPlayerCharacterBase* PlayerCharacter = Cast<ABBPlayerCharacterBase>(Character);
if (LootInRoom.Num() > 0)
{
for (int32 Index = LootInRoom.Num() - 1; Index >= 0; Index--)
{
ELootType Loot = LootInRoom[Index];
if (!(Loot == ELootType::GoldBar && PlayerCharacter->Loot.Contains(ELootType::GoldBar)))
{
RemoveLootFromRoom(Loot);
UBBLootLibrary::AttachLootToPlayer(Loot, PlayerCharacter);
}
}
}
if (ToolsInRoom.Num() > 0)
{
for (int32 Index = ToolsInRoom.Num() - 1; Index >= 0; Index--)
{
EToolType Tool = ToolsInRoom[Index];
PlayerCharacter->Tools.Add(Tool);
ToolsInRoom.RemoveAt(Index);
}
}
}
}
OnRoomCharacterEnter.Broadcast(Character);
return IsNotBlocked;
}
void ABBRoomBase::OnRoomLeft(ABBCharacterBase* Character)
{
RoomFunction->OnLeave(Character);
OnRoomCharacterLeave.Broadcast(Character);
}
void ABBRoomBase::SetAlarm(bool HasAlarm)
{
if (HasAlarm && UBBToolLibrary::ActiveTools.Contains(EToolType::EMP))
{
return;
}
bool AlarmChanged = bHasAlarm != HasAlarm;
bHasAlarm = HasAlarm;
if (!AlarmChanged)
return;
if (HasAlarm)
{
++AmountAlarms[Position.Floor];
}
else
{
--AmountAlarms[Position.Floor];
}
OnAlarmChanged.Broadcast(bHasAlarm);
OnRoomItemChanged.Broadcast();
}
void ABBRoomBase::SetSelected(bool IsSelected)
{
bIsSelected = IsSelected;
if (bIsSelected)
{
SetHovered(false);
}
SelectionMesh->SetVisibility(IsSelected);
SelectionMeshMaterialInstance->SetVectorParameterValue("Color", SelectedColor);
}
void ABBRoomBase::SetHovered(bool IsHovered)
{
if (bIsSelected)
return;
bIsHovered = IsHovered;
SelectionMesh->SetVisibility(bIsHovered);
SelectionMeshMaterialInstance->SetVectorParameterValue("Color", HoveredColor);
}
void ABBRoomBase::SetHasStairsDown(bool HasStairs)
{
bHasStairsDown = HasStairs;
}
void ABBRoomBase::SetHasStairsUp(bool HasStairs)
{
bHasStairsUp = HasStairs;
}
void ABBRoomBase::MoveDown(class ABBPlayerCharacterBase* Character)
{
ABBRoomBase* RoomBelow = CurrentLevel->GetRoomAt(Position.GetBelowRoomPosition());
if (!RoomBelow || !Character)
return;
LeaveRoom(Character);
RoomBelow->EnterRoom(Character);
RoomBelow->TeleportToRoom(Character);
}
ERoomType ABBRoomBase::GetRoomType()
{
return RoomType;
}
bool ABBRoomBase::HasAlarm()
{
return bHasAlarm;
}
bool ABBRoomBase::IsDiscovered()
{
return bIsDiscovered;
}
bool ABBRoomBase::HasStairsUp()
{
return bHasStairsUp;
}
bool ABBRoomBase::HasStairsDown()
{
return bHasStairsDown;
}
bool ABBRoomBase::IsSafeCombinationNumberCracked()
{
return bSafeCombinationNumberCracked;
}
bool ABBRoomBase::ContainsRaven(bool IsAltRaven)
{
if (IsAltRaven)
return bContainsRavenAlt;
return bContainsRaven;
}
int32 ABBRoomBase::GetSafeCombinationNumber()
{
return SafeCombinationNumber;
}
TArray<ELootType> ABBRoomBase::GetLootInRoom()
{
return TArray<ELootType>(LootInRoom);
}
TArray<EToolType> ABBRoomBase::GetToolsInRoom()
{
return TArray<EToolType>(ToolsInRoom);
}
bool ABBRoomBase::IsAlarmRoom()
{
return RoomType == ERoomType::Camera
|| RoomType == ERoomType::Detector
|| RoomType == ERoomType::Laser
|| RoomType == ERoomType::Motion
|| RoomType == ERoomType::Thermo
|| RoomType == ERoomType::Fingerprint;
}
void ABBRoomBase::AddLootToRoom(ELootType Loot)
{
LootInRoom.Add(Loot);
OnRoomItemChanged.Broadcast();
}
void ABBRoomBase::AddToolToRoom(EToolType Tool)
{
ToolsInRoom.Add(Tool);
OnRoomItemChanged.Broadcast();
}
void ABBRoomBase::RemoveLootFromRoom(ELootType Loot)
{
LootInRoom.RemoveSingle(Loot);
OnRoomItemChanged.Broadcast();
}
void ABBRoomBase::RemoveToolToRoom(EToolType Tool)
{
ToolsInRoom.Remove(Tool);
OnRoomItemChanged.Broadcast();
}
void ABBRoomBase::SetRavenInRoom(bool HasRaven, bool IsAltRaven)
{
if (IsAltRaven)
{
bContainsRavenAlt = HasRaven;
}
else
{
bContainsRaven = HasRaven;
}
OnRoomItemChanged.Broadcast();
}
|
//Author:LanceYu
#include<iostream>
#include<string>
#include<cstring>
#include<cstdio>
#include<fstream>
#include<iosfwd>
#include<vector>
#include<cstdlib>
#include<queue>
#include<set>
#include<ctime>
#include<algorithm>
#include<complex>
#include<cmath>
#include<array>
#include<valarray>
#include<bitset>
#define ll long long
using namespace std;
const double clf=1e-8;
//const double e=2.718281828;
const double PI=3.141592653589793;
const int MMAX=2147483647;
const int mod=1e9+7;
//priority_queue<int>p;
//priority_queue<int,vector<int>,greater<int> >pq;
char s1[100001],s2[100001];
int main()
{
//freopen("C:\\Users\\LENOVO\\Desktop\\in.txt","r",stdin);
//freopen("C:\\Users\\LENOVO\\Desktop\\out.txt","w",stdout);
while(scanf("%s%s",s1,s2)!=EOF)
{
int len1=strlen(s1);
int len2=strlen(s2);
int num=0;
for(int i=0;i<len2;i++)
{
if(s2[i]==s1[num])
num++;
}
if(num==len1)
printf("Yes\n");
else
printf("No\n");
}
return 0;
}
|
#ifndef __SIMPLE3DOBJECT_INCLUDE__
#define __SIMPLE3DOBJECT_INCLUDE__
#include <sl/Camera.hpp>
#include <GL/glew.h>
#include <GL/freeglut.h>
#include <mutex>
class Shader{
public:
Shader(GLchar* vs, GLchar* fs);
~Shader();
GLuint getProgramId();
static const GLint ATTRIB_VERTICES_POS = 0;
private:
bool compile(GLuint &shaderId, GLenum type, GLchar* src);
GLuint verterxId_;
GLuint fragmentId_;
GLuint programId_;
};
class SubMapObj {
GLuint vaoID_;
GLuint vboID_[2];
int current_fc;
bool need_update;
bool isUpdating;
std::vector<sl::float3> vert;
std::vector<sl::uint3> tri;
std::vector<sl::uint1> index;
public:
bool display_mesh;
SubMapObj();
~SubMapObj();
template<typename T>
void update(T &chunks);
void pushToGPU();
void draw();
};
class GLViewer {
public:
GLViewer();
~GLViewer();
bool isAvailable();
bool init(int argc, char **argv, sl::CameraParameters);
bool updateImageAndState(sl::Mat &image, sl::Transform &pose, sl::TRACKING_STATE track_state, sl::SPATIAL_MAPPING_STATE mapp_state);
template<typename T>
void updateMap(T &map);
void clearCurrentMesh();
void exit();
private:
// Rendering loop method called each frame by glutDisplayFunc
void render();
// Everything that needs to be updated before rendering must be done in this method
void update();
// Once everything is updated, every renderable objects must be drawn in this method
void draw();
void printText();
static void drawCallback();
static void keyReleasedCallback(unsigned char c, int x, int y);
std::mutex mtx;
bool available;
bool change_state;
// For CUDA-OpenGL interoperability
cudaGraphicsResource* cuda_gl_ressource;//cuda GL resource
// OpenGL mesh container
std::vector<SubMapObj> sub_maps; // Opengl mesh container
sl::float3 vertices_color; // Defines the color of the mesh
// OpenGL camera projection matrix
sl::Transform camera_projection;
sl::Mat image;
sl::Transform pose;
sl::TRACKING_STATE tracking_state;
sl::SPATIAL_MAPPING_STATE mapping_state;
bool new_data;
bool ask_clear;
// Opengl object
Shader *shader_mesh; //GLSL Shader for mesh
Shader *shader_image;//GLSL Shader for image
GLuint imageTex; //OpenGL texture mapped with a cuda array (opengl gpu interop)
GLuint shMVPMatrixLoc; //Shader variable loc
GLuint shColorLoc; //Shader variable loc
GLuint texID; //Shader variable loc (sampler/texture)
GLuint fbo = 0; //FBO
GLuint renderedTexture = 0; //Render Texture for FBO
GLuint quad_vb; //buffer for vertices/coords for image
};
/* Find MyDocuments directory for windows platforms.*/
std::string getDir();
#endif
|
// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/base_switches.h"
#include "base/command_line.h"
#include "base/hi_res_timer_manager.h"
#include "base/message_loop.h"
#include "base/string_util.h"
#include "base/system_monitor/system_monitor.h"
#include "base/threading/platform_thread.h"
#include "content/common/child_process.h"
#include "content/public/common/main_function_params.h"
#include "content/public/common/sandbox_init.h"
#include "content/worker/worker_thread.h"
#if defined(OS_WIN)
#include "sandbox/win/src/sandbox.h"
#endif
// Mainline routine for running as the worker process.
int WorkerMain(const content::MainFunctionParams& parameters) {
// The main message loop of the worker process.
MessageLoop main_message_loop;
base::PlatformThread::SetName("CrWorkerMain");
base::SystemMonitor system_monitor;
HighResolutionTimerManager hi_res_timer_manager;
ChildProcess worker_process;
worker_process.set_main_thread(new WorkerThread());
#if defined(OS_WIN)
sandbox::TargetServices* target_services =
parameters.sandbox_info->target_services;
if (!target_services)
return false;
// Cause advapi32 to load before the sandbox is turned on.
unsigned int dummy_rand;
rand_s(&dummy_rand);
// Warm up language subsystems before the sandbox is turned on.
::GetUserDefaultLangID();
::GetUserDefaultLCID();
target_services->LowerToken();
#endif
#if defined(OS_LINUX)
content::InitializeSandbox();
#endif
const CommandLine& parsed_command_line = parameters.command_line;
if (parsed_command_line.HasSwitch(switches::kWaitForDebugger)) {
ChildProcess::WaitForDebugger("Worker");
}
// Load the accelerator table from the browser executable and tell the
// message loop to use it when translating messages.
MessageLoop::current()->Run();
return 0;
}
|
// Copyright (c) 2011-2013 The Bitcoin developers
// Copyright (c) 2017-2019 The HodlCash developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "notificator.h"
#include <QApplication>
#include <QByteArray>
#include <QIcon>
#include <QImageWriter>
#include <QMessageBox>
#include <QMetaType>
#include <QStyle>
#include <QSystemTrayIcon>
#include <QTemporaryFile>
#include <QVariant>
#ifdef USE_DBUS
#include <QtDBus>
#include <stdint.h>
#endif
// Include ApplicationServices.h after QtDbus to avoid redefinition of check().
// This affects at least OSX 10.6. See /usr/include/AssertMacros.h for details.
// Note: This could also be worked around using:
// #define __ASSERT_MACROS_DEFINE_VERSIONS_WITHOUT_UNDERSCORES 0
#ifdef Q_OS_MAC
#include "macnotificationhandler.h"
#include <ApplicationServices/ApplicationServices.h>
#endif
#ifdef USE_DBUS
// https://wiki.ubuntu.com/NotificationDevelopmentGuidelines recommends at least 128
const int FREEDESKTOP_NOTIFICATION_ICON_SIZE = 128;
#endif
Notificator::Notificator(const QString& programName, QSystemTrayIcon* trayicon, QWidget* parent) : QObject(parent),
parent(parent),
programName(programName),
mode(None),
trayIcon(trayicon)
#ifdef USE_DBUS
,
interface(0)
#endif
{
if (trayicon && trayicon->supportsMessages()) {
mode = QSystemTray;
}
#ifdef USE_DBUS
interface = new QDBusInterface("org.freedesktop.Notifications",
"/org/freedesktop/Notifications", "org.freedesktop.Notifications");
if (interface->isValid()) {
mode = Freedesktop;
}
#endif
#ifdef Q_OS_MAC
// check if users OS has support for NSUserNotification
if (MacNotificationHandler::instance()->hasUserNotificationCenterSupport()) {
mode = UserNotificationCenter;
}
#endif
}
Notificator::~Notificator()
{
#ifdef USE_DBUS
delete interface;
#endif
}
#ifdef USE_DBUS
// Loosely based on http://www.qtcentre.org/archive/index.php/t-25879.html
class FreedesktopImage
{
public:
FreedesktopImage() {}
FreedesktopImage(const QImage& img);
static int metaType();
// Image to variant that can be marshalled over DBus
static QVariant toVariant(const QImage& img);
private:
int width, height, stride;
bool hasAlpha;
int channels;
int bitsPerSample;
QByteArray image;
friend QDBusArgument& operator<<(QDBusArgument& a, const FreedesktopImage& i);
friend const QDBusArgument& operator>>(const QDBusArgument& a, FreedesktopImage& i);
};
Q_DECLARE_METATYPE(FreedesktopImage);
// Image configuration settings
const int CHANNELS = 4;
const int BYTES_PER_PIXEL = 4;
const int BITS_PER_SAMPLE = 8;
FreedesktopImage::FreedesktopImage(const QImage& img) : width(img.width()),
height(img.height()),
stride(img.width() * BYTES_PER_PIXEL),
hasAlpha(true),
channels(CHANNELS),
bitsPerSample(BITS_PER_SAMPLE)
{
// Convert 00xAARRGGBB to RGBA bytewise (endian-independent) format
QImage tmp = img.convertToFormat(QImage::Format_ARGB32);
const uint32_t* data = reinterpret_cast<const uint32_t*>(tmp.bits());
unsigned int num_pixels = width * height;
image.resize(num_pixels * BYTES_PER_PIXEL);
for (unsigned int ptr = 0; ptr < num_pixels; ++ptr) {
image[ptr * BYTES_PER_PIXEL + 0] = data[ptr] >> 16; // R
image[ptr * BYTES_PER_PIXEL + 1] = data[ptr] >> 8; // G
image[ptr * BYTES_PER_PIXEL + 2] = data[ptr]; // B
image[ptr * BYTES_PER_PIXEL + 3] = data[ptr] >> 24; // A
}
}
QDBusArgument& operator<<(QDBusArgument& a, const FreedesktopImage& i)
{
a.beginStructure();
a << i.width << i.height << i.stride << i.hasAlpha << i.bitsPerSample << i.channels << i.image;
a.endStructure();
return a;
}
const QDBusArgument& operator>>(const QDBusArgument& a, FreedesktopImage& i)
{
a.beginStructure();
a >> i.width >> i.height >> i.stride >> i.hasAlpha >> i.bitsPerSample >> i.channels >> i.image;
a.endStructure();
return a;
}
int FreedesktopImage::metaType()
{
return qDBusRegisterMetaType<FreedesktopImage>();
}
QVariant FreedesktopImage::toVariant(const QImage& img)
{
FreedesktopImage fimg(img);
return QVariant(FreedesktopImage::metaType(), &fimg);
}
void Notificator::notifyDBus(Class cls, const QString& title, const QString& text, const QIcon& icon, int millisTimeout)
{
Q_UNUSED(cls);
// Arguments for DBus call:
QList<QVariant> args;
// Program Name:
args.append(programName);
// Unique ID of this notification type:
args.append(0U);
// Application Icon, empty string
args.append(QString());
// Summary
args.append(title);
// Body
args.append(text);
// Actions (none, actions are deprecated)
QStringList actions;
args.append(actions);
// Hints
QVariantMap hints;
// If no icon specified, set icon based on class
QIcon tmpicon;
if (icon.isNull()) {
QStyle::StandardPixmap sicon = QStyle::SP_MessageBoxQuestion;
switch (cls) {
case Information:
sicon = QStyle::SP_MessageBoxInformation;
break;
case Warning:
sicon = QStyle::SP_MessageBoxWarning;
break;
case Critical:
sicon = QStyle::SP_MessageBoxCritical;
break;
default:
break;
}
tmpicon = QApplication::style()->standardIcon(sicon);
} else {
tmpicon = icon;
}
hints["icon_data"] = FreedesktopImage::toVariant(tmpicon.pixmap(FREEDESKTOP_NOTIFICATION_ICON_SIZE).toImage());
args.append(hints);
// Timeout (in msec)
args.append(millisTimeout);
// "Fire and forget"
interface->callWithArgumentList(QDBus::NoBlock, "Notify", args);
}
#endif
void Notificator::notifySystray(Class cls, const QString& title, const QString& text, const QIcon& icon, int millisTimeout)
{
Q_UNUSED(icon);
QSystemTrayIcon::MessageIcon sicon = QSystemTrayIcon::NoIcon;
switch (cls) // Set icon based on class
{
case Information:
sicon = QSystemTrayIcon::Information;
break;
case Warning:
sicon = QSystemTrayIcon::Warning;
break;
case Critical:
sicon = QSystemTrayIcon::Critical;
break;
}
trayIcon->showMessage(title, text, sicon, millisTimeout);
}
// Based on Qt's tray icon implementation
#ifdef Q_OS_MAC
void Notificator::notifyMacUserNotificationCenter(Class cls, const QString& title, const QString& text, const QIcon& icon)
{
// icon is not supported by the user notification center yet. OSX will use the app icon.
MacNotificationHandler::instance()->showNotification(title, text);
}
#endif
void Notificator::notify(Class cls, const QString& title, const QString& text, const QIcon& icon, int millisTimeout)
{
switch (mode) {
#ifdef USE_DBUS
case Freedesktop:
notifyDBus(cls, title, text, icon, millisTimeout);
break;
#endif
case QSystemTray:
notifySystray(cls, title, text, icon, millisTimeout);
break;
#ifdef Q_OS_MAC
case UserNotificationCenter:
notifyMacUserNotificationCenter(cls, title, text, icon);
break;
#endif
default:
if (cls == Critical) {
// Fall back to old fashioned pop-up dialog if critical and no other notification available
QMessageBox::critical(parent, title, text, QMessageBox::Ok, QMessageBox::Ok);
}
break;
}
}
|
// Copyright 2020 Makani Technologies LLC
//
// 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 <glog/logging.h>
#include <csignal>
#include "common/macros.h"
#include "lib/logger/logger.h"
int main(int argc, char *argv[]) {
UNUSED(argc);
UNUSED(argv);
auto logger = logger::Logger::GetInstance();
signal(SIGTERM, logger.HandleStopSignal);
signal(SIGINT, logger.HandleStopSignal);
bool success = logger.Start();
return success ? EXIT_SUCCESS : EXIT_FAILURE;
}
|
/*
TinyGPS++ - a small GPS library for Arduino providing universal NMEA parsing
Based on work by and "distanceBetween" and "courseTo" courtesy of Maarten Lamers.
Suggestion to add satellites, courseTo(), and cardinal() by Matt Monson.
Location precision improvements suggested by Wayne Holder.
Copyright (C) 2008-2013 Mikal Hart
All rights reserved.
This 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 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "TinyGPS++.h"
#include <string.h>
#include <ctype.h>
#include <stdlib.h>
#define _GPRMCterm "GPRMC"
#define _GPGGAterm "GPGGA"
#define _GNRMCterm "GNRMC"
#define _GNGGAterm "GNGGA"
TinyGPSPlus::TinyGPSPlus()
: parity(0)
, isChecksumTerm(false)
, curSentenceType(GPS_SENTENCE_OTHER)
, curTermNumber(0)
, curTermOffset(0)
, sentenceHasFix(false)
, customElts(0)
, customCandidates(0)
, encodedCharCount(0)
, sentencesWithFixCount(0)
, failedChecksumCount(0)
, passedChecksumCount(0)
{
term[0] = '\0';
}
//
// public methods
//
bool TinyGPSPlus::encode(char c)
{
++encodedCharCount;
switch(c)
{
case ',': // term terminators
parity ^= (uint8_t)c;
case '\r':
case '\n':
case '*':
{
bool isValidSentence = false;
if (curTermOffset < sizeof(term))
{
term[curTermOffset] = 0;
isValidSentence = endOfTermHandler();
}
++curTermNumber;
curTermOffset = 0;
isChecksumTerm = c == '*';
return isValidSentence;
}
break;
case '$': // sentence begin
curTermNumber = curTermOffset = 0;
parity = 0;
curSentenceType = GPS_SENTENCE_OTHER;
isChecksumTerm = false;
sentenceHasFix = false;
return false;
default: // ordinary characters
if (curTermOffset < sizeof(term) - 1)
term[curTermOffset++] = c;
if (!isChecksumTerm)
parity ^= c;
return false;
}
return false;
}
//
// internal utilities
//
int TinyGPSPlus::fromHex(char a)
{
if (a >= 'A' && a <= 'F')
return a - 'A' + 10;
else if (a >= 'a' && a <= 'f')
return a - 'a' + 10;
else
return a - '0';
}
// static
// Parse a (potentially negative) number with up to 2 decimal digits -xxxx.yy
int32_t TinyGPSPlus::parseDecimal(const char *term)
{
bool negative = *term == '-';
if (negative) ++term;
int32_t ret = 100 * (int32_t)atol(term);
while (isdigit(*term)) ++term;
if (*term == '.' && isdigit(term[1]))
{
ret += 10 * (term[1] - '0');
if (isdigit(term[2]))
ret += term[2] - '0';
}
return negative ? -ret : ret;
}
// static
// Parse degrees in that funny NMEA format DDMM.MMMM
void TinyGPSPlus::parseDegrees(const char *term, RawDegrees °)
{
uint32_t leftOfDecimal = (uint32_t)atol(term);
uint16_t minutes = (uint16_t)(leftOfDecimal % 100);
uint32_t multiplier = 10000000UL;
uint32_t tenMillionthsOfMinutes = minutes * multiplier;
deg.deg = (int16_t)(leftOfDecimal / 100);
while (isdigit(*term))
++term;
if (*term == '.')
while (isdigit(*++term))
{
multiplier /= 10;
tenMillionthsOfMinutes += (*term - '0') * multiplier;
}
deg.billionths = (5 * tenMillionthsOfMinutes + 1) / 3;
deg.negative = false;
}
#define COMBINE(sentence_type, term_number) (((unsigned)(sentence_type) << 5) | term_number)
// Processes a just-completed term
// Returns true if new sentence has just passed checksum test and is validated
bool TinyGPSPlus::endOfTermHandler()
{
// If it's the checksum term, and the checksum checks out, commit
if (isChecksumTerm)
{
byte checksum = 16 * fromHex(term[0]) + fromHex(term[1]);
if (checksum == parity)
{
passedChecksumCount++;
if (sentenceHasFix)
++sentencesWithFixCount;
switch(curSentenceType)
{
case GPS_SENTENCE_GPRMC:
date.commit();
time.commit();
if (sentenceHasFix)
{
location.commit();
speed.commit();
course.commit();
}
break;
case GPS_SENTENCE_GPGGA:
time.commit();
if (sentenceHasFix)
{
location.commit();
altitude.commit();
}
satellites.commit();
hdop.commit();
break;
}
// Commit all custom listeners of this sentence type
for (TinyGPSCustom *p = customCandidates; p != NULL && strcmp(p->sentenceName, customCandidates->sentenceName) == 0; p = p->next)
p->commit();
return true;
}
else
{
++failedChecksumCount;
}
return false;
}
// the first term determines the sentence type
if (curTermNumber == 0)
{
if (!strcmp(term, _GPRMCterm) || !strcmp(term, _GNRMCterm))
curSentenceType = GPS_SENTENCE_GPRMC;
else if (!strcmp(term, _GPGGAterm) || !strcmp(term, _GNGGAterm))
curSentenceType = GPS_SENTENCE_GPGGA;
else
curSentenceType = GPS_SENTENCE_OTHER;
// Any custom candidates of this sentence type?
for (customCandidates = customElts; customCandidates != NULL && strcmp(customCandidates->sentenceName, term) < 0; customCandidates = customCandidates->next);
if (customCandidates != NULL && strcmp(customCandidates->sentenceName, term) > 0)
customCandidates = NULL;
return false;
}
if (curSentenceType != GPS_SENTENCE_OTHER && term[0])
switch(COMBINE(curSentenceType, curTermNumber))
{
case COMBINE(GPS_SENTENCE_GPRMC, 1): // Time in both sentences
case COMBINE(GPS_SENTENCE_GPGGA, 1):
time.setTime(term);
break;
case COMBINE(GPS_SENTENCE_GPRMC, 2): // GPRMC validity
sentenceHasFix = term[0] == 'A';
break;
case COMBINE(GPS_SENTENCE_GPRMC, 3): // Latitude
case COMBINE(GPS_SENTENCE_GPGGA, 2):
location.setLatitude(term);
break;
case COMBINE(GPS_SENTENCE_GPRMC, 4): // N/S
case COMBINE(GPS_SENTENCE_GPGGA, 3):
location.rawNewLatData.negative = term[0] == 'S';
break;
case COMBINE(GPS_SENTENCE_GPRMC, 5): // Longitude
case COMBINE(GPS_SENTENCE_GPGGA, 4):
location.setLongitude(term);
break;
case COMBINE(GPS_SENTENCE_GPRMC, 6): // E/W
case COMBINE(GPS_SENTENCE_GPGGA, 5):
location.rawNewLngData.negative = term[0] == 'W';
break;
case COMBINE(GPS_SENTENCE_GPRMC, 7): // Speed (GPRMC)
speed.set(term);
break;
case COMBINE(GPS_SENTENCE_GPRMC, 8): // Course (GPRMC)
course.set(term);
break;
case COMBINE(GPS_SENTENCE_GPRMC, 9): // Date (GPRMC)
date.setDate(term);
break;
case COMBINE(GPS_SENTENCE_GPGGA, 6): // Fix data (GPGGA)
sentenceHasFix = term[0] > '0';
break;
case COMBINE(GPS_SENTENCE_GPGGA, 7): // Satellites used (GPGGA)
satellites.set(term);
break;
case COMBINE(GPS_SENTENCE_GPGGA, 8): // HDOP
hdop.set(term);
break;
case COMBINE(GPS_SENTENCE_GPGGA, 9): // Altitude (GPGGA)
altitude.set(term);
break;
}
// Set custom values as needed
for (TinyGPSCustom *p = customCandidates; p != NULL && strcmp(p->sentenceName, customCandidates->sentenceName) == 0 && p->termNumber <= curTermNumber; p = p->next)
if (p->termNumber == curTermNumber)
p->set(term);
return false;
}
/* static */
double TinyGPSPlus::distanceBetween(double lat1, double long1, double lat2, double long2)
{
// returns distance in meters between two positions, both specified
// as signed decimal-degrees latitude and longitude. Uses great-circle
// distance computation for hypothetical sphere of radius 6372795 meters.
// Because Earth is no exact sphere, rounding errors may be up to 0.5%.
// Courtesy of Maarten Lamers
double delta = radians(long1-long2);
double sdlong = sin(delta);
double cdlong = cos(delta);
lat1 = radians(lat1);
lat2 = radians(lat2);
double slat1 = sin(lat1);
double clat1 = cos(lat1);
double slat2 = sin(lat2);
double clat2 = cos(lat2);
delta = (clat1 * slat2) - (slat1 * clat2 * cdlong);
delta = sq(delta);
delta += sq(clat2 * sdlong);
delta = sqrt(delta);
double denom = (slat1 * slat2) + (clat1 * clat2 * cdlong);
delta = atan2(delta, denom);
return delta * 6372795;
}
double TinyGPSPlus::courseTo(double lat1, double long1, double lat2, double long2)
{
// returns course in degrees (North=0, West=270) from position 1 to position 2,
// both specified as signed decimal-degrees latitude and longitude.
// Because Earth is no exact sphere, calculated course may be off by a tiny fraction.
// Courtesy of Maarten Lamers
double dlon = radians(long2-long1);
lat1 = radians(lat1);
lat2 = radians(lat2);
double a1 = sin(dlon) * cos(lat2);
double a2 = sin(lat1) * cos(lat2) * cos(dlon);
a2 = cos(lat1) * sin(lat2) - a2;
a2 = atan2(a1, a2);
if (a2 < 0.0)
{
a2 += TWO_PI;
}
return degrees(a2);
}
const char *TinyGPSPlus::cardinal(double course)
{
static const char* directions[] = {"N", "NNE", "NE", "ENE", "E", "ESE", "SE", "SSE", "S", "SSW", "SW", "WSW", "W", "WNW", "NW", "NNW"};
int direction = (int)((course + 11.25f) / 22.5f);
return directions[direction % 16];
}
void TinyGPSLocation::commit()
{
rawLatData = rawNewLatData;
rawLngData = rawNewLngData;
lastCommitTime = millis();
valid = updated = true;
}
void TinyGPSLocation::setLatitude(const char *term)
{
TinyGPSPlus::parseDegrees(term, rawNewLatData);
}
void TinyGPSLocation::setLongitude(const char *term)
{
TinyGPSPlus::parseDegrees(term, rawNewLngData);
}
double TinyGPSLocation::lat()
{
updated = false;
double ret = rawLatData.deg + rawLatData.billionths / 1000000000.0;
return rawLatData.negative ? -ret : ret;
}
double TinyGPSLocation::lng()
{
updated = false;
double ret = rawLngData.deg + rawLngData.billionths / 1000000000.0;
return rawLngData.negative ? -ret : ret;
}
void TinyGPSDate::commit()
{
date = newDate;
lastCommitTime = millis();
valid = updated = true;
}
void TinyGPSTime::commit()
{
time = newTime;
lastCommitTime = millis();
valid = updated = true;
}
void TinyGPSTime::setTime(const char *term)
{
newTime = (uint32_t)TinyGPSPlus::parseDecimal(term);
}
void TinyGPSDate::setDate(const char *term)
{
newDate = atol(term);
}
uint16_t TinyGPSDate::year()
{
updated = false;
uint16_t year = date % 100;
return year + 2000;
}
uint8_t TinyGPSDate::month()
{
updated = false;
return (date / 100) % 100;
}
uint8_t TinyGPSDate::day()
{
updated = false;
return date / 10000;
}
uint8_t TinyGPSTime::hour()
{
updated = false;
return time / 1000000;
}
uint8_t TinyGPSTime::minute()
{
updated = false;
return (time / 10000) % 100;
}
uint8_t TinyGPSTime::second()
{
updated = false;
return (time / 100) % 100;
}
uint8_t TinyGPSTime::centisecond()
{
updated = false;
return time % 100;
}
void TinyGPSDecimal::commit()
{
val = newval;
lastCommitTime = millis();
valid = updated = true;
}
void TinyGPSDecimal::set(const char *term)
{
newval = TinyGPSPlus::parseDecimal(term);
}
void TinyGPSInteger::commit()
{
val = newval;
lastCommitTime = millis();
valid = updated = true;
}
void TinyGPSInteger::set(const char *term)
{
newval = atol(term);
}
TinyGPSCustom::TinyGPSCustom(TinyGPSPlus &gps, const char *_sentenceName, int _termNumber)
{
begin(gps, _sentenceName, _termNumber);
}
void TinyGPSCustom::begin(TinyGPSPlus &gps, const char *_sentenceName, int _termNumber)
{
lastCommitTime = 0;
updated = valid = false;
sentenceName = _sentenceName;
termNumber = _termNumber;
memset(stagingBuffer, '\0', sizeof(stagingBuffer));
memset(buffer, '\0', sizeof(buffer));
// Insert this item into the GPS tree
gps.insertCustom(this, _sentenceName, _termNumber);
}
void TinyGPSCustom::commit()
{
strcpy(this->buffer, this->stagingBuffer);
lastCommitTime = millis();
valid = updated = true;
}
void TinyGPSCustom::set(const char *term)
{
strncpy(this->stagingBuffer, term, sizeof(this->stagingBuffer));
}
void TinyGPSPlus::insertCustom(TinyGPSCustom *pElt, const char *sentenceName, int termNumber)
{
TinyGPSCustom **ppelt;
for (ppelt = &this->customElts; *ppelt != NULL; ppelt = &(*ppelt)->next)
{
int cmp = strcmp(sentenceName, (*ppelt)->sentenceName);
if (cmp < 0 || (cmp == 0 && termNumber < (*ppelt)->termNumber))
break;
}
pElt->next = *ppelt;
*ppelt = pElt;
}
|
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE36_Absolute_Path_Traversal__char_file_ofstream_13.cpp
Label Definition File: CWE36_Absolute_Path_Traversal.label.xml
Template File: sources-sink-13.tmpl.cpp
*/
/*
* @description
* CWE: 36 Absolute Path Traversal
* BadSource: file Read input from a file
* GoodSource: Full path and file name
* Sink: ofstream
* BadSink : Open the file named in data using ofstream::open()
* Flow Variant: 13 Control flow: if(GLOBAL_CONST_FIVE==5) and if(GLOBAL_CONST_FIVE!=5)
*
* */
#include "std_testcase.h"
#ifndef _WIN32
#include <wchar.h>
#endif
#ifdef _WIN32
#define FILENAME "C:\\temp\\file.txt"
#else
#define FILENAME "/tmp/file.txt"
#endif
#include <fstream>
using namespace std;
namespace CWE36_Absolute_Path_Traversal__char_file_ofstream_13
{
#ifndef OMITBAD
void bad()
{
char * data;
char dataBuffer[FILENAME_MAX] = "";
data = dataBuffer;
if(GLOBAL_CONST_FIVE==5)
{
{
/* Read input from a file */
size_t dataLen = strlen(data);
FILE * pFile;
/* if there is room in data, attempt to read the input from a file */
if (FILENAME_MAX-dataLen > 1)
{
pFile = fopen(FILENAME, "r");
if (pFile != NULL)
{
/* POTENTIAL FLAW: Read data from a file */
if (fgets(data+dataLen, (int)(FILENAME_MAX-dataLen), pFile) == NULL)
{
printLine("fgets() failed");
/* Restore NUL terminator if fgets fails */
data[dataLen] = '\0';
}
fclose(pFile);
}
}
}
}
{
ofstream outputFile;
/* POTENTIAL FLAW: Possibly opening a file without validating the file name or path */
outputFile.open((char *)data);
outputFile.close();
}
}
#endif /* OMITBAD */
#ifndef OMITGOOD
/* goodG2B1() - use goodsource and badsink by changing the GLOBAL_CONST_FIVE==5 to GLOBAL_CONST_FIVE!=5 */
static void goodG2B1()
{
char * data;
char dataBuffer[FILENAME_MAX] = "";
data = dataBuffer;
if(GLOBAL_CONST_FIVE!=5)
{
/* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
printLine("Benign, fixed string");
}
else
{
#ifdef _WIN32
/* FIX: Use a fixed, full path and file name */
strcat(data, "c:\\temp\\file.txt");
#else
/* FIX: Use a fixed, full path and file name */
strcat(data, "/tmp/file.txt");
#endif
}
{
ofstream outputFile;
/* POTENTIAL FLAW: Possibly opening a file without validating the file name or path */
outputFile.open((char *)data);
outputFile.close();
}
}
/* goodG2B2() - use goodsource and badsink by reversing the blocks in the if statement */
static void goodG2B2()
{
char * data;
char dataBuffer[FILENAME_MAX] = "";
data = dataBuffer;
if(GLOBAL_CONST_FIVE==5)
{
#ifdef _WIN32
/* FIX: Use a fixed, full path and file name */
strcat(data, "c:\\temp\\file.txt");
#else
/* FIX: Use a fixed, full path and file name */
strcat(data, "/tmp/file.txt");
#endif
}
{
ofstream outputFile;
/* POTENTIAL FLAW: Possibly opening a file without validating the file name or path */
outputFile.open((char *)data);
outputFile.close();
}
}
void good()
{
goodG2B1();
goodG2B2();
}
#endif /* OMITGOOD */
} /* close namespace */
/* Below is the main(). It is only used when building this testcase on
its own for testing or for building a binary to use in testing binary
analysis tools. It is not used when compiling all the testcases as one
application, which is how source code analysis tools are tested. */
#ifdef INCLUDEMAIN
using namespace CWE36_Absolute_Path_Traversal__char_file_ofstream_13; /* so that we can use good and bad easily */
int main(int argc, char * argv[])
{
/* seed randomness */
srand( (unsigned)time(NULL) );
#ifndef OMITGOOD
printLine("Calling good()...");
good();
printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
printLine("Calling bad()...");
bad();
printLine("Finished bad()");
#endif /* OMITBAD */
return 0;
}
#endif
|
/*Exercise 1 - Calculations
Convert the C program given below which converts a length given in cm to inches to a C++ program.
Please Note that the input command in C++ is std::cin. This is a representation of the Keyboard.
e.g.
float data1;
int data2;
scanf("%f", &data1); --> std::cin >> data1;
scanf("%d", &data2); --> std::cin >> data2;
You already know that printf() in C is std::cout in C++ e.g.
printf("Hello World") --> std::cout << "Hello World";
2.54cm = 1 inch
*/
//#include <stdio.h>
#include <iostream>
using namespace std;
int main()
{
float cm, inches;
//printf("Enter a length in cm : ");
cout<<"Enter a length in cm : ";
//scanf("%f",&cm);
cin>>cm;
inches = cm / 2.54;
//printf("Length in inches is %f \n", inches);
cout<<" Length in inches is "<<inches<<endl;
return 0;
}
|
/*
* Automatically Generated from Mathematica.
* Thu 14 Oct 2021 09:59:29 GMT-04:00
*/
#ifdef MATLAB_MEX_FILE
#include <stdexcept>
#include <cmath>
#include<math.h>
/**
* Copied from Wolfram Mathematica C Definitions file mdefs.hpp
* Changed marcos to inline functions (Eric Cousineau)
*/
inline double Power(double x, double y) { return pow(x, y); }
inline double Sqrt(double x) { return sqrt(x); }
inline double Abs(double x) { return fabs(x); }
inline double Exp(double x) { return exp(x); }
inline double Log(double x) { return log(x); }
inline double Sin(double x) { return sin(x); }
inline double Cos(double x) { return cos(x); }
inline double Tan(double x) { return tan(x); }
inline double ArcSin(double x) { return asin(x); }
inline double ArcCos(double x) { return acos(x); }
inline double ArcTan(double x) { return atan(x); }
/* update ArcTan function to use atan2 instead. */
inline double ArcTan(double x, double y) { return atan2(y,x); }
inline double Sinh(double x) { return sinh(x); }
inline double Cosh(double x) { return cosh(x); }
inline double Tanh(double x) { return tanh(x); }
const double E = 2.71828182845904523536029;
const double Pi = 3.14159265358979323846264;
const double Degree = 0.01745329251994329576924;
inline double Sec(double x) { return 1/cos(x); }
inline double Csc(double x) { return 1/sin(x); }
#endif
/*
* Sub functions
*/
static void output1(double *p_output1,const double *var1)
{
double _NotUsed;
NULL;
p_output1[0]=1;
p_output1[1]=1;
p_output1[2]=1;
p_output1[3]=1;
p_output1[4]=1;
p_output1[5]=1;
p_output1[6]=1;
p_output1[7]=1;
p_output1[8]=1;
p_output1[9]=1;
p_output1[10]=1;
p_output1[11]=1;
p_output1[12]=1;
p_output1[13]=2;
p_output1[14]=2;
p_output1[15]=2;
p_output1[16]=2;
p_output1[17]=2;
p_output1[18]=2;
p_output1[19]=2;
p_output1[20]=2;
p_output1[21]=2;
p_output1[22]=2;
p_output1[23]=2;
p_output1[24]=2;
p_output1[25]=2;
p_output1[26]=3;
p_output1[27]=3;
p_output1[28]=3;
p_output1[29]=3;
p_output1[30]=3;
p_output1[31]=3;
p_output1[32]=3;
p_output1[33]=3;
p_output1[34]=3;
p_output1[35]=3;
p_output1[36]=3;
p_output1[37]=3;
p_output1[38]=3;
p_output1[39]=4;
p_output1[40]=4;
p_output1[41]=4;
p_output1[42]=4;
p_output1[43]=4;
p_output1[44]=4;
p_output1[45]=4;
p_output1[46]=4;
p_output1[47]=4;
p_output1[48]=4;
p_output1[49]=4;
p_output1[50]=4;
p_output1[51]=4;
p_output1[52]=5;
p_output1[53]=5;
p_output1[54]=5;
p_output1[55]=5;
p_output1[56]=5;
p_output1[57]=5;
p_output1[58]=5;
p_output1[59]=5;
p_output1[60]=5;
p_output1[61]=5;
p_output1[62]=5;
p_output1[63]=5;
p_output1[64]=5;
p_output1[65]=6;
p_output1[66]=6;
p_output1[67]=6;
p_output1[68]=6;
p_output1[69]=6;
p_output1[70]=6;
p_output1[71]=6;
p_output1[72]=6;
p_output1[73]=6;
p_output1[74]=6;
p_output1[75]=6;
p_output1[76]=6;
p_output1[77]=6;
p_output1[78]=7;
p_output1[79]=7;
p_output1[80]=7;
p_output1[81]=7;
p_output1[82]=7;
p_output1[83]=7;
p_output1[84]=7;
p_output1[85]=7;
p_output1[86]=7;
p_output1[87]=7;
p_output1[88]=7;
p_output1[89]=7;
p_output1[90]=7;
p_output1[91]=8;
p_output1[92]=8;
p_output1[93]=8;
p_output1[94]=8;
p_output1[95]=8;
p_output1[96]=8;
p_output1[97]=8;
p_output1[98]=8;
p_output1[99]=8;
p_output1[100]=8;
p_output1[101]=8;
p_output1[102]=8;
p_output1[103]=8;
p_output1[104]=9;
p_output1[105]=9;
p_output1[106]=9;
p_output1[107]=9;
p_output1[108]=9;
p_output1[109]=9;
p_output1[110]=9;
p_output1[111]=9;
p_output1[112]=9;
p_output1[113]=9;
p_output1[114]=9;
p_output1[115]=9;
p_output1[116]=9;
p_output1[117]=10;
p_output1[118]=10;
p_output1[119]=10;
p_output1[120]=10;
p_output1[121]=10;
p_output1[122]=10;
p_output1[123]=10;
p_output1[124]=10;
p_output1[125]=10;
p_output1[126]=10;
p_output1[127]=10;
p_output1[128]=10;
p_output1[129]=10;
p_output1[130]=1;
p_output1[131]=2;
p_output1[132]=9;
p_output1[133]=29;
p_output1[134]=49;
p_output1[135]=63;
p_output1[136]=73;
p_output1[137]=83;
p_output1[138]=93;
p_output1[139]=103;
p_output1[140]=113;
p_output1[141]=123;
p_output1[142]=124;
p_output1[143]=1;
p_output1[144]=2;
p_output1[145]=10;
p_output1[146]=30;
p_output1[147]=50;
p_output1[148]=64;
p_output1[149]=74;
p_output1[150]=84;
p_output1[151]=94;
p_output1[152]=104;
p_output1[153]=114;
p_output1[154]=123;
p_output1[155]=124;
p_output1[156]=1;
p_output1[157]=2;
p_output1[158]=11;
p_output1[159]=31;
p_output1[160]=51;
p_output1[161]=65;
p_output1[162]=75;
p_output1[163]=85;
p_output1[164]=95;
p_output1[165]=105;
p_output1[166]=115;
p_output1[167]=123;
p_output1[168]=124;
p_output1[169]=1;
p_output1[170]=2;
p_output1[171]=12;
p_output1[172]=32;
p_output1[173]=52;
p_output1[174]=66;
p_output1[175]=76;
p_output1[176]=86;
p_output1[177]=96;
p_output1[178]=106;
p_output1[179]=116;
p_output1[180]=123;
p_output1[181]=124;
p_output1[182]=1;
p_output1[183]=2;
p_output1[184]=15;
p_output1[185]=35;
p_output1[186]=55;
p_output1[187]=67;
p_output1[188]=77;
p_output1[189]=87;
p_output1[190]=97;
p_output1[191]=107;
p_output1[192]=117;
p_output1[193]=123;
p_output1[194]=124;
p_output1[195]=1;
p_output1[196]=2;
p_output1[197]=16;
p_output1[198]=36;
p_output1[199]=56;
p_output1[200]=68;
p_output1[201]=78;
p_output1[202]=88;
p_output1[203]=98;
p_output1[204]=108;
p_output1[205]=118;
p_output1[206]=123;
p_output1[207]=124;
p_output1[208]=1;
p_output1[209]=2;
p_output1[210]=17;
p_output1[211]=37;
p_output1[212]=57;
p_output1[213]=69;
p_output1[214]=79;
p_output1[215]=89;
p_output1[216]=99;
p_output1[217]=109;
p_output1[218]=119;
p_output1[219]=123;
p_output1[220]=124;
p_output1[221]=1;
p_output1[222]=2;
p_output1[223]=18;
p_output1[224]=38;
p_output1[225]=58;
p_output1[226]=70;
p_output1[227]=80;
p_output1[228]=90;
p_output1[229]=100;
p_output1[230]=110;
p_output1[231]=120;
p_output1[232]=123;
p_output1[233]=124;
p_output1[234]=1;
p_output1[235]=2;
p_output1[236]=19;
p_output1[237]=39;
p_output1[238]=59;
p_output1[239]=71;
p_output1[240]=81;
p_output1[241]=91;
p_output1[242]=101;
p_output1[243]=111;
p_output1[244]=121;
p_output1[245]=123;
p_output1[246]=124;
p_output1[247]=1;
p_output1[248]=2;
p_output1[249]=22;
p_output1[250]=42;
p_output1[251]=62;
p_output1[252]=72;
p_output1[253]=82;
p_output1[254]=92;
p_output1[255]=102;
p_output1[256]=112;
p_output1[257]=122;
p_output1[258]=123;
p_output1[259]=124;
}
#ifdef MATLAB_MEX_FILE
#include "mex.h"
/*
* Main function
*/
void mexFunction( int nlhs, mxArray *plhs[],
int nrhs, const mxArray *prhs[] )
{
size_t mrows, ncols;
double *var1;
double *p_output1;
/* Check for proper number of arguments. */
if( nrhs != 1)
{
mexErrMsgIdAndTxt("MATLAB:MShaped:invalidNumInputs", "One input(s) required (var1).");
}
else if( nlhs > 1)
{
mexErrMsgIdAndTxt("MATLAB:MShaped:maxlhs", "Too many output arguments.");
}
/* The input must be a noncomplex double vector or scaler. */
mrows = mxGetM(prhs[0]);
ncols = mxGetN(prhs[0]);
if( !mxIsDouble(prhs[0]) || mxIsComplex(prhs[0]) ||
( !(mrows == 1 && ncols == 1) &&
!(mrows == 1 && ncols == 1)))
{
mexErrMsgIdAndTxt( "MATLAB:MShaped:inputNotRealVector", "var1 is wrong.");
}
/* Assign pointers to each input. */
var1 = mxGetPr(prhs[0]);
/* Create matrices for return arguments. */
plhs[0] = mxCreateDoubleMatrix((mwSize) 130, (mwSize) 2, mxREAL);
p_output1 = mxGetPr(plhs[0]);
/* Call the calculation subroutine. */
output1(p_output1,var1);
}
#else // MATLAB_MEX_FILE
#include "Js_d2y_time_LeftStance.hh"
namespace LeftStance
{
void Js_d2y_time_LeftStance_raw(double *p_output1, const double *var1)
{
// Call Subroutines
output1(p_output1, var1);
}
}
#endif // MATLAB_MEX_FILE
|
/****************************************************************************
*
* Copyright (c) 2017 PX4 Development Team. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. 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.
* 3. Neither the name PX4 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 OWNER 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.
*
****************************************************************************/
/**
*
* This module is a modification of the fixed wing module and it is designed for ground rovers.
* It has been developed starting from the fw module, simplified and improved with dedicated items.
*
* All the acknowledgments and credits for the fw wing app are reported in those files.
*
* @author Marco Zorzi <mzorzi@student.ethz.ch>
*/
#include "RoverPositionControl.hpp"
#include <lib/ecl/geo/geo.h>
#define ACTUATOR_PUBLISH_PERIOD_MS 4
#define BATTERY_VOLT 12.0f
#define PI 3.14159f
using namespace matrix;
/**
* L1 control app start / stop handling function
*
* @ingroup apps
*/
extern "C" __EXPORT int rover_pos_control_main(int argc, char *argv[]);
RoverPositionControl::RoverPositionControl() :
ModuleParams(nullptr),
/* performance counters */
_loop_perf(perf_alloc(PC_ELAPSED, "rover position control")) // TODO : do we even need these perf counters
{
}
RoverPositionControl::~RoverPositionControl()
{
perf_free(_loop_perf);
}
void RoverPositionControl::parameters_update(bool force)
{
// check for parameter updates
if (_parameter_update_sub.updated() || force) {
// clear update
parameter_update_s pupdate;
_parameter_update_sub.copy(&pupdate);
// update parameters from storage
updateParams();
_gnd_control.set_l1_damping(_param_l1_damping.get());
_gnd_control.set_l1_period(_param_l1_period.get());
_gnd_control.set_l1_roll_limit(math::radians(0.0f));
pid_init(&_speed_ctrl, PID_MODE_DERIVATIV_CALC, 0.01f);
pid_set_parameters(&_speed_ctrl,
_param_speed_p.get(),
_param_speed_i.get(),
_param_speed_d.get(),
_param_speed_imax.get(),
_param_gndspeed_max.get());
}
}
// void
// RoverPositionControl::vehicle_angular_velocity_poll()
// {
// orb_copy(ORB_ID(vehicle_angular_velocity), _angular_velocity_sub, &_angular_velocity);
// }
void
RoverPositionControl::vehicle_control_mode_poll()
{
bool updated;
orb_check(_control_mode_sub, &updated);
if (updated) {
orb_copy(ORB_ID(vehicle_control_mode), _control_mode_sub, &_control_mode);
}
}
void
RoverPositionControl::manual_control_setpoint_poll()
{
bool manual_updated;
orb_check(_manual_control_setpoint_sub, &manual_updated);
if (manual_updated) {
orb_copy(ORB_ID(manual_control_setpoint), _manual_control_setpoint_sub, &_manual_control_setpoint);
}
}
void
RoverPositionControl::position_setpoint_triplet_poll()
{
bool pos_sp_triplet_updated;
orb_check(_pos_sp_triplet_sub, &pos_sp_triplet_updated);
if (pos_sp_triplet_updated) {
orb_copy(ORB_ID(position_setpoint_triplet), _pos_sp_triplet_sub, &_pos_sp_triplet);
}
}
void
RoverPositionControl::attitude_setpoint_poll()
{
bool att_sp_updated;
orb_check(_att_sp_sub, &att_sp_updated);
if (att_sp_updated) {
orb_copy(ORB_ID(vehicle_attitude_setpoint), _att_sp_sub, &_att_sp);
}
}
void
RoverPositionControl::vehicle_attitude_poll()
{
bool att_updated;
orb_check(_vehicle_attitude_sub, &att_updated);
if (att_updated) {
orb_copy(ORB_ID(vehicle_attitude), _vehicle_attitude_sub, &_vehicle_att);
}
}
bool
RoverPositionControl::control_position(const matrix::Vector2f ¤t_position,
const matrix::Vector3f &ground_speed, const position_setpoint_triplet_s &pos_sp_triplet)
{
float dt = 0.01; // Using non zero value to a avoid division by zero
if (_control_position_last_called > 0) {
dt = hrt_elapsed_time(&_control_position_last_called) * 1e-6f;
}
_control_position_last_called = hrt_absolute_time();
bool setpoint = true;
if ((_control_mode.flag_control_auto_enabled ||
_control_mode.flag_control_offboard_enabled) && pos_sp_triplet.current.valid) {
/* AUTONOMOUS FLIGHT */
_control_mode_current = UGV_POSCTRL_MODE_AUTO;
/* get circle mode */
//bool was_circle_mode = _gnd_control.circle_mode();
/* current waypoint (the one currently heading for) */
matrix::Vector2f curr_wp((float)pos_sp_triplet.current.lat, (float)pos_sp_triplet.current.lon);
/* previous waypoint */
matrix::Vector2f prev_wp = curr_wp;
if (pos_sp_triplet.previous.valid) {
prev_wp(0) = (float)pos_sp_triplet.previous.lat;
prev_wp(1) = (float)pos_sp_triplet.previous.lon;
}
matrix::Vector2f ground_speed_2d(ground_speed);
float mission_throttle = _param_throttle_cruise.get();
/* Just control the throttle */
if (_param_speed_control_mode.get() == 1) {
/* control the speed in closed loop */
float mission_target_speed = _param_gndspeed_trim.get();
if (PX4_ISFINITE(_pos_sp_triplet.current.cruising_speed) &&
_pos_sp_triplet.current.cruising_speed > 0.1f) {
mission_target_speed = _pos_sp_triplet.current.cruising_speed;
}
// Velocity in body frame
const Dcmf R_to_body(Quatf(_vehicle_att.q).inversed());
const Vector3f vel = R_to_body * Vector3f(ground_speed(0), ground_speed(1), ground_speed(2));
const float x_vel = vel(0);
const float x_acc = _vehicle_acceleration_sub.get().xyz[0];
// Compute airspeed control out and just scale it as a constant
mission_throttle = _param_throttle_speed_scaler.get()
* pid_calculate(&_speed_ctrl, mission_target_speed, x_vel, x_acc, dt);
// Constrain throttle between min and max
mission_throttle = math::constrain(mission_throttle, _param_throttle_min.get(), _param_throttle_max.get());
} else {
/* Just control throttle in open loop */
if (PX4_ISFINITE(_pos_sp_triplet.current.cruising_throttle) &&
_pos_sp_triplet.current.cruising_throttle > 0.01f) {
mission_throttle = _pos_sp_triplet.current.cruising_throttle;
}
}
float dist_target = get_distance_to_next_waypoint(_global_pos.lat, _global_pos.lon,
(double)curr_wp(0), (double)curr_wp(1)); // pos_sp_triplet.current.lat, pos_sp_triplet.current.lon);
//PX4_INFO("Setpoint type %d", (int) pos_sp_triplet.current.type );
//PX4_INFO(" State machine state %d", (int) _pos_ctrl_state);
//PX4_INFO(" Setpoint Lat %f, Lon %f", (double) curr_wp(0), (double)curr_wp(1));
//PX4_INFO(" Distance to target %f", (double) dist_target);
switch (_pos_ctrl_state) {
case GOTO_WAYPOINT: {
if (dist_target < _param_nav_loiter_rad.get()) {
_pos_ctrl_state = STOPPING; // We are closer than loiter radius to waypoint, stop.
} else {
_gnd_control.navigate_waypoints(prev_wp, curr_wp, current_position, ground_speed_2d);
_act_controls.control[actuator_controls_s::INDEX_THROTTLE] = mission_throttle;
float desired_r = ground_speed_2d.norm_squared() / math::abs_t(_gnd_control.nav_lateral_acceleration_demand());
float desired_theta = (0.5f * M_PI_F) - atan2f(desired_r, _param_wheel_base.get());
float control_effort = (desired_theta / _param_max_turn_angle.get()) * sign(
_gnd_control.nav_lateral_acceleration_demand());
control_effort = math::constrain(control_effort, -1.0f, 1.0f);
_act_controls.control[actuator_controls_s::INDEX_YAW] = control_effort;
}
}
break;
case STOPPING: {
_act_controls.control[actuator_controls_s::INDEX_YAW] = 0.0f;
_act_controls.control[actuator_controls_s::INDEX_THROTTLE] = 0.0f;
// Note _prev_wp is different to the local prev_wp which is related to a mission waypoint.
float dist_between_waypoints = get_distance_to_next_waypoint((double)_prev_wp(0), (double)_prev_wp(1),
(double)curr_wp(0), (double)curr_wp(1));
if (dist_between_waypoints > 0) {
_pos_ctrl_state = GOTO_WAYPOINT; // A new waypoint has arrived go to it
}
//PX4_INFO(" Distance between prev and curr waypoints %f", (double)dist_between_waypoints);
}
break;
default:
PX4_ERR("Unknown Rover State");
_pos_ctrl_state = STOPPING;
break;
}
_prev_wp = curr_wp;
} else {
_control_mode_current = UGV_POSCTRL_MODE_OTHER;
setpoint = false;
}
return setpoint;
}
void
RoverPositionControl::control_velocity(const matrix::Vector3f ¤t_velocity,
const position_setpoint_triplet_s &pos_sp_triplet)
{
float dt = 0.01; // Using non zero value to a avoid division by zero
const float mission_throttle = _param_throttle_cruise.get();
const matrix::Vector3f desired_velocity{pos_sp_triplet.current.vx, pos_sp_triplet.current.vy, pos_sp_triplet.current.vz};
const float desired_speed = desired_velocity.norm();
if (desired_speed > 0.01f) {
const Dcmf R_to_body(Quatf(_vehicle_att.q).inversed());
const Vector3f vel = R_to_body * Vector3f(current_velocity(0), current_velocity(1), current_velocity(2));
const float x_vel = vel(0);
const float x_acc = _vehicle_acceleration_sub.get().xyz[0];
const float control_throttle = pid_calculate(&_speed_ctrl, desired_speed, x_vel, x_acc, dt);
//Constrain maximum throttle to mission throttle
_act_controls.control[actuator_controls_s::INDEX_THROTTLE] = math::constrain(control_throttle, 0.0f, mission_throttle);
Vector3f desired_body_velocity;
if (pos_sp_triplet.current.velocity_frame == position_setpoint_s::VELOCITY_FRAME_BODY_NED) {
desired_body_velocity = desired_velocity;
} else {
// If the frame of the velocity setpoint is unknown, assume it is in local frame
desired_body_velocity = R_to_body * desired_velocity;
}
const float desired_theta = atan2f(desired_body_velocity(1), desired_body_velocity(0));
float control_effort = desired_theta / _param_max_turn_angle.get();
control_effort = math::constrain(control_effort, -1.0f, 1.0f);
_act_controls.control[actuator_controls_s::INDEX_YAW] = control_effort;
} else {
_act_controls.control[actuator_controls_s::INDEX_THROTTLE] = 0.0f;
_act_controls.control[actuator_controls_s::INDEX_YAW] = 0.0f;
}
}
void
RoverPositionControl::control_attitude(const vehicle_attitude_s &att, const vehicle_attitude_setpoint_s &att_sp)
{
// quaternion attitude control law, qe is rotation from q to qd
const Quatf qe = Quatf(att.q).inversed() * Quatf(att_sp.q_d);
const Eulerf euler_sp = qe;
float control_effort = euler_sp(2) / _param_max_turn_angle.get();
control_effort = math::constrain(control_effort, -1.0f, 1.0f);
_act_controls.control[actuator_controls_s::INDEX_YAW] = control_effort;
const float control_throttle = att_sp.thrust_body[0];
_act_controls.control[actuator_controls_s::INDEX_THROTTLE] = math::constrain(control_throttle, 0.0f, 1.0f);
}
void
RoverPositionControl::run()
{
_control_mode_sub = orb_subscribe(ORB_ID(vehicle_control_mode));
_global_pos_sub = orb_subscribe(ORB_ID(vehicle_global_position));
_local_pos_sub = orb_subscribe(ORB_ID(vehicle_local_position));
_manual_control_setpoint_sub = orb_subscribe(ORB_ID(manual_control_setpoint));
_pos_sp_triplet_sub = orb_subscribe(ORB_ID(position_setpoint_triplet));
_att_sp_sub = orb_subscribe(ORB_ID(vehicle_attitude_setpoint));
_vehicle_attitude_sub = orb_subscribe(ORB_ID(vehicle_attitude));
_sensor_combined_sub = orb_subscribe(ORB_ID(sensor_combined));
// _angular_velocity_sub = orb_subscribe(ORB_ID(vehicle_angular_velocity));
/* rate limit control mode updates to 5Hz */
orb_set_interval(_control_mode_sub, 200);
/* rate limit position updates to 50 Hz */
orb_set_interval(_global_pos_sub, 20);
orb_set_interval(_local_pos_sub, 20);
parameters_update(true);
/* wakeup source(s) */
px4_pollfd_struct_t fds[5];
/* Setup of loop */
fds[0].fd = _global_pos_sub;
fds[0].events = POLLIN;
fds[1].fd = _manual_control_setpoint_sub;
fds[1].events = POLLIN;
fds[2].fd = _sensor_combined_sub;
fds[2].events = POLLIN;
fds[3].fd = _vehicle_attitude_sub; // Poll attitude
fds[3].events = POLLIN;
fds[4].fd = _local_pos_sub; // Added local position as source of position
fds[4].events = POLLIN;
// QuadratureEncoder D(M4A,M4B);
// QuadratureEncoder B(M2A,M2B);
// QuadratureEncoder C(M3A,M3B);
// QuadratureEncoder A(M1A,M1B);
while (!should_exit()) {
/* wait for up to 500ms for data */
int pret = px4_poll(&fds[0], (sizeof(fds) / sizeof(fds[0])), 500);
/* this is undesirable but not much we can do - might want to flag unhappy status */
if (pret < 0) {
warn("poll error %d, %d", pret, errno);
continue;
}
/* check vehicle control mode for changes to publication state */
vehicle_control_mode_poll();
attitude_setpoint_poll();
//manual_control_setpoint_poll();
_vehicle_acceleration_sub.update();
/* Added for heading control*/
_angular_velocity_sub.update();
_angular_acceleration_sub.update();
_wheel_encoder_sub[0].update(&_wheelEncoderMsg[0]);
_wheel_encoder_sub[1].update(&_wheelEncoderMsg[1]);
/* update parameters from storage */
parameters_update();
bool manual_mode = _control_mode.flag_control_manual_enabled;
/* only run controller if position changed */
if (fds[0].revents & POLLIN || fds[4].revents & POLLIN) {
perf_begin(_loop_perf);
/* load local copies */
orb_copy(ORB_ID(vehicle_global_position), _global_pos_sub, &_global_pos);
orb_copy(ORB_ID(vehicle_local_position), _local_pos_sub, &_local_pos);
position_setpoint_triplet_poll();
//Convert Local setpoints to global setpoints
if (_control_mode.flag_control_offboard_enabled) {
if (!globallocalconverter_initialized()) {
globallocalconverter_init(_local_pos.ref_lat, _local_pos.ref_lon,
_local_pos.ref_alt, _local_pos.ref_timestamp);
} else {
globallocalconverter_toglobal(_pos_sp_triplet.current.x, _pos_sp_triplet.current.y, _pos_sp_triplet.current.z,
&_pos_sp_triplet.current.lat, &_pos_sp_triplet.current.lon, &_pos_sp_triplet.current.alt);
}
}
// update the reset counters in any case
_pos_reset_counter = _global_pos.lat_lon_reset_counter;
matrix::Vector3f ground_speed(_local_pos.vx, _local_pos.vy, _local_pos.vz);
matrix::Vector2f current_position((float)_global_pos.lat, (float)_global_pos.lon);
matrix::Vector3f current_velocity(_local_pos.vx, _local_pos.vy, _local_pos.vz);
if (!manual_mode && _control_mode.flag_control_position_enabled) {
if (control_position(current_position, ground_speed, _pos_sp_triplet)) {
//TODO: check if radius makes sense here
float turn_distance = _param_l1_distance.get(); //_gnd_control.switch_distance(100.0f);
// publish status
position_controller_status_s pos_ctrl_status = {};
pos_ctrl_status.nav_roll = 0.0f;
pos_ctrl_status.nav_pitch = 0.0f;
pos_ctrl_status.nav_bearing = _gnd_control.nav_bearing();
pos_ctrl_status.target_bearing = _gnd_control.target_bearing();
pos_ctrl_status.xtrack_error = _gnd_control.crosstrack_error();
pos_ctrl_status.wp_dist = get_distance_to_next_waypoint(_global_pos.lat, _global_pos.lon,
_pos_sp_triplet.current.lat, _pos_sp_triplet.current.lon);
pos_ctrl_status.acceptance_radius = turn_distance;
pos_ctrl_status.yaw_acceptance = NAN;
pos_ctrl_status.timestamp = hrt_absolute_time();
_pos_ctrl_status_pub.publish(pos_ctrl_status);
}
} else if (!manual_mode && _control_mode.flag_control_velocity_enabled) {
control_velocity(current_velocity, _pos_sp_triplet);
}
perf_end(_loop_perf);
}
if (fds[3].revents & POLLIN) {
vehicle_attitude_poll();
if (!manual_mode && _control_mode.flag_control_attitude_enabled
&& !_control_mode.flag_control_position_enabled
&& !_control_mode.flag_control_velocity_enabled) {
control_attitude(_vehicle_att, _att_sp);
}
}
if (fds[1].revents & POLLIN) {
// This should be copied even if not in manual mode. Otherwise, the poll(...) call will keep
// returning immediately and this loop will eat up resources.
orb_copy(ORB_ID(manual_control_setpoint), _manual_control_setpoint_sub, &_manual_control_setpoint);
vehicle_attitude_poll();
orb_copy(ORB_ID(sensor_combined), _sensor_combined_sub, &_sensor_combined);
// vehicle_angular_velocity_poll();
if (manual_mode) {
// /* manual/direct control */
// No inputs to ROLL and PITCH
_act_controls.control[actuator_controls_s::INDEX_ROLL] = 0.0f;
_act_controls.control[actuator_controls_s::INDEX_PITCH] = 0.0f;
// Convert Quterion to Eular angle
const Eulerf euler_att{Quatf(_vehicle_att.q)};
// Control Heading using P control
float error = refHeading - euler_att.psi();
//Deal with Turn more than 180 degrees
// Always turn back with the smallest angle
if(error > PI)
error -= 2 * PI;
else if(error < -PI)
error += 2 * PI;
const float speedError = - _angular_velocity_sub.get().xyz[2];
const float threshold = _param_rc_thr.get();
const float yaw = error / PI * _param_heading_p.get() + speedError / PI * _param_heading_d.get();
const float lpf_const = _param_lpf_const.get();
if((_manual_control_setpoint.r > 0.05f) || (_manual_control_setpoint.r < - 0.05f))
refHeading = euler_att.psi();
if(((_manual_control_setpoint.r - yaw) > threshold)
|| ((_manual_control_setpoint.r - yaw) < - threshold))
_act_controls.control[actuator_controls_s::INDEX_YAW] = lpf_const * _act_controls.control[actuator_controls_s::INDEX_YAW]
+ (1-lpf_const) * (_manual_control_setpoint.r) - yaw;
else{
_act_controls.control[actuator_controls_s::INDEX_YAW] *= lpf_const;
}
// Pitch Control
// Control Pitching using PD control
const float pitch = euler_att.theta();
const float pitchRate = 0.96f * lastPitchRate + 0.04f * _angular_velocity_sub.get().xyz[1];
const float pitchAccel = 0.99f * lastPitchAccel + 0.01f * _angular_acceleration_sub.get().xyz[1]/0.004f;
if(pitch > 0.44f )
error = (0.44f - pitch) * _param_pitching_p.get();
else if(pitch < -0.44f )
error = (-0.44f - pitch) * _param_pitching_p.get();
error += (-pitchRate * _param_pitching_d.get() - pitchAccel * _param_pitching_dd.get());
// If it's falling, it should let it fall to equilibrium, not accelerate
if(euler_att.theta() > 0)
{
error = error < 0 ? error : 0;
}
else
{
error = error > 0 ? error : 0;
}
float command = _manual_control_setpoint.z * 0.9f + error;
// Torque limitation
float Km{_param_torq_const.get()}, Kb{_param_emf_const.get()}, R{2.1429}, h{_param_hight_cog.get()}, lf{0.05}, lr{0.05}, m{3.55};//, mw, rw;
float Icm = m * (0.2286f * 0.2286f + 0.1524f * 0.1524f) / 12.0f;
float Ir = Icm + m * (h*h + lr*lr);
float If = Icm + m * (h*h + lf*lf);
float maxTorque = (((cos(pitch) * lr) - (sin(pitch) * h)) * m * 9.81f)
// + cos(pitch) * (lr+lf) * mw * 9.81
- (lastPitchAccel * Ir);
float minTorque = 0-((((cos(pitch) * lf) + (sin(pitch) * h)) * m * 9.81f)
// + cos(pitch) * (lr+lf) * mw * 9.81
+ (lastPitchAccel * If));
float maxVol = maxTorque * R / Km - _param_torq_offset.get() + _wheelEncoderMsg[1].speed * Kb;
float minVol = minTorque * R / Km + _param_torq_offset.get() + _wheelEncoderMsg[0].speed * Kb;
float maxCommand = maxVol / BATTERY_VOLT;
float minCommand = minVol / BATTERY_VOLT;
if(maxCommand < minCommand)
{
maxCommand = minCommand;
minCommand = maxVol / BATTERY_VOLT;
}
// maxCommand = 0.95f * lastMaxVol + 0.05f * maxCommand;
// minCommand = 0.95f * lastMinVol + 0.05f * minCommand;
// lastMaxVol = maxCommand;
// lastMinVol = minCommand;
_act_controls.control[actuator_controls_s::INDEX_ROLL] = maxCommand;
_act_controls.control[actuator_controls_s::INDEX_PITCH] = minCommand;
if((command > threshold)
|| (command < - threshold))
_act_controls.control[actuator_controls_s::INDEX_THROTTLE] = lpf_const * _act_controls.control[actuator_controls_s::INDEX_THROTTLE]
+ (1-lpf_const) * command;
else
_act_controls.control[actuator_controls_s::INDEX_THROTTLE] *= lpf_const;
if(_param_torq_on.get())
{
_act_controls.control[actuator_controls_s::INDEX_THROTTLE] = _act_controls.control[actuator_controls_s::INDEX_THROTTLE] < maxCommand ? _act_controls.control[actuator_controls_s::INDEX_THROTTLE] : maxCommand;
_act_controls.control[actuator_controls_s::INDEX_THROTTLE] = _act_controls.control[actuator_controls_s::INDEX_THROTTLE] > minCommand ? _act_controls.control[actuator_controls_s::INDEX_THROTTLE] : minCommand;
}
// Safety Feature
// If Roll/Pitch angle larger then a threshold, stop
if(abs(euler_att.phi()) > _param_shutdown_thr.get() || abs(euler_att.theta()) > _param_shutdown_thr.get())
{
_act_controls.control[actuator_controls_s::INDEX_YAW] = 0.0f;
_act_controls.control[actuator_controls_s::INDEX_THROTTLE] = 0.0f;
}
lastPitchAccel = pitchAccel;
lastPitchRate = pitchRate;
}
}
if (fds[2].revents & POLLIN) {
orb_copy(ORB_ID(sensor_combined), _sensor_combined_sub, &_sensor_combined);
//orb_copy(ORB_ID(vehicle_attitude), _vehicle_attitude_sub, &_vehicle_att);
_act_controls.timestamp = hrt_absolute_time();
/* Only publish if any of the proper modes are enabled */
if (_control_mode.flag_control_velocity_enabled ||
_control_mode.flag_control_attitude_enabled ||
_control_mode.flag_control_position_enabled ||
manual_mode) {
/* publish the actuator controls */
_actuator_controls_pub.publish(_act_controls);
}
}
}
orb_unsubscribe(_control_mode_sub);
orb_unsubscribe(_global_pos_sub);
orb_unsubscribe(_local_pos_sub);
orb_unsubscribe(_manual_control_setpoint_sub);
orb_unsubscribe(_pos_sp_triplet_sub);
orb_unsubscribe(_vehicle_attitude_sub);
orb_unsubscribe(_sensor_combined_sub);
warnx("exiting.\n");
}
int RoverPositionControl::task_spawn(int argc, char *argv[])
{
/* start the task */
_task_id = px4_task_spawn_cmd("rover_pos_ctrl",
SCHED_DEFAULT,
SCHED_PRIORITY_POSITION_CONTROL,
1700,
(px4_main_t)&RoverPositionControl::run_trampoline,
nullptr);
if (_task_id < 0) {
warn("task start failed");
return -errno;
}
return OK;
}
RoverPositionControl *RoverPositionControl::instantiate(int argc, char *argv[])
{
if (argc > 0) {
PX4_WARN("Command 'start' takes no arguments.");
return nullptr;
}
RoverPositionControl *instance = new RoverPositionControl();
if (instance == nullptr) {
PX4_ERR("Failed to instantiate RoverPositionControl object");
}
return instance;
}
int RoverPositionControl::custom_command(int argc, char *argv[])
{
return print_usage("unknown command");
}
int RoverPositionControl::print_usage(const char *reason)
{
if (reason) {
PX4_WARN("%s\n", reason);
}
PRINT_MODULE_DESCRIPTION(
R"DESCR_STR(
### Description
Controls the position of a ground rover using an L1 controller.
Publishes `actuator_controls_0` messages at a constant 250Hz.
### Implementation
Currently, this implementation supports only a few modes:
* Full manual: Throttle and yaw controls are passed directly through to the actuators
* Auto mission: The rover runs missions
* Loiter: The rover will navigate to within the loiter radius, then stop the motors
### Examples
CLI usage example:
$ rover_pos_control start
$ rover_pos_control status
$ rover_pos_control stop
)DESCR_STR");
PRINT_MODULE_USAGE_NAME("rover_pos_control", "controller");
PRINT_MODULE_USAGE_COMMAND("start")
PRINT_MODULE_USAGE_DEFAULT_COMMANDS();
return 0;
}
int rover_pos_control_main(int argc, char *argv[])
{
return RoverPositionControl::main(argc, argv);
}
|
#include "IfSearch.h"
#include <QDir>
#include <QFileSystemWatcher>
#include <QStringList>
#include <QTimer>
#include <EigenFace.h>
#include <EigenFaceGenerator.h>
#include <EigenFaceFace.h>
#include <EigenFaceTemplate.h>
#include <EigenFaceSearchResultList.h>
#include <FaceBase.h>
#include <FileWriteProfile.h>
#include <ImageCache.h>
#include <InfoMacros.h>
#include <InputHotdir.h>
#include <Return.h>
#include <Settings.h>
void IfSearch::doAuthenticate(void)
{
if (ffdBusy)
{
INFO("[SEARCH] ffdBusy");
if (--searchTimeout)
return searchError("Timeout");
QTimer::singleShot(100, this, SLOT(doAuthenticate()));
return;
}
searchResults.clear();
authConfidence = -1;
authUpdate = 0;
appSettings->setValue("Search/Results", searchResults);
appSettings->setValue("Search/Reason", QString());
appSettings->setValue("Search/Confidence", authConfidence = 0);
searchPersonKey = appSettings->value("Search/PersonKey", 0).toInt();
searchPersonId = appSettings->value("Search/PersonId", QString()).toString();
PROGRESS("[SEARCH] Started for Authenticate: %1 #%2", searchPersonId, searchPersonKey);
searchTemplate.clear();
appSettings->setValue("Search/Status", "Checking FaceBase");
if ( ! faceBase)
return searchError("No FaceBase");
if (searchPersonKey)
{
searchPersonId = faceBase->personId(searchPersonKey);
if (searchPersonId.isEmpty())
return searchError(tr("PersonKey %1 does not exist").arg(searchPersonKey));
}
else
{
if (searchPersonId.isEmpty())
return searchError(tr("PersonId or PersonKey must be specified for Authenticate"));
searchPersonKey = faceBase->personKey(searchPersonId);
if ( ! searchPersonKey)
return searchError(tr("PersonId %1 does not exist").arg(searchPersonId));
}
NULLPTR(appSettings); NULLPTR(writer);
QStringList qsl;
appSettings->setValue("Search/Status", "Scanning Directory");
QString dirName = appSettings->value("Search/InputDir", "../Search").toString();
if (dirName.isEmpty())
return searchError("Search/InputDir is empty");
searchDir = writer->baseDir();
if ( ! searchDir.cd(dirName))
return searchError(tr("Can't cd to %1").arg(dirName));
searchPending = searchDir.entryList(QDir::Files);
authWatcher = new QFileSystemWatcher(QStringList() << searchDir.absolutePath(), this);
connect(authWatcher, SIGNAL(directoryChanged(QString)),
this, SLOT(authDirChange(QString)));
searchResults = tr("Authenticating %1:%2").arg(searchPersonKey).arg(searchPersonId);
appSettings->setValue("Search/Status", "Collecting");
int toMsec = appSettings->value("Search/AuthTimeout", 5000).toInt();
QTimer::singleShot(toMsec, this, SLOT(authFinished()));
QTimer::singleShot(10, this, SLOT(tryAuthenticate()));
} // doAuthenticate()
void IfSearch::authDirChange(QString path)
{
searchPending = searchDir.entryList(QDir::Files);
if ( ! searchTemplate.isEmpty() && searchPending.isEmpty())
{
searchResults += resultsDelimiter + "Cancelled";
authFinished();
}
else
QTimer::singleShot(10, this, SLOT(tryAuthenticate()));
}
void IfSearch::tryAuthenticate(void)
{
foreach (QString id, searchTemplate.idList())
{
if (searchPending.contains(id))
searchPending.removeAll(id);
else
{
searchTemplate.removeById(id);
searchResults += resultsDelimiter + tr("%1 Removed").arg(id);
}
}
foreach (QString fileName, searchPending)
{
INDI::EigenFaceTemplate tpl;
DDT::Return rtn = tpl.read(searchDir.absoluteFilePath(fileName));
if (rtn.isError()) return searchError(rtn.toString());
tpl.setVectorId(fileName);
searchTemplate.add(tpl);
searchResults += resultsDelimiter + tr("%1 Active").arg(fileName);
}
int minFaces = appSettings->value("Search/AuthMinFaces", 3).toInt();
int maxFaces = appSettings->value("Search/AuthMaxFaces", 10).toInt();
int passConfidence = appSettings->value("Search/AuthPassConfidence", 850).toInt();
if (searchTemplate.size() >= minFaces)
{
QList<int> faceKeys = faceBase->personFaceKeys(searchPersonKey);
EigenFaceSearchResultList resList
= eigenMatcher->search(INDI::EigenFaceSearchSettings::Authenticate,
searchTemplate,
&searchSettings,
faceKeys);
authConfidence = resList.bestConfidence();
searchResults += resultsDelimiter + tr("Confidence=%1").arg(authConfidence);
appSettings->setValue("Search/Confidence", authConfidence);
appSettings->setValue("Search/Status", tr("Update %1").arg(++authUpdate));
if (authConfidence >= passConfidence)
{
searchResults += resultsDelimiter + "Pass";
authFinished();
}
if (searchTemplate.size() >= maxFaces)
{
searchResults += resultsDelimiter + "MaxFaces";
authFinished();
}
}
}
void IfSearch::authFinished(void)
{
delete authWatcher;
authWatcher = 0;
int failConfidence = appSettings->value("Search/AuthFailConfidence", 600).toInt();
int passConfidence = appSettings->value("Search/AuthPassConfidence", 850).toInt();
if (authConfidence < failConfidence)
appSettings->setValue("Search/Authenticate", "Fail");
else if (authConfidence >= passConfidence)
appSettings->setValue("Search/Authenticate", "Pass");
else
appSettings->setValue("Search/Authenticate", "Maybe");
return searchFinish();
}
|
// Copyright 2014 PDFium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Original code copyright 2014 Foxit Software Inc. http://www.foxitsoftware.com
#include "core/fxcodec/tiff/tiff_decoder.h"
#include <limits>
#include <memory>
#include "core/fxcodec/cfx_codec_memory.h"
#include "core/fxcodec/fx_codec.h"
#include "core/fxcodec/fx_codec_def.h"
#include "core/fxcrt/fx_safe_types.h"
#include "core/fxcrt/fx_stream.h"
#include "core/fxcrt/fx_system.h"
#include "core/fxcrt/retain_ptr.h"
#include "core/fxge/dib/cfx_dibitmap.h"
#include "core/fxge/dib/fx_dib.h"
#include "third_party/base/check.h"
#include "third_party/base/notreached.h"
#include "third_party/base/numerics/safe_conversions.h"
extern "C" {
#include "third_party/libtiff/tiffiop.h"
} // extern C
namespace {
// For use with std::unique_ptr<TIFF>.
struct TiffDeleter {
inline void operator()(TIFF* context) { TIFFClose(context); }
};
} // namespace
class CTiffContext final : public ProgressiveDecoderIface::Context {
public:
CTiffContext() = default;
~CTiffContext() override = default;
bool InitDecoder(const RetainPtr<IFX_SeekableReadStream>& file_ptr);
bool LoadFrameInfo(int32_t frame,
int32_t* width,
int32_t* height,
int32_t* comps,
int32_t* bpc,
CFX_DIBAttribute* pAttribute);
bool Decode(const RetainPtr<CFX_DIBitmap>& pDIBitmap);
RetainPtr<IFX_SeekableReadStream> io_in() const { return m_io_in; }
uint32_t offset() const { return m_offset; }
void set_offset(uint32_t offset) { m_offset = offset; }
private:
bool IsSupport(const RetainPtr<CFX_DIBitmap>& pDIBitmap) const;
void SetPalette(const RetainPtr<CFX_DIBitmap>& pDIBitmap, uint16_t bps);
bool Decode1bppRGB(const RetainPtr<CFX_DIBitmap>& pDIBitmap,
int32_t height,
int32_t width,
uint16_t bps,
uint16_t spp);
bool Decode8bppRGB(const RetainPtr<CFX_DIBitmap>& pDIBitmap,
int32_t height,
int32_t width,
uint16_t bps,
uint16_t spp);
bool Decode24bppRGB(const RetainPtr<CFX_DIBitmap>& pDIBitmap,
int32_t height,
int32_t width,
uint16_t bps,
uint16_t spp);
RetainPtr<IFX_SeekableReadStream> m_io_in;
uint32_t m_offset = 0;
std::unique_ptr<TIFF, TiffDeleter> m_tif_ctx;
};
void* _TIFFcalloc(tmsize_t nmemb, tmsize_t siz) {
return FXMEM_DefaultCalloc(nmemb, siz);
}
void* _TIFFmalloc(tmsize_t size) {
return FXMEM_DefaultAlloc(size);
}
void _TIFFfree(void* ptr) {
if (ptr)
FXMEM_DefaultFree(ptr);
}
void* _TIFFrealloc(void* ptr, tmsize_t size) {
return FXMEM_DefaultRealloc(ptr, size);
}
void _TIFFmemset(void* ptr, int val, tmsize_t size) {
memset(ptr, val, static_cast<size_t>(size));
}
void _TIFFmemcpy(void* des, const void* src, tmsize_t size) {
memcpy(des, src, static_cast<size_t>(size));
}
int _TIFFmemcmp(const void* ptr1, const void* ptr2, tmsize_t size) {
return memcmp(ptr1, ptr2, static_cast<size_t>(size));
}
TIFFErrorHandler _TIFFwarningHandler = nullptr;
TIFFErrorHandler _TIFFerrorHandler = nullptr;
namespace {
tsize_t tiff_read(thandle_t context, tdata_t buf, tsize_t length) {
CTiffContext* pTiffContext = reinterpret_cast<CTiffContext*>(context);
FX_SAFE_UINT32 increment = pTiffContext->offset();
increment += length;
if (!increment.IsValid())
return 0;
FX_FILESIZE offset = pTiffContext->offset();
if (!pTiffContext->io_in()->ReadBlockAtOffset(buf, offset, length))
return 0;
pTiffContext->set_offset(increment.ValueOrDie());
if (offset + length > pTiffContext->io_in()->GetSize()) {
return pdfium::base::checked_cast<tsize_t>(
pTiffContext->io_in()->GetSize() - offset);
}
return length;
}
tsize_t tiff_write(thandle_t context, tdata_t buf, tsize_t length) {
NOTREACHED();
return 0;
}
toff_t tiff_seek(thandle_t context, toff_t offset, int whence) {
CTiffContext* pTiffContext = reinterpret_cast<CTiffContext*>(context);
FX_SAFE_FILESIZE safe_offset = offset;
if (!safe_offset.IsValid())
return static_cast<toff_t>(-1);
FX_FILESIZE file_offset = safe_offset.ValueOrDie();
switch (whence) {
case 0: {
if (file_offset > pTiffContext->io_in()->GetSize())
return static_cast<toff_t>(-1);
pTiffContext->set_offset(
pdfium::base::checked_cast<uint32_t>(file_offset));
return pTiffContext->offset();
}
case 1: {
FX_SAFE_UINT32 new_increment = pTiffContext->offset();
new_increment += file_offset;
if (!new_increment.IsValid())
return static_cast<toff_t>(-1);
pTiffContext->set_offset(new_increment.ValueOrDie());
return pTiffContext->offset();
}
case 2: {
if (pTiffContext->io_in()->GetSize() < file_offset)
return static_cast<toff_t>(-1);
pTiffContext->set_offset(pdfium::base::checked_cast<uint32_t>(
pTiffContext->io_in()->GetSize() - file_offset));
return pTiffContext->offset();
}
default:
return static_cast<toff_t>(-1);
}
}
int tiff_close(thandle_t context) {
return 0;
}
toff_t tiff_get_size(thandle_t context) {
CTiffContext* pTiffContext = reinterpret_cast<CTiffContext*>(context);
return static_cast<toff_t>(pTiffContext->io_in()->GetSize());
}
int tiff_map(thandle_t context, tdata_t*, toff_t*) {
return 0;
}
void tiff_unmap(thandle_t context, tdata_t, toff_t) {}
TIFF* tiff_open(void* context, const char* mode) {
TIFF* tif = TIFFClientOpen("Tiff Image", mode, (thandle_t)context, tiff_read,
tiff_write, tiff_seek, tiff_close, tiff_get_size,
tiff_map, tiff_unmap);
if (tif) {
tif->tif_fd = (int)(intptr_t)context;
}
return tif;
}
template <class T>
bool Tiff_Exif_GetInfo(TIFF* tif_ctx, ttag_t tag, CFX_DIBAttribute* pAttr) {
T val = 0;
TIFFGetField(tif_ctx, tag, &val);
if (!val)
return false;
T* ptr = FX_Alloc(T, 1);
*ptr = val;
pAttr->m_Exif[tag] = ptr;
return true;
}
void Tiff_Exif_GetStringInfo(TIFF* tif_ctx,
ttag_t tag,
CFX_DIBAttribute* pAttr) {
char* buf = nullptr;
TIFFGetField(tif_ctx, tag, &buf);
if (!buf)
return;
size_t size = strlen(buf);
uint8_t* ptr = FX_AllocUninit(uint8_t, size + 1);
memcpy(ptr, buf, size);
ptr[size] = 0;
pAttr->m_Exif[tag] = ptr;
}
void TiffBGRA2RGBA(uint8_t* pBuf, int32_t pixel, int32_t spp) {
for (int32_t n = 0; n < pixel; n++) {
uint8_t tmp = pBuf[0];
pBuf[0] = pBuf[2];
pBuf[2] = tmp;
pBuf += spp;
}
}
} // namespace
bool CTiffContext::InitDecoder(
const RetainPtr<IFX_SeekableReadStream>& file_ptr) {
m_io_in = file_ptr;
m_tif_ctx.reset(tiff_open(this, "r"));
return !!m_tif_ctx;
}
bool CTiffContext::LoadFrameInfo(int32_t frame,
int32_t* width,
int32_t* height,
int32_t* comps,
int32_t* bpc,
CFX_DIBAttribute* pAttribute) {
if (!TIFFSetDirectory(m_tif_ctx.get(), (uint16)frame))
return false;
uint32_t tif_width = 0;
uint32_t tif_height = 0;
uint16_t tif_comps = 0;
uint16_t tif_bpc = 0;
uint32_t tif_rps = 0;
TIFFGetField(m_tif_ctx.get(), TIFFTAG_IMAGEWIDTH, &tif_width);
TIFFGetField(m_tif_ctx.get(), TIFFTAG_IMAGELENGTH, &tif_height);
TIFFGetField(m_tif_ctx.get(), TIFFTAG_SAMPLESPERPIXEL, &tif_comps);
TIFFGetField(m_tif_ctx.get(), TIFFTAG_BITSPERSAMPLE, &tif_bpc);
TIFFGetField(m_tif_ctx.get(), TIFFTAG_ROWSPERSTRIP, &tif_rps);
pAttribute->m_wDPIUnit = FXCODEC_RESUNIT_INCH;
if (TIFFGetField(m_tif_ctx.get(), TIFFTAG_RESOLUTIONUNIT,
&pAttribute->m_wDPIUnit)) {
pAttribute->m_wDPIUnit--;
}
Tiff_Exif_GetInfo<uint16_t>(m_tif_ctx.get(), TIFFTAG_ORIENTATION, pAttribute);
if (Tiff_Exif_GetInfo<float>(m_tif_ctx.get(), TIFFTAG_XRESOLUTION,
pAttribute)) {
void* val = pAttribute->m_Exif[TIFFTAG_XRESOLUTION];
float fDpi = val ? *reinterpret_cast<float*>(val) : 0;
pAttribute->m_nXDPI = static_cast<int32_t>(fDpi + 0.5f);
}
if (Tiff_Exif_GetInfo<float>(m_tif_ctx.get(), TIFFTAG_YRESOLUTION,
pAttribute)) {
void* val = pAttribute->m_Exif[TIFFTAG_YRESOLUTION];
float fDpi = val ? *reinterpret_cast<float*>(val) : 0;
pAttribute->m_nYDPI = static_cast<int32_t>(fDpi + 0.5f);
}
Tiff_Exif_GetStringInfo(m_tif_ctx.get(), TIFFTAG_IMAGEDESCRIPTION,
pAttribute);
Tiff_Exif_GetStringInfo(m_tif_ctx.get(), TIFFTAG_MAKE, pAttribute);
Tiff_Exif_GetStringInfo(m_tif_ctx.get(), TIFFTAG_MODEL, pAttribute);
FX_SAFE_INT32 checked_width = tif_width;
FX_SAFE_INT32 checked_height = tif_height;
if (!checked_width.IsValid() || !checked_height.IsValid())
return false;
*width = checked_width.ValueOrDie();
*height = checked_height.ValueOrDie();
*comps = tif_comps;
*bpc = tif_bpc;
if (tif_rps > tif_height) {
tif_rps = tif_height;
TIFFSetField(m_tif_ctx.get(), TIFFTAG_ROWSPERSTRIP, tif_rps);
}
return true;
}
bool CTiffContext::IsSupport(const RetainPtr<CFX_DIBitmap>& pDIBitmap) const {
if (TIFFIsTiled(m_tif_ctx.get()))
return false;
uint16_t photometric = 0;
if (!TIFFGetField(m_tif_ctx.get(), TIFFTAG_PHOTOMETRIC, &photometric))
return false;
switch (pDIBitmap->GetBPP()) {
case 1:
case 8:
if (photometric != PHOTOMETRIC_PALETTE) {
return false;
}
break;
case 24:
if (photometric != PHOTOMETRIC_RGB) {
return false;
}
break;
default:
return false;
}
uint16_t planarconfig = 0;
if (!TIFFGetFieldDefaulted(m_tif_ctx.get(), TIFFTAG_PLANARCONFIG,
&planarconfig))
return false;
return planarconfig != PLANARCONFIG_SEPARATE;
}
void CTiffContext::SetPalette(const RetainPtr<CFX_DIBitmap>& pDIBitmap,
uint16_t bps) {
uint16_t* red_orig = nullptr;
uint16_t* green_orig = nullptr;
uint16_t* blue_orig = nullptr;
TIFFGetField(m_tif_ctx.get(), TIFFTAG_COLORMAP, &red_orig, &green_orig,
&blue_orig);
for (int32_t i = pdfium::base::checked_cast<int32_t>((1L << bps) - 1); i >= 0;
i--) {
#define CVT(x) ((uint16_t)((x) >> 8))
red_orig[i] = CVT(red_orig[i]);
green_orig[i] = CVT(green_orig[i]);
blue_orig[i] = CVT(blue_orig[i]);
#undef CVT
}
int32_t len = 1 << bps;
for (int32_t index = 0; index < len; index++) {
uint32_t r = red_orig[index] & 0xFF;
uint32_t g = green_orig[index] & 0xFF;
uint32_t b = blue_orig[index] & 0xFF;
uint32_t color = (uint32_t)b | ((uint32_t)g << 8) | ((uint32_t)r << 16) |
(((uint32)0xffL) << 24);
pDIBitmap->SetPaletteArgb(index, color);
}
}
bool CTiffContext::Decode1bppRGB(const RetainPtr<CFX_DIBitmap>& pDIBitmap,
int32_t height,
int32_t width,
uint16_t bps,
uint16_t spp) {
if (pDIBitmap->GetBPP() != 1 || spp != 1 || bps != 1 ||
!IsSupport(pDIBitmap)) {
return false;
}
SetPalette(pDIBitmap, bps);
int32_t size = static_cast<int32_t>(TIFFScanlineSize(m_tif_ctx.get()));
uint8_t* buf = (uint8_t*)_TIFFmalloc(size);
if (!buf) {
TIFFError(TIFFFileName(m_tif_ctx.get()), "No space for scanline buffer");
return false;
}
for (int32_t row = 0; row < height; row++) {
uint8_t* bitMapbuffer = pDIBitmap->GetWritableScanline(row).data();
TIFFReadScanline(m_tif_ctx.get(), buf, row, 0);
for (int32_t j = 0; j < size; j++) {
bitMapbuffer[j] = buf[j];
}
}
_TIFFfree(buf);
return true;
}
bool CTiffContext::Decode8bppRGB(const RetainPtr<CFX_DIBitmap>& pDIBitmap,
int32_t height,
int32_t width,
uint16_t bps,
uint16_t spp) {
if (pDIBitmap->GetBPP() != 8 || spp != 1 || (bps != 4 && bps != 8) ||
!IsSupport(pDIBitmap)) {
return false;
}
SetPalette(pDIBitmap, bps);
int32_t size = static_cast<int32_t>(TIFFScanlineSize(m_tif_ctx.get()));
uint8_t* buf = (uint8_t*)_TIFFmalloc(size);
if (!buf) {
TIFFError(TIFFFileName(m_tif_ctx.get()), "No space for scanline buffer");
return false;
}
for (int32_t row = 0; row < height; row++) {
uint8_t* bitMapbuffer = pDIBitmap->GetWritableScanline(row).data();
TIFFReadScanline(m_tif_ctx.get(), buf, row, 0);
for (int32_t j = 0; j < size; j++) {
switch (bps) {
case 4:
bitMapbuffer[2 * j + 0] = (buf[j] & 0xF0) >> 4;
bitMapbuffer[2 * j + 1] = (buf[j] & 0x0F) >> 0;
break;
case 8:
bitMapbuffer[j] = buf[j];
break;
}
}
}
_TIFFfree(buf);
return true;
}
bool CTiffContext::Decode24bppRGB(const RetainPtr<CFX_DIBitmap>& pDIBitmap,
int32_t height,
int32_t width,
uint16_t bps,
uint16_t spp) {
if (pDIBitmap->GetBPP() != 24 || !IsSupport(pDIBitmap))
return false;
int32_t size = static_cast<int32_t>(TIFFScanlineSize(m_tif_ctx.get()));
uint8_t* buf = (uint8_t*)_TIFFmalloc(size);
if (!buf) {
TIFFError(TIFFFileName(m_tif_ctx.get()), "No space for scanline buffer");
return false;
}
for (int32_t row = 0; row < height; row++) {
uint8_t* bitMapbuffer = pDIBitmap->GetWritableScanline(row).data();
TIFFReadScanline(m_tif_ctx.get(), buf, row, 0);
for (int32_t j = 0; j < size - 2; j += 3) {
bitMapbuffer[j + 0] = buf[j + 2];
bitMapbuffer[j + 1] = buf[j + 1];
bitMapbuffer[j + 2] = buf[j + 0];
}
}
_TIFFfree(buf);
return true;
}
bool CTiffContext::Decode(const RetainPtr<CFX_DIBitmap>& pDIBitmap) {
uint32_t img_width = pDIBitmap->GetWidth();
uint32_t img_height = pDIBitmap->GetHeight();
uint32_t width = 0;
uint32_t height = 0;
TIFFGetField(m_tif_ctx.get(), TIFFTAG_IMAGEWIDTH, &width);
TIFFGetField(m_tif_ctx.get(), TIFFTAG_IMAGELENGTH, &height);
if (img_width != width || img_height != height)
return false;
if (pDIBitmap->GetBPP() == 32) {
uint16_t rotation = ORIENTATION_TOPLEFT;
TIFFGetField(m_tif_ctx.get(), TIFFTAG_ORIENTATION, &rotation);
if (TIFFReadRGBAImageOriented(m_tif_ctx.get(), img_width, img_height,
(uint32*)pDIBitmap->GetBuffer(), rotation,
1)) {
for (uint32_t row = 0; row < img_height; row++) {
uint8_t* row_buf = pDIBitmap->GetWritableScanline(row).data();
TiffBGRA2RGBA(row_buf, img_width, 4);
}
return true;
}
}
uint16_t spp = 0;
uint16_t bps = 0;
TIFFGetField(m_tif_ctx.get(), TIFFTAG_SAMPLESPERPIXEL, &spp);
TIFFGetField(m_tif_ctx.get(), TIFFTAG_BITSPERSAMPLE, &bps);
FX_SAFE_UINT32 safe_bpp = bps;
safe_bpp *= spp;
if (!safe_bpp.IsValid())
return false;
uint32_t bpp = safe_bpp.ValueOrDie();
if (bpp == 1)
return Decode1bppRGB(pDIBitmap, height, width, bps, spp);
if (bpp <= 8)
return Decode8bppRGB(pDIBitmap, height, width, bps, spp);
if (bpp <= 24)
return Decode24bppRGB(pDIBitmap, height, width, bps, spp);
return false;
}
namespace fxcodec {
// static
std::unique_ptr<ProgressiveDecoderIface::Context> TiffDecoder::CreateDecoder(
const RetainPtr<IFX_SeekableReadStream>& file_ptr) {
auto pDecoder = std::make_unique<CTiffContext>();
if (!pDecoder->InitDecoder(file_ptr))
return nullptr;
return pDecoder;
}
// static
bool TiffDecoder::LoadFrameInfo(ProgressiveDecoderIface::Context* pContext,
int32_t frame,
int32_t* width,
int32_t* height,
int32_t* comps,
int32_t* bpc,
CFX_DIBAttribute* pAttribute) {
DCHECK(pAttribute);
auto* ctx = static_cast<CTiffContext*>(pContext);
return ctx->LoadFrameInfo(frame, width, height, comps, bpc, pAttribute);
}
// static
bool TiffDecoder::Decode(ProgressiveDecoderIface::Context* pContext,
const RetainPtr<CFX_DIBitmap>& pDIBitmap) {
auto* ctx = static_cast<CTiffContext*>(pContext);
return ctx->Decode(pDIBitmap);
}
} // namespace fxcodec
|
#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32
#define WIN32_LEAN_AND_MEAN
#include "windows.h"
#endif
#include "BvhViewerApp.h"
#ifdef __cplusplus
extern "C" {
#endif
#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32
INT WINAPI WinMain( HINSTANCE hInst, HINSTANCE, LPSTR strCmdLine, INT )
#else
int main(int argc, char *argv[])
#endif
{
// Create application object
BVHViewer_Application::BvhViewerApp app;
try {
app.go();
} catch( Ogre::Exception& e ) {
#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32
MessageBox( NULL, e.getFullDescription().c_str(), "An exception has occured!", MB_OK | MB_ICONERROR | MB_TASKMODAL);
#else
std::cerr << "An exception has occured: " <<
e.getFullDescription().c_str() << std::endl;
#endif
}
return 0;
}
#ifdef __cplusplus
}
#endif
|
// Name: S, Version: b
#include "../SDK.h"
#ifdef _MSC_VER
#pragma pack(push, 0x01)
#endif
/*!!HELPER_DEF!!*/
/*!!DEFINE!!*/
namespace UFT
{
//---------------------------------------------------------------------------
// Functions
//---------------------------------------------------------------------------
// Function W_WorldMarker.W_WorldMarker_C.ADS
// (Public, HasOutParms, BlueprintCallable, BlueprintEvent, BlueprintPure)
// Parameters:
// bool In_ADS (Parm, OutParm, ZeroConstructor, IsPlainOldData, NoDestructor)
void UW_WorldMarker_C::ADS(bool* In_ADS)
{
static auto fn = UObject::FindObject<UFunction>("Function W_WorldMarker.W_WorldMarker_C.ADS");
UW_WorldMarker_C_ADS_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
if (In_ADS != nullptr)
*In_ADS = params.In_ADS;
}
// Function W_WorldMarker.W_WorldMarker_C.Construct
// (BlueprintCosmetic, Event, Public, BlueprintEvent)
void UW_WorldMarker_C::Construct()
{
static auto fn = UObject::FindObject<UFunction>("Function W_WorldMarker.W_WorldMarker_C.Construct");
UW_WorldMarker_C_Construct_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function W_WorldMarker.W_WorldMarker_C.Tick
// (BlueprintCosmetic, Event, Public, BlueprintEvent)
// Parameters:
// struct FGeometry MyGeometry (BlueprintVisible, BlueprintReadOnly, Parm, IsPlainOldData, NoDestructor)
// float InDeltaTime (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash)
void UW_WorldMarker_C::Tick(const struct FGeometry& MyGeometry, float InDeltaTime)
{
static auto fn = UObject::FindObject<UFunction>("Function W_WorldMarker.W_WorldMarker_C.Tick");
UW_WorldMarker_C_Tick_Params params;
params.MyGeometry = MyGeometry;
params.InDeltaTime = InDeltaTime;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function W_WorldMarker.W_WorldMarker_C.End
// (BlueprintCallable, BlueprintEvent)
void UW_WorldMarker_C::End()
{
static auto fn = UObject::FindObject<UFunction>("Function W_WorldMarker.W_WorldMarker_C.End");
UW_WorldMarker_C_End_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function W_WorldMarker.W_WorldMarker_C.ExecuteUbergraph_W_WorldMarker
// (Final, HasDefaults)
// Parameters:
// int EntryPoint (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash)
void UW_WorldMarker_C::ExecuteUbergraph_W_WorldMarker(int EntryPoint)
{
static auto fn = UObject::FindObject<UFunction>("Function W_WorldMarker.W_WorldMarker_C.ExecuteUbergraph_W_WorldMarker");
UW_WorldMarker_C_ExecuteUbergraph_W_WorldMarker_Params params;
params.EntryPoint = EntryPoint;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
|
//
// Created by Lars Gebraad on 16/04/19.
//
// Includes
#include "../src/fdModel.h"
#include <fstream>
#include <iomanip>
#include <iostream>
#include <omp.h>
#include <tgmath.h>
int main() {
std::cout << "Maximum amount of OpenMP threads:" << omp_get_max_threads()
<< std::endl;
// Define test, should be the same set up as the configuration file:
// "../tests/test_configurations/default_testing_configuration.ini"
auto conf_file = "../tests/test_configurations/default_testing_configuration.ini";
auto *model_1 = new fdModel(conf_file);
auto *model_2 = new fdModel(*model_1);
real_simulation deterministic_sum_1 = 0.0;
real_simulation deterministic_sum_2 = 0.0;
for (int is = 0; is < model_1->n_shots; ++is) {
model_1->forward_simulate(is, false, true);
model_2->forward_simulate(is, false, true);
for (int i_shot = 0; i_shot < model_1->n_shots; ++i_shot) {
for (int i_receiver = 0; i_receiver < model_1->nr; ++i_receiver) {
for (int it = 0; it < model_1->nt; ++it) {
deterministic_sum_1 += model_1->rtf_ux[i_shot][i_receiver][it];
deterministic_sum_2 += model_2->rtf_ux[i_shot][i_receiver][it];
}
}
}
}
delete model_1;
delete model_2;
if (deterministic_sum_1 == deterministic_sum_2) {
std::cout << "All simulations produced the same seismograms. The test succeeded."
<< std::endl
<< std::endl;
exit(0);
} else {
std::cout << "Simulations were not consistent. The test failed." << std::endl
<< std::endl;
exit(1);
}
}
|
/*
//@HEADER
// ************************************************************************
//
// KokkosKernels 0.9: Linear Algebra and Graph Kernels
// Copyright 2017 Sandia Corporation
//
// Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
// the U.S. Government retains certain rights in this software.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// 1. Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// 2. 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.
//
// 3. Neither the name of the Corporation nor the names of the
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY SANDIA CORPORATION "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 SANDIA CORPORATION OR THE
// 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.
//
// Questions? Contact Siva Rajamanickam (srajama@sandia.gov)
//
// ************************************************************************
//@HEADER
*/
#ifndef KOKKOS_BLAS1_IMPL_HPP_
#define KOKKOS_BLAS1_IMPL_HPP_
#include <KokkosKernels_config.h>
#include <Kokkos_Core.hpp>
#include <Kokkos_InnerProductSpaceTraits.hpp>
namespace KokkosBlas {
namespace Impl {
/// \brief Functor that implements the single-vector, two-argument
/// version of KokkosBlas::dot (dot product of two vectors).
///
/// \tparam XVector Type of the first vector x; 1-D View
/// \tparam YVector Type of the second vector y; 1-D View
/// \tparam SizeType Type of the row index used in the dot product.
/// For best performance, use int instead of size_t here.
template<class XVector, class YVector, typename SizeType = typename XVector::size_type>
struct DotFunctor
{
typedef typename XVector::execution_space execution_space;
typedef SizeType size_type;
typedef typename XVector::non_const_value_type xvalue_type;
typedef Kokkos::Details::InnerProductSpaceTraits<xvalue_type> IPT;
typedef typename IPT::dot_type value_type;
XVector m_x;
YVector m_y;
DotFunctor (const XVector& x, const YVector& y) : m_x (x), m_y (y) {}
// Prefer const size_type& to const size_type or size_type,
// since the compiler has an easier time inlining the former.
KOKKOS_FORCEINLINE_FUNCTION void
operator() (const size_type &i, value_type& sum) const
{
sum += IPT::dot (m_x(i), m_y(i)); // m_x(i) * m_y(i)
}
KOKKOS_INLINE_FUNCTION void
init (volatile value_type& update) const
{
update = Kokkos::Details::ArithTraits<value_type>::zero ();
}
KOKKOS_INLINE_FUNCTION void
join (volatile value_type& update,
const volatile value_type& source) const
{
update += source ;
}
};
/// \brief Struct that implements the single-vector, two-argument
/// version of KokkosBlas::dot (dot product of two vectors).
///
/// The first five template parameters correspond to the template
/// parameters of XVector in DotFunctor (see above). The last five
/// template parameters correspond to the template parameters of
/// YVector in DotFunctor.
///
/// This is the "generic" implementation of the dot product. We
/// declare full specializations in this header file. Definitions of
/// those specializations live in one or more .cpp files in this
/// directory.
template<class XT, class XL, class XD, class XM,
class YT, class YL, class YD, class YM>
struct Dot
#ifndef KOKKOSKERNELS_ETI_ONLY
{
typedef Kokkos::View<XT,XL,XD,XM> XVector;
typedef Kokkos::View<YT,YL,YD,YM> YVector;
typedef typename Kokkos::Details::InnerProductSpaceTraits<typename XVector::non_const_value_type>::dot_type dot_type;
//! Return the dot product of x and y.
static dot_type
dot (const XVector& x, const YVector& y)
{
dot_type result;
// With Intel 15, Scalar = double, Kokkos::Serial execution space,
// with 100000 entries for 1000 trials, using int instead of
// size_t is 2x faster.
if (x.dimension_0 () < typename XVector::size_type (INT_MAX)) {
Kokkos::RangePolicy<typename XVector::execution_space, int> policy (0, x.dimension_0 ());
typedef DotFunctor<XVector, YVector, int> functor_type;
Kokkos::parallel_reduce (policy, functor_type (x, y), result);
}
else {
typedef typename XVector::size_type size_type;
Kokkos::RangePolicy<typename XVector::execution_space, size_type> policy (0, x.dimension_0 ());
typedef DotFunctor<XVector, YVector, size_type> functor_type;
Kokkos::parallel_reduce (policy, functor_type (x, y), result);
}
return result;
}
/// \brief Return the dot product of x and y.
///
/// \param x [in] First vector.
/// \param y [in] Second vector.
/// \param label [in] This is passed into Kokkos::parallel_for, as a
/// label for profiling.
static dot_type
dot (const std::string& label, const XVector& x, const YVector& y)
{
dot_type result;
if (x.dimension_0 () < typename XVector::size_type (INT_MAX)) {
Kokkos::RangePolicy<typename XVector::execution_space, int> policy (0, x.dimension_0 ());
typedef DotFunctor<XVector, YVector, int> functor_type;
Kokkos::parallel_reduce (label, policy, functor_type (x, y), result);
}
else {
typedef typename XVector::size_type size_type;
Kokkos::RangePolicy<typename XVector::execution_space, size_type> policy (0, x.dimension_0 ());
typedef DotFunctor<XVector, YVector, size_type> functor_type;
Kokkos::parallel_reduce (label, policy, functor_type (x, y), result);
}
return result;
}
}
#endif
;
//
// Macro that declares a full specialization of the Dot struct.
//
#define KOKKOSBLAS_IMPL_V_DOT_DECL( SCALAR, LAYOUT, EXEC_SPACE, MEM_SPACE ) \
extern template struct Dot<const SCALAR*, \
LAYOUT, \
Kokkos::Device<EXEC_SPACE, MEM_SPACE>, \
Kokkos::MemoryTraits<Kokkos::Unmanaged> , \
const SCALAR*, \
LAYOUT, \
Kokkos::Device<EXEC_SPACE, MEM_SPACE>, \
Kokkos::MemoryTraits<Kokkos::Unmanaged> >;
//
// Macro that defines a full specialization of the Dot struct.
// This macro is invoked in one or more .cpp files in this directory.
//
#define KOKKOSBLAS_IMPL_V_DOT_DEF( SCALAR, LAYOUT, EXEC_SPACE, MEM_SPACE ) \
template struct Dot<const SCALAR*, \
LAYOUT, \
Kokkos::Device<EXEC_SPACE, MEM_SPACE>, \
Kokkos::MemoryTraits<Kokkos::Unmanaged> , \
const SCALAR*, \
LAYOUT, \
Kokkos::Device<EXEC_SPACE, MEM_SPACE>, \
Kokkos::MemoryTraits<Kokkos::Unmanaged> >;
} // namespace Impl
} // namespace KokkosBlas
#endif // KOKKOS_BLAS1_IMPL_HPP_
|
/**
* 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 "src/runtime/kernel/arm/fp16/matmul_fp16.h"
#include "include/errorcode.h"
#include "src/kernel_registry.h"
using mindspore::lite::KernelRegistrar;
using mindspore::lite::RET_ERROR;
using mindspore::lite::RET_OK;
using mindspore::schema::PrimitiveType_MatMul;
namespace mindspore::kernel {
void MatmulFP16CPUKernel::InitAShape() {
auto a_shape = in_tensors_[0]->shape();
if (a_shape.empty()) {
return;
}
MS_CHECK_TRUE_RET_VOID(a_shape.size() >= 2);
int batch = 1;
for (size_t i = 0; i < a_shape.size() - 2; ++i) {
batch *= a_shape[i];
}
params_->batch = batch;
params_->row_ = params_->a_transpose_ ? a_shape[a_shape.size() - 1] : a_shape[a_shape.size() - 2];
params_->deep_ = params_->a_transpose_ ? a_shape[a_shape.size() - 2] : a_shape[a_shape.size() - 1];
params_->row_16_ = UP_ROUND(params_->row_, row_tile_);
}
void MatmulFP16CPUKernel::InitBShape() {
auto b_shape = in_tensors_[1]->shape();
if (b_shape.empty()) {
return;
}
MS_CHECK_TRUE_RET_VOID(b_shape.size() >= 2);
int batch = 1;
for (size_t i = 0; i < b_shape.size() - 2; ++i) {
batch *= b_shape[i];
}
params_->batch = batch;
params_->col_ = params_->b_transpose_ ? b_shape[b_shape.size() - 2] : b_shape[b_shape.size() - 1];
params_->col_8_ = UP_ROUND(params_->col_, 8);
params_->deep_ = params_->b_transpose_ ? b_shape[b_shape.size() - 1] : b_shape[b_shape.size() - 2];
}
int MatmulFP16CPUKernel::Prepare() {
CHECK_LESS_RETURN(in_tensors_.size(), 2);
CHECK_LESS_RETURN(out_tensors_.size(), 1);
#ifdef ENABLE_ARM64
row_tile_ = C4NUM;
#else
row_tile_ = C12NUM;
#endif
MatmulBaseFP16CPUKernel::InitParameter();
if (params_->a_const_) {
InitAShape();
}
if (params_->b_const_) {
InitBShape();
}
auto ret = MatmulBaseFP16CPUKernel::Prepare();
if (ret != RET_OK) {
return ret;
}
if (!InferShapeDone()) {
return RET_OK;
}
return ReSize();
}
int MatmulFP16CPUKernel::ReSize() {
InitAShape();
InitBShape();
return MatmulBaseFP16CPUKernel::ReSize();
}
int MatmulFP16CPUKernel::Run() {
if (IsTrainable() && (IsTrain())) {
is_repack_ = true;
}
auto ret = MatmulBaseFP16CPUKernel::Run();
if (ret != RET_OK) {
MS_LOG(ERROR) << "MatmulFP16CPUKernel run failed";
}
is_repack_ = false;
return ret;
}
int MatmulFP16CPUKernel::Eval() {
InnerKernel::Eval();
if (IsTrainable()) {
is_repack_ = true;
}
return RET_OK;
}
REG_KERNEL(kCPU, kNumberTypeFloat16, PrimitiveType_MatMul, LiteKernelCreator<MatmulFP16CPUKernel>)
} // namespace mindspore::kernel
|
/*
Copyright (c) 2013-2014 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Leonardo de Moura
Soonho Kong
*/
#include <vector>
#include <sstream>
#include <string>
#include <algorithm>
#include <limits>
#include <lean/hash.h>
#include <lean/buffer.h>
#include "util/list_fn.h"
#include "kernel/expr.h"
#include "kernel/expr_eq_fn.h"
#include "kernel/expr_sets.h"
#include "kernel/for_each_fn.h"
#include "kernel/replace_fn.h"
#include "kernel/abstract.h"
#include "kernel/instantiate.h"
namespace lean {
/* Expression literal values */
literal::literal(char const * v):
object_ref(mk_cnstr(static_cast<unsigned>(literal_kind::String), mk_string(v))) {
}
literal::literal(unsigned v):
object_ref(mk_cnstr(static_cast<unsigned>(literal_kind::Nat), mk_nat_obj(v))) {
}
literal::literal(mpz const & v):
object_ref(mk_cnstr(static_cast<unsigned>(literal_kind::Nat), mk_nat_obj(v))) {
}
literal::literal(nat const & v):
object_ref(mk_cnstr(static_cast<unsigned>(literal_kind::Nat), v)) {
}
bool operator==(literal const & a, literal const & b) {
if (a.kind() != b.kind()) return false;
switch (a.kind()) {
case literal_kind::String: return a.get_string() == b.get_string();
case literal_kind::Nat: return a.get_nat() == b.get_nat();
}
lean_unreachable();
}
bool operator<(literal const & a, literal const & b) {
if (a.kind() != b.kind()) return static_cast<unsigned>(a.kind()) < static_cast<unsigned>(b.kind());
switch (a.kind()) {
case literal_kind::String: return a.get_string() < b.get_string();
case literal_kind::Nat: return a.get_nat() < b.get_nat();
}
lean_unreachable();
}
bool is_atomic(expr const & e) {
switch (e.kind()) {
case expr_kind::Const: case expr_kind::Sort:
case expr_kind::BVar: case expr_kind::Lit:
case expr_kind::MVar: case expr_kind::FVar:
return true;
case expr_kind::App:
case expr_kind::Lambda:
case expr_kind::Pi: case expr_kind::Let:
case expr_kind::MData: case expr_kind::Proj:
return false;
}
lean_unreachable(); // LCOV_EXCL_LINE
}
extern "C" uint8 lean_expr_binder_info(object * e);
binder_info binding_info(expr const & e) { return static_cast<binder_info>(lean_expr_binder_info(e.to_obj_arg())); }
extern "C" object * lean_lit_type(obj_arg e);
expr lit_type(literal const & lit) { return expr(lean_lit_type(lit.to_obj_arg())); }
extern "C" uint64_t lean_expr_hash(obj_arg e);
unsigned hash(expr const & e) { return lean_expr_hash(e.to_obj_arg()); }
extern "C" uint8 lean_expr_has_fvar(obj_arg e);
bool has_fvar(expr const & e) { return lean_expr_has_fvar(e.to_obj_arg()); }
extern "C" uint8 lean_expr_has_expr_mvar(obj_arg e);
bool has_expr_mvar(expr const & e) { return lean_expr_has_expr_mvar(e.to_obj_arg()); }
extern "C" uint8 lean_expr_has_level_mvar(obj_arg e);
bool has_univ_mvar(expr const & e) { return lean_expr_has_level_mvar(e.to_obj_arg()); }
extern "C" uint8 lean_expr_has_level_param(obj_arg e);
bool has_univ_param(expr const & e) { return lean_expr_has_level_param(e.to_obj_arg()); }
extern "C" unsigned lean_expr_loose_bvar_range(object * e);
unsigned get_loose_bvar_range(expr const & e) { return lean_expr_loose_bvar_range(e.to_obj_arg()); }
// =======================================
// Constructors
static expr * g_dummy = nullptr;
static expr const & get_dummy() {
if (!g_dummy) {
g_dummy = new expr(mk_constant("__expr_for_default_constructor__"));
mark_persistent(g_dummy->raw());
}
return *g_dummy;
}
expr::expr():expr(get_dummy()) {}
extern "C" object * lean_expr_mk_lit(obj_arg l);
expr mk_lit(literal const & l) { return expr(lean_expr_mk_lit(l.to_obj_arg())); }
extern "C" object * lean_expr_mk_mdata(obj_arg m, obj_arg e);
expr mk_mdata(kvmap const & m, expr const & e) { return expr(lean_expr_mk_mdata(m.to_obj_arg(), e.to_obj_arg())); }
extern "C" object * lean_expr_mk_proj(obj_arg s, obj_arg idx, obj_arg e);
expr mk_proj(name const & s, nat const & idx, expr const & e) { return expr(lean_expr_mk_proj(s.to_obj_arg(), idx.to_obj_arg(), e.to_obj_arg())); }
extern "C" object * lean_expr_mk_bvar(obj_arg idx);
expr mk_bvar(nat const & idx) { return expr(lean_expr_mk_bvar(idx.to_obj_arg())); }
extern "C" object * lean_expr_mk_fvar(obj_arg n);
expr mk_fvar(name const & n) { return expr(lean_expr_mk_fvar(n.to_obj_arg())); }
extern "C" object * lean_expr_mk_mvar(object * n);
expr mk_mvar(name const & n) { return expr(lean_expr_mk_mvar(n.to_obj_arg())); }
extern "C" object * lean_expr_mk_const(obj_arg n, obj_arg ls);
expr mk_const(name const & n, levels const & ls) { return expr(lean_expr_mk_const(n.to_obj_arg(), ls.to_obj_arg())); }
extern "C" object * lean_expr_mk_app(obj_arg f, obj_arg a);
expr mk_app(expr const & f, expr const & a) { return expr(lean_expr_mk_app(f.to_obj_arg(), a.to_obj_arg())); }
extern "C" object * lean_expr_mk_sort(obj_arg l);
expr mk_sort(level const & l) { return expr(lean_expr_mk_sort(l.to_obj_arg())); }
extern "C" object * lean_expr_mk_lambda(obj_arg n, obj_arg t, obj_arg e, uint8 bi);
expr mk_lambda(name const & n, expr const & t, expr const & e, binder_info bi) {
return expr(lean_expr_mk_lambda(n.to_obj_arg(), t.to_obj_arg(), e.to_obj_arg(), static_cast<uint8>(bi)));
}
extern "C" object * lean_expr_mk_forall(obj_arg n, obj_arg t, obj_arg e, uint8 bi);
expr mk_pi(name const & n, expr const & t, expr const & e, binder_info bi) {
return expr(lean_expr_mk_forall(n.to_obj_arg(), t.to_obj_arg(), e.to_obj_arg(), static_cast<uint8>(bi)));
}
static name * g_default_name = nullptr;
expr mk_arrow(expr const & t, expr const & e) {
return mk_pi(*g_default_name, t, e, mk_binder_info());
}
extern "C" object * lean_expr_mk_let(object * n, object * t, object * v, object * b);
expr mk_let(name const & n, expr const & t, expr const & v, expr const & b) {
return expr(lean_expr_mk_let(n.to_obj_arg(), t.to_obj_arg(), v.to_obj_arg(), b.to_obj_arg()));
}
static expr * g_Prop = nullptr;
static expr * g_Type0 = nullptr;
expr mk_Prop() { return *g_Prop; }
expr mk_Type() { return *g_Type0; }
// =======================================
// Auxiliary constructors and accessors
expr mk_app(expr const & f, unsigned num_args, expr const * args) {
expr r = f;
for (unsigned i = 0; i < num_args; i++)
r = mk_app(r, args[i]);
return r;
}
expr mk_app(unsigned num_args, expr const * args) {
lean_assert(num_args >= 2);
return mk_app(mk_app(args[0], args[1]), num_args - 2, args+2);
}
expr mk_app(expr const & f, list<expr> const & args) {
buffer<expr> _args;
to_buffer(args, _args);
return mk_app(f, _args);
}
expr mk_rev_app(expr const & f, unsigned num_args, expr const * args) {
expr r = f;
unsigned i = num_args;
while (i > 0) {
--i;
r = mk_app(r, args[i]);
}
return r;
}
expr mk_rev_app(unsigned num_args, expr const * args) {
lean_assert(num_args >= 2);
return mk_rev_app(mk_app(args[num_args-1], args[num_args-2]), num_args-2, args);
}
expr const & get_app_args(expr const & e, buffer<expr> & args) {
unsigned sz = args.size();
expr const * it = &e;
while (is_app(*it)) {
args.push_back(app_arg(*it));
it = &(app_fn(*it));
}
std::reverse(args.begin() + sz, args.end());
return *it;
}
expr const & get_app_args_at_most(expr const & e, unsigned num, buffer<expr> & args) {
unsigned sz = args.size();
expr const * it = &e;
unsigned i = 0;
while (is_app(*it)) {
if (i == num)
break;
args.push_back(app_arg(*it));
it = &(app_fn(*it));
i++;
}
std::reverse(args.begin() + sz, args.end());
return *it;
}
expr const & get_app_rev_args(expr const & e, buffer<expr> & args) {
expr const * it = &e;
while (is_app(*it)) {
args.push_back(app_arg(*it));
it = &(app_fn(*it));
}
return *it;
}
expr const & get_app_fn(expr const & e) {
expr const * it = &e;
while (is_app(*it)) {
it = &(app_fn(*it));
}
return *it;
}
unsigned get_app_num_args(expr const & e) {
expr const * it = &e;
unsigned n = 0;
while (is_app(*it)) {
it = &(app_fn(*it));
n++;
}
return n;
}
bool is_arrow(expr const & t) {
if (!is_pi(t)) return false;
if (has_loose_bvars(t)) {
return !has_loose_bvar(binding_body(t), 0);
} else {
lean_assert(has_loose_bvars(binding_body(t)) == has_loose_bvar(binding_body(t), 0));
return !has_loose_bvars(binding_body(t));
}
}
bool is_default_var_name(name const & n) {
return n == *g_default_name;
}
// =======================================
// Update
expr update_mdata(expr const & e, expr const & t) {
if (!is_eqp(mdata_expr(e), t))
return mk_mdata(mdata_data(e), t);
else
return e;
}
expr update_proj(expr const & e, expr const & t) {
if (!is_eqp(proj_expr(e), t))
return mk_proj(proj_sname(e), proj_idx(e), t);
else
return e;
}
expr update_app(expr const & e, expr const & new_fn, expr const & new_arg) {
if (!is_eqp(app_fn(e), new_fn) || !is_eqp(app_arg(e), new_arg))
return mk_app(new_fn, new_arg);
else
return e;
}
expr update_binding(expr const & e, expr const & new_domain, expr const & new_body) {
if (!is_eqp(binding_domain(e), new_domain) || !is_eqp(binding_body(e), new_body))
return mk_binding(e.kind(), binding_name(e), new_domain, new_body, binding_info(e));
else
return e;
}
expr update_binding(expr const & e, expr const & new_domain, expr const & new_body, binder_info bi) {
if (!is_eqp(binding_domain(e), new_domain) || !is_eqp(binding_body(e), new_body) || bi != binding_info(e))
return mk_binding(e.kind(), binding_name(e), new_domain, new_body, bi);
else
return e;
}
expr update_sort(expr const & e, level const & new_level) {
if (!is_eqp(sort_level(e), new_level))
return mk_sort(new_level);
else
return e;
}
expr update_const(expr const & e, levels const & new_levels) {
if (!is_eqp(const_levels(e), new_levels))
return mk_const(const_name(e), new_levels);
else
return e;
}
expr update_let(expr const & e, expr const & new_type, expr const & new_value, expr const & new_body) {
if (!is_eqp(let_type(e), new_type) || !is_eqp(let_value(e), new_value) || !is_eqp(let_body(e), new_body))
return mk_let(let_name(e), new_type, new_value, new_body);
else
return e;
}
extern "C" object * lean_expr_update_mdata(obj_arg e, obj_arg new_expr) {
if (mdata_expr(TO_REF(expr, e)).raw() != new_expr) {
object * r = lean_expr_mk_mdata(mdata_data(TO_REF(expr, e)).to_obj_arg(), new_expr);
lean_dec_ref(e);
return r;
} else {
lean_dec_ref(new_expr);
return e;
}
}
extern "C" object * lean_expr_update_const(obj_arg e, obj_arg new_levels) {
if (const_levels(TO_REF(expr, e)).raw() != new_levels) {
object * r = lean_expr_mk_const(const_name(TO_REF(expr, e)).to_obj_arg(), new_levels);
lean_dec_ref(e);
return r;
} else {
lean_dec(new_levels);
return e;
}
}
extern "C" object * lean_expr_update_sort(obj_arg e, obj_arg new_level) {
if (sort_level(TO_REF(expr, e)).raw() != new_level) {
object * r = lean_expr_mk_sort(new_level);
lean_dec_ref(e);
return r;
} else {
lean_dec(new_level);
return e;
}
}
extern "C" object * lean_expr_update_proj(obj_arg e, obj_arg new_expr) {
if (proj_expr(TO_REF(expr, e)).raw() != new_expr) {
object * r = lean_expr_mk_proj(proj_sname(TO_REF(expr, e)).to_obj_arg(), proj_idx(TO_REF(expr, e)).to_obj_arg(), new_expr);
lean_dec_ref(e);
return r;
} else {
lean_dec_ref(new_expr);
return e;
}
}
extern "C" object * lean_expr_update_app(obj_arg e, obj_arg new_fn, obj_arg new_arg) {
if (app_fn(TO_REF(expr, e)).raw() != new_fn || app_arg(TO_REF(expr, e)).raw() != new_arg) {
object * r = lean_expr_mk_app(new_fn, new_arg);
lean_dec_ref(e);
return r;
} else {
lean_dec_ref(new_fn); lean_dec_ref(new_arg);
return e;
}
}
extern "C" object * lean_expr_update_forall(obj_arg e, uint8 new_binfo, obj_arg new_domain, obj_arg new_body) {
if (binding_domain(TO_REF(expr, e)).raw() != new_domain || binding_body(TO_REF(expr, e)).raw() != new_body ||
binding_info(TO_REF(expr, e)) != static_cast<binder_info>(new_binfo)) {
object * r = lean_expr_mk_forall(binding_name(TO_REF(expr, e)).to_obj_arg(), new_domain, new_body, new_binfo);
lean_dec_ref(e);
return r;
} else {
lean_dec_ref(new_domain); lean_dec_ref(new_body);
return e;
}
}
extern "C" object * lean_expr_update_lambda(obj_arg e, uint8 new_binfo, obj_arg new_domain, obj_arg new_body) {
if (binding_domain(TO_REF(expr, e)).raw() != new_domain || binding_body(TO_REF(expr, e)).raw() != new_body ||
binding_info(TO_REF(expr, e)) != static_cast<binder_info>(new_binfo)) {
object * r = lean_expr_mk_lambda(binding_name(TO_REF(expr, e)).to_obj_arg(), new_domain, new_body, new_binfo);
lean_dec_ref(e);
return r;
} else {
lean_dec_ref(new_domain); lean_dec_ref(new_body);
return e;
}
}
extern "C" object * lean_expr_update_let(obj_arg e, obj_arg new_type, obj_arg new_val, obj_arg new_body) {
if (let_type(TO_REF(expr, e)).raw() != new_type || let_value(TO_REF(expr, e)).raw() != new_val ||
let_body(TO_REF(expr, e)).raw() != new_body) {
object * r = lean_expr_mk_let(let_name(TO_REF(expr, e)).to_obj_arg(), new_type, new_val, new_body);
lean_dec_ref(e);
return r;
} else {
lean_dec_ref(new_type); lean_dec_ref(new_val); lean_dec_ref(new_body);
return e;
}
}
// =======================================
// Loose bound variable management
static bool has_loose_bvars_in_domain(expr const & b, unsigned vidx, bool strict) {
if (is_pi(b)) {
if (has_loose_bvar(binding_domain(b), vidx)) {
if (is_explicit(binding_info(b))) {
return true;
} else if (has_loose_bvars_in_domain(binding_body(b), 0, strict)) {
// "Transitivity": vidx occurs in current implicit argument, so we search for current argument in the body.
return true;
}
}
// finally we search for vidx in the body
return has_loose_bvars_in_domain(binding_body(b), vidx+1, strict);
} else if (!strict) {
return has_loose_bvar(b, vidx);
} else {
return false;
}
}
bool has_loose_bvar(expr const & e, unsigned i) {
if (!has_loose_bvars(e))
return false;
bool found = false;
for_each(e, [&](expr const & e, unsigned offset) {
if (found)
return false; // already found
unsigned n_i = i + offset;
if (n_i < i)
return false; // overflow, vidx can't be >= max unsigned
if (n_i >= get_loose_bvar_range(e))
return false; // expression e does not contain bound variables with idx >= n_i
if (is_var(e)) {
nat const & vidx = bvar_idx(e);
if (vidx == n_i)
found = true;
}
return true; // continue search
});
return found;
}
extern "C" uint8 lean_expr_has_loose_bvar(b_obj_arg e, b_obj_arg i) {
if (!lean_is_scalar(i))
return false;
return has_loose_bvar(TO_REF(expr, e), lean_unbox(i));
}
expr lower_loose_bvars(expr const & e, unsigned s, unsigned d) {
if (d == 0 || s >= get_loose_bvar_range(e))
return e;
lean_assert(s >= d);
return replace(e, [=](expr const & e, unsigned offset) -> optional<expr> {
unsigned s1 = s + offset;
if (s1 < s)
return some_expr(e); // overflow, vidx can't be >= max unsigned
if (s1 >= get_loose_bvar_range(e))
return some_expr(e); // expression e does not contain bound variables with idx >= s1
if (is_bvar(e) && bvar_idx(e) >= s1) {
lean_assert(bvar_idx(e) >= offset + d);
return some_expr(mk_bvar(bvar_idx(e) - nat(d)));
} else {
return none_expr();
}
});
}
expr lower_loose_bvars(expr const & e, unsigned d) {
return lower_loose_bvars(e, d, d);
}
extern "C" object * lean_expr_lower_loose_bvars(b_obj_arg e, b_obj_arg s, b_obj_arg d) {
if (!lean_is_scalar(s) || !lean_is_scalar(d) || lean_unbox(s) < lean_unbox(d)) {
lean_inc(e);
return e;
}
return lower_loose_bvars(TO_REF(expr, e), lean_unbox(s), lean_unbox(d)).steal();
}
expr lift_loose_bvars(expr const & e, unsigned s, unsigned d) {
if (d == 0 || s >= get_loose_bvar_range(e))
return e;
return replace(e, [=](expr const & e, unsigned offset) -> optional<expr> {
unsigned s1 = s + offset;
if (s1 < s)
return some_expr(e); // overflow, vidx can't be >= max unsigned
if (s1 >= get_loose_bvar_range(e))
return some_expr(e); // expression e does not contain bound variables with idx >= s1
if (is_var(e) && bvar_idx(e) >= s + offset) {
return some_expr(mk_bvar(bvar_idx(e) + nat(d)));
} else {
return none_expr();
}
});
}
expr lift_loose_bvars(expr const & e, unsigned d) {
return lift_loose_bvars(e, 0, d);
}
extern "C" object * lean_expr_lift_loose_bvars(b_obj_arg e, b_obj_arg s, b_obj_arg d) {
if (!lean_is_scalar(s) || !lean_is_scalar(d)) {
lean_inc(e);
return e;
}
return lift_loose_bvars(TO_REF(expr, e), lean_unbox(s), lean_unbox(d)).steal();
}
// =======================================
// Implicit argument inference
expr infer_implicit(expr const & t, unsigned num_params, bool strict) {
if (num_params == 0) {
return t;
} else if (is_pi(t)) {
expr new_body = infer_implicit(binding_body(t), num_params-1, strict);
if (!is_explicit(binding_info(t))) {
// argument is already marked as implicit
return update_binding(t, binding_domain(t), new_body);
} else if (has_loose_bvars_in_domain(new_body, 0, strict)) {
return update_binding(t, binding_domain(t), new_body, mk_implicit_binder_info());
} else {
return update_binding(t, binding_domain(t), new_body);
}
} else {
return t;
}
}
expr infer_implicit(expr const & t, bool strict) {
return infer_implicit(t, std::numeric_limits<unsigned>::max(), strict);
}
// =======================================
// Initialization & Finalization
void initialize_expr() {
get_dummy();
g_default_name = new name("a");
mark_persistent(g_default_name->raw());
g_Type0 = new expr(mk_sort(mk_level_one()));
mark_persistent(g_Type0->raw());
g_Prop = new expr(mk_sort(mk_level_zero()));
mark_persistent(g_Prop->raw());
/* TODO(Leo): add support for builtin constants in the kernel.
Something similar to what we have in the library directory. */
}
void finalize_expr() {
delete g_Prop;
delete g_Type0;
delete g_dummy;
delete g_default_name;
}
// =======================================
// Legacy
optional<expr> has_expr_metavar_strict(expr const & e) {
if (!has_expr_metavar(e))
return none_expr();
optional<expr> r;
for_each(e, [&](expr const & e, unsigned) {
if (r || !has_expr_metavar(e)) return false;
if (is_metavar_app(e)) { r = e; return false; }
return true;
});
return r;
}
}
|
#include "stdafx.h"
CustomActionData::CustomActionData() :
domainUser(false),
doInstallSysprobe(false)
{
}
CustomActionData::~CustomActionData()
{
}
bool CustomActionData::init(MSIHANDLE hi)
{
this->hInstall = hi;
std::wstring data;
if (!loadPropertyString(this->hInstall, propertyCustomActionData.c_str(), data)) {
return false;
}
return init(data);
}
bool CustomActionData::init(const std::wstring& data)
{
DWORD errCode = machine.Detect();
if (errCode != ERROR_SUCCESS)
{
WcaLog(LOGMSG_STANDARD, "Could not determine machine information: %d", errCode);
return false;
}
// first, the string is KEY=VAL;KEY=VAL....
// first split into key/value pairs
std::wstringstream ss(data);
std::wstring token;
while (std::getline(ss, token, L';')) {
// now 'token' has the key=val; do the same thing for the key=value
bool boolval = false;
std::wstringstream instream(token);
std::wstring key, val;
if (std::getline(instream, key, L'=')) {
std::getline(instream, val);
}
if (val.length() > 0) {
this->values[key] = val;
}
}
// pre-populate the domain/user information
this->parseUsernameData();
// pre-populate sysprobe
this->parseSysprobeData();
return true;
}
bool CustomActionData::present(const std::wstring& key) const {
return this->values.count(key) != 0 ? true : false;
}
bool CustomActionData::value(const std::wstring& key, std::wstring &val) const {
const auto kvp = values.find(key);
if (kvp == values.end()) {
return false;
}
val = kvp->second;
return true;
}
// return value of this function is true if the data was parsed,
// false otherwise. Return value of this function doesn't indicate whether
// sysprobe is to be installed; this function sets the boolean that can
// be checked by installSysprobe();
bool CustomActionData::parseSysprobeData()
{
std::wstring sysprobePresent;
std::wstring addlocal;
this->doInstallSysprobe = false;
if(!this->value(L"SYSPROBE_PRESENT", sysprobePresent))
{
// key isn't even there.
WcaLog(LOGMSG_STANDARD, "SYSPROBE_PRESENT not present");
return true;
}
WcaLog(LOGMSG_STANDARD, "SYSPROBE_PRESENT is %S", sysprobePresent.c_str());
if(sysprobePresent.compare(L"true") != 0) {
// explicitly disabled
WcaLog(LOGMSG_STANDARD, "SYSPROBE_PRESENT explicitly disabled %S", sysprobePresent.c_str());
return true;
}
if(!this->value(L"ADDLOCAL", addlocal))
{
// should never happen. But if the addlocalkey isn't there,
// don't bother trying
WcaLog(LOGMSG_STANDARD, "ADDLOCAL not present");
return true;
}
WcaLog(LOGMSG_STANDARD, "ADDLOCAL is (%S)", addlocal.c_str());
if(_wcsicmp(addlocal.c_str(), L"ALL")== 0){
// installing all components, do it
this->doInstallSysprobe = true;
WcaLog(LOGMSG_STANDARD, "ADDLOCAL is ALL");
} else if (addlocal.find(L"WindowsNP") != std::wstring::npos) {
WcaLog(LOGMSG_STANDARD, "ADDLOCAL contains WindowsNP %S", addlocal.c_str());
this->doInstallSysprobe = true;
}
return true;
}
bool CustomActionData::parseUsernameData()
{
std::wstring tmpName = ddAgentUserName;
if (this->value(propertyDDAgentUserName, tmpName)) {
if (tmpName.length() == 0) {
tmpName = ddAgentUserName;
}
}
if (std::wstring::npos == tmpName.find(L'\\')) {
WcaLog(LOGMSG_STANDARD, "loaded username doesn't have domain specifier, assuming local");
tmpName = L".\\" + tmpName;
}
// now create the splits between the domain and user for all to use, too
std::wstring computed_domain, computed_user;
std::wistringstream asStream(tmpName);
// username is going to be of the form <domain>\<username>
// if the <domain> is ".", then just do local machine
getline(asStream, computed_domain, L'\\');
getline(asStream, computed_user, L'\\');
if (computed_domain == L".")
{
WcaLog(LOGMSG_STANDARD, "Supplied qualified domain '.', using hostname");
computed_domain = machine.GetMachineName();
this->domainUser = false;
}
else
{
if(0 == _wcsicmp(computed_domain.c_str(), machine.GetMachineName().c_str()))
{
WcaLog(LOGMSG_STANDARD, "Supplied hostname as authority");
this->domainUser = false;
}
else if(0 == _wcsicmp(computed_domain.c_str(), machine.GetDomain().c_str()))
{
WcaLog(LOGMSG_STANDARD, "Supplied domain name %S %S", computed_domain.c_str(), machine.GetDomain().c_str());
this->domainUser = true;
}
else
{
WcaLog(LOGMSG_STANDARD, "Warning: Supplied user in different domain (%S != %S)", computed_domain.c_str(), machine.GetDomain().c_str());
computed_domain = machine.GetDomain();
this->domainUser = true;
}
}
this->domain = computed_domain;
this->username = computed_domain + L"\\" + computed_user;
this->uqusername = computed_user;
WcaLog(LOGMSG_STANDARD, "Computed fully qualified username %S", this->username.c_str());
return true;
}
|
/*
* Copyright (C) 2014 Google Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. 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 APPLE COMPUTER, INC. ``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 APPLE COMPUTER, INC. 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 "third_party/blink/renderer/core/dom/events/node_event_context.h"
#include "third_party/blink/renderer/core/dom/events/event.h"
#include "third_party/blink/renderer/core/events/focus_event.h"
#include "third_party/blink/renderer/core/events/mouse_event.h"
#include "third_party/blink/renderer/core/events/pointer_event.h"
#include "third_party/blink/renderer/core/events/touch_event_context.h"
#include "third_party/blink/renderer/core/input/touch_list.h"
namespace blink {
NodeEventContext::NodeEventContext(Node& node, EventTarget& current_target)
: node_(node), current_target_(current_target) {}
void NodeEventContext::Trace(Visitor* visitor) {
visitor->Trace(node_);
visitor->Trace(current_target_);
visitor->Trace(tree_scope_event_context_);
}
void NodeEventContext::HandleLocalEvents(Event& event) const {
if (TouchEventContext* touch_context = GetTouchEventContext()) {
touch_context->HandleLocalEvents(event);
} else if (RelatedTarget()) {
event.SetRelatedTargetIfExists(RelatedTarget());
}
event.SetTarget(Target());
event.SetCurrentTarget(current_target_.Get());
node_->HandleLocalEvents(event);
}
} // namespace blink
|
/*
* Copyright Andrey Semashev 2007 - 2013.
* Distributed under 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)
*/
/*!
* \file timer.cpp
* \author Andrey Semashev
* \date 02.12.2007
*
* \brief This header is the Boost.Log library implementation, see the library documentation
* at http://www.boost.org/doc/libs/release/libs/log/doc/html/index.html.
*/
#include <boost/config.hpp>
#include <boost/log/attributes/timer.hpp>
#include <boost/log/attributes/attribute_value_impl.hpp>
#if defined(BOOST_WINDOWS) && !defined(BOOST_LOG_NO_QUERY_PERFORMANCE_COUNTER)
#include "windows_version.hpp"
#include <boost/assert.hpp>
#include <boost/cstdint.hpp>
#include <boost/log/detail/config.hpp>
#if !defined(BOOST_LOG_NO_THREADS)
#include <boost/log/detail/locks.hpp>
#include <boost/thread/mutex.hpp>
#endif
#include <windows.h>
#include <boost/log/detail/header.hpp>
namespace boost {
BOOST_LOG_OPEN_NAMESPACE
namespace attributes {
//! Factory implementation
class BOOST_SYMBOL_VISIBLE timer::impl :
public attribute::impl
{
private:
#if !defined(BOOST_LOG_NO_THREADS)
//! Synchronization mutex type
typedef boost::mutex mutex_type;
//! Synchronization mutex
mutex_type m_Mutex;
#endif
//! Frequency factor for calculating duration
double m_FrequencyFactor;
//! Last value of the performance counter
uint64_t m_LastCounter;
//! Elapsed time duration, in microseconds
uint64_t m_Duration;
public:
//! Constructor
impl() : m_Duration(0)
{
LARGE_INTEGER li;
QueryPerformanceFrequency(&li);
BOOST_ASSERT(li.QuadPart != 0LL);
m_FrequencyFactor = 1000000.0 / static_cast< double >(li.QuadPart);
QueryPerformanceCounter(&li);
m_LastCounter = static_cast< uint64_t >(li.QuadPart);
}
//! The method returns the actual attribute value. It must not return NULL.
attribute_value get_value()
{
uint64_t duration;
{
BOOST_LOG_EXPR_IF_MT(log::aux::exclusive_lock_guard< mutex_type > lock(m_Mutex);)
LARGE_INTEGER li;
QueryPerformanceCounter(&li);
const uint64_t counter = static_cast< uint64_t >(li.QuadPart);
const uint64_t counts = counter - m_LastCounter;
m_LastCounter = counter;
duration = m_Duration + static_cast< uint64_t >(counts * m_FrequencyFactor);
m_Duration = duration;
}
return attribute_value(new attribute_value_impl< value_type >(boost::posix_time::microseconds(duration)));
}
};
//! Constructor
timer::timer() : attribute(new impl())
{
}
//! Constructor for casting support
timer::timer(cast_source const& source) : attribute(source.as< impl >())
{
}
} // namespace attributes
BOOST_LOG_CLOSE_NAMESPACE // namespace log
} // namespace boost
#include <boost/log/detail/footer.hpp>
#else // defined(BOOST_WINDOWS) && !defined(BOOST_LOG_NO_QUERY_PERFORMANCE_COUNTER)
#include <boost/log/detail/header.hpp>
namespace boost {
BOOST_LOG_OPEN_NAMESPACE
namespace attributes {
//! Factory implementation
class BOOST_SYMBOL_VISIBLE timer::impl :
public attribute::impl
{
public:
//! Time type
typedef utc_time_traits::time_type time_type;
private:
//! Base time point
const time_type m_BaseTimePoint;
public:
/*!
* Constructor. Starts time counting.
*/
impl() : m_BaseTimePoint(utc_time_traits::get_clock()) {}
attribute_value get_value()
{
return attribute_value(new attribute_value_impl< value_type >(
utc_time_traits::get_clock() - m_BaseTimePoint));
}
};
//! Constructor
timer::timer() : attribute(new impl())
{
}
//! Constructor for casting support
timer::timer(cast_source const& source) : attribute(source.as< impl >())
{
}
} // namespace attributes
BOOST_LOG_CLOSE_NAMESPACE // namespace log
} // namespace boost
#include <boost/log/detail/footer.hpp>
#endif // defined(BOOST_WINDOWS) && !defined(BOOST_LOG_NO_QUERY_PERFORMANCE_COUNTER)
|
// Copyright Carl Philipp Reh 2009 - 2021.
// Distributed under 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 <fcppt/mpl/list/object.hpp>
#include <fcppt/record/from_list.hpp>
#include <fcppt/record/object_impl.hpp>
#include <fcppt/config/external_begin.hpp>
#include <type_traits>
#include <fcppt/config/external_end.hpp>
int main()
{
static_assert(std::is_same_v<
fcppt::record::object<int, float>,
fcppt::record::from_list<fcppt::mpl::list::object<int, float>>>);
}
|
#ifndef __PARA__
#define __PARA__
const char *e_para[5] =
{
"The fastest typing speed ever, 216 words per minute, was achieved by Stella Pajunas-Garnand from Chicago in 1946 in one minute on an IBM electric. As of 2005, writer Barbara Blackburn was the fastest English language typist in the world, according to The Guinness Book of World Records. Using the Dvorak Simplified Keyboard, she had maintained 150 wpm for 50 minutes, and 170 wpm for shorter periods, with a peak speed of 212 wpm. Blackburn, who failed her QWERTY typing class in high school, first encountered the Dvorak keyboard in 1938, quickly learned to achieve very high speeds, and occasionally toured giving speed-typing demonstrations during her secretarial career. She appeared on Late Night with David Letterman on January 24, 1985, but felt that Letterman made a spectacle of her. Blackburn died in April 2008",
"Scolding is something common in student life. Being a naughty boy, I am always scolded by my parents. But one day I was severely scolded by my English teacher. She infect teaches well. But that day, I could not resist the temptation that an adventure of Nancy Drew offered. While she was teaching, I was completely engrossed in reading that book. Nancy Drew was caught in the trap laid by some smugglers and it was then when I felt a light tap on my bent head. The teacher had caught me red handed. She scolded me then and there and insulted me in front of the whole class. I was embarrassed. My cheeks burned being guilty conscious. When the class was over, I went to the teacher to apologize. When she saw that I had realized my mistake, she cooled down and then told me in a very kind manner how disheartening it was when she found any student not paying attention. I was genuinely sorry and promised to myself never to commit such a mistake again.",
"Pollution is a significant threat to our environment and is caused by the reckless attitude of man towards nature. Our Earth provides us with food and shelter, whereas we treat it mercilessly and plunder its resources. Pollution is a direct result of our greed. We dump waste into our water bodies without caring for the organisms living in them. The balance of various gases in the atmosphere has been disrupted because of the large number of vehicles plying on the road. Even factories that release harmful gases into the atmosphere contribute to air pollution. When we do excessive and uncontrolled farming on a piece of land, it loses its natural minerals. So, when we use fertilizers to boost their productivity, it pollutes the soil. Noise pollution is caused by factories, jets, airplanes, etc. It harms our ears and can impair hearing.",
"Tigers are animals that live in the wild. They are hungry animals that prey on smaller organisms. Their food usually consists of deer and boars. These animals grow up fast and attain maturity at around 3 or 4 years. They can live for up to 20 years in the wild. Males of the species are heavier than their female counterparts as they have different body functions. The young ones of tigers are known as cubs and require special care at the time of their birth. This is the reason why most of the cubs don't survive in the wild. They are endangered species, and their number has been declining for the past decade. Efforts are being made to conserve these mammals, and it has seen some improvement in countries like Nepal, India, Russia, and China. These animals are ferocious yet sensitive, so they must remain in the wild without any human interference.",
"Christmas is the most important festival for Christians. It brings home a spirit of cheer across the entire world. Christmas dates back to the time when Jesus was born to Mother Mary in a small stable. This festival is celebrated to mark the arrival of Jesus into this world. It is believed that the birth of Jesus Christ was prophesized earlier. Therefore, this festival is dear to traditional Christians. It has found widespread popularity among all the people irrespective of their religion or community. It is the time when families get together and cook delicious food for each other. The Christmas tree is a big attraction point of Christmas. People install Christmas trees at their homes and decorate it with bells, balls, glitter, and stars. It is all about baking sweet cakes and sharing them with your loved ones.",
};
const char *m_para[5] =
{
"A healthy body and mind are essential to achieve complete wellbeing. If we are healthy, we can resist our bodies from being attacked by germs. Our bodies are really sensitive and therefore, must be handled with necessary precautions. We can develop healthy habits like eating and sleeping on time to boost our overall health. This helps in becoming a healthier version of ourselves. Holistic growth can be achieved if we focus on all the aspects of our health. Such as nutrition, wellness, spirituality, and mental health. There are plenty of exercises that will boost our physical health and help us to become stronger. A stronger body would lead to less fatigue while performing any activity. It is advised that we must exercise for at least 2 hours every day for better health. We can even join fitness classes to take professional help and practice the art of health and wellness in a better way.",
"Yoga is the ultimate act of harmony between one's physical existence and spiritual conscience. The perfect synchronization between the mind and the body is known as yoga. More than a physical form of exercise, it is considered as a spiritual act that makes you aware of yourself. The deep introspection that we do when our mind is relaxed makes us feel connected to our inner selves. Yoga took shape in ancient India during the early Indus Valley civilizations. It became popular after it was documented in detail by the Hindu priests who originally practiced yoga. In India, Yoga has been adopted as a way of life rather than a form of exercise.",
"The environment is the natural surroundings of the earth that enables an organism's survival. The French word 'environ' that means to surround is a derivative of the word environment. It consists of living beings such as humans, plants, and animals. The air, water, and land are non-living entities. Their functioning is designed by nature in such a way that everything is dependent on each other. The human being is the most dominant creature of all the beings who can depend on all the natural resources of the earth. He requires the air to breathe. Not only humans but plants and animals also need air to breathe. There will be no life on earth without air. It is only the human being who is responsible for the destruction of the environment.",
"The earth consists of surroundings in which all living and non-living beings live their lives. The physical, biological, and natural forces of nature combine together and create circumstances that enable an organism to live. Such circumstances are called the environment. The French word 'environ' which means to surround is a derivative of the word environment. All the biotic (living) and abiotic (non-living) entities constitute the environment. Biotic things include- humans, plants, animals, and insects. They are classified as biological components of the environment. Every biotic creature has its own fixed life cycle. For example, human-being is the strongest living organism on earth. He needs plants and animals in order to fulfill his needs. His life-cycle will be disorganized without them.",
"The highest share in global unemployment is that of young people in emerging or underdeveloped countries where they live in moderate or poor conditions despite having an undeserving job. The wide disparity between young men and women has mostly contributed to unemployment. This problem has been faced, particularly by African and Asian countries where female discrimination is prevalent. According to the International Labor Organization (ILO) report, the rates of female employment is 32.9 percentage points lower than that of males in the year 2016.",
};
const char *d_para[5] =
{
"India is a country known for its values since biblical times. We begin to learn moral values from our family. Here children are taught to respect their elders, greet them properly whenever they meet them. A child knows that he should obey his elders whatever is ask him to do. There are many examples from history which have represented the importance of moral values in life. One such example was when Lord Ram was asked to go to fourteen years in exile. Lord Ram could have denied it, But to keep his father's words, he accepted the exile graciously and went into exile.",
"Moral values are the principles of good and evil, which shows a person's behavior and judgments. A person may embrace moral values from society and government, religion, or self. They are derived from the family as well. Moral values can be adjusted to some extent if they become a cause of pressure. Teens these days are more inclined towards seeking happiness rather than esteeming moral values. This may be attributed to the growing influence of western culture.",
"Population explosion is a big concern in today's age. There are many reasons why the population is increasing so rapidly. One of the major reason is the illiteracy among the people. We see high population growth where there are poverty and illiteracy. Illiterate people are generally unaware of the birth control and usage of it. Also, poor people tend to marry at a young age without any sex education and end up having many kids. One of the other reasons for the population explosion is the development of science and medicine. The life expectancy of people has increased drastically.",
"Population explosion more than often comes under negative limelight. It is so because more population means more exploitation of natural resources, and it isn't good for the environment. It leads to the devastation of flora and fauna in that place. More population means more industrialization, which means more pollution of water and air. It also leads to inequitable distribution of the money i.e., per capita income of the country drops. The higher population needs more investment for better infrastructure. If the government cannot provide that, it leads to a poor standard of living. It becomes difficult for the government to provide employment. It sometimes leads the unemployed youth to the path of crime, and thus the country becomes a bad neighborhood to live. The food produced every year is insufficient, and it becomes costly. Because of which the prices of other useful items also increase. It has also been seen that where the population is high, the status of women is subordinate.",
"On April 18, 1982, on the event of a symposium organized by ICOMOS International Council of Monuments and Sites in Tunisia, the holding of the “International Day for Sites & Monuments” to be celebrated together throughout the world was suggested. The idea was also stamped by the UNESCO General Conference, which cleared a resolution at its 22nd session in Nov 1983, recommending that the Member States examine the chances of declaring April 18 each year “International Sites & Monuments Day.” This has been called the World Heritage Day since then. World heritage day could be celebrated by doing different things. Few suggestions of ICOMOS are by going to the sites and relishing the culture and monuments. Restoration works are done for free of the dilapidated monuments—advertising about the monuments through articles in newspapers and ads in televisions. Many exhibitions are done with paintings and posters. Many foreign experts are invited, and press conferences are held to increase awareness in the world."
};
const char *s_para[5] =
{
"The international worker's day or international labour's day marks the end of exploitation, prolonged working hours, maltreatment towards the labourers and working classes across the continents. In the late 1800s, the labour union initiated a movement to raise their voice against the unfair and unjust treatment toward labourers.",
"International labour's day is observed to celebrate the efforts of the working classes in building the nation's economy. The annual celebration of labour's day symbolizes the victory of the labour union movement for promoting the welfare of the labourers.",
"Labour's day is marked as a remembrance of their victory. It is celebrated with pomp and show with street parades, parties, and unique athletic events. The workers are the backbone of every nation. A country cannot see economic progress and industrial growth without the contribution of workers. Thus, on International labour's day, we can pay our gratitude to all the workers.",
"The day marks an important day, and on this very occasion, the Technology Development Board awards the contribution of fellow citizens in the field of science and technology. This is how the Technology Development Board celebrates National Technology Day.",
"India, after the successful testing at Pokhran, became the sixth full-fledged nuclear country of the world. The operation was originally named ” operation Shakti-98,” there were five nuclear devices. India's first indigenous aircraft, Hansa 3, was tested on the same day, i.e., the 11th day of May 1998 at Banglore."
};
const char *test_char = "i am sahil";
#endif
|
//
// $Id: struct_client.cpp 82155 2008-06-24 14:11:03Z sma $
//
#include "tao/AnyTypeCode/AnyTypeCode_methods.h"
#include "tao/DynamicAny/DynAnyFactory.h"
#include "structC.h"
#include <ace/streams.h>
using namespace StructTest;
using namespace DynamicAny;
//--------------------------------------------------------------------
int ACE_TMAIN (int argc, ACE_TCHAR *argv[])
//--------------------------------------------------------------------
{
// Generic catch handler
try {
// Initialize the ORB
// ------------------
CORBA::ORB_var orb; // _var, so we don't need/may not CORBA::release(orb)
try {
orb = CORBA::ORB_init (argc, argv);
} catch (...) {
cerr << "Cannot initialize ORB" << endl;
throw;
}
// Get reference to the DynAny Factory
CORBA::Object_var obj = orb->resolve_initial_references("DynAnyFactory");
DynAnyFactory_var daf =
DynAnyFactory::_narrow(obj.in());
MyStruct my_struct;
MyStructAlias my_struct_alias;
MyUnion my_union;
MyUnionAlias my_union_alias;
CORBA::Any any_struct;
CORBA::Any any_struct_alias;
CORBA::Any any_union;
CORBA::Any any_union_alias;
// Write the structs and unions to anys so we can get the TypeCode info
any_struct <<= my_struct;
any_struct_alias <<= my_struct_alias;
any_union <<= my_union;
any_union_alias <<= my_union_alias;
// Explicitly set the TypeCode for the aliased types because the any
// doesn't take care of aliases
any_struct_alias.type(_tc_MyStructAlias);
any_union_alias.type(_tc_MyUnionAlias);
CORBA::TypeCode_var tc_struct = any_struct.type();
CORBA::TypeCode_var tc_struct_alias = any_struct_alias.type();
CORBA::TypeCode_var tc_union = any_union.type();
CORBA::TypeCode_var tc_union_alias = any_union_alias.type();
cout << "Type Code of the struct: " << tc_struct->kind() << endl;
cout << "Type Code of the struct alias: " << tc_struct_alias->kind() << endl;
cout << "Type Code of the union: " << tc_union->kind() << endl;
cout << "Type Code of the union alias: " << tc_union_alias->kind() << endl;
// equal returns true only when the TypeCodes are exactly the same.
if (tc_struct->equal(tc_struct_alias.in())) {
cout << "Type Codes are identical" << endl;
} else {
cout << "Type Codes are different" << endl;
}
// equivalent returns true when the TypeCode is an alias
if (tc_struct->equivalent(tc_struct_alias.in())) {
cout << "Type Codes are equivalent" << endl;
} else {
cout << "Type Codes are not equivalent" << endl;
}
DynAny_var da_struct = daf->create_dyn_any_from_type_code (tc_struct.in());
try {
DynAny_var da_struct_alias = daf->create_dyn_any_from_type_code (tc_struct_alias.in());
} catch ( const CORBA::UNKNOWN &) {
cout << "CORBA::UNKNOWN exception when calling create_dyn_any_from_type_code (tc_struct_alias)" << endl;
}
try {
DynAny_var da_struct_alias = daf->create_dyn_any (any_struct_alias);
} catch ( const CORBA::UNKNOWN &) {
cout << "CORBA::UNKNOWN exception when calling create_dyn_any (any_struct_alias)" << endl;
}
DynAny_var da_union = daf->create_dyn_any_from_type_code (tc_union.in());
try {
DynAny_var da_union_alias = daf->create_dyn_any_from_type_code (tc_union_alias.in());
} catch ( const CORBA::UNKNOWN &) {
cout << "CORBA::UNKNOWN exception when calling create_dyn_any_from_type_code (tc_union_alias)" << endl;
}
try {
DynAny_var da_union_alias = daf->create_dyn_any (any_union_alias);
} catch ( const CORBA::UNKNOWN &) {
cout << "CORBA::UNKNOWN exception when calling create_dyn_any (any_union_alias)" << endl;
}
} // end try
catch (const CORBA::Exception &) {
cerr << "Caught CORBA exception" << endl;
return 1;
}
catch (...) {
return 1;
}
return 0;
}
|
/* Copyright 2013-2021 MultiMC Contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* 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 <QStringList>
#include <QString>
#include <QDir>
#include <QStringList>
#include <settings/Setting.h>
#include <QDebug>
#include "java/JavaUtils.h"
#include "java/JavaInstallList.h"
#include "FileSystem.h"
#define IBUS "@im=ibus"
JavaUtils::JavaUtils()
{
}
#ifdef Q_OS_LINUX
static QString processLD_LIBRARY_PATH(const QString & LD_LIBRARY_PATH)
{
QDir mmcBin(QCoreApplication::applicationDirPath());
auto items = LD_LIBRARY_PATH.split(':');
QStringList final;
for(auto & item: items)
{
QDir test(item);
if(test == mmcBin)
{
qDebug() << "Env:LD_LIBRARY_PATH ignoring path" << item;
continue;
}
final.append(item);
}
return final.join(':');
}
#endif
QProcessEnvironment CleanEnviroment()
{
// prepare the process environment
QProcessEnvironment rawenv = QProcessEnvironment::systemEnvironment();
QProcessEnvironment env;
QStringList ignored =
{
"JAVA_ARGS",
"CLASSPATH",
"CONFIGPATH",
"JAVA_HOME",
"JRE_HOME",
"_JAVA_OPTIONS",
"JAVA_OPTIONS",
"JAVA_TOOL_OPTIONS"
};
for(auto key: rawenv.keys())
{
auto value = rawenv.value(key);
// filter out dangerous java crap
if(ignored.contains(key))
{
qDebug() << "Env: ignoring" << key << value;
continue;
}
// filter MultiMC-related things
if(key.startsWith("QT_"))
{
qDebug() << "Env: ignoring" << key << value;
continue;
}
#ifdef Q_OS_LINUX
// Do not pass LD_* variables to java. They were intended for MultiMC
if(key.startsWith("LD_"))
{
qDebug() << "Env: ignoring" << key << value;
continue;
}
// Strip IBus
// IBus is a Linux IME framework. For some reason, it breaks MC?
if (key == "XMODIFIERS" && value.contains(IBUS))
{
QString save = value;
value.replace(IBUS, "");
qDebug() << "Env: stripped" << IBUS << "from" << save << ":" << value;
}
if(key == "GAME_PRELOAD")
{
env.insert("LD_PRELOAD", value);
continue;
}
if(key == "GAME_LIBRARY_PATH")
{
env.insert("LD_LIBRARY_PATH", processLD_LIBRARY_PATH(value));
continue;
}
#endif
// qDebug() << "Env: " << key << value;
env.insert(key, value);
}
#ifdef Q_OS_LINUX
// HACK: Workaround for QTBUG42500
if(!env.contains("LD_LIBRARY_PATH"))
{
env.insert("LD_LIBRARY_PATH", "");
}
#endif
return env;
}
JavaInstallPtr JavaUtils::MakeJavaPtr(QString path, QString id, QString arch)
{
JavaInstallPtr javaVersion(new JavaInstall());
javaVersion->id = id;
javaVersion->arch = arch;
javaVersion->path = path;
return javaVersion;
}
JavaInstallPtr JavaUtils::GetDefaultJava()
{
JavaInstallPtr javaVersion(new JavaInstall());
javaVersion->id = "java";
javaVersion->arch = "unknown";
#if defined(Q_OS_WIN32)
javaVersion->path = "javaw";
#else
javaVersion->path = "java";
#endif
return javaVersion;
}
#if defined(Q_OS_WIN32)
QList<JavaInstallPtr> JavaUtils::FindJavaFromRegistryKey(DWORD keyType, QString keyName, QString keyJavaDir, QString subkeySuffix)
{
QList<JavaInstallPtr> javas;
QString archType = "unknown";
if (keyType == KEY_WOW64_64KEY)
archType = "64";
else if (keyType == KEY_WOW64_32KEY)
archType = "32";
HKEY jreKey;
if (RegOpenKeyExA(HKEY_LOCAL_MACHINE, keyName.toStdString().c_str(), 0,
KEY_READ | keyType | KEY_ENUMERATE_SUB_KEYS, &jreKey) == ERROR_SUCCESS)
{
// Read the current type version from the registry.
// This will be used to find any key that contains the JavaHome value.
char *value = new char[0];
DWORD valueSz = 0;
if (RegQueryValueExA(jreKey, "CurrentVersion", NULL, NULL, (BYTE *)value, &valueSz) ==
ERROR_MORE_DATA)
{
value = new char[valueSz];
RegQueryValueExA(jreKey, "CurrentVersion", NULL, NULL, (BYTE *)value, &valueSz);
}
TCHAR subKeyName[255];
DWORD subKeyNameSize, numSubKeys, retCode;
// Get the number of subkeys
RegQueryInfoKey(jreKey, NULL, NULL, NULL, &numSubKeys, NULL, NULL, NULL, NULL, NULL,
NULL, NULL);
// Iterate until RegEnumKeyEx fails
if (numSubKeys > 0)
{
for (DWORD i = 0; i < numSubKeys; i++)
{
subKeyNameSize = 255;
retCode = RegEnumKeyEx(jreKey, i, subKeyName, &subKeyNameSize, NULL, NULL, NULL,
NULL);
if (retCode == ERROR_SUCCESS)
{
// Now open the registry key for the version that we just got.
QString newKeyName = keyName + "\\" + subKeyName + subkeySuffix;
HKEY newKey;
if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, newKeyName.toStdString().c_str(), 0,
KEY_READ | KEY_WOW64_64KEY, &newKey) == ERROR_SUCCESS)
{
// Read the JavaHome value to find where Java is installed.
value = new char[0];
valueSz = 0;
if (RegQueryValueEx(newKey, keyJavaDir.toStdString().c_str(), NULL, NULL, (BYTE *)value,
&valueSz) == ERROR_MORE_DATA)
{
value = new char[valueSz];
RegQueryValueEx(newKey, keyJavaDir.toStdString().c_str(), NULL, NULL, (BYTE *)value,
&valueSz);
// Now, we construct the version object and add it to the list.
JavaInstallPtr javaVersion(new JavaInstall());
javaVersion->id = subKeyName;
javaVersion->arch = archType;
javaVersion->path =
QDir(FS::PathCombine(value, "bin")).absoluteFilePath("javaw.exe");
javas.append(javaVersion);
}
RegCloseKey(newKey);
}
}
}
}
RegCloseKey(jreKey);
}
return javas;
}
QList<QString> JavaUtils::FindJavaPaths()
{
QList<JavaInstallPtr> java_candidates;
// Oracle
QList<JavaInstallPtr> JRE64s = this->FindJavaFromRegistryKey(
KEY_WOW64_64KEY, "SOFTWARE\\JavaSoft\\Java Runtime Environment", "JavaHome");
QList<JavaInstallPtr> JDK64s = this->FindJavaFromRegistryKey(
KEY_WOW64_64KEY, "SOFTWARE\\JavaSoft\\Java Development Kit", "JavaHome");
QList<JavaInstallPtr> JRE32s = this->FindJavaFromRegistryKey(
KEY_WOW64_32KEY, "SOFTWARE\\JavaSoft\\Java Runtime Environment", "JavaHome");
QList<JavaInstallPtr> JDK32s = this->FindJavaFromRegistryKey(
KEY_WOW64_32KEY, "SOFTWARE\\JavaSoft\\Java Development Kit", "JavaHome");
// Oracle for Java 9 and newer
QList<JavaInstallPtr> NEWJRE64s = this->FindJavaFromRegistryKey(
KEY_WOW64_64KEY, "SOFTWARE\\JavaSoft\\JRE", "JavaHome");
QList<JavaInstallPtr> NEWJDK64s = this->FindJavaFromRegistryKey(
KEY_WOW64_64KEY, "SOFTWARE\\JavaSoft\\JDK", "JavaHome");
QList<JavaInstallPtr> NEWJRE32s = this->FindJavaFromRegistryKey(
KEY_WOW64_32KEY, "SOFTWARE\\JavaSoft\\JRE", "JavaHome");
QList<JavaInstallPtr> NEWJDK32s = this->FindJavaFromRegistryKey(
KEY_WOW64_32KEY, "SOFTWARE\\JavaSoft\\JDK", "JavaHome");
// AdoptOpenJDK
QList<JavaInstallPtr> ADOPTOPENJRE32s = this->FindJavaFromRegistryKey(
KEY_WOW64_32KEY, "SOFTWARE\\AdoptOpenJDK\\JRE", "Path", "\\hotspot\\MSI");
QList<JavaInstallPtr> ADOPTOPENJRE64s = this->FindJavaFromRegistryKey(
KEY_WOW64_64KEY, "SOFTWARE\\AdoptOpenJDK\\JRE", "Path", "\\hotspot\\MSI");
QList<JavaInstallPtr> ADOPTOPENJDK32s = this->FindJavaFromRegistryKey(
KEY_WOW64_32KEY, "SOFTWARE\\AdoptOpenJDK\\JDK", "Path", "\\hotspot\\MSI");
QList<JavaInstallPtr> ADOPTOPENJDK64s = this->FindJavaFromRegistryKey(
KEY_WOW64_64KEY, "SOFTWARE\\AdoptOpenJDK\\JDK", "Path", "\\hotspot\\MSI");
// Microsoft
QList<JavaInstallPtr> MICROSOFTJDK64s = this->FindJavaFromRegistryKey(
KEY_WOW64_64KEY, "SOFTWARE\\Microsoft\\JDK", "Path", "\\hotspot\\MSI");
// Azul Zulu
QList<JavaInstallPtr> ZULU64s = this->FindJavaFromRegistryKey(
KEY_WOW64_64KEY, "SOFTWARE\\Azul Systems\\Zulu", "InstallationPath");
QList<JavaInstallPtr> ZULU32s = this->FindJavaFromRegistryKey(
KEY_WOW64_64KEY, "SOFTWARE\\Azul Systems\\Zulu", "InstallationPath");
// BellSoft Liberica
QList<JavaInstallPtr> LIBERICA64s = this->FindJavaFromRegistryKey(
KEY_WOW64_64KEY, "SOFTWARE\\BellSoft\\Liberica", "InstallationPath");
QList<JavaInstallPtr> LIBERICA32s = this->FindJavaFromRegistryKey(
KEY_WOW64_64KEY, "SOFTWARE\\BellSoft\\Liberica", "InstallationPath");
// List x64 before x86
java_candidates.append(JRE64s);
java_candidates.append(NEWJRE64s);
java_candidates.append(ADOPTOPENJRE64s);
java_candidates.append(MakeJavaPtr("C:/Program Files/Java/jre8/bin/javaw.exe"));
java_candidates.append(MakeJavaPtr("C:/Program Files/Java/jre7/bin/javaw.exe"));
java_candidates.append(MakeJavaPtr("C:/Program Files/Java/jre6/bin/javaw.exe"));
java_candidates.append(JDK64s);
java_candidates.append(NEWJDK64s);
java_candidates.append(ADOPTOPENJDK64s);
java_candidates.append(MICROSOFTJDK64s);
java_candidates.append(ZULU64s);
java_candidates.append(LIBERICA64s);
java_candidates.append(JRE32s);
java_candidates.append(NEWJRE32s);
java_candidates.append(ADOPTOPENJRE32s);
java_candidates.append(MakeJavaPtr("C:/Program Files (x86)/Java/jre8/bin/javaw.exe"));
java_candidates.append(MakeJavaPtr("C:/Program Files (x86)/Java/jre7/bin/javaw.exe"));
java_candidates.append(MakeJavaPtr("C:/Program Files (x86)/Java/jre6/bin/javaw.exe"));
java_candidates.append(JDK32s);
java_candidates.append(NEWJDK32s);
java_candidates.append(ADOPTOPENJDK32s);
java_candidates.append(ZULU32s);
java_candidates.append(LIBERICA32s);
java_candidates.append(MakeJavaPtr(this->GetDefaultJava()->path));
QList<QString> candidates;
for(JavaInstallPtr java_candidate : java_candidates)
{
if(!candidates.contains(java_candidate->path))
{
candidates.append(java_candidate->path);
}
}
return candidates;
}
#elif defined(Q_OS_MAC)
QList<QString> JavaUtils::FindJavaPaths()
{
QList<QString> javas;
javas.append(this->GetDefaultJava()->path);
javas.append("/Applications/Xcode.app/Contents/Applications/Application Loader.app/Contents/MacOS/itms/java/bin/java");
javas.append("/Library/Internet Plug-Ins/JavaAppletPlugin.plugin/Contents/Home/bin/java");
javas.append("/System/Library/Frameworks/JavaVM.framework/Versions/Current/Commands/java");
QDir libraryJVMDir("/Library/Java/JavaVirtualMachines/");
QStringList libraryJVMJavas = libraryJVMDir.entryList(QDir::Dirs | QDir::NoDotAndDotDot);
foreach (const QString &java, libraryJVMJavas) {
javas.append(libraryJVMDir.absolutePath() + "/" + java + "/Contents/Home/bin/java");
javas.append(libraryJVMDir.absolutePath() + "/" + java + "/Contents/Home/jre/bin/java");
}
QDir systemLibraryJVMDir("/System/Library/Java/JavaVirtualMachines/");
QStringList systemLibraryJVMJavas = systemLibraryJVMDir.entryList(QDir::Dirs | QDir::NoDotAndDotDot);
foreach (const QString &java, systemLibraryJVMJavas) {
javas.append(systemLibraryJVMDir.absolutePath() + "/" + java + "/Contents/Home/bin/java");
javas.append(systemLibraryJVMDir.absolutePath() + "/" + java + "/Contents/Commands/java");
}
return javas;
}
#elif defined(Q_OS_LINUX)
QList<QString> JavaUtils::FindJavaPaths()
{
qDebug() << "Linux Java detection incomplete - defaulting to \"java\"";
QList<QString> javas;
javas.append(this->GetDefaultJava()->path);
auto scanJavaDir = [&](const QString & dirPath)
{
QDir dir(dirPath);
if(!dir.exists())
return;
auto entries = dir.entryInfoList(QDir::Dirs | QDir::NoDotAndDotDot | QDir::NoSymLinks);
for(auto & entry: entries)
{
QString prefix;
if(entry.isAbsolute())
{
prefix = entry.absoluteFilePath();
}
else
{
prefix = entry.filePath();
}
javas.append(FS::PathCombine(prefix, "jre/bin/java"));
javas.append(FS::PathCombine(prefix, "bin/java"));
}
};
// oracle RPMs
scanJavaDir("/usr/java");
// general locations used by distro packaging
scanJavaDir("/usr/lib/jvm");
scanJavaDir("/usr/lib32/jvm");
// javas stored in MultiMC's folder
scanJavaDir("java");
// manually installed JDKs in /opt
scanJavaDir("/opt/jdk");
scanJavaDir("/opt/jdks");
return javas;
}
#else
QList<QString> JavaUtils::FindJavaPaths()
{
qDebug() << "Unknown operating system build - defaulting to \"java\"";
QList<QString> javas;
javas.append(this->GetDefaultJava()->path);
return javas;
}
#endif
|
#pragma once
#include "entity.hpp"
#include <string>
#include <sstream>
namespace gal
{
template <typename A, typename T, elem_t... E>
[[nodiscard]] std::string to_string(entity<A, T, E...> in)
{
if constexpr (sizeof...(E) == 0)
{
return "0";
}
else
{
std::stringstream stream;
auto const& elements = in.elements;
for (size_t i = 0; i != elements.size(); ++i)
{
stream << in[i];
auto e = elements[i];
if (e > 0)
{
stream << 'e';
}
int j = 0;
while (e > 0)
{
if ((e & 1) == 1)
{
stream << j;
}
e >>= 1;
++j;
}
if (i != elements.size() - 1)
{
stream << " + ";
}
}
return stream.str();
}
}
} // namespace gal
|
#include "deheap/functions.hpp"
#include <benchmark/benchmark.h>
#include <random>
static void make_deheap(benchmark::State &state) {
std::vector<int> v;
std::mt19937 gen;
std::generate_n(std::back_inserter(v), state.range(0), std::ref(gen));
for (auto _ : state) {
state.PauseTiming();
std::shuffle(v.begin(), v.end(), gen);
state.ResumeTiming();
deheap::make_deheap(v.begin(), v.end());
}
state.SetComplexityN(v.size());
}
BENCHMARK(make_deheap)->DenseRange(1 << 10, 1 << 14, 1024)->Complexity();
static void push_deheap(benchmark::State &state) {
std::vector<int> v;
std::mt19937 gen;
std::generate_n(std::back_inserter(v), state.range(0), std::ref(gen));
for (auto _ : state) {
state.PauseTiming();
std::shuffle(v.begin(), v.end(), gen);
state.ResumeTiming();
for (auto it = v.begin() + 1; it <= v.end(); ++it)
deheap::push_deheap(v.begin(), it);
}
state.SetComplexityN(v.size());
}
BENCHMARK(push_deheap)->DenseRange(1 << 10, 1 << 14, 1024)->Complexity();
static void make_heap(benchmark::State &state) {
std::vector<int> v;
std::mt19937 gen;
std::generate_n(std::back_inserter(v), state.range(0), std::ref(gen));
for (auto _ : state) {
state.PauseTiming();
std::shuffle(v.begin(), v.end(), gen);
state.ResumeTiming();
std::make_heap(v.begin(), v.end());
}
state.SetComplexityN(v.size());
}
BENCHMARK(make_heap)->DenseRange(1 << 10, 1 << 14, 1024)->Complexity();
static void push_heap(benchmark::State &state) {
std::vector<int> v;
std::mt19937 gen;
std::generate_n(std::back_inserter(v), state.range(0), std::ref(gen));
for (auto _ : state) {
state.PauseTiming();
std::shuffle(v.begin(), v.end(), gen);
state.ResumeTiming();
for (auto it = v.begin() + 1; it <= v.end(); ++it)
std::push_heap(v.begin(), it);
}
state.SetComplexityN(v.size());
}
BENCHMARK(push_heap)->DenseRange(1 << 10, 1 << 14, 1024)->Complexity();
static void sort_deheap(benchmark::State &state) {
std::vector<int> v;
std::mt19937 gen;
std::generate_n(std::back_inserter(v), state.range(0), std::ref(gen));
for (auto _ : state) {
state.PauseTiming();
std::shuffle(v.begin(), v.end(), gen);
state.ResumeTiming();
deheap::make_deheap(v.begin(), v.end());
deheap::sort_deheap_ascending(v.begin(), v.end());
}
state.SetComplexityN(v.size());
}
BENCHMARK(sort_deheap)->DenseRange(1 << 10, 1 << 14, 1024)->Complexity();
static void sort_heap(benchmark::State &state) {
std::vector<int> v;
std::mt19937 gen;
std::generate_n(std::back_inserter(v), state.range(0), std::ref(gen));
for (auto _ : state) {
state.PauseTiming();
std::shuffle(v.begin(), v.end(), gen);
state.ResumeTiming();
std::make_heap(v.begin(), v.end());
std::sort_heap(v.begin(), v.end());
}
state.SetComplexityN(v.size());
}
BENCHMARK(sort_heap)->DenseRange(1 << 10, 1 << 14, 1024)->Complexity();
|
#include <string>
#include <iostream>
#include <boost/asio/ip/address.hpp>
#include <boost/format.hpp>
#include <boost/asio/deadline_timer.hpp>
#include <boost/asio/ip/address.hpp>
#include <boost/format.hpp>
#include <boost/asio/deadline_timer.hpp>
#include <boost/format.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/program_options.hpp>
#include <boost/format.hpp>
#include <boost/algorithm/string.hpp>
#include <redisclient/redisasyncclient.h>
using namespace redisclient;
using namespace std;
using namespace std::chrono;
namespace po = boost::program_options;
class Config
{
public:
static std::string pubTopic;
static std::string subTopic;
static std::string redisIP;
static uint64_t redisPort;
};
std::string Config::pubTopic;
std::string Config::subTopic;
std::string Config::redisIP;
uint64_t Config::redisPort;
class Client
{
public:
Client(boost::asio::io_service &ioService,
const boost::asio::ip::address &address,
unsigned short port)
: ioService(ioService), publishTimer(ioService),
connectSubscriberTimer(ioService), connectPublisherTimer(ioService),
address(address), port(port),
publisher(ioService), subscriber(ioService)
{
publisher.installErrorHandler(std::bind(&Client::connectPublisher, this));
subscriber.installErrorHandler(std::bind(&Client::connectSubscriber, this));
}
void publish(const std::string &str)
{
publisher.publish(Config::pubTopic, str);
}
void start()
{
connectPublisher();
connectSubscriber();
cout<<"Echoer Initialized"<<endl;
}
protected:
void errorPubProxy(const std::string &)
{
publishTimer.cancel();
connectPublisher();
}
void errorSubProxy(const std::string &)
{
connectSubscriber();
}
void connectPublisher()
{
//std::cerr << "connectPublisher\n";
if( publisher.state() == RedisAsyncClient::State::Connected )
{
std::cerr << "disconnectPublisher\n";
publisher.disconnect();
publishTimer.cancel();
}
boost::asio::ip::tcp::endpoint endpoint(address, port);
publisher.connect(endpoint,
std::bind(&Client::onPublisherConnected, this, std::placeholders::_1));
}
void connectSubscriber()
{
//std::cerr << "connectSubscriber\n";
if( subscriber.state() == RedisAsyncClient::State::Connected ||
subscriber.state() == RedisAsyncClient::State::Subscribed )
{
std::cerr << "disconnectSubscriber\n";
subscriber.disconnect();
}
boost::asio::ip::tcp::endpoint endpoint(address, port);
subscriber.connect(endpoint,
std::bind(&Client::onSubscriberConnected, this, std::placeholders::_1));
}
void callLater(boost::asio::deadline_timer &timer,
void(Client::*callback)())
{
std::cerr << "callLater\n";
timer.expires_from_now(boost::posix_time::seconds(1000));
timer.async_wait([callback, this](const boost::system::error_code &ec) {
if( !ec )
{
(this->*callback)();
}
});
}
void onPublishTimeout()
{
static size_t counter = 0;
std::string msg = str(boost::format("message %1%") % counter++);
if( publisher.state() == RedisAsyncClient::State::Connected )
{
std::cerr << "pub " << msg << "\n";
publish(msg);
}
callLater(publishTimer, &Client::onPublishTimeout);
}
void onPublisherConnected(boost::system::error_code ec)
{
if(ec){} //TBU
}
void onSubscriberConnected(boost::system::error_code ec)
{
if( ec )
{
std::cerr << "onSubscriberConnected: can't connect to redis: " << ec.message() << "\n";
callLater(connectSubscriberTimer, &Client::connectSubscriber);
}
else
{
//std::cerr << "onSubscriberConnected ok\n";
subscriber.subscribe(Config::subTopic,
std::bind(&Client::onMessage, this, std::placeholders::_1));
}
}
void onMessage(const std::vector<char> &buf)
{
std::string s(buf.begin(), buf.end());
if (s.find(std::string("Dummy")) != string::npos) {
//cout<<"Dummy #" << counter <<endl;
return;//Avoid pinging back dummy publishers
}
//cout << "pong #" << this->counter <<endl;
publish(s);
counter ++;
}
private:
boost::asio::io_service &ioService;
boost::asio::deadline_timer publishTimer;
boost::asio::deadline_timer connectSubscriberTimer;
boost::asio::deadline_timer connectPublisherTimer;
const boost::asio::ip::address address;
const unsigned short port;
RedisAsyncClient publisher;
RedisAsyncClient subscriber;
int counter = 0;
};
int main(int argc, char ** argv)
{
po::options_description description("Options");
description.add_options()
("help", "produce help message")
("redisIP", po::value(&Config::redisIP)->default_value("127.0.0.1"), "Redis server IP")
("redisPort", po::value(&Config::redisPort)->default_value(6379), "Redis server port")
("PubTopic", po::value(&Config::pubTopic)->default_value("pong"), "Publish to Topic (Pong)")
("SubTopic", po::value(&Config::subTopic)->default_value("ping"), "Subscribe to Topic (ping) ");
po::variables_map vm;
try
{
po::store(po::parse_command_line(argc, argv, description), vm);
po::notify(vm);
}
catch (const po::error &e)
{
std::cerr << e.what() << "\n";
return EXIT_FAILURE;
}
if (vm.count("help"))
{
std::cout << description << "\n";
return EXIT_SUCCESS;
}
boost::asio::ip::address address = boost::asio::ip::address::from_string(Config::redisIP);
const unsigned short port = Config::redisPort;
boost::asio::io_service ioService;
Client client(ioService, address, port);
client.start();
ioService.run();
std::cerr << "done\n";
return 0;
}
|
#include "duckdb/execution/operator/join/physical_piecewise_merge_join.hpp"
#include "duckdb/common/vector_operations/vector_operations.hpp"
#include "duckdb/execution/expression_executor.hpp"
#include "duckdb/execution/merge_join.hpp"
#include "duckdb/common/operator/comparison_operators.hpp"
namespace duckdb {
PhysicalPiecewiseMergeJoin::PhysicalPiecewiseMergeJoin(LogicalOperator &op, unique_ptr<PhysicalOperator> left,
unique_ptr<PhysicalOperator> right, vector<JoinCondition> cond,
JoinType join_type, idx_t estimated_cardinality)
: PhysicalComparisonJoin(op, PhysicalOperatorType::PIECEWISE_MERGE_JOIN, move(cond), join_type,
estimated_cardinality) {
// for now we only support one condition!
D_ASSERT(conditions.size() == 1);
for (auto &cond : conditions) {
// COMPARE NOT EQUAL not supported with merge join
D_ASSERT(cond.comparison != ExpressionType::COMPARE_NOTEQUAL);
D_ASSERT(cond.left->return_type == cond.right->return_type);
join_key_types.push_back(cond.left->return_type);
}
children.push_back(move(left));
children.push_back(move(right));
}
//===--------------------------------------------------------------------===//
// Sink
//===--------------------------------------------------------------------===//
class MergeJoinLocalState : public LocalSinkState {
public:
explicit MergeJoinLocalState(vector<JoinCondition> &conditions) {
vector<LogicalType> condition_types;
for (auto &cond : conditions) {
rhs_executor.AddExpression(*cond.right);
condition_types.push_back(cond.right->return_type);
}
join_keys.Initialize(condition_types);
}
//! The chunk holding the right condition
DataChunk join_keys;
//! The executor of the RHS condition
ExpressionExecutor rhs_executor;
};
class MergeJoinGlobalState : public GlobalOperatorState {
public:
MergeJoinGlobalState() : has_null(false), right_outer_position(0) {
}
//! The materialized data of the RHS
ChunkCollection right_chunks;
//! The materialized join keys of the RHS
ChunkCollection right_conditions;
//! The join orders of the RHS
vector<MergeOrder> right_orders;
//! Whether or not the RHS of the nested loop join has NULL values
bool has_null;
//! A bool indicating for each tuple in the RHS if they found a match (only used in FULL OUTER JOIN)
unique_ptr<bool[]> right_found_match;
//! The position in the RHS in the final scan of the FULL OUTER JOIN
idx_t right_outer_position;
};
unique_ptr<GlobalOperatorState> PhysicalPiecewiseMergeJoin::GetGlobalState(ClientContext &context) {
return make_unique<MergeJoinGlobalState>();
}
unique_ptr<LocalSinkState> PhysicalPiecewiseMergeJoin::GetLocalSinkState(ExecutionContext &context) {
return make_unique<MergeJoinLocalState>(conditions);
}
void PhysicalPiecewiseMergeJoin::Sink(ExecutionContext &context, GlobalOperatorState &state, LocalSinkState &lstate,
DataChunk &input) {
auto &gstate = (MergeJoinGlobalState &)state;
auto &mj_state = (MergeJoinLocalState &)lstate;
// resolve the join keys for this chunk
mj_state.rhs_executor.SetChunk(input);
mj_state.join_keys.Reset();
mj_state.join_keys.SetCardinality(input);
for (idx_t k = 0; k < conditions.size(); k++) {
// resolve the join key
mj_state.rhs_executor.ExecuteExpression(k, mj_state.join_keys.data[k]);
}
// append the join keys and the chunk to the chunk collection
gstate.right_chunks.Append(input);
gstate.right_conditions.Append(mj_state.join_keys);
}
//===--------------------------------------------------------------------===//
// Finalize
//===--------------------------------------------------------------------===//
static void OrderVector(Vector &vector, idx_t count, MergeOrder &order);
void PhysicalPiecewiseMergeJoin::Finalize(Pipeline &pipeline, ClientContext &context,
unique_ptr<GlobalOperatorState> state) {
auto &gstate = (MergeJoinGlobalState &)*state;
if (gstate.right_conditions.ChunkCount() > 0) {
// now order all the chunks
gstate.right_orders.resize(gstate.right_conditions.ChunkCount());
for (idx_t i = 0; i < gstate.right_conditions.ChunkCount(); i++) {
auto &chunk_to_order = gstate.right_conditions.GetChunk(i);
D_ASSERT(chunk_to_order.ColumnCount() == 1);
for (idx_t col_idx = 0; col_idx < chunk_to_order.ColumnCount(); col_idx++) {
OrderVector(chunk_to_order.data[col_idx], chunk_to_order.size(), gstate.right_orders[i]);
if (gstate.right_orders[i].count < chunk_to_order.size()) {
// the amount of entries in the order vector is smaller than the amount of entries in the vector
// this only happens if there are NULL values in the right-hand side
// hence we set the has_null to true (this is required for the MARK join)
gstate.has_null = true;
}
}
}
}
if (IsRightOuterJoin(join_type)) {
// for FULL/RIGHT OUTER JOIN, initialize found_match to false for every tuple
gstate.right_found_match = unique_ptr<bool[]>(new bool[gstate.right_chunks.Count()]);
memset(gstate.right_found_match.get(), 0, sizeof(bool) * gstate.right_chunks.Count());
}
PhysicalSink::Finalize(pipeline, context, move(state));
}
//===--------------------------------------------------------------------===//
// GetChunkInternal
//===--------------------------------------------------------------------===//
class PhysicalPiecewiseMergeJoinState : public PhysicalOperatorState {
public:
PhysicalPiecewiseMergeJoinState(PhysicalOperator &op, PhysicalOperator *left, vector<JoinCondition> &conditions)
: PhysicalOperatorState(op, left), fetch_next_left(true), left_position(0), right_position(0),
right_chunk_index(0) {
vector<LogicalType> condition_types;
for (auto &cond : conditions) {
lhs_executor.AddExpression(*cond.left);
condition_types.push_back(cond.left->return_type);
}
join_keys.Initialize(condition_types);
}
bool fetch_next_left;
idx_t left_position;
idx_t right_position;
idx_t right_chunk_index;
DataChunk left_chunk;
DataChunk join_keys;
MergeOrder left_orders;
//! The executor of the RHS condition
ExpressionExecutor lhs_executor;
unique_ptr<bool[]> left_found_match;
};
void PhysicalPiecewiseMergeJoin::ResolveSimpleJoin(ExecutionContext &context, DataChunk &chunk,
PhysicalOperatorState *state_p) {
auto state = reinterpret_cast<PhysicalPiecewiseMergeJoinState *>(state_p);
auto &gstate = (MergeJoinGlobalState &)*sink_state;
do {
children[0]->GetChunk(context, state->child_chunk, state->child_state.get());
if (state->child_chunk.size() == 0) {
return;
}
state->join_keys.Reset();
state->lhs_executor.SetChunk(state->child_chunk);
state->join_keys.SetCardinality(state->child_chunk);
for (idx_t k = 0; k < conditions.size(); k++) {
state->lhs_executor.ExecuteExpression(k, state->join_keys.data[k]);
// sort by join key
OrderVector(state->join_keys.data[k], state->join_keys.size(), state->left_orders);
}
ScalarMergeInfo left_info(state->left_orders, state->join_keys.data[0].GetType(), state->left_position);
ChunkMergeInfo right_info(gstate.right_conditions, gstate.right_orders);
// perform the actual join
MergeJoinSimple::Perform(left_info, right_info, conditions[0].comparison);
// now construct the result based ont he join result
switch (join_type) {
case JoinType::MARK:
PhysicalJoin::ConstructMarkJoinResult(state->join_keys, state->child_chunk, chunk, right_info.found_match,
gstate.has_null);
break;
case JoinType::SEMI:
PhysicalJoin::ConstructSemiJoinResult(state->child_chunk, chunk, right_info.found_match);
break;
case JoinType::ANTI:
PhysicalJoin::ConstructAntiJoinResult(state->child_chunk, chunk, right_info.found_match);
break;
default:
throw NotImplementedException("Unimplemented join type for merge join");
}
} while (chunk.size() == 0);
}
void PhysicalPiecewiseMergeJoin::ResolveComplexJoin(ExecutionContext &context, DataChunk &chunk,
PhysicalOperatorState *state_p) {
auto state = reinterpret_cast<PhysicalPiecewiseMergeJoinState *>(state_p);
auto &gstate = (MergeJoinGlobalState &)*sink_state;
do {
// check if we have to fetch a child from the left side
if (state->fetch_next_left) {
if (IsLeftOuterJoin(join_type)) {
// left join: before we move to the next chunk, see if we need to output any vectors that didn't
// have a match found
if (state->left_found_match) {
PhysicalJoin::ConstructLeftJoinResult(state->child_chunk, chunk, state->left_found_match.get());
state->left_found_match.reset();
if (chunk.size() > 0) {
return;
}
}
state->left_found_match = unique_ptr<bool[]>(new bool[STANDARD_VECTOR_SIZE]);
memset(state->left_found_match.get(), 0, sizeof(bool) * STANDARD_VECTOR_SIZE);
}
// fetch the chunk from the left side
children[0]->GetChunk(context, state->child_chunk, state->child_state.get());
if (state->child_chunk.size() == 0) {
// exhausted LHS: in case of full outer join output remaining entries
if (IsRightOuterJoin(join_type)) {
// if the LHS is exhausted in a FULL OUTER JOIN, we scan the found_match for any chunks we still
// need to output
ConstructFullOuterJoinResult(gstate.right_found_match.get(), gstate.right_chunks, chunk,
gstate.right_outer_position);
}
return;
}
// resolve the join keys for the left chunk
state->join_keys.Reset();
state->lhs_executor.SetChunk(state->child_chunk);
state->join_keys.SetCardinality(state->child_chunk);
for (idx_t k = 0; k < conditions.size(); k++) {
state->lhs_executor.ExecuteExpression(k, state->join_keys.data[k]);
// sort by join key
OrderVector(state->join_keys.data[k], state->join_keys.size(), state->left_orders);
}
state->right_chunk_index = 0;
state->left_position = 0;
state->right_position = 0;
state->fetch_next_left = false;
}
auto &right_chunk = gstate.right_chunks.GetChunk(state->right_chunk_index);
auto &right_condition_chunk = gstate.right_conditions.GetChunk(state->right_chunk_index);
auto &right_orders = gstate.right_orders[state->right_chunk_index];
ScalarMergeInfo left_info(state->left_orders, state->join_keys.data[0].GetType(), state->left_position);
ScalarMergeInfo right_info(right_orders, right_condition_chunk.data[0].GetType(), state->right_position);
idx_t result_count = MergeJoinComplex::Perform(left_info, right_info, conditions[0].comparison);
if (result_count == 0) {
// exhausted this chunk on the right side
// move to the next right chunk
state->left_position = 0;
state->right_position = 0;
state->right_chunk_index++;
if (state->right_chunk_index >= gstate.right_chunks.ChunkCount()) {
state->fetch_next_left = true;
}
} else {
// found matches: mark the found matches if required
if (state->left_found_match) {
for (idx_t i = 0; i < result_count; i++) {
state->left_found_match[left_info.result.get_index(i)] = true;
}
}
if (gstate.right_found_match) {
idx_t base_index = state->right_chunk_index * STANDARD_VECTOR_SIZE;
for (idx_t i = 0; i < result_count; i++) {
gstate.right_found_match[base_index + right_info.result.get_index(i)] = true;
}
}
// found matches: output them
chunk.Slice(state->child_chunk, left_info.result, result_count);
chunk.Slice(right_chunk, right_info.result, result_count, state->child_chunk.ColumnCount());
}
} while (chunk.size() == 0);
}
void PhysicalPiecewiseMergeJoin::GetChunkInternal(ExecutionContext &context, DataChunk &chunk,
PhysicalOperatorState *state_p) {
auto state = reinterpret_cast<PhysicalPiecewiseMergeJoinState *>(state_p);
auto &gstate = (MergeJoinGlobalState &)*sink_state;
if (gstate.right_chunks.Count() == 0) {
// empty RHS: construct empty result
if (join_type == JoinType::SEMI || join_type == JoinType::INNER) {
return;
}
children[0]->GetChunk(context, state->child_chunk, state->child_state.get());
if (state->child_chunk.size() == 0) {
return;
}
// empty RHS: construct empty result
ConstructEmptyJoinResult(join_type, gstate.has_null, state->child_chunk, chunk);
return;
}
switch (join_type) {
case JoinType::SEMI:
case JoinType::ANTI:
case JoinType::MARK:
// simple joins can have max STANDARD_VECTOR_SIZE matches per chunk
ResolveSimpleJoin(context, chunk, state_p);
break;
case JoinType::LEFT:
case JoinType::INNER:
case JoinType::RIGHT:
case JoinType::OUTER:
ResolveComplexJoin(context, chunk, state_p);
break;
default:
throw NotImplementedException("Unimplemented type for nested loop join!");
}
}
unique_ptr<PhysicalOperatorState> PhysicalPiecewiseMergeJoin::GetOperatorState() {
return make_unique<PhysicalPiecewiseMergeJoinState>(*this, children[0].get(), conditions);
}
//===--------------------------------------------------------------------===//
// OrderVector
//===--------------------------------------------------------------------===//
template <class T, class OP>
static sel_t TemplatedQuicksortInitial(T *data, const SelectionVector &sel, const SelectionVector ¬_null_sel,
idx_t count, SelectionVector &result) {
// select pivot
auto pivot_idx = not_null_sel.get_index(0);
auto dpivot_idx = sel.get_index(pivot_idx);
sel_t low = 0, high = count - 1;
// now insert elements
for (idx_t i = 1; i < count; i++) {
auto idx = not_null_sel.get_index(i);
auto didx = sel.get_index(idx);
if (OP::Operation(data[didx], data[dpivot_idx])) {
result.set_index(low++, idx);
} else {
result.set_index(high--, idx);
}
}
D_ASSERT(low == high);
result.set_index(low, pivot_idx);
return low;
}
template <class T, class OP>
static void TemplatedQuicksortRefine(T *data, const SelectionVector &sel, idx_t count, SelectionVector &result,
sel_t left, sel_t right) {
if (left >= right) {
return;
}
sel_t middle = left + (right - left) / 2;
sel_t dpivot_idx = sel.get_index(result.get_index(middle));
// move the mid point value to the front.
sel_t i = left + 1;
sel_t j = right;
result.swap(middle, left);
while (i <= j) {
while (i <= j && (OP::Operation(data[sel.get_index(result.get_index(i))], data[dpivot_idx]))) {
i++;
}
while (i <= j && !OP::Operation(data[sel.get_index(result.get_index(j))], data[dpivot_idx])) {
j--;
}
if (i < j) {
result.swap(i, j);
}
}
result.swap(i - 1, left);
sel_t part = i - 1;
if (part > 0) {
TemplatedQuicksortRefine<T, OP>(data, sel, count, result, left, part - 1);
}
TemplatedQuicksortRefine<T, OP>(data, sel, count, result, part + 1, right);
}
template <class T, class OP>
void TemplatedQuicksort(T *__restrict data, const SelectionVector &sel, const SelectionVector ¬_null_sel,
idx_t count, SelectionVector &result) {
auto part = TemplatedQuicksortInitial<T, OP>(data, sel, not_null_sel, count, result);
if (part > count) {
return;
}
TemplatedQuicksortRefine<T, OP>(data, sel, count, result, 0, part);
TemplatedQuicksortRefine<T, OP>(data, sel, count, result, part + 1, count - 1);
}
template <class T>
static void TemplatedQuicksort(VectorData &vdata, const SelectionVector ¬_null_sel, idx_t not_null_count,
SelectionVector &result) {
if (not_null_count == 0) {
return;
}
TemplatedQuicksort<T, duckdb::LessThanEquals>((T *)vdata.data, *vdata.sel, not_null_sel, not_null_count, result);
}
void OrderVector(Vector &vector, idx_t count, MergeOrder &order) {
if (count == 0) {
order.count = 0;
return;
}
vector.Orrify(count, order.vdata);
auto &vdata = order.vdata;
// first filter out all the non-null values
SelectionVector not_null(STANDARD_VECTOR_SIZE);
idx_t not_null_count = 0;
for (idx_t i = 0; i < count; i++) {
auto idx = vdata.sel->get_index(i);
if (vdata.validity.RowIsValid(idx)) {
not_null.set_index(not_null_count++, i);
}
}
order.count = not_null_count;
order.order.Initialize(STANDARD_VECTOR_SIZE);
switch (vector.GetType().InternalType()) {
case PhysicalType::BOOL:
case PhysicalType::INT8:
TemplatedQuicksort<int8_t>(vdata, not_null, not_null_count, order.order);
break;
case PhysicalType::INT16:
TemplatedQuicksort<int16_t>(vdata, not_null, not_null_count, order.order);
break;
case PhysicalType::INT32:
TemplatedQuicksort<int32_t>(vdata, not_null, not_null_count, order.order);
break;
case PhysicalType::INT64:
TemplatedQuicksort<int64_t>(vdata, not_null, not_null_count, order.order);
break;
case PhysicalType::UINT8:
TemplatedQuicksort<uint8_t>(vdata, not_null, not_null_count, order.order);
break;
case PhysicalType::UINT16:
TemplatedQuicksort<uint16_t>(vdata, not_null, not_null_count, order.order);
break;
case PhysicalType::UINT32:
TemplatedQuicksort<uint32_t>(vdata, not_null, not_null_count, order.order);
break;
case PhysicalType::UINT64:
TemplatedQuicksort<uint64_t>(vdata, not_null, not_null_count, order.order);
break;
case PhysicalType::INT128:
TemplatedQuicksort<hugeint_t>(vdata, not_null, not_null_count, order.order);
break;
case PhysicalType::FLOAT:
TemplatedQuicksort<float>(vdata, not_null, not_null_count, order.order);
break;
case PhysicalType::DOUBLE:
TemplatedQuicksort<double>(vdata, not_null, not_null_count, order.order);
break;
case PhysicalType::INTERVAL:
TemplatedQuicksort<interval_t>(vdata, not_null, not_null_count, order.order);
break;
case PhysicalType::VARCHAR:
TemplatedQuicksort<string_t>(vdata, not_null, not_null_count, order.order);
break;
default:
throw NotImplementedException("Unimplemented type for sort");
}
}
} // namespace duckdb
|
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See License.txt in the repo root for license information.
// ------------------------------------------------------------
#include "stdafx.h"
using namespace std;
using namespace Common;
using namespace ServiceModel;
StringLiteral const TraceSource("ReplicaEvaluation");
INITIALIZE_SIZE_ESTIMATION(ReplicaHealthEvaluation)
ReplicaHealthEvaluation::ReplicaHealthEvaluation()
: HealthEvaluationWithChildrenBase(FABRIC_HEALTH_EVALUATION_KIND_REPLICA)
, partitionId_(Guid::Empty())
, replicaId_(FABRIC_INVALID_REPLICA_ID)
{
}
ReplicaHealthEvaluation::ReplicaHealthEvaluation(
Common::Guid const & partitionId,
FABRIC_REPLICA_ID replicaId,
FABRIC_HEALTH_STATE aggregatedHealthState,
HealthEvaluationList && unhealthyEvaluations)
: HealthEvaluationWithChildrenBase(FABRIC_HEALTH_EVALUATION_KIND_REPLICA, aggregatedHealthState, move(unhealthyEvaluations))
, partitionId_(partitionId)
, replicaId_(replicaId)
{
}
ReplicaHealthEvaluation::~ReplicaHealthEvaluation()
{
}
ErrorCode ReplicaHealthEvaluation::ToPublicApi(
__in Common::ScopedHeap & heap,
__out FABRIC_HEALTH_EVALUATION & publicHealthEvaluation) const
{
auto publicReplicaHealthEvaluation = heap.AddItem<FABRIC_REPLICA_HEALTH_EVALUATION>();
publicReplicaHealthEvaluation->Description = heap.AddString(description_);
publicReplicaHealthEvaluation->PartitionId = partitionId_.AsGUID();
publicReplicaHealthEvaluation->ReplicaOrInstanceId = replicaId_;
publicReplicaHealthEvaluation->AggregatedHealthState = aggregatedHealthState_;
auto publicHealthEvaluationList = heap.AddItem<FABRIC_HEALTH_EVALUATION_LIST>();
auto error = PublicApiHelper::ToPublicApiList<HealthEvaluation, FABRIC_HEALTH_EVALUATION, FABRIC_HEALTH_EVALUATION_LIST>(
heap,
unhealthyEvaluations_,
*publicHealthEvaluationList);
if (!error.IsSuccess()) { return error; }
publicReplicaHealthEvaluation->UnhealthyEvaluations = publicHealthEvaluationList.GetRawPointer();
publicHealthEvaluation.Kind = FABRIC_HEALTH_EVALUATION_KIND_REPLICA;
publicHealthEvaluation.Value = publicReplicaHealthEvaluation.GetRawPointer();
return ErrorCode::Success();
}
Common::ErrorCode ReplicaHealthEvaluation::FromPublicApi(
FABRIC_HEALTH_EVALUATION const & publicHealthEvaluation)
{
ErrorCode error(ErrorCodeValue::Success);
auto publicReplicaHealthEvaluation = reinterpret_cast<FABRIC_REPLICA_HEALTH_EVALUATION *>(publicHealthEvaluation.Value);
partitionId_ = Guid(publicReplicaHealthEvaluation->PartitionId);
replicaId_= publicReplicaHealthEvaluation->ReplicaOrInstanceId;
auto hr = StringUtility::LpcwstrToWstring(publicReplicaHealthEvaluation->Description, false, ParameterValidator::MinStringSize, ParameterValidator::MaxStringSize, description_);
if (FAILED(hr))
{
error = ErrorCode::FromHResult(hr);
Trace.WriteInfo(TraceSource, "Error parsing description in FromPublicAPI: {0}", error);
return error;
}
aggregatedHealthState_ = publicReplicaHealthEvaluation->AggregatedHealthState;
error = PublicApiHelper::FromPublicApiList<HealthEvaluation, FABRIC_HEALTH_EVALUATION_LIST>(
publicReplicaHealthEvaluation->UnhealthyEvaluations,
unhealthyEvaluations_);
if (!error.IsSuccess()) { return error; }
return ErrorCode::Success();
}
void ReplicaHealthEvaluation::SetDescription()
{
description_ = wformatString(
HMResource::GetResources().HealthEvaluationUnhealthyReplica,
replicaId_,
aggregatedHealthState_);
}
|
//===-- Background.cpp - Build an index in a background thread ------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#include "index/Background.h"
#include "Compiler.h"
#include "Context.h"
#include "FSProvider.h"
#include "Headers.h"
#include "Logger.h"
#include "ParsedAST.h"
#include "Path.h"
#include "SourceCode.h"
#include "Symbol.h"
#include "Threading.h"
#include "Trace.h"
#include "URI.h"
#include "index/BackgroundIndexLoader.h"
#include "index/FileIndex.h"
#include "index/IndexAction.h"
#include "index/MemIndex.h"
#include "index/Ref.h"
#include "index/Relation.h"
#include "index/Serialization.h"
#include "index/SymbolCollector.h"
#include "clang/Basic/SourceLocation.h"
#include "clang/Basic/SourceManager.h"
#include "clang/Driver/Types.h"
#include "llvm/ADT/ArrayRef.h"
#include "llvm/ADT/DenseSet.h"
#include "llvm/ADT/Hashing.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/ScopeExit.h"
#include "llvm/ADT/StringMap.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/ADT/StringSet.h"
#include "llvm/Support/Error.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/Threading.h"
#include <algorithm>
#include <atomic>
#include <chrono>
#include <condition_variable>
#include <cstddef>
#include <memory>
#include <mutex>
#include <numeric>
#include <queue>
#include <random>
#include <string>
#include <thread>
#include <utility>
#include <vector>
namespace clang {
namespace clangd {
namespace {
// Resolves URI to file paths with cache.
class URIToFileCache {
public:
URIToFileCache(llvm::StringRef HintPath) : HintPath(HintPath) {}
llvm::StringRef resolve(llvm::StringRef FileURI) {
auto I = URIToPathCache.try_emplace(FileURI);
if (I.second) {
auto Path = URI::resolve(FileURI, HintPath);
if (!Path) {
elog("Failed to resolve URI {0}: {1}", FileURI, Path.takeError());
assert(false && "Failed to resolve URI");
return "";
}
I.first->second = *Path;
}
return I.first->second;
}
private:
std::string HintPath;
llvm::StringMap<std::string> URIToPathCache;
};
// We keep only the node "U" and its edges. Any node other than "U" will be
// empty in the resultant graph.
IncludeGraph getSubGraph(const URI &U, const IncludeGraph &FullGraph) {
IncludeGraph IG;
std::string FileURI = U.toString();
auto Entry = IG.try_emplace(FileURI).first;
auto &Node = Entry->getValue();
Node = FullGraph.lookup(Entry->getKey());
Node.URI = Entry->getKey();
// URIs inside nodes must point into the keys of the same IncludeGraph.
for (auto &Include : Node.DirectIncludes) {
auto I = IG.try_emplace(Include).first;
I->getValue().URI = I->getKey();
Include = I->getKey();
}
return IG;
}
// We cannot use vfs->makeAbsolute because Cmd.FileName is either absolute or
// relative to Cmd.Directory, which might not be the same as current working
// directory.
llvm::SmallString<128> getAbsolutePath(const tooling::CompileCommand &Cmd) {
llvm::SmallString<128> AbsolutePath;
if (llvm::sys::path::is_absolute(Cmd.Filename)) {
AbsolutePath = Cmd.Filename;
} else {
AbsolutePath = Cmd.Directory;
llvm::sys::path::append(AbsolutePath, Cmd.Filename);
llvm::sys::path::remove_dots(AbsolutePath, true);
}
return AbsolutePath;
}
bool shardIsStale(const LoadedShard &LS, llvm::vfs::FileSystem *FS) {
auto Buf = FS->getBufferForFile(LS.AbsolutePath);
if (!Buf) {
elog("Background-index: Couldn't read {0} to validate stored index: {1}",
LS.AbsolutePath, Buf.getError().message());
// There is no point in indexing an unreadable file.
return false;
}
return digest(Buf->get()->getBuffer()) != LS.Digest;
}
} // namespace
BackgroundIndex::BackgroundIndex(
Context BackgroundContext, const FileSystemProvider &FSProvider,
const GlobalCompilationDatabase &CDB,
BackgroundIndexStorage::Factory IndexStorageFactory, size_t ThreadPoolSize)
: SwapIndex(std::make_unique<MemIndex>()), FSProvider(FSProvider),
CDB(CDB), BackgroundContext(std::move(BackgroundContext)),
Rebuilder(this, &IndexedSymbols, ThreadPoolSize),
IndexStorageFactory(std::move(IndexStorageFactory)),
CommandsChanged(
CDB.watch([&](const std::vector<std::string> &ChangedFiles) {
enqueue(ChangedFiles);
})) {
assert(ThreadPoolSize > 0 && "Thread pool size can't be zero.");
assert(this->IndexStorageFactory && "Storage factory can not be null!");
for (unsigned I = 0; I < ThreadPoolSize; ++I) {
ThreadPool.runAsync("background-worker-" + llvm::Twine(I + 1), [this] {
WithContext Ctx(this->BackgroundContext.clone());
Queue.work([&] { Rebuilder.idle(); });
});
}
}
BackgroundIndex::~BackgroundIndex() {
stop();
ThreadPool.wait();
}
BackgroundQueue::Task BackgroundIndex::changedFilesTask(
const std::vector<std::string> &ChangedFiles) {
BackgroundQueue::Task T([this, ChangedFiles] {
trace::Span Tracer("BackgroundIndexEnqueue");
// We're doing this asynchronously, because we'll read shards here too.
log("Enqueueing {0} commands for indexing", ChangedFiles.size());
SPAN_ATTACH(Tracer, "files", int64_t(ChangedFiles.size()));
auto NeedsReIndexing = loadProject(std::move(ChangedFiles));
// Run indexing for files that need to be updated.
std::shuffle(NeedsReIndexing.begin(), NeedsReIndexing.end(),
std::mt19937(std::random_device{}()));
std::vector<BackgroundQueue::Task> Tasks;
Tasks.reserve(NeedsReIndexing.size());
for (auto &Cmd : NeedsReIndexing)
Tasks.push_back(indexFileTask(std::move(Cmd)));
Queue.append(std::move(Tasks));
});
T.QueuePri = LoadShards;
T.ThreadPri = llvm::ThreadPriority::Default;
return T;
}
static llvm::StringRef filenameWithoutExtension(llvm::StringRef Path) {
Path = llvm::sys::path::filename(Path);
return Path.drop_back(llvm::sys::path::extension(Path).size());
}
BackgroundQueue::Task
BackgroundIndex::indexFileTask(tooling::CompileCommand Cmd) {
BackgroundQueue::Task T([this, Cmd] {
// We can't use llvm::StringRef here since we are going to
// move from Cmd during the call below.
const std::string FileName = Cmd.Filename;
if (auto Error = index(std::move(Cmd)))
elog("Indexing {0} failed: {1}", FileName, std::move(Error));
});
T.QueuePri = IndexFile;
T.Tag = filenameWithoutExtension(Cmd.Filename);
return T;
}
void BackgroundIndex::boostRelated(llvm::StringRef Path) {
namespace types = clang::driver::types;
auto Type =
types::lookupTypeForExtension(llvm::sys::path::extension(Path).substr(1));
// is this a header?
if (Type != types::TY_INVALID && types::onlyPrecompileType(Type))
Queue.boost(filenameWithoutExtension(Path), IndexBoostedFile);
}
/// Given index results from a TU, only update symbols coming from files that
/// are different or missing from than \p ShardVersionsSnapshot. Also stores new
/// index information on IndexStorage.
void BackgroundIndex::update(
llvm::StringRef MainFile, IndexFileIn Index,
const llvm::StringMap<ShardVersion> &ShardVersionsSnapshot,
bool HadErrors) {
// Partition symbols/references into files.
struct File {
llvm::DenseSet<const Symbol *> Symbols;
llvm::DenseSet<const Ref *> Refs;
llvm::DenseSet<const Relation *> Relations;
FileDigest Digest;
};
llvm::StringMap<File> Files;
URIToFileCache URICache(MainFile);
for (const auto &IndexIt : *Index.Sources) {
const auto &IGN = IndexIt.getValue();
// Note that sources do not contain any information regarding missing
// headers, since we don't even know what absolute path they should fall in.
const auto AbsPath = URICache.resolve(IGN.URI);
const auto DigestIt = ShardVersionsSnapshot.find(AbsPath);
// File has different contents, or indexing was successfull this time.
if (DigestIt == ShardVersionsSnapshot.end() ||
DigestIt->getValue().Digest != IGN.Digest ||
(DigestIt->getValue().HadErrors && !HadErrors))
Files.try_emplace(AbsPath).first->getValue().Digest = IGN.Digest;
}
// This map is used to figure out where to store relations.
llvm::DenseMap<SymbolID, File *> SymbolIDToFile;
for (const auto &Sym : *Index.Symbols) {
if (Sym.CanonicalDeclaration) {
auto DeclPath = URICache.resolve(Sym.CanonicalDeclaration.FileURI);
const auto FileIt = Files.find(DeclPath);
if (FileIt != Files.end()) {
FileIt->second.Symbols.insert(&Sym);
SymbolIDToFile[Sym.ID] = &FileIt->second;
}
}
// For symbols with different declaration and definition locations, we store
// the full symbol in both the header file and the implementation file, so
// that merging can tell the preferred symbols (from canonical headers) from
// other symbols (e.g. forward declarations).
if (Sym.Definition &&
Sym.Definition.FileURI != Sym.CanonicalDeclaration.FileURI) {
auto DefPath = URICache.resolve(Sym.Definition.FileURI);
const auto FileIt = Files.find(DefPath);
if (FileIt != Files.end())
FileIt->second.Symbols.insert(&Sym);
}
}
llvm::DenseMap<const Ref *, SymbolID> RefToIDs;
for (const auto &SymRefs : *Index.Refs) {
for (const auto &R : SymRefs.second) {
auto Path = URICache.resolve(R.Location.FileURI);
const auto FileIt = Files.find(Path);
if (FileIt != Files.end()) {
auto &F = FileIt->getValue();
RefToIDs[&R] = SymRefs.first;
F.Refs.insert(&R);
}
}
}
for (const auto &Rel : *Index.Relations) {
const auto FileIt = SymbolIDToFile.find(Rel.Subject);
if (FileIt != SymbolIDToFile.end())
FileIt->second->Relations.insert(&Rel);
}
// Build and store new slabs for each updated file.
for (const auto &FileIt : Files) {
llvm::StringRef Path = FileIt.getKey();
SymbolSlab::Builder Syms;
RefSlab::Builder Refs;
RelationSlab::Builder Relations;
for (const auto *S : FileIt.second.Symbols)
Syms.insert(*S);
for (const auto *R : FileIt.second.Refs)
Refs.insert(RefToIDs[R], *R);
for (const auto *Rel : FileIt.second.Relations)
Relations.insert(*Rel);
auto SS = std::make_unique<SymbolSlab>(std::move(Syms).build());
auto RS = std::make_unique<RefSlab>(std::move(Refs).build());
auto RelS = std::make_unique<RelationSlab>(std::move(Relations).build());
auto IG = std::make_unique<IncludeGraph>(
getSubGraph(URI::create(Path), Index.Sources.getValue()));
// We need to store shards before updating the index, since the latter
// consumes slabs.
// FIXME: Also skip serializing the shard if it is already up-to-date.
BackgroundIndexStorage *IndexStorage = IndexStorageFactory(Path);
IndexFileOut Shard;
Shard.Symbols = SS.get();
Shard.Refs = RS.get();
Shard.Relations = RelS.get();
Shard.Sources = IG.get();
// Only store command line hash for main files of the TU, since our
// current model keeps only one version of a header file.
if (Path == MainFile)
Shard.Cmd = Index.Cmd.getPointer();
if (auto Error = IndexStorage->storeShard(Path, Shard))
elog("Failed to write background-index shard for file {0}: {1}", Path,
std::move(Error));
{
std::lock_guard<std::mutex> Lock(ShardVersionsMu);
auto Hash = FileIt.second.Digest;
auto DigestIt = ShardVersions.try_emplace(Path);
ShardVersion &SV = DigestIt.first->second;
// Skip if file is already up to date, unless previous index was broken
// and this one is not.
if (!DigestIt.second && SV.Digest == Hash && SV.HadErrors && !HadErrors)
continue;
SV.Digest = Hash;
SV.HadErrors = HadErrors;
// This can override a newer version that is added in another thread, if
// this thread sees the older version but finishes later. This should be
// rare in practice.
IndexedSymbols.update(Path, std::move(SS), std::move(RS), std::move(RelS),
Path == MainFile);
}
}
}
llvm::Error BackgroundIndex::index(tooling::CompileCommand Cmd) {
trace::Span Tracer("BackgroundIndex");
SPAN_ATTACH(Tracer, "file", Cmd.Filename);
auto AbsolutePath = getAbsolutePath(Cmd);
auto FS = FSProvider.getFileSystem();
auto Buf = FS->getBufferForFile(AbsolutePath);
if (!Buf)
return llvm::errorCodeToError(Buf.getError());
auto Hash = digest(Buf->get()->getBuffer());
// Take a snapshot of the versions to avoid locking for each file in the TU.
llvm::StringMap<ShardVersion> ShardVersionsSnapshot;
{
std::lock_guard<std::mutex> Lock(ShardVersionsMu);
ShardVersionsSnapshot = ShardVersions;
}
vlog("Indexing {0} (digest:={1})", Cmd.Filename, llvm::toHex(Hash));
ParseInputs Inputs;
Inputs.FS = std::move(FS);
Inputs.FS->setCurrentWorkingDirectory(Cmd.Directory);
Inputs.CompileCommand = std::move(Cmd);
IgnoreDiagnostics IgnoreDiags;
auto CI = buildCompilerInvocation(Inputs, IgnoreDiags);
if (!CI)
return llvm::createStringError(llvm::inconvertibleErrorCode(),
"Couldn't build compiler invocation");
auto Clang = prepareCompilerInstance(std::move(CI), /*Preamble=*/nullptr,
std::move(*Buf), Inputs.FS, IgnoreDiags);
if (!Clang)
return llvm::createStringError(llvm::inconvertibleErrorCode(),
"Couldn't build compiler instance");
SymbolCollector::Options IndexOpts;
// Creates a filter to not collect index results from files with unchanged
// digests.
IndexOpts.FileFilter = [&ShardVersionsSnapshot](const SourceManager &SM,
FileID FID) {
const auto *F = SM.getFileEntryForID(FID);
if (!F)
return false; // Skip invalid files.
auto AbsPath = getCanonicalPath(F, SM);
if (!AbsPath)
return false; // Skip files without absolute path.
auto Digest = digestFile(SM, FID);
if (!Digest)
return false;
auto D = ShardVersionsSnapshot.find(*AbsPath);
if (D != ShardVersionsSnapshot.end() && D->second.Digest == Digest &&
!D->second.HadErrors)
return false; // Skip files that haven't changed, without errors.
return true;
};
IndexFileIn Index;
auto Action = createStaticIndexingAction(
IndexOpts, [&](SymbolSlab S) { Index.Symbols = std::move(S); },
[&](RefSlab R) { Index.Refs = std::move(R); },
[&](RelationSlab R) { Index.Relations = std::move(R); },
[&](IncludeGraph IG) { Index.Sources = std::move(IG); });
// We're going to run clang here, and it could potentially crash.
// We could use CrashRecoveryContext to try to make indexing crashes nonfatal,
// but the leaky "recovery" is pretty scary too in a long-running process.
// If crashes are a real problem, maybe we should fork a child process.
const FrontendInputFile &Input = Clang->getFrontendOpts().Inputs.front();
if (!Action->BeginSourceFile(*Clang, Input))
return llvm::createStringError(llvm::inconvertibleErrorCode(),
"BeginSourceFile() failed");
if (llvm::Error Err = Action->Execute())
return Err;
Action->EndSourceFile();
Index.Cmd = Inputs.CompileCommand;
assert(Index.Symbols && Index.Refs && Index.Sources &&
"Symbols, Refs and Sources must be set.");
log("Indexed {0} ({1} symbols, {2} refs, {3} files)",
Inputs.CompileCommand.Filename, Index.Symbols->size(),
Index.Refs->numRefs(), Index.Sources->size());
SPAN_ATTACH(Tracer, "symbols", int(Index.Symbols->size()));
SPAN_ATTACH(Tracer, "refs", int(Index.Refs->numRefs()));
SPAN_ATTACH(Tracer, "sources", int(Index.Sources->size()));
bool HadErrors = Clang->hasDiagnostics() &&
Clang->getDiagnostics().hasUncompilableErrorOccurred();
if (HadErrors) {
log("Failed to compile {0}, index may be incomplete", AbsolutePath);
for (auto &It : *Index.Sources)
It.second.Flags |= IncludeGraphNode::SourceFlag::HadErrors;
}
update(AbsolutePath, std::move(Index), ShardVersionsSnapshot, HadErrors);
Rebuilder.indexedTU();
return llvm::Error::success();
}
// Restores shards for \p MainFiles from index storage. Then checks staleness of
// those shards and returns a list of TUs that needs to be indexed to update
// staleness.
std::vector<tooling::CompileCommand>
BackgroundIndex::loadProject(std::vector<std::string> MainFiles) {
std::vector<tooling::CompileCommand> NeedsReIndexing;
Rebuilder.startLoading();
// Load shards for all of the mainfiles.
const std::vector<LoadedShard> Result =
loadIndexShards(MainFiles, IndexStorageFactory, CDB);
size_t LoadedShards = 0;
{
// Update in-memory state.
std::lock_guard<std::mutex> Lock(ShardVersionsMu);
for (auto &LS : Result) {
if (!LS.Shard)
continue;
auto SS =
LS.Shard->Symbols
? std::make_unique<SymbolSlab>(std::move(*LS.Shard->Symbols))
: nullptr;
auto RS = LS.Shard->Refs
? std::make_unique<RefSlab>(std::move(*LS.Shard->Refs))
: nullptr;
auto RelS =
LS.Shard->Relations
? std::make_unique<RelationSlab>(std::move(*LS.Shard->Relations))
: nullptr;
ShardVersion &SV = ShardVersions[LS.AbsolutePath];
SV.Digest = LS.Digest;
SV.HadErrors = LS.HadErrors;
++LoadedShards;
IndexedSymbols.update(LS.AbsolutePath, std::move(SS), std::move(RS),
std::move(RelS), LS.CountReferences);
}
}
Rebuilder.loadedShard(LoadedShards);
Rebuilder.doneLoading();
auto FS = FSProvider.getFileSystem();
llvm::DenseSet<PathRef> TUsToIndex;
// We'll accept data from stale shards, but ensure the files get reindexed
// soon.
for (auto &LS : Result) {
if (!shardIsStale(LS, FS.get()))
continue;
PathRef TUForFile = LS.DependentTU;
assert(!TUForFile.empty() && "File without a TU!");
// FIXME: Currently, we simply schedule indexing on a TU whenever any of
// its dependencies needs re-indexing. We might do it smarter by figuring
// out a minimal set of TUs that will cover all the stale dependencies.
// FIXME: Try looking at other TUs if no compile commands are available
// for this TU, i.e TU was deleted after we performed indexing.
TUsToIndex.insert(TUForFile);
}
for (PathRef TU : TUsToIndex) {
auto Cmd = CDB.getCompileCommand(TU);
if (!Cmd)
continue;
NeedsReIndexing.emplace_back(std::move(*Cmd));
}
return NeedsReIndexing;
}
} // namespace clangd
} // namespace clang
|
// Copyright (c) 2017 Jackal Engine, MIT License.
#include "OpenGLDevice/OpenGLUniformBuffer.hpp"
#include "OpenGLDevice/OpenGLGraphicsPipelineState.hpp"
#include "Core/Logging/Debugging.hpp"
#include <stdlib.h>
namespace jackal {
void OpenGLUniformBuffer::Initialize(UniformBufferCreateInfoT& info)
{
CleanUp();
// OpenGL Stuff.
glGenBuffers(1, &ubo);
glBindBuffer(GL_UNIFORM_BUFFER, ubo);
glBufferData(GL_UNIFORM_BUFFER, info.Size, NULL,
(mDataType == DATA_DYNAMIC ? GL_DYNAMIC_DRAW : GL_STATIC_DRAW));
glBindBufferBase(GL_UNIFORM_BUFFER, (GLuint )info.Bind, ubo);
void* data = Map();
memcpy(data, info.Data, info.Size);
UnMap();
OPENGL_CHECK_ERROR(GLenum error);
if (error != GL_NO_ERROR) {
return;
}
glBindBuffer(GL_UNIFORM_BUFFER, 0);
}
void OpenGLUniformBuffer::CleanUp()
{
if (!ubo) {
return;
}
glDeleteBuffers(1, &ubo);
ubo = -1;
}
void* OpenGLUniformBuffer::Map()
{
glBindBuffer(GL_UNIFORM_BUFFER, ubo);
void* data = glMapBuffer(GL_UNIFORM_BUFFER, GL_READ_WRITE);
OPENGL_CHECK_ERROR(GLenum error);
if (error != GL_NO_ERROR) {
return nullptr;
}
return data;
}
void OpenGLUniformBuffer::UnMap()
{
glBindBuffer(GL_UNIFORM_BUFFER, ubo);
glUnmapBuffer(GL_UNIFORM_BUFFER);
OPENGL_CHECK_ERROR(GLenum error);
if (error != GL_NO_ERROR) {
JDEBUG("UnMap error!\n");
return;
}
}
} // jackal
|
#include <flutter/dart_project.h>
#include <flutter/flutter_view_controller.h>
#include <windows.h>
#include "flutter_window.h"
#include "run_loop.h"
#include "utils.h"
int APIENTRY wWinMain(_In_ HINSTANCE instance, _In_opt_ HINSTANCE prev,
_In_ wchar_t *command_line, _In_ int show_command) {
// Attach to console when present (e.g., 'flutter run') or create a
// new console when running with a debugger.
if (!::AttachConsole(ATTACH_PARENT_PROCESS) && ::IsDebuggerPresent()) {
CreateAndAttachConsole();
}
// Initialize COM, so that it is available for use in the library and/or
// plugins.
::CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED);
RunLoop run_loop;
flutter::DartProject project(L"data");
std::vector<std::string> command_line_arguments =
GetCommandLineArguments();
project.set_dart_entrypoint_arguments(std::move(command_line_arguments));
FlutterWindow window(&run_loop, project);
Win32Window::Point origin(10, 10);
Win32Window::Size size(1280, 720);
if (!window.CreateAndShow(L"zwift_converter", origin, size)) {
return EXIT_FAILURE;
}
window.SetQuitOnClose(true);
run_loop.Run();
::CoUninitialize();
return EXIT_SUCCESS;
}
|
#include "mpi.h"
#include "mlpack/core.hpp"
#include "mlpack/methods/decision_tree/decision_tree.hpp"
#include "mlpack/methods/softmax_regression/softmax_regression.hpp"
#include <string>
const std::string data_files_extension = ".bin";
const std::string get_object_data_file_prefix(const int object_id);
const std::string get_test_file_name(const int object_id);
const std::string get_predictions_file_name(const int object_id);
const std::string get_model_save_file_name(const int object_id, const int classifier_num);
const std::string get_model_type_save_file_name(const int object_id, const int classifier_num);
const std::string get_model_accuracy_save_file_name(const int object_id, const int classifier_num);
int main(int argc, char **argv)
{
// Initialize the MPI environment
MPI_Init(&argc, &argv);
// Get the number of processes
int world_size;
MPI_Comm_size(MPI_COMM_WORLD, &world_size);
// Get the rank of the process
int world_rank;
MPI_Comm_rank(MPI_COMM_WORLD, &world_rank);
const int num_classifiers = std::stoi(argv[1]);
const int ensemble_object_id = std::stoi(argv[2]);
arma::mat X;
X.load(get_test_file_name(ensemble_object_id));
int *sub_predictions = nullptr;
double *accuracy = nullptr;
int predictions_size;
int num_classes;
int seg_size, seg_size_2;
for (int classifier_num = world_rank; classifier_num < num_classifiers; classifier_num += world_size)
{
arma::Row<size_t> type;
type.load(get_model_type_save_file_name(ensemble_object_id, classifier_num));
arma::Row<size_t> predictions;
if (type(0) == 0)
{
mlpack::tree::DecisionTree<> decision_tree;
mlpack::data::Load(get_model_save_file_name(ensemble_object_id, classifier_num), "model", decision_tree, true);
decision_tree.Classify(X, predictions);
if (world_rank == 0 and classifier_num == world_rank)
num_classes = decision_tree.NumClasses();
}
else
{
mlpack::regression::SoftmaxRegression softmax_regressor;
mlpack::data::Load(get_model_save_file_name(ensemble_object_id, classifier_num), "model", softmax_regressor, true);
softmax_regressor.Classify(X, predictions);
if (world_rank == 0 and classifier_num == world_rank)
num_classes = softmax_regressor.NumClasses();
}
if (classifier_num == world_rank)
{
predictions_size = predictions.n_elem;
seg_size = predictions_size * ((num_classifiers + world_size - 1) / world_size);
seg_size_2 = (num_classifiers + world_size - 1) / world_size;
sub_predictions = new int[seg_size];
accuracy = new double[seg_size_2];
}
for (int i = 0; i < predictions_size; i++)
sub_predictions[predictions_size * (classifier_num / world_size) + i] = predictions[i];
arma::mat accuracy_mat;
accuracy_mat.load(get_model_accuracy_save_file_name(ensemble_object_id, classifier_num));
accuracy[classifier_num / world_size] = accuracy_mat(0, 0);
}
int *all_predictions = nullptr;
double *all_accuracies = nullptr;
if (world_rank == 0)
{
all_predictions = new int[world_size * seg_size];
all_accuracies = new double[world_size * seg_size_2];
}
MPI_Gather(sub_predictions, seg_size, MPI_INT, all_predictions, seg_size, MPI_INT, 0, MPI_COMM_WORLD);
MPI_Gather(accuracy, seg_size_2, MPI_DOUBLE, all_accuracies, seg_size_2, MPI_DOUBLE, 0, MPI_COMM_WORLD);
delete sub_predictions;
delete accuracy;
if (world_rank == 0)
{
arma::Row<size_t> ensemble_predictions(predictions_size);
for (int i = 0; i < predictions_size; i++)
{
std::vector<double> weight_predictions(num_classes);
for (int j = 0; j < num_classifiers; j++)
weight_predictions[all_predictions[seg_size * (j % world_size) + predictions_size * (j / world_size) + i]] += all_accuracies[seg_size_2 * (j % world_size) + (j / world_size)];
int max_weight_index = -1;
double max_weight = -1;
for (int i = 0; i < num_classes; i++)
if (weight_predictions[i] > max_weight)
{
max_weight = weight_predictions[i];
max_weight_index = i;
}
ensemble_predictions[i] = max_weight_index;
}
ensemble_predictions.save(get_predictions_file_name(ensemble_object_id).c_str());
delete all_predictions;
}
// Finalize the MPI environment.
MPI_Finalize();
}
const std::string get_object_data_file_prefix(const int object_id)
{
return "Ensemble_Object" + std::to_string(object_id);
}
const std::string get_test_file_name(const int object_id)
{
return get_object_data_file_prefix(object_id) + "_Test" + data_files_extension;
}
const std::string get_predictions_file_name(const int object_id)
{
return get_object_data_file_prefix(object_id) + "_Predictions" + data_files_extension;
}
const std::string get_model_save_file_name(const int object_id, const int classifier_num)
{
return get_object_data_file_prefix(object_id) + "_Model_" + std::to_string(classifier_num) + data_files_extension;
}
const std::string get_model_type_save_file_name(const int object_id, const int classifier_num)
{
return get_object_data_file_prefix(object_id) + "_Model_Type_" + std::to_string(classifier_num) + data_files_extension;
}
const std::string get_model_accuracy_save_file_name(const int object_id, const int classifier_num)
{
return get_object_data_file_prefix(object_id) + "_Model_Accuracy_" + std::to_string(classifier_num) + data_files_extension;
}
|
#include "MainWindow.h"
#include "GlobalManager.h"
#include <assert.h>
#include <QCloseEvent>
#include <QMenu>
#include <QAction>
#include <QApplication>
#include <QDir>
#include <QStandardItemModel>
#include <QDesktopWidget>
#include <QDateTime>
#include <QtNetwork/QHostInfo>
#include <QPropertyAnimation>
#include <QMenuBar>
#include <QtConcurrent>
#include <QScreen>
#include "../UICom/uicom.h"
#include "../interface/view/IUITitleBarPlug.h"
#include "../interface/view/IUINavigationPlug.h"
#include "../interface/view/IUIChatViewPlug.h"
#include "../interface/view/IUIGroupManagerPlug.h"
#include "../interface/view/IUIPictureBroswerPlug.h"
#include "../interface/view/IUIAddressBookPlug.h"
#include "../UICom/UIEntity.h"
#include "../CustomUi/UShadowEffect.h"
#include "../interface/view/IUICardManagerPlug.h"
#include "../interface/view/IUILoginPlug.h"
#include "../Platform/Platform.h"
#include "MessageManager.h"
#include "SystemTray.h"
#include "../interface/view/IUIOAManagerPlug.h"
#include "../Platform/AppSetting.h"
#include "../CustomUi/QtMessageBox.h"
#include "MacApp.h"
#include "../QtUtil/Utils/utils.h"
#ifdef _WINDOWS
#include <windows.h>
#include <windowsx.h>
#endif
#ifdef _MACOS
#include <sys/stat.h>
#endif
#define WIN_STATE "WIN_STATE"
#define WIN_WIDTH "WIN_WIDTH"
#define WIN_HEIGHT "WIN_HEIGHT"
#define WIN_X "WIN_X"
#define WIN_Y "WIN_Y"
//class StSessionInfo;
extern bool _sys_run;
MainWindow::MainWindow(QWidget *parent) :
#ifdef _MACOS
UShadowDialog(parent, true, false)
#else
UShadowDialog(parent, true, false)
#endif
{
//
new QTalkMsgListener(this);
#if defined(_STARTALK)
setWindowTitle("StarTalk");
#elif defined(_QCHAT)
setWindowTitle("QChat");
#else
setWindowTitle("QTalk");
#endif
//
_timr = new QTimer;
_timr->setInterval(90 * 1000);
connect(_timr, &QTimer::timeout, this, &MainWindow::sendHeartBeat);
connect(this, &MainWindow::LoginSuccess, this, &MainWindow::LoginResult);
connect(this, &MainWindow::sgRestartWithMessage, this, &MainWindow::restartWithMessage, Qt::QueuedConnection);
connect(this, &MainWindow::sgCheckUpdate, this, &MainWindow::onCheckUpdater, Qt::QueuedConnection);
//
QHostInfo info = QHostInfo::fromName(QHostInfo::localHostName());
for(const QHostAddress &address : info.addresses())
{
if(address.protocol() == QAbstractSocket::IPv4Protocol)
{
auto addr = address.toString();
if(addr != "127.0.0.1")
_ipv4Address += QString("%1; ").arg(addr);
}
}
//
#ifdef Q_OS_MAC
_pWindowMenuBar = new QMenuBar(nullptr);
//
QMenu *toolMenu = _pWindowMenuBar->addMenu(tr("工具"));
auto* addNew = new QAction(tr("程序多开"), toolMenu);
_pFeedBackLog = new QAction(tr("快速反馈日志"), toolMenu);
toolMenu->addAction(addNew);
toolMenu->addAction(_pFeedBackLog);
//
connect(addNew, &QAction::triggered, this, &MainWindow::sgRunNewInstance);
auto *dockMenu = new QMenu(this);
dockMenu->setAsDockMenu();
auto* addNewDock = new QAction(tr("程序多开"), dockMenu);
dockMenu->addAction(addNewDock);
connect(addNewDock, &QAction::triggered, this, &MainWindow::sgRunNewInstance);
#endif
// auto screens = QApplication::screens();
// for(auto* sc : screens)
// qInfo() << sc->name() << sc->availableGeometry() ;
#if defined(Q_OS_WIN)
// connect(qApp, &QApplication::screenAdded, [this](QScreen* screen){
// qInfo() << screen->name() << this->geometry();
// });
connect(qApp, &QApplication::screenRemoved, this, &MainWindow::onScreenRemoved);
#endif
// process info
_prcessInfo = new ProcessInfo;
_prcessInfo->start();
}
MainWindow::~MainWindow()
{
_prcessInfo->terminate();
delete _prcessInfo;
if(_pLocalServer)
delete _pLocalServer;
}
bool MainWindow::nativeEvent(const QByteArray &eventType, void *message, long *result)
{
#ifdef _WINDOWS
static const int boundaryWidth = 5;
MSG* msg = (MSG*)message;
double pixelRatio = this->devicePixelRatioF();
pixelRatio = qMax(pixelRatio, 1.0);
int tempBorderWidth = boundaryWidth;
switch (msg->message)
{
case WM_NCHITTEST:
qreal xPos = GET_X_LPARAM(msg->lParam) / pixelRatio - this->frameGeometry().x();
qreal yPos = GET_Y_LPARAM(msg->lParam) / pixelRatio - this->frameGeometry().y();
if (xPos < tempBorderWidth && yPos < tempBorderWidth)
*result = HTTOPLEFT;
else if (xPos >= width() - tempBorderWidth && yPos < tempBorderWidth)
*result = HTTOPRIGHT;
else if (xPos < tempBorderWidth&&yPos >= height() - tempBorderWidth)
*result = HTBOTTOMLEFT;
else if (xPos >= width() - tempBorderWidth && yPos >= height() - tempBorderWidth)
*result = HTBOTTOMRIGHT;
else if (xPos < tempBorderWidth)
*result = HTLEFT;
else if (xPos >= width() - tempBorderWidth)
*result = HTRIGHT;
else if (yPos < tempBorderWidth)
*result = HTTOP;
else if (yPos >= height() - tempBorderWidth)
*result = HTBOTTOM;
else
return false;
return true;
}
#endif // _WINDOWS
return false;
}
void MainWindow::closeEvent(QCloseEvent *e)
{
if (_sys_run)
{
this->setVisible(false);
e->ignore();
}
}
void MainWindow::init()
{
initPanels();
initQml();
//
GlobalManager::instance()->setStyleSheetAll();
}
//
void MainWindow::initQml()
{
_pView = new QmlView;
_pView->init();
// QUrl source ("qrc:/qml/main.qml");
// view->setSource(source);
// view->show();
}
/**
* @函数名
* @功能描述 获取所需面板插件及初始化面板
* @参数
* @date 2018.9.16
*/
void MainWindow::initPanels()
{
initTitleBar();
initChatView();
initAddressBook();
initGroupManager();
initCardManager();
initPictureBrowser();
initOAManager();
initNavigation();
}
void MainWindow::initLayouts()
{
_mainFrm = new QFrame(this);
_mainFrm->setObjectName("MainWindowMainFrm");
auto *glay = new QVBoxLayout;
glay->setContentsMargins(0, 0, 0, 0);
glay->setSpacing(0);
_pCenternWgt->setLayout(glay);
glay->addWidget(_mainFrm);
// _mainBottomFrm = new QFrame(this);
// _mainBottomFrm->setFixedHeight(6);
// _mainBottomFrm->setObjectName("MainWindowMainBottomFrm");
// glay->addWidget(_mainBottomFrm);
if (!_mainLayout)
{
_mainLayout = new QVBoxLayout;
_mainLayout->setContentsMargins(0, 0, 0, 0);
_mainLayout->setSpacing(0);
_mainFrm->setLayout(_mainLayout);
}
if (_titleBar)
{
_mainLayout->addWidget(_titleBar);
if (_titleBarPlugin)
{
_titleBarPlugin->setCtrlWdt(this);
}
}
_bottomFrm = new QFrame(this);
_mainLayout->addWidget(_bottomFrm);
bodyLay = new QStackedLayout(_bottomFrm);
bodyLay->setMargin(0);
bodyLay->setSpacing(0);
// 聊天窗口区域
_bottomSplt = new QSplitter;
_bottomSplt->setHandleWidth(1);
bodyLay->addWidget(_bottomSplt);
bodyLay->setCurrentWidget(_bottomSplt);
if (_navigationPanel)
{
_bottomSplt->addWidget(_navigationPanel);
}
if (_chatViewPanel)
{
_bottomSplt->addWidget(_chatViewPanel);
}
_bottomSplt->setStretchFactor(1,1);
_bottomSplt->setCollapsible(0, false);
_bottomSplt->setCollapsible(1, false);
// 通讯录相关
if (_pAddressBook)
{
_pAddressBook->setVisible(false);
bodyLay->addWidget(_pAddressBook);
}
// OA相关
if (_pOAManager)
{
_pOAManager->setVisible(false);
bodyLay->addWidget(_pOAManager);
}
}
/**
* @功能描述 加载标题栏插件
* @参数
* @date 2018.9.16
*/
void MainWindow::initTitleBar()
{
QObject* plugin = GlobalManager::instance()->getPluginInstanceQt("UITitlebarPlug");
if (plugin)
{
_titleBarPlugin = qobject_cast<IUITitlebarPlug *>(plugin);
if (_titleBarPlugin)
{
_titleBarPlugin->init();
_titleBar = _titleBarPlugin->widget();
}
}
assert(_titleBarPlugin);
assert(_titleBar);
}
void MainWindow::initCardManager()
{
QObject* plugin = GlobalManager::instance()->getPluginInstanceQt("UICardManager");
if (plugin)
{
_pCardManagerPlug = qobject_cast<IUICardManagerPlug *>(plugin);
if (_pCardManagerPlug)
{
_pCardManagerPlug->init();
_pCardManager = _pCardManagerPlug->widget();
}
}
assert(_pCardManagerPlug);
assert(_pCardManager);
}
/**
* @功能描述 加载导航插件
* @参数
* @date 2018.9.17
*/
void MainWindow::initNavigation()
{
QObject* plugin = GlobalManager::instance()->getPluginInstanceQt("UINavigationPlug");
if (plugin)
{
_navigationPlugin = qobject_cast<IUINavigationPlug *>(plugin);
if (_navigationPlugin)
{
_navigationPlugin->init();
_navigationPanel = _navigationPlugin->widget();
}
}
assert(_navigationPlugin);
assert(_navigationPanel);
}
/**
* @功能描述 加载聊天面板插件
* @参数
* @date 2018.9.17
*/
void MainWindow::initChatView()
{
QObject* plugin = GlobalManager::instance()->getPluginInstanceQt("UIChatViewPlug");
if (plugin)
{
_chatViewPlugin = qobject_cast<IUIChatViewPlug *>(plugin);
if (_chatViewPlugin)
{
_chatViewPlugin->init();
_chatViewPanel = _chatViewPlugin->widget();
}
}
assert(_chatViewPlugin);
assert(_chatViewPanel);
}
/**
* @功能描述 链接插件间信号槽
* @参数
* @date 2018.9.18
*/
void MainWindow::connectPlugs()
{
connect(this, SIGNAL(sgSystemQuit()), this, SLOT(systemQuit()));
qRegisterMetaType<QVector<int>>("QVector<int>");
// connect(_chatViewPanel, SIGNAL(recvMessageSignal()), _pSysTrayIcon, SLOT(onRecvMessage()));
connect(_titleBar, SIGNAL(sgCurFunChanged(int)),
this, SLOT(onCurFunChanged(int)));
connect(_pAddressBook, SIGNAL(sgSwitchCurFun(int)),
this, SLOT(onCurFunChanged(int)));
connect(_pCardManager, SIGNAL(sgSwitchCurFun(int)),
this, SLOT(onCurFunChanged(int)));
connect(_chatViewPanel, SIGNAL(sgSwitchCurFun(int)),
this, SLOT(onCurFunChanged(int)));
connect(_titleBar, SIGNAL(sgJumpToNewMessage()), _navigationPanel, SLOT(jumpToNewMessage()));
connect(this, SIGNAL(appDeactivated()), _titleBar, SLOT(onAppDeactivated()));
connect(this, SIGNAL(appDeactivated()), _chatViewPanel, SLOT(onAppDeactivated()));
connect(this, SIGNAL(appDeactivated()), _navigationPanel, SLOT(onAppDeactivated()));
connect(this, SIGNAL(appDeactivated()), _pSysTrayIcon, SLOT(onAppDeactivated()));
connect(_navigationPanel, SIGNAL(sgSessionInfo(const StSessionInfo&)),
_chatViewPanel, SLOT(onChatUserChanged(const StSessionInfo&)), Qt::QueuedConnection);
connect(_titleBar, SIGNAL(showSelfUserCard(const QString&)),
_pCardManager, SLOT(shwoUserCard(const QString&)));
connect(_chatViewPanel, SIGNAL(sgShowUserCard(const QString&)),
_pCardManager, SLOT(shwoUserCard(const QString&)));
connect(_chatViewPanel, SIGNAL(showUserCardSignal(const QString&)),
_pCardManager, SLOT(shwoUserCard(const QString&)));
connect(_navigationPanel, SIGNAL(showUserCardSignal(const QString&)),
_pCardManager, SLOT(shwoUserCard(const QString&)));
connect(_navigationPanel, SIGNAL(showGroupCardSignal(const QString&)),
_pCardManager, SLOT(showGroupCard(const QString&)));
connect(_chatViewPanel, SIGNAL(showGroupCardSignal(const QString&)),
_pCardManager, SLOT(showGroupCard(const QString&)));
qRegisterMetaType<QTalk::Entity::UID>("QTalk::Entity::UID");
connect(_navigationPanel, SIGNAL(removeSession(const QTalk::Entity::UID&)),
_chatViewPanel, SLOT(onRemoveSession(const QTalk::Entity::UID&)));
connect(_titleBar, SIGNAL(sgOpenNewSession(const StSessionInfo&)),
_navigationPanel, SLOT(onNewSession(const StSessionInfo&)));
connect(this, SIGNAL(sgJumtoSession(const StSessionInfo&)),
_navigationPanel, SLOT(onNewSession(const StSessionInfo&)));
connect(_pCardManager, SIGNAL(sgOpenNewSession(const StSessionInfo&)),
_navigationPanel, SLOT(onNewSession(const StSessionInfo&)));
connect(_chatViewPanel, SIGNAL(sgOpenNewSession(const StSessionInfo&)),
_navigationPanel, SLOT(onNewSession(const StSessionInfo&)));
connect(_pAddressBook, SIGNAL(sgOpenNewSession(const StSessionInfo&)),
_navigationPanel, SLOT(onNewSession(const StSessionInfo&)));
connect(_pAddressBook, SIGNAL(sgSwitchCurFun(int)),
_titleBar, SLOT(onSwitchFunc(int)));
connect(_pCardManager, SIGNAL(sgSwitchCurFun(int)),
_titleBar, SLOT(onSwitchFunc(int)));
connect(_chatViewPanel, SIGNAL(sgJumpToStructre(const QString&)),
_pAddressBook, SLOT(jumpToUserStructre(const QString&)));
connect(_chatViewPanel, SIGNAL(sgSwitchCurFun(int)),
_titleBar, SLOT(onSwitchFunc(int)));
connect(_chatViewPanel, SIGNAL(creatGroup(const QString&)),
_pGroupManager, SLOT(onCreatGroup(const QString&)));
connect(_titleBar, SIGNAL(creatGroup(const QString&)),
_pGroupManager, SLOT(onCreatGroup(const QString&)));
connect(_chatViewPanel, SIGNAL(addGroupMember(const QString&)),
_pGroupManager, SLOT(onAddGroupMember(const QString&)));
connect(_chatViewPanel, SIGNAL(showChatPicture(const QString&, const QString&, int)),
_pPictureBrowser, SLOT(onShowChatPicture(const QString&, const QString&, int)));
connect(_chatViewPanel, SIGNAL(sgShowPicture(const QString&, const QString&)),
_pPictureBrowser, SLOT(showPicture(const QString&, const QString&)));
// connect(_pGroupManager, SIGNAL(setTreeDataFinised()), _pAddressBook, SLOT(updateStaffUi()));
connect(_navigationPanel, SIGNAL(updateTotalUnreadCount(int)), _titleBar, SLOT(updateUnreadCount(int)));
connect(_titleBar, SIGNAL(feedbackLog(const QString&)), _chatViewPanel, SLOT(packAndSendLog(const QString&)));
connect(this, SIGNAL(systemShortCut()), _chatViewPanel, SLOT(systemShortCut()));
connect(_titleBar, SIGNAL(systemQuitSignal()), this, SLOT(systemQuit()), Qt::QueuedConnection);
connect(this, SIGNAL(systemQuitSignal()), this, SLOT(systemQuit()), Qt::QueuedConnection);
connect(_chatViewPanel, SIGNAL(sgShortCutSwitchSession(int)),
_navigationPanel, SLOT(onShortCutSwitchSession(int)));
connect(_navigationPanel, SIGNAL(sgShowUnreadMessage(int, const QTalk::Entity::UID&, const QString&, qint64, int)),
_pSysTrayIcon, SIGNAL(sgShowUnreadMessage(int, const QTalk::Entity::UID&, const QString&, qint64, int)));
//
connect(_pCardManager, SIGNAL(sgJumpToStructre(const QString&)), _pAddressBook, SLOT(onJumpToStructre(const QString&)));
connect(_pCardManager, SIGNAL(sgShowHeadWnd(const QString&, bool)),
_titleBar, SLOT(onShowHeadWnd(const QString&, bool)));
//connect(_chatViewPanel, SIGNAL(sgForwardMessage(const QString&)), _pGroupManager, SLOT(onForfardMessage(const QString&)));
connect(_titleBar, SIGNAL(sgSetAutoLogin(bool)), this, SLOT(setAutoLogin(bool)));
connect(_titleBar, SIGNAL(sgUpdateHotKey()), this, SLOT(onUpdateHotKey()));
connect(_titleBar, SIGNAL(sgSaveSysConfig()), GlobalManager::instance(), SLOT(saveSysConfig()));
connect(_titleBar, SIGNAL(sgSaveSysConfig()), this, SLOT(onSaveSysConfig()));
connect(_titleBar, SIGNAL(msgSoundChanged()), _chatViewPanel, SLOT(onMsgSoundChanged()));
//
connect(_titleBar, SIGNAL(sgShowMessageRecordWnd(const QString&, const QString&)),
_chatViewPanel, SLOT(onShowSearchResult(const QString&, const QString&)));
connect(_titleBar, SIGNAL(sgShowFileRecordWnd(const QString&)),
_chatViewPanel, SLOT(onShowSearchFileWnd(const QString&)));
connect(_chatViewPanel, SIGNAL(sgWakeUpWindow()), this, SLOT(wakeUpWindow()));
connect(this, SIGNAL(sgAppActive()), _chatViewPanel, SLOT(onAppActive()));
connect(this, SIGNAL(sgAppActive()), _navigationPanel, SLOT(onAppActive()));
connect(_titleBar, SIGNAL(sgActiveWnd()), this, SLOT(wakeUpWindow()));
//
connect(_chatViewPanel, SIGNAL(sgUserSendMessage()),
this, SLOT(onUserSendMessage()));
connect(GlobalManager::instance(), SIGNAL(sgMousePressGlobalPos(QPoint)), _titleBar,
SLOT(onMousePressGolbalPos(QPoint)));
// show draft
connect(_chatViewPanel, SIGNAL(sgShowDraft(const QTalk::Entity::UID&, const QString&)),
_navigationPanel, SIGNAL(sgShowDraft(const QTalk::Entity::UID&, const QString&)));
// sgShowNotify
qRegisterMetaType<QTalk::StNotificationParam>("QTalk::StNotificationParam");
connect(_chatViewPanel, SIGNAL(sgShowNotify(const QTalk::StNotificationParam&)),
_pSysTrayIcon, SLOT(onShowNotify(const QTalk::StNotificationParam&)));
//
connect(this, SIGNAL(sgShowUpdateClientLabel(bool)), _titleBar, SLOT(onShowUpdateLabel(bool)));
connect(_pView, SIGNAL(sgShowUpdateClientLabel(bool)), _titleBar, SLOT(onShowUpdateLabel(bool)));
connect(_titleBar, SIGNAL(sgDoUpdateClient()), this, SLOT(onShowCheckUpdateWnd()));
// 自动回复
connect(_titleBar, SIGNAL(sgAutoReply(bool)), _chatViewPanel, SLOT(setAutoReplyFlag(bool)));
// 操作日志
connect(_titleBar, SIGNAL(sgOperator(const QString&)), this, SLOT(addOperatorLog(const QString&)));
connect(_chatViewPanel, SIGNAL(sgOperator(const QString&)), this, SLOT(addOperatorLog(const QString&)));
connect(_navigationPanel, SIGNAL(sgOperator(const QString&)), this, SLOT(addOperatorLog(const QString&)));
connect(_pCardManager, SIGNAL(sgOperator(const QString&)), this, SLOT(addOperatorLog(const QString&)));
connect(_pAddressBook, SIGNAL(sgOpeartor(const QString&)), this, SLOT(addOperatorLog(const QString&)));
connect(_pOfflineTimer, &QTimer::timeout, [this](){
// if(_pMessageManager)
{
_isOffline = true;
_pOfflineTimer->stop();
_logout_t = QDateTime::currentMSecsSinceEpoch();
QTalkMsgManager::sendOnlineState(_login_t, _logout_t, _ipv4Address.toStdString());
}
});
connect(_pLogTimer, &QTimer::timeout, this, &MainWindow::onHourTimer);
//
#ifdef TSCREEN
connect(_pOAManager, SIGNAL(sgShowThrowingScreenWnd()), this, SLOT(startTScreen()));
connect(_titleBar, SIGNAL(sgShowThrowingScreenWnd()), this, SLOT(startTScreen()));
#endif
}
//
void MainWindow::onHourTimer() {
#if !defined(_STARTALK) && !defined(_QCHAT)
if(_loginDate != QDate::currentDate())
{
//
_loginDate = QDate::currentDate();
QtConcurrent::run(&QTalkMsgManager::reportLogin);
}
#endif
// check update
if(AppSetting::instance().getNewVersion() <= PLAT.getClientNumVerison()) {
checkUpdater();
}
// report
if(_operators.empty())
return;
std::vector<QTalk::StActLog> operators(_operators);
QtConcurrent::run(&QTalkMsgManager::sendOperatorStatistics, _ipv4Address.toStdString(), operators);
_operators.clear();
}
#include <QLocalSocket>
void MainWindow::startTScreen() {
#ifdef _LINUX
return;
#endif
//
static const char * QUNAR_THROW_SCREEN = "QUNAR_THROW_SCREEN";
QLocalSocket localSocket;
localSocket.connectToServer(QUNAR_THROW_SCREEN);
if (localSocket.waitForConnected(2000)) {
localSocket.disconnectFromServer();
localSocket.close();
return;
}
//
QStringList arguments;
#if defined(_WINDOWS)
const QString& cmd = QString("%1/%2").arg(QApplication::applicationDirPath(), "TScreen/TScreen.exe");
arguments << QString("LOGIN_USER_NAME=").append(PLAT.getSelfUserId().data());
QProcess::startDetached(cmd, arguments);
#elif defined(_MACOS)
const QString& cmd = QString("%1/%2").arg(QApplication::applicationDirPath(), "TScreen");
chmod(cmd.toStdString().data(), S_IRWXU);
arguments << QString("LOGIN_USER_NAME=").append(PLAT.getSelfName().data());
QProcess::startDetached(cmd, arguments);
#endif
}
/**
*
* @param autoFlag
*/
void MainWindow::setAutoLogin(bool autoFlag)
{
_pLoginPlug->setAutoLoginFlag(autoFlag);
}
/**
* @函数名 initSystemTray
* @功能描述 初始化系统托盘
* @参数
* @author cc
* @date 2018/11/09
*/
void MainWindow::initSystemTray()
{
_pSysTrayIcon = new SystemTray(this);
#ifdef _MACOS
connect(_pFeedBackLog, &QAction::triggered, _pSysTrayIcon, &SystemTray::onSendLog);
#endif
}
/**
* @函数名
* @功能描述
* @参数
* @author cc
* @date 2018/11/11
*/
void MainWindow::initGroupManager()
{
QObject* plugin = GlobalManager::instance()->getPluginInstanceQt("UIGroupManager");
if (plugin)
{
_pGroupManagerPlug = qobject_cast<IUIGroupManagerPlug *>(plugin);
if (_pGroupManagerPlug)
{
_pGroupManagerPlug->init();
_pGroupManager = _pGroupManagerPlug->widget();
}
}
assert(_pGroupManagerPlug);
assert(_pGroupManager);
}
void MainWindow::InitLogin(bool _enable, const QString& loginMsg)
{
QObject* plugin = GlobalManager::instance()->getPluginInstanceQt("UILoginPlug");
if (plugin)
{
_pLoginPlug = qobject_cast<IUILoginPlug *>(plugin);
if (_pLoginPlug)
{
_pLoginPlug->init();
_pLoginPlug->enableAutoLogin(_enable);
_pLoginPlug->initConf();
if(!loginMsg.isEmpty())
_pLoginPlug->setLoginMessage(loginMsg);
_logindlg = (QDialog *)_pLoginPlug->widget();
}
if (_logindlg)
{
GlobalManager::instance()->setStyleSheetForPlugin("UILoginPlug");
connect(_logindlg, SIGNAL(sgSynDataSuccess()), this, SLOT(openMainWindow()));
connect(_logindlg, SIGNAL(systemQuitSignal()), this, SLOT(systemQuit()), Qt::QueuedConnection);
_logindlg->show();
}
}
}
// 登陆成功 打开数据库同步服务器数据
void MainWindow::LoginResult(bool result)
{
if (result)
{
_timr->start();
}
}
void MainWindow::OnLoginSuccess(const std::string& strSessionId)
{
emit LoginSuccess(true);
}
void MainWindow::openMainWindow()
{
if (_initUi)
{
_isOffline = false;
_login_t = QDateTime::currentMSecsSinceEpoch();
_pOfflineTimer = new QTimer(this);
_pLogTimer = new QTimer(this);
_pOfflineTimer->setInterval(1000 * 60 * 60);
_pLogTimer->setInterval(1000 * 60 * 60);
_pLogTimer->start();
//
_pLocalServer = new LocalServer;
_pLocalServer->runServer(QApplication::applicationName());
//
_initUi = false;
init();
initLayouts();
connectPlugs();
_chatViewPanel->setFocus();
//
_navigationPlugin->updateReadCount();
// setwindow states
QString configPath = QString("%1/mainWnd").arg(PLAT.getConfigPath().data());
//
_pConfigLoader = new QTalk::ConfigLoader(configPath.toLocal8Bit());
if(_pConfigLoader->reload())
{
int wndstate = _pConfigLoader->getInteger(WIN_STATE);
int wndWidth = _pConfigLoader->getInteger(WIN_WIDTH);
int wndHeight = _pConfigLoader->getInteger(WIN_HEIGHT);
int wndX = _pConfigLoader->getInteger(WIN_X);
int wndY = _pConfigLoader->getInteger(WIN_Y);
if(wndWidth <= 0 || wndHeight <= 0)
{
QDesktopWidget *deskTop = QApplication::desktop();
int curMonitor = deskTop->screenNumber(_logindlg);
QRect deskRect = deskTop->screenGeometry(curMonitor);
wndWidth = deskRect.height();
wndHeight = (int)(deskRect.height() * 0.75);
wndX = (deskRect.width() - wndWidth) / 2 + deskRect.x();
wndY = (deskRect.height() - wndHeight) / 2 + deskRect.y();
//
_pConfigLoader->setInteger(WIN_WIDTH, wndWidth);
_pConfigLoader->setInteger(WIN_HEIGHT, wndHeight);
_pConfigLoader->setInteger(WIN_X, wndX);
_pConfigLoader->setInteger(WIN_Y, wndY);
_pConfigLoader->saveConfig();
}
setGeometry(wndX, wndY, wndWidth, wndHeight);
switch (wndstate)
{
case WND_MAXSIZE:
//showMaximized();
//break;
case WND_NORMAL:
default:
{
showNormal();
// 判断是否超出屏幕范围
adjustWndRect();
break;
}
}
}
UICom::getInstance()->setAcltiveMainWnd(this);
// 注册快捷键
_pScreentShot = new QHotkey(this);
_pWakeWnd = new QHotkey(this);
onUpdateHotKey();
connect(_pScreentShot, &QHotkey::activated, this, &MainWindow::onScreentShot);
connect(_pWakeWnd, &QHotkey::activated, this, &MainWindow::wakeUpWindow);
connect(_pLocalServer, &LocalServer::sgWakeupWindow, this, &MainWindow::wakeUpWindow);
//
if (_logindlg)
{
_logindlg->setVisible(false);
_pLoginPlug->saveHeadPath();
}
std::function<int(STLazyQueue<bool > *)> func
= [this](STLazyQueue<bool > *queue)->int
{
int count = 0;
while (!queue->empty()) {
queue->pop();
count++;
}
emit systemShortCut();
return count;
};
_pScreentShotQueue = new STLazyQueue<bool >(300, func);
//
_noOperatorThread = new NoOperationThread;
connect(this, &MainWindow::sgResetOperator,
_noOperatorThread, &NoOperationThread::resetUnOperatorTime,
Qt::QueuedConnection);
connect(_noOperatorThread, SIGNAL(sgUserLeave(bool)), _chatViewPanel, SLOT(setAutoReplyFlag(bool)));
connect(_noOperatorThread, SIGNAL(sgUserLeave(bool)), this, SLOT(setUserStatus(bool)));
connect(_titleBar, SIGNAL(sgAutoReply(bool)), _noOperatorThread, SLOT(setAutoReplyFlag(bool)));
//
#ifdef _MACOS
QMenu *wndMenu = _pWindowMenuBar->addMenu(tr("窗口"));
auto* minSize = new QAction(tr("最小化"), wndMenu);
auto* maxSize = new QAction(tr("缩放"), wndMenu);
auto* showWnd = new QAction(tr("显示面板"), wndMenu);
wndMenu->addAction(minSize);
wndMenu->addAction(maxSize);
wndMenu->addSeparator();
wndMenu->addAction(showWnd);
QMenu *systemMenu = _pWindowMenuBar->addMenu(tr("系统"));
auto* setting = new QAction(tr("系统设置"), wndMenu);
auto* about = new QAction(tr("关于"), wndMenu);
systemMenu->addAction(setting);
systemMenu->addAction(about);
connect(minSize, &QAction::triggered, [this](){
MacApp::showMinWnd(this);
});
connect(maxSize, &QAction::triggered, [this](){
if(this->isMaximized())
this->showNormal();
else
this->showMaximized();
});
connect(showWnd, &QAction::triggered, [this](){
this->wakeUpWindow();
});
connect(setting, SIGNAL(triggered()), _titleBar, SLOT(onShowSystemWnd()));
connect(about, SIGNAL(triggered()), _titleBar, SLOT(onShowAboutWnd()));
#endif
//
#if !defined(_STARTALK) && !defined(_QCHAT)
_loginDate = QDate::currentDate();
QtConcurrent::run(&QTalkMsgManager::reportLogin);
#endif
//
dealDumpFile();
checkUpdater();
}
}
/**
* @函数名
* @功能描述
* @参数
* @author cc
* @date 2018/12/14
*/
void MainWindow::onCurFunChanged(int index)
{
//
switch (index)
{
case 0:
bodyLay->setCurrentWidget(_bottomSplt);
break;
case 1:
bodyLay->setCurrentWidget(_pAddressBook);
break;
case 2:
bodyLay->setCurrentWidget(_pOAManager);
break;
default:break;
}
}
//
void MainWindow::onAppActive()
{
emit sgResetOperator();
#ifdef Q_OS_MAC
MacApp::resetWindow(this);
#endif
if(_initUi)
{
}
else
{
if(_isOffline)
{
_isOffline = false;
_login_t = QDateTime::currentMSecsSinceEpoch();
}
else
{
if(_pOfflineTimer)
_pOfflineTimer->stop();
}
_pSysTrayIcon->onWndActived();
#ifdef _MACOS
if(!this->isVisible())
MacApp::wakeUpWnd(this);
#endif
emit sgAppActive();
setVisible(true);
raise();
}
}
void MainWindow::initPictureBrowser()
{
QObject* plugin = GlobalManager::instance()->getPluginInstanceQt("UIPictureBrowser");
if (plugin)
{
_pPictureBrowserPlug = qobject_cast<IUIPictureBroswerPlug *>(plugin);
if (_pPictureBrowserPlug)
{
_pPictureBrowserPlug->init();
_pPictureBrowser = _pPictureBrowserPlug->widget();
}
}
assert(_pPictureBrowserPlug);
assert(_pPictureBrowser);
}
/**
* @函数名
* @功能描述
* @参数
* @author cc
* @date 2018/12/15
*/
void MainWindow::initAddressBook()
{
QObject* plugin = GlobalManager::instance()->getPluginInstanceQt("UIAddressBook");
if (plugin)
{
_pAddressBookPlug = qobject_cast<IUIAddressBookPlug*>(plugin);
if (_pAddressBookPlug)
{
_pAddressBookPlug->init();
_pAddressBook = _pAddressBookPlug->widget();
}
}
assert(_pAddressBookPlug);
assert(_pAddressBook);
}
/**
* @函数名
* @功能描述
* @参数
* @author cc
* @date 2018/12/15
*/
void MainWindow::initOAManager()
{
QObject* plugin = GlobalManager::instance()->getPluginInstanceQt("UIOAManager");
if (plugin)
{
_pOAManagerPlug = qobject_cast<IUIOAManagerPlug*>(plugin);
if (_pOAManagerPlug)
{
_pOAManagerPlug->init();
_pOAManager = _pOAManagerPlug->widget();
}
}
assert(_pOAManagerPlug);
assert(_pOAManager);
}
/**
* @函数名
* @功能描述
* @参数
* @author cc
* @date 2018/12/15
*/
void MainWindow::onAppDeactivate()
{
if(!_isOffline && _pOfflineTimer)
{
_pOfflineTimer->start();
}
emit appDeactivated();
}
void MainWindow::saveWndState()
{
int wndstate = WND_NORMAL;
if(windowState() == Qt::WindowMaximized)
{
wndstate = WND_MAXSIZE;
}
QRect geo = this->normalGeometry();
if(_pConfigLoader)
{
_pConfigLoader->setInteger(WIN_STATE, wndstate);
_pConfigLoader->setInteger(WIN_WIDTH, geo.width());
_pConfigLoader->setInteger(WIN_HEIGHT, geo.height());
_pConfigLoader->setInteger(WIN_X, geo.x());
_pConfigLoader->setInteger(WIN_Y, geo.y());
_pConfigLoader->saveConfig();
}
}
/**
* 系统退出
*/
void MainWindow::systemQuit()
{
_sys_run = false;
//
QLocalServer::removeServer(PLAT.getSelfXmppId().data());
_logout_t = QDateTime::currentMSecsSinceEpoch();
saveWndState();
QApplication::exit(0);
}
/**
*
*/
void MainWindow::sendHeartBeat()
{
QtConcurrent::run(&QTalkMsgManager::sendHearBeat);
}
// 多屏处理
void MainWindow::adjustWndRect() {
QRect thisGeo = this->geometry();
QDesktopWidget *deskTop = QApplication::desktop();
int curMonitor = deskTop->screenNumber(this);
QRect deskRect = deskTop->screenGeometry(curMonitor);
if(!deskRect.contains(thisGeo, true))
{
auto wndWidth = deskRect.height();
auto wndHeight = (int)(deskRect.height() * 0.75);
auto wndX = (deskRect.width() - wndWidth) / 2 + deskRect.x();
auto wndY = (deskRect.height() - wndHeight) / 2 + deskRect.y();
setGeometry(wndX, wndY, wndWidth, wndHeight);
}
}
/**
*
*/
void MainWindow::onUpdateHotKey()
{
std::string screentHot = AppSetting::instance().getScreenshotHotKey();
std::string wakeWnd = AppSetting::instance().getWakeWndHotKey();
bool isok = _pScreentShot->setShortcut(QKeySequence::fromString(screentHot.data(), QKeySequence::NativeText), true);
isok = _pWakeWnd->setShortcut(QKeySequence::fromString(wakeWnd.data(), QKeySequence::NativeText), true);
}
void MainWindow::onScreentShot()
{
_pScreentShotQueue->push(true);
}
void MainWindow::hideEvent(QHideEvent *e) {
if(Qt::ApplicationActive == QApplication::applicationState())
onAppDeactivate();
QWidget::hideEvent(e);
}
void MainWindow::keyPressEvent(QKeyEvent *e)
{
if (e->key() == Qt::Key_Escape || e->key() == Qt::Key_Space)
{
e->accept();
}
#ifdef _MACOS
if (e->modifiers() == Qt::ControlModifier)
{
if(e->key() == Qt::Key_W)
this->setVisible(false);
else if(e->key() == Qt::Key_M)
this->showMinimized();
else if(e->key() == Qt::Key_Q)
{
// int ret =
// if(ret == QtMessageBox::EM_BUTTON_YES)
// {
// exit(0);
// }
// e->accept();
// return;
}
}
#endif
UShadowDialog::keyPressEvent(e);
}
QWidget * MainWindow::getActiveWnd() {
QWidget* wakeUpWgt = nullptr;
if(_initUi)
wakeUpWgt = _logindlg;
else
wakeUpWgt = this;
return wakeUpWgt;
}
void MainWindow::wakeUpWindow()
{
QWidget* wakeUpWgt = getActiveWnd();
if (!wakeUpWgt)
{
qWarning() << "no active windows";
return;
}
if(wakeUpWgt->isMinimized())
wakeUpWgt->setWindowState((wakeUpWgt->windowState() & ~Qt::WindowMinimized) | Qt::WindowActive);
wakeUpWgt->setVisible(true);
QApplication::setActiveWindow(wakeUpWgt);
wakeUpWgt->raise();
#ifdef Q_OS_WIN
HWND hForgroundWnd = GetForegroundWindow();
DWORD dwForeID = ::GetWindowThreadProcessId(hForgroundWnd, NULL);
DWORD dwCurID = ::GetCurrentThreadId();
::AttachThreadInput(dwCurID, dwForeID, TRUE);
::SetForegroundWindow((HWND)winId());
::AttachThreadInput(dwCurID, dwForeID, FALSE);
#endif // Q_OS_WIN
}
/**
*
* @param desc
*/
void MainWindow::addOperatorLog(const QString &desc)
{
QTalk::StActLog log;
log.desc = desc.toStdString();
log.operatorTime = QDateTime::currentMSecsSinceEpoch();
_operators.push_back(log);
}
///**
// *
// */
//void MainWindow::onShockWnd()
//{
// if(!this->isMaximized() && !this->isFullScreen())
// {
// QRect now = this->geometry();
// auto* animation = new QPropertyAnimation(this, "pos");
// animation->setDuration(500);
// animation->setStartValue(QPoint(now.x(), now.y() + 20));
// animation->setEndValue(QPoint(now.x(), now.y() - 20));
// animation->setEasingCurve(QEasingCurve::InOutBounce);
// connect(animation, &QPropertyAnimation::finished, [this, now](){
// setGeometry(now);
// });
// animation->start(QAbstractAnimation::DeleteWhenStopped);
// }
//}
/**
*
*/
void MainWindow::onSaveSysConfig()
{
if(_noOperatorThread)
_noOperatorThread->setLeaveMinute();
//
GlobalManager::instance()->saveSysConfig();
}
void MainWindow::setUserStatus(bool isAway)
{
QTalkMsgManager::chanegUserStatus(isAway ? "away" : "online");
}
void MainWindow::onUserSendMessage()
{
_noOperatorThread->resetUnOperatorTime();
QTalkMsgManager::chanegUserStatus("online");
}
void MainWindow::checkUpdater() {
//#ifndef QT_DEBUG
auto version = GlobalManager::instance()->_updater_version;
QtConcurrent::run(&QTalkMsgManager::checkUpdater, version);
//#endif
}
//
#include <QDesktopServices>
void MainWindow::onCheckUpdater(bool hasUpdate, const QString& link, bool force) {
if(hasUpdate) {
#ifdef Q_OS_LINUX
if(!PLAT.isMainThread()) {
emit sgCheckUpdate(hasUpdate, link, force);
return;
}
if (hasUpdate) {
QtMessageBox::information(this, tr("升级提醒"),
tr("主程序有更新,麻烦您及时到官网下载最新版本"));
return;
}
#else
emit sgShowUpdateClientLabel(true);
if(force) {
_pView->showWnd();
}
#endif
}
}
#ifdef Q_OS_MAC
void MainWindow::onShowMinWnd() {
MacApp::showMinWnd(this);
}
#endif
void MainWindow::changeEvent(QEvent *event) {
switch (event->type()) {
case QEvent::WindowStateChange :
{
auto sts = this->windowState();
if (sts == Qt::WindowNoState) {
}
break;
}
default:
break;
}
UShadowDialog::changeEvent(event);
}
void MainWindow::onGetHistoryError() {
emit sgRestartWithMessage(tr("获取历史记录失败, 请重新登录!"));
}
//
void MainWindow::reLoginWithErr(const std::string &err) {
emit sgRestartWithMessage(err.data());
}
void MainWindow::systemQuitByEvt() {
emit sgSystemQuit();
}
//
void MainWindow::restartWithMessage(const QString &msg) {
QString program = QApplication::applicationFilePath();
QStringList arguments;
arguments << "AUTO_LOGIN=OFF"
<< QString("MSG=%1").arg(msg);
QProcess::startDetached(program, arguments);
QApplication::exit(0);
}
void delDmpFun(const QString& path, const std::string& ip)
{
QDir dir(path);
QFileInfoList infoList = dir.entryInfoList(QDir::Dirs | QDir::Files | QDir::NoDotAndDotDot);
for (const auto& tmpInfo : infoList)
{
if(tmpInfo.isSymLink()) continue;
if (tmpInfo.isFile())
{
auto now = QDateTime::currentMSecsSinceEpoch();
#if QT_VERSION >= QT_VERSION_CHECK(5, 10, 0)
auto birth = tmpInfo.birthTime().toMSecsSinceEpoch();
#else
auto birth = tmpInfo.lastModified().toMSecsSinceEpoch();
#endif
if (tmpInfo.suffix().toLower() == "dmp")
{
if(tmpInfo.size() > 0 && tmpInfo.size() <= 50 * 1024 * 1024 && now - birth < 1000 * 60 * 60 * 24 * 7)
{
std::string dumpFilePath = std::string(tmpInfo.absoluteFilePath().toLocal8Bit());
QTalkMsgManager::reportDump(ip, dir.dirName().toStdString(), dumpFilePath, birth);
}
QFile::remove(tmpInfo.absoluteFilePath());
}
else if(now - birth > 1000 * 60 * 60 * 24)
QFile::remove(tmpInfo.absoluteFilePath());
}
else if(tmpInfo.isDir())
{
auto infoPath = tmpInfo.absoluteFilePath();
delDmpFun(infoPath, ip);
if(QDir(infoPath).isEmpty())
dir.rmpath(infoPath);
}
}
}
////
//qint64 calculateFolderSize(const QString& folderPath)
//{
// qint64 size = 0;
//
// QDir dir(folderPath);
// QFileInfoList infoList = dir.entryInfoList(QDir::Dirs | QDir::Files | QDir::NoDotAndDotDot);
// for (const auto& tmpInfo : infoList)
// {
// if(tmpInfo.isSymLink()) continue;
//
// if (tmpInfo.isFile())
// {
// size += tmpInfo.size();
// }
// else if(tmpInfo.isDir())
// {
// auto infoPath = tmpInfo.absoluteFilePath();
// size += calculateFolderSize(infoPath);
// }
// }
//
// return size;
//}
void clearCache(const QString& folderPath)
{
QDir dir(folderPath);
QFileInfoList infoList = dir.entryInfoList(QDir::Dirs | QDir::Files | QDir::NoDotAndDotDot);
for (const auto& tmpInfo : infoList) {
if (tmpInfo.isSymLink()) continue;
auto now = QDateTime::currentMSecsSinceEpoch();
#if QT_VERSION >= QT_VERSION_CHECK(5, 10, 0)
auto birth = tmpInfo.birthTime().toMSecsSinceEpoch();
#else
auto birth = tmpInfo.lastModified().toMSecsSinceEpoch();
#endif
if(now - birth < 1000 * 60 * 60 * 24 * 2)
continue;
if (tmpInfo.isFile()) {
QFile::remove(tmpInfo.absoluteFilePath());
} else if (tmpInfo.isDir()) {
auto infoPath = tmpInfo.absoluteFilePath();
clearCache(infoPath);
}
}
}
//
void MainWindow::dealDumpFile()
{
QTimer::singleShot(30 * 1000, [this](){
QtConcurrent::run([this](){
// deal dump
QDateTime curDateTime = QDateTime::currentDateTime();
auto appdata = QStandardPaths::writableLocation(QStandardPaths::AppDataLocation).toLocal8Bit();
QString logDirPath = QString("%1/logs/").arg(appdata.data());
delDmpFun(logDirPath, _ipv4Address.toStdString());
// clear cache
auto userDir = PLAT.getAppdataRoamingUserPath();
clearCache((userDir + "/video").data());
clearCache((userDir + "/voice").data());
clearCache((userDir + "/temp").data());
clearCache((userDir + "/image/temp").data());
clearCache((userDir + "/image/source").data());
clearCache((appdata + "/HotPic").data());
// delete old app
QString oldApp = QString("%1/apps").arg(appdata.data());
if(QFile::exists(oldApp))
{
QDir dir;
dir.setPath(oldApp);
qInfo() << "delete old appps" << dir.removeRecursively();
}
});
});
}
//
void MainWindow::onScreenRemoved(QScreen *screen)
{
Q_UNUSED(screen)
{
QTimer::singleShot(500, [this]() {
auto screenGeometry = QApplication::primaryScreen()->availableGeometry();
//if(!screenGeometry.contains(this->geometry()))
{
auto geometry = this->geometry();
geometry.setWidth(qMin(screenGeometry.width() -100, geometry.width()) );
geometry.setHeight(qMin(screenGeometry.height() -100, geometry.height()));
geometry.setX((screenGeometry.width() - geometry.width()) / 2);
geometry.setY((screenGeometry.height() - geometry.height()) / 2);
qInfo() << geometry;
// this->setGeometry(geometry);
}
});
}
}
#include <QMetaObject>
bool MainWindow::event(QEvent *e) {
return QWidget::event(e);
}
void MainWindow::onShowCheckUpdateWnd() {
if(_pView) {
_pView->showWnd();
}
}
|
#ifndef DYNSYS_WRAPPERS_HPP_
#define DYNSYS_WRAPPERS_HPP_
// Macro for MatLab users that prefer external functions
template<typename T>
inline auto GetLength(const T& v) {
return v.length();
}
// Macro for MatLab users that prefer external functions
template<typename T>
inline auto GetDimension(const T& g) {
return g.length();
}
#endif // DYNSYS_WRAPPERS_HPP_
|
#include "MinValNode.h"
#include "Base/ImGuiShapes.h"
#include "Generators/CPUNodeEditor/CPUNodeEditor.h"
#include <iostream>
#include <mutex>
#include "Base/ImGuiCurveEditor.h"
NodeOutput MinValNode::Evaluate(NodeInputParam input, NodeEditorPin* pin)
{
float x = inputf;
if (inputPins[0]->IsLinked())
x = inputPins[0]->other->Evaluate(input).value;
float y = thresholdf;
if (inputPins[1]->IsLinked())
y = inputPins[1]->other->Evaluate(input).value;
if(x > thresholdf)
return NodeOutput({ outputr });
else
return NodeOutput({ outputf });
}
void MinValNode::Load(nlohmann::json data)
{
inputf = data["inputf"];
outputf = data["outputf"];
outputr = data["outputr"];
thresholdf = data["thresholdf"];
}
nlohmann::json MinValNode::Save()
{
nlohmann::json data;
data["type"] = MeshNodeEditor::MeshNodeType::MinVal;
data["inputf"] = inputf;
data["outputf"] = outputf;
data["outputr"] = outputr;
data["thresholdf"] = thresholdf;
return data;
}
void MinValNode::OnRender()
{
DrawHeader("Min Val");
inputPins[0]->Render();
if (inputPins[0]->IsLinked())
ImGui::Text("Input");
else
{
ImGui::PushItemWidth(100);
ImGui::DragFloat(("##" + std::to_string(inputPins[0]->id)).c_str(), &inputf, 0.01f);
ImGui::PopItemWidth();
}
ImGui::SameLine();
ImGui::Text("Output");
outputPins[0]->Render();
inputPins[1]->Render();
if (inputPins[1]->IsLinked())
ImGui::Text("Threshold");
else
{
ImGui::PushItemWidth(100);
ImGui::DragFloat(("##" + std::to_string(inputPins[1]->id)).c_str(), &thresholdf, 0.01f);
ImGui::PopItemWidth();
}
ImGui::PushItemWidth(100);
ImGui::DragFloat(("##" + std::to_string(inputPins[2]->id)).c_str(), &outputf, 0.01f);
ImGui::PopItemWidth();
ImGui::PushItemWidth(100);
ImGui::DragFloat(("##" + std::to_string(inputPins[3]->id)).c_str(), &outputr, 0.01f);
ImGui::PopItemWidth();
}
MinValNode::MinValNode()
{
inputPins.push_back(new NodeEditorPin());
inputPins.push_back(new NodeEditorPin());
inputPins.push_back(new NodeEditorPin()); // FOR FUTURE
inputPins.push_back(new NodeEditorPin()); // FOR FUTURE
outputPins.push_back(new NodeEditorPin(NodeEditorPinType::Output));
headerColor = ImColor(OP_NODE_COLOR);
outputf = inputf = outputr = thresholdf = 0.0f;
thresholdf = 0.5f;
}
|
#include<iostream>
using namespace std;
string reverseString(string s){
string rev_s;
for(int i = s.size()-1;i>=0;--i){
rev_s.push_back(s[i]);
}
return rev_s;
}
bool isPailndrome(string s){
if(s==reverseString(s)){
return true;
}
else return false;
}
bool isPailndrome_better(string s){
for(int i=0;i<s.size();i++){
if(s[i]!=s[s.size()-i-1]){
return false;
}
}
return true;
}
int main(){
string s;
cin>>s;
bool ans = isPailndrome_better(s);
cout<<ans<<endl;
return 0;
}
|
#include <napi/napi.h>
#include <napi/napi_pointer.h>
#include <NativeCamera.h>
#include "NativeVideo.h"
#include "NativeCameraImpl.h"
#include <Babylon/JsRuntime.h>
#include <Babylon/Graphics/DeviceContext.h>
#include <Babylon/Graphics/Texture.h>
#include <vector>
#include <algorithm>
namespace Babylon
{
namespace Plugins
{
class NativeCamera : public Napi::ObjectWrap<NativeCamera>
{
static constexpr auto JS_NAVIGATOR_NAME = "navigator";
static constexpr auto JS_CLASS_NAME = "_NativeCamera";
static constexpr auto JS_CONSTRUCTOR_NAME = "Camera";
public:
static void Initialize(Napi::Env env)
{
Napi::HandleScope scope{ env };
Napi::Function func = NativeCamera::DefineClass(
env,
JS_CLASS_NAME,
{
NativeCamera::InstanceMethod("createVideo", &NativeCamera::CreateVideo),
NativeCamera::InstanceMethod("updateVideoTexture", &NativeCamera::UpdateVideoTexture),
});
JsRuntime::NativeObject::GetFromJavaScript(env).Set(JS_CONSTRUCTOR_NAME, func);
// create or get global navigator object
Napi::Object global = env.Global();
Napi::Object navigator;
if (global.Has(JS_NAVIGATOR_NAME))
{
navigator = global.Get(JS_NAVIGATOR_NAME).As<Napi::Object>();
}
else
{
navigator = Napi::Object::New(env);
global.Set(JS_NAVIGATOR_NAME, navigator);
}
// append media devices to navigator
Napi::Object mediaDevices = Napi::Object::New(env);
mediaDevices.Set("getUserMedia", Napi::Function::New(env, [](const Napi::CallbackInfo& info) {
auto env = info.Env();
auto deferred{Napi::Promise::Deferred::New(env)};
auto promise{deferred.Promise()};
auto& jsRuntime{JsRuntime::GetFromJavaScript(env)};
jsRuntime.Dispatch([deferred{std::move(deferred)}](Napi::Env env) {
deferred.Resolve(env.Null());
});
return static_cast<Napi::Value>(promise);
}, "getUserMedia"));
navigator.Set("mediaDevices", mediaDevices);
}
NativeCamera(const Napi::CallbackInfo& info)
: Napi::ObjectWrap<NativeCamera>{ info }
{
}
private:
Napi::Value CreateVideo(const Napi::CallbackInfo& info)
{
auto constraints = info[0].As<Napi::Object>();
uint32_t maxWidth{256}, maxHeight{256};
std::string facingMode{};
auto maxWidthValue{constraints.Get("maxWidth")};
auto maxHeightValue{constraints.Get("maxHeight")};
auto facingModeValue{constraints.Get("facingMode")};
if (maxWidthValue.IsNumber())
{
maxWidth = maxWidthValue.As<Napi::Number>().Uint32Value();
}
if (maxHeightValue.IsNumber())
{
maxHeight = maxHeightValue.As<Napi::Number>().Uint32Value();
}
if (facingModeValue.IsString())
{
facingMode = facingModeValue.As<Napi::String>().Utf8Value();
}
return NativeVideo::New(info, maxWidth, maxHeight, facingMode == "user");
}
void UpdateVideoTexture(const Napi::CallbackInfo& info)
{
const auto& texture = *info[0].As<Napi::Pointer<Graphics::TextureData>>().Get();
auto videoObject = NativeVideo::Unwrap(info[1].As<Napi::Object>());
videoObject->UpdateTexture(texture.Handle);
}
};
Camera::Camera(std::shared_ptr<Impl> impl)
: m_impl{std::move(impl)}
{
}
Camera Camera::Initialize(Napi::Env env, bool overrideCameraTexture)
{
auto impl{std::make_shared<Impl>(env, overrideCameraTexture)};
Babylon::Plugins::NativeVideo::Initialize(env, impl);
Babylon::Plugins::NativeCamera::Initialize(env);
return {impl};
}
void Camera::SetTextureOverride(void* texturePtr)
{
m_impl->SetTextureOverride(texturePtr);
}
}
}
|
//---------------------------------------------------------------------
//
// File: TCueEffect.cpp
//
// Author: Mike Ost
//
// Date: 10.09.98
//
// Desc:
//
// Effects are data modifiers that have a sense of time. They have
// a start time and a duration within the cue they are contained by.
// As a cue's data is rendered an effect is allowed to work on a
// cue's output. Each of the cue editing tools in ultraDV ---
// transitions, stage tools, opacity, etc. --- is implemented as
// an effect. They each have a cue as source data and a sense of
// time within the cue.
//
// The base class supports key frames, which give effects a point
// in time to make changes in an evolving effect. An effect also
// has a Settings method which gives it an opportunity to bring up
// an edit dialog box.
//
//---------------------------------------------------------------------
#include "BuildApp.h"
#include <support/Debug.h> // for ASSERT()
#include "TCueEffect.h"
using namespace std;
// Constants
// Names used in a message
const char* TCueEffect::kStartLabel = "startTime";
const char* TCueEffect::kDurationLabel = "duration";
const char* TCueEffect::kKeyFrameCountLabel = "keyFrameCount";
const char* TCueEffect::kKeyFrameTimeLabel = "keyFrameTime";
const char* TCueEffect::kKeyFrameStateLabel = "keyFrameState";
//---------------------------------------------------------------------
// Constructor/destructor
//---------------------------------------------------------------------
//
TCueEffect::TCueEffect() :
m_startTime(0),
m_duration(0)
{
}
TCueEffect::~TCueEffect()
{
}
TCueEffect::TCueEffect(BMessage* msg) :
BArchivable(msg)
{
status_t err;
err = msg->FindInt32(kStartLabel, (int32 *)&m_startTime);
if (err != B_OK) {
ASSERT(false);
return;
}
err = msg->FindInt32(kDurationLabel, (int32 *)&m_duration);
if (err != B_OK) {
ASSERT(false);
return;
}
// Read in the keyframe list
uint32 size;
err = msg->FindInt32(kKeyFrameCountLabel, (int32 *)&size);
if (err != B_OK) {
ASSERT(false);
return;
}
for (int i = 0; i < size; i++) {
// Read in the time field
TKeyFrame kf;
err = msg->FindInt32(kKeyFrameTimeLabel, &kf.m_time);
if (err != B_OK)
break;
// Read in, and instantiate, the state field
BMessage stateMsg;
err = msg->FindMessage(kKeyFrameStateLabel, i, &stateMsg);
if (err != B_OK) {
ASSERT(false);
break;
}
BArchivable* a = instantiate_object(&stateMsg);
if (a == 0) {
ASSERT(a);
break;
}
kf.m_state = dynamic_cast<TEffectState*>(a);
if (kf.m_state == 0) {
ASSERT(kf.m_state);
break;
}
// Add it to our list
m_keyFrames.push_back(kf);
}
}
//---------------------------------------------------------------------
// BArchivable overrides (file support)
//---------------------------------------------------------------------
//
//
BArchivable* TCueEffect::Instantiate(BMessage* data)
{
// NOTE: this is an error. We can't instantiate this class
// since it is an abstract base class.
ASSERT(false);
return 0;
}
status_t TCueEffect::Archive(BMessage* data, bool deep) const
{
// Start by calling inherited archive
status_t err = BArchivable::Archive(data, deep);
if (err != B_OK)
return err;
// NOTE: we don't instantiate this class --- it's an ABC ---
// so we don't add the class name data
// And local data
err = data->AddInt32(kStartLabel, m_startTime);
if (err != B_OK)
return err;
err = data->AddInt32(kDurationLabel, m_duration);
if (err != B_OK)
return err;
// Archive out the keyframe list
err = data->AddInt32(kKeyFrameCountLabel, m_keyFrames.size());
if (err != B_OK)
return err;
for (TKeyFrameIterator k = m_keyFrames.begin(); k != m_keyFrames.end();
k++) {
// err = data->AddFloat(kKeyFrameTimeLabel, k->m_time); DOESN'T STL SUPPORT THIS?
err = data->AddFloat(kKeyFrameTimeLabel, (*k).m_time);
if (err != B_OK)
break;
// Archive the state data
BMessage state;
// err = k->m_state->Archive(&state, deep); DOESN'T STL SUPPORT THIS?
err = (*k).m_state->Archive(&state, deep);
if (err != B_OK)
break;
err = data->AddMessage(kKeyFrameStateLabel, &state);
if (err != B_OK)
break;
}
return err;
}
//---------------------------------------------------------------------
// CanOverlap
//---------------------------------------------------------------------
//
//
bool TCueEffect::CanOverlap(const TCueEffect* effect) const
{
// Test for same class. They can't overlap by default.
if (class_name(this) == class_name(effect))
return false;
return true;
}
//---------------------------------------------------------------------
// IsSizeable
//---------------------------------------------------------------------
//
//
bool TCueEffect::IsSizeable(const TCueEffect* effect) const
{
return false;
}
//---------------------------------------------------------------------
// StartTime
//---------------------------------------------------------------------
//
//
void TCueEffect::StartTime(uint32 time)
{
m_startTime = time;
}
//---------------------------------------------------------------------
// Duration
//---------------------------------------------------------------------
//
//
void TCueEffect::Duration(uint32 time)
{
m_duration = time;
// Set up the defaults if they haven't already been
if (m_keyFrames.size() < 2) {
SetDefaultKeyFrames();
return;
}
// Set up the last entry to go to the new end of the effect
TKeyFrameIterator_vol last = LastKeyFrame();
// last->m_time = time;
(*last).m_time = time;
// check for key frames which must be removed
for (TKeyFrameIterator_vol later = m_keyFrames.begin();
later != last; later++) {
// Frames from this point on to the final one are now invalid
// if (later->m_time >= time) {
if ((*later).m_time >= time) {
m_keyFrames.erase(later, last);
break;
}
}
}
//---------------------------------------------------------------------
// MarkKeyFrame
//---------------------------------------------------------------------
//
//
void TCueEffect::SetDefaultKeyFrames()
{
// Set up the defaults
if (m_keyFrames.size() < 2) {
TKeyFrame kf;
m_keyFrames.push_front(kf);
m_keyFrames.push_back(kf);
// Set up the first
TKeyFrameIterator_vol itr = m_keyFrames.begin();
(*itr).m_time = 0;
(*itr).m_state = NewEffectState();
// and last
itr++;
(*itr).m_time = m_duration;
(*itr).m_state = NewEffectState();
return;
}
// Eliminate all key frames between the first and last
TKeyFrameIterator_vol second = m_keyFrames.begin();
second++;
TKeyFrameIterator_vol last = LastKeyFrame();
if (second != last)
m_keyFrames.erase(second, last);
}
//---------------------------------------------------------------------
// MarkKeyFrame
//---------------------------------------------------------------------
//
//
// ABH
//TCueEffect::TKeyFrameIterator TCueEffect::MarkKeyFrame(uint32 time)
TKeyFrameIterator TCueEffect::MarkKeyFrame(uint32 time)
{
// Convert from a global to a local time value
time -= m_startTime;
// Can't mark a key frame after the effect is through...
if (time > m_duration) {
ASSERT(false);
return TKeyFrameIterator();
}
// Find the key frame after or at 'time'
TKeyFrameIterator_vol before = m_keyFrames.begin();
TKeyFrameIterator_vol later = before;
for ( ; later != m_keyFrames.end(); later++) {
if ((*later).m_time >= time)
break;
before++;
}
// There is already a key frame at this time. Choose a different time
if ((*later).m_time == time) {
ASSERT(false);
return TKeyFrameIterator();
}
// Create a key frame here
TKeyFrameIterator_vol kf;
// ABH!
// kf = m_keyFrames.insert(later);
kf = later; // dirty hack to get a compile
// (*kf).m_time = time;
// (*kf).m_state = NewEffectState();
printf("TCueEffect::MarkKeyFrame - Needs to be implemented!\n");
// Interpolate a reasonable value
Interpolate(kf);
return kf;
}
//---------------------------------------------------------------------
// RemoveKeyFrame
//---------------------------------------------------------------------
//
//
// ABH
//void TCueEffect::RemoveKeyFrame(TCueEffect::TKeyFrameIterator kf)
void TCueEffect::RemoveKeyFrame(TKeyFrameIterator kf)
{
// Can't remove the first or last key frame
if (kf == m_keyFrames.begin() || kf == LastKeyFrame())
return;
TKeyFrameIterator_vol v = VolatileIterator(kf);
m_keyFrames.erase(v);
}
//---------------------------------------------------------------------
// MoveKeyFrame
//---------------------------------------------------------------------
//
//
// ABH
//void TCueEffect::MoveKeyFrame(TCueEffect::TKeyFrameIterator kf, uint32 newTime)
void TCueEffect::MoveKeyFrame(TKeyFrameIterator kf, uint32 newTime)
{
// Can't move the first or last key frame
if (kf == m_keyFrames.begin() || kf == LastKeyFrame())
return;
TKeyFrameIterator_vol v = VolatileIterator(kf);
// Set the key frame to a new time, converted from global to local
// v->m_time = newTime - m_startTime;
(*v).m_time = newTime - m_startTime;
m_keyFrames.sort();
}
//---------------------------------------------------------------------
// LastKeyFrame
//---------------------------------------------------------------------
//
//
// ABH
//TCueEffect::TKeyFrameIterator_vol TCueEffect::LastKeyFrame(void) const
TKeyFrameIterator_vol TCueEffect::LastKeyFrame(void) const
{
// force 'end()' to return a non-const iterator
TCueEffect* volatileMe = const_cast<TCueEffect*>(this);
TKeyFrameIterator_vol last = volatileMe->m_keyFrames.end();
last--;
return last;
}
//---------------------------------------------------------------------
// VolatileIterator
//---------------------------------------------------------------------
//
//
// ABH
//TCueEffect::TKeyFrameIterator_vol TCueEffect::VolatileIterator(
TKeyFrameIterator_vol TCueEffect::VolatileIterator(
// ABH
// TCueEffect::TKeyFrameIterator kf) const
TKeyFrameIterator kf) const
{
// TODO: isn't there a way to just cast one of these puppies?
// force 'begin()' to return a non-const iterator
TCueEffect* volatileMe = const_cast<TCueEffect*>(this);
TKeyFrameIterator_vol v = volatileMe->m_keyFrames.begin();
//for ( ; v != m_keyFrames.end(); v++)
//{
// if (v == kf)
// return v;
//}
// 'kf' couldn't be found
ASSERT(false);
return v;
}
//---------------------------------------------------------------------
// KeyFrameState
//---------------------------------------------------------------------
//
//
// ABH
//bool TCueEffect::KeyFrameState(TCueEffect::TKeyFrameIterator kf,
bool TCueEffect::KeyFrameState(TKeyFrameIterator kf,
const TEffectState* state) const
{
TKeyFrameIterator_vol v = VolatileIterator(kf);
// if (v->m_state)
// v->m_state->Assign(state);
if ((*v).m_state)
return (*v).m_state->Assign(state);
return false;
}
|
#ifndef COMMANDERROR_HPP
#define COMMANDERROR_HPP
#include <deque>
#include <stdexcept>
#include <string>
#include <memory>
#include "BotError.hpp"
#include "Command.hpp"
#include "Player.hpp"
namespace hlt {
class Command;
class BaseCommandError;
/** Type of command errors exposed to users. */
using CommandError = std::unique_ptr<BaseCommandError>;
/** The type of a command context. */
using ErrorContext = std::deque<std::reference_wrapper<const Command>>;
/** Error for when bot commands are logically invalid. */
class BaseCommandError : public BotError {
protected:
std::string buffer; /** The message buffer of the error. */
const ErrorContext _context; /**< The command context. */
public:
const Player::id_type player; /**< The player issuing the command. */
bool ignored{}; /**< If true, this error was ignored by the engine. */
/**
* Construct BaseCommandError from player.
* @param player The player.
* @param context The command context.
* @param ignored Whether this error was ignored by the engine.
*/
BaseCommandError(Player::id_type player, ErrorContext context, bool ignored) :
_context(std::move(context)), player(player), ignored(ignored) {}
/**
* Get the command that caused the error.
* @return The command.
*/
virtual const Command &command() const = 0;
/**
* Get the context commands of the error, i.e. the other commands that contributed to the issue.
* @return The list of context commands.
*/
virtual const ErrorContext &context() const { return _context; }
/**
* Get a message for the player log.
* @return The message.
*/
virtual std::string log_message() const = 0;
/**
* Get a message printed immediately before the context if there is any.
* @return The message.
*/
virtual std::string context_message() const {
return "Commands contributing to this error:";
}
/**
* Get the exception description.
* @return The exception description.
*/
const char *what() const noexcept override {
return buffer.c_str();
}
};
/** Error for when too many commands are issued to an entity. */
class ExcessiveCommandsError : public BaseCommandError {
private:
const Command &_command; /**< The command that caused the error. */
public:
const Entity::id_type entity; /**< The entity. */
/**
* Get the command that caused the error.
* @return The command.
*/
const Command &command() const override { return _command; }
/**
* Get a message printed immediately before the context if there is any.
* @return The message.
*/
std::string context_message() const override {
return "The other commands issued to this entity:";
}
/**
* Get a message for the player log.
* @return The message.
*/
std::string log_message() const override;
/**
* Construct ExcessiveCommandsError from player, entity, and commands.
* @param player The player.
* @param command The first faulty command.
* @param context The command context.
* @param entity The entity.
* @param ignored Whether this error was ignored by the engine.
*/
ExcessiveCommandsError(Player::id_type player, const Command &command, ErrorContext context,
Entity::id_type entity, bool ignored = false) :
BaseCommandError(player, std::move(context), ignored), _command(command), entity(entity) {
buffer = log_message();
}
};
/** Error for when too many spawn commands are attempted on one turn. */
class ExcessiveSpawnsError : public BaseCommandError {
private:
const Command &_command; /**< The command that caused the error. */
public:
/**
* Get the command that caused the error.
* @return The command.
*/
const Command &command() const override { return _command; }
/**
* Get a message printed immediately before the context if there is any.
* @return The message.
*/
std::string context_message() const override {
return "The other spawn commands issued on this turn:";
}
/**
* Get a message for the player log.
* @return The message.
*/
std::string log_message() const override;
/**
* Construct ExcessiveSpawnsError from player.
* @param player The player.
* @param command The first faulty command.
* @param context The command context.
* @param ignored Whether this error was ignored by the engine.
*/
ExcessiveSpawnsError(Player::id_type player, const Command &command,
ErrorContext context, bool ignored = false)
: BaseCommandError(player, std::move(context), ignored), _command(command) {
buffer = log_message();
}
};
/**
* Error for when a required entity is not found.
* @tparam Command The type of the command.
*/
template<class Command>
class EntityNotFoundError : public BaseCommandError {
private:
const Command &_command; /**< The command that caused the error. */
public:
/**
* Get the command that caused the error.
* @return The command.
*/
const Command &command() const override { return _command; }
/**
* Get a message for the player log.
* @return The message.
*/
std::string log_message() const override;
/**
* Construct EntityNotFoundError from player and command.
* @param player The player.
* @param command The command.
* @param ignored Whether this error was ignored by the engine.
*/
EntityNotFoundError(Player::id_type player, const Command &command, bool ignored = false) :
BaseCommandError(player, {}, ignored), _command(command) {
buffer = log_message();
}
};
/**
* Error for when entity energy is insufficient.
* @tparam Command The type of the command, or Player.
*/
template<class Command>
class InsufficientEnergyError : public BaseCommandError {
private:
const Command &_command; /**< The command that caused the error. */
public:
const energy_type available; /**< The available energy. */
const energy_type requested; /**< The requested energy. */
/**
* Get the command that caused the error.
* @return The command.
*/
const Command &command() const override { return _command; }
/**
* Get a message for the player log.
* @return The message.
*/
std::string log_message() const override;
/**
* Construct InsufficientEnergyError from player, command, available and requested energy.
* @param player The player.
* @param command The command.
* @param available The available energy.
* @param requested The requested energy.
* @param ignored Whether this error was ignored by the engine.
*/
InsufficientEnergyError(Player::id_type player, const Command &command,
energy_type available, energy_type requested, bool ignored = false) :
BaseCommandError(player, {}, ignored), _command(command), available(available), requested(requested) {
buffer = log_message();
}
};
/** Error for when player energy is insufficient. */
class PlayerInsufficientEnergyError : public BaseCommandError {
private:
const Command &_command; /**< The command that caused the error. */
public:
const energy_type available; /**< The available energy. */
const energy_type requested; /**< The requested energy. */
/**
* Get the command that caused the error.
* @return The command.
*/
const Command &command() const override { return _command; }
/**
* Get a message for the player log.
* @return The message.
*/
std::string log_message() const override;
/**
* Get a message printed immediately before the context if there is any.
* @return The message.
*/
std::string context_message() const override {
return "The other commands that used player energy on this turn:";
}
/**
* Construct PlayerInsufficientEnergyError from player and available and requested energy.
* @param player The player.
* @param command The first faulty command.
* @param context The command context.
* @param available The available energy.
* @param requested The requested energy.
* @param ignored Whether this error was ignored by the engine.
*/
PlayerInsufficientEnergyError(Player::id_type player, const Command &command, ErrorContext context,
energy_type available, energy_type requested, bool ignored = false) :
BaseCommandError(player, std::move(context), ignored), _command(command),
available(available), requested(requested) {
buffer = log_message();
}
};
/**
* Error for when a required cell is already owned.
* @tparam Command The type of the command.
*/
template<class Command>
class CellOwnedError : public BaseCommandError {
private:
const Command &_command; /**< The command that caused the error. */
public:
const Location cell; /**< The location of the cell. */
const Player::id_type owner; /**< The current owner of the cell. */
/**
* Get the command that caused the error.
* @return The command.
*/
const Command &command() const override { return _command; }
/**
* Get a message for the player log.
* @return The message.
*/
std::string log_message() const override;
/**
* Construct CellOwnedError from player, command, cell, and current owner.
* @param player The player.
* @param command The command.
* @param cell The cell.
* @param owner The current owner.
* @param ignored Whether this error was ignored by the engine.
*/
CellOwnedError(Player::id_type player, const Command &command, Location cell,
Player::id_type owner, bool ignored = false) :
BaseCommandError(player, {}, ignored), _command(command), cell(cell), owner(owner) {
buffer = log_message();
}
};
/**
* Error for when a player causes their own entities to collide.
* @tparam Command The type of the command.
*/
template<class Command>
class SelfCollisionError : public BaseCommandError {
private:
const Command &_command; /** The command that caused the error. */
public:
const Location cell; /**< The location of the collision. */
const std::vector<Entity::id_type> entities; /**< The entities that collided. */
/**
* Get the command that caused the error.
* @return The command.
*/
const Command &command() const override { return _command; }
/**
* Get a message for the player log.
* @return The message.
*/
std::string log_message() const override;
/**
* Get a message printed immediately before the context if there is any.
* @return The message.
*/
std::string context_message() const override {
return "Other commands that placed an entity on this cell:";
}
/**
* Construct SelfCollisionError from player, command, context, cell, and entities.
* @param player The player.
* @param command The command.
* @param context The context.
* @param cell The cell of the collision.
* @param entities The entities that collided.
* @param ignored Whether this error was ignored by the engine.
*/
SelfCollisionError(Player::id_type player, const Command &command, ErrorContext context, Location cell,
std::vector<Entity::id_type> entities, bool ignored = false) :
BaseCommandError(player, std::move(context), ignored), _command(command), cell(cell),
entities(std::move(entities)) {}
};
}
#endif // COMMANDERROR_HPP
|
/*
* Copyright (c) 2020, Andreas Kling <kling@serenityos.org>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. 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 <AK/FlyString.h>
#include <AK/Function.h>
#include <LibJS/Interpreter.h>
#include <LibJS/Runtime/Error.h>
#include <LibJS/Runtime/Function.h>
#include <LibWeb/Bindings/DocumentWrapper.h>
#include <LibWeb/Bindings/NavigatorObject.h>
#include <LibWeb/Bindings/WindowObject.h>
#include <LibWeb/DOM/Document.h>
#include <LibWeb/DOM/Window.h>
namespace Web {
namespace Bindings {
WindowObject::WindowObject(Window& impl)
: m_impl(impl)
{
put_native_property("document", document_getter, document_setter);
put_native_function("alert", alert);
put_native_function("setInterval", set_interval, 1);
put_native_function("setTimeout", set_timeout, 1);
put_native_function("requestAnimationFrame", request_animation_frame, 1);
put_native_function("cancelAnimationFrame", cancel_animation_frame, 1);
put("navigator", heap().allocate<NavigatorObject>());
}
WindowObject::~WindowObject()
{
}
static Window* impl_from(JS::Interpreter& interpreter)
{
auto* this_object = interpreter.this_value().to_object(interpreter.heap());
if (!this_object) {
ASSERT_NOT_REACHED();
return nullptr;
}
if (StringView("WindowObject") != this_object->class_name()) {
interpreter.throw_exception<JS::Error>("TypeError", "That's not a WindowObject, bro.");
return nullptr;
}
return &static_cast<WindowObject*>(this_object)->impl();
}
JS::Value WindowObject::alert(JS::Interpreter& interpreter)
{
auto* impl = impl_from(interpreter);
if (!impl)
return {};
auto& arguments = interpreter.call_frame().arguments;
if (arguments.size() < 1)
return {};
impl->alert(arguments[0].to_string());
return {};
}
JS::Value WindowObject::set_interval(JS::Interpreter& interpreter)
{
auto* impl = impl_from(interpreter);
if (!impl)
return {};
auto& arguments = interpreter.call_frame().arguments;
if (arguments.size() < 2)
return {};
auto* callback_object = arguments[0].to_object(interpreter.heap());
if (!callback_object)
return {};
if (!callback_object->is_function())
return interpreter.throw_exception<JS::Error>("TypeError", "Not a function");
impl->set_interval(*static_cast<JS::Function*>(callback_object), arguments[1].to_i32());
return {};
}
JS::Value WindowObject::set_timeout(JS::Interpreter& interpreter)
{
auto* impl = impl_from(interpreter);
if (!impl)
return {};
auto& arguments = interpreter.call_frame().arguments;
if (arguments.size() < 2)
return {};
auto* callback_object = arguments[0].to_object(interpreter.heap());
if (!callback_object)
return {};
if (!callback_object->is_function())
return interpreter.throw_exception<JS::Error>("TypeError", "Not a function");
impl->set_timeout(*static_cast<JS::Function*>(callback_object), arguments[1].to_i32());
return {};
}
JS::Value WindowObject::request_animation_frame(JS::Interpreter& interpreter)
{
auto* impl = impl_from(interpreter);
if (!impl)
return {};
auto& arguments = interpreter.call_frame().arguments;
if (arguments.size() < 1)
return {};
auto* callback_object = arguments[0].to_object(interpreter.heap());
if (!callback_object)
return {};
if (!callback_object->is_function())
return interpreter.throw_exception<JS::Error>("TypeError", "Not a function");
return JS::Value(impl->request_animation_frame(*static_cast<JS::Function*>(callback_object)));
}
JS::Value WindowObject::cancel_animation_frame(JS::Interpreter& interpreter)
{
auto* impl = impl_from(interpreter);
if (!impl)
return {};
auto& arguments = interpreter.call_frame().arguments;
if (arguments.size() < 1)
return {};
impl->cancel_animation_frame(arguments[0].to_i32());
return {};
}
JS::Value WindowObject::document_getter(JS::Interpreter& interpreter)
{
auto* impl = impl_from(interpreter);
if (!impl)
return {};
return wrap(interpreter.heap(), impl->document());
}
void WindowObject::document_setter(JS::Interpreter&, JS::Value)
{
// FIXME: Figure out what we should do here. Just ignore attempts to set window.document for now.
}
}
}
|
#include <netinet/in.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <unistd.h>
#include <iostream>
#include <optional>
#include <string>
#include <string_view>
#include <fmt/format.h>
namespace {
constexpr const int kPort = 8080;
constexpr const int kBufferSize = 512;
using descriptor = int;
using message = std::string;
using message_view = std::string_view;
[[nodiscard, gnu::always_inline]] inline bool sent_message(descriptor const descriptor, message_view const data) {
long const bytes = write(descriptor, data.data(), data.size());
return bytes >= 0;
}
[[nodiscard]] std::optional<message> receive_message(descriptor const descriptor) {
message rmessage(kBufferSize, '0');
long const bytes = read(descriptor, rmessage.data(), rmessage.size());
if (bytes <= 0) {
return std::nullopt;
}
rmessage.resize(bytes);
return {std::move(rmessage)};
}
[[nodiscard, gnu::always_inline]] inline message make_http_response(message_view const payload) {
return fmt::format("HTTP/1.1 200 OK\nContent-Length: {}\n\n{}", payload.size(), payload);
}
[[nodiscard]] message get_payload_from_message(message const& msg) {
std::size_t const payload_start = msg.find_last_of("\n\n", msg.find_last_of("\n\n"));
if (payload_start != message::npos) [[likely]] {
return msg.substr(payload_start + 1U, msg.size() - payload_start);
}
return {};
}
int start_handling_requests_on_socket(descriptor const listen_socket) {
fd_set active_sockets;
FD_ZERO(&active_sockets);
FD_SET(listen_socket, &active_sockets);
while (true) {
fd_set snapshot_sockets = active_sockets;
if (select(FD_SETSIZE, &snapshot_sockets, nullptr, nullptr, nullptr) < 0) {
break;
}
for (descriptor socket{}; socket < FD_SETSIZE; ++socket) {
if (!FD_ISSET(socket, &snapshot_sockets)) {
continue;
}
if (socket == listen_socket) [[unlikely]] {
sockaddr_in client_socket_description{};
socklen_t size = sizeof(client_socket_description);
descriptor new_connection_descriptor =
accept(listen_socket, reinterpret_cast<sockaddr*>(&client_socket_description), &size);
if (new_connection_descriptor < 0) {
break;
}
FD_SET(new_connection_descriptor, &active_sockets);
} else {
if (auto const request = receive_message(socket); request.has_value()) {
message const response = make_http_response(get_payload_from_message(request.value()));
if (!sent_message(socket, response)) {
std::cout << fmt::format("could not sent message '{}' to the socket {}", response, socket) << std::endl;
}
}
close(socket);
FD_CLR(socket, &active_sockets);
}
}
}
close(listen_socket);
return 0;
}
} // namespace
int main([[maybe_unused]] int argc, [[maybe_unused]] char* argv[]) {
constexpr const int kUseTcp = 0;
descriptor const listen_socket = socket(PF_INET, SOCK_STREAM, kUseTcp);
if (listen_socket < 0) {
std::cout << "listen socket was not created" << std::endl;
return 1;
}
int opt = 1;
setsockopt(listen_socket, SOL_SOCKET, SO_REUSEADDR, reinterpret_cast<char*>(&opt), sizeof(opt));
sockaddr_in sock_description{};
sock_description.sin_family = AF_INET;
sock_description.sin_port = htons(kPort);
sock_description.sin_addr.s_addr = htonl(INADDR_ANY);
int const error_bind = bind(listen_socket, reinterpret_cast<sockaddr*>(&sock_description), sizeof(sock_description));
if (error_bind < 0) {
std::cout << "Failed to bind a socket" << std::endl;
return 1;
}
constexpr const int kSizeQueue = 3;
if (int const error = listen(listen_socket, kSizeQueue); error < 0) {
std::cout << "Listen queue failure" << std::endl;
return 1;
}
return start_handling_requests_on_socket(listen_socket);
}
|
//*****************************************************************************
// Copyright 2017-2020 Intel Corporation
//
// 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 <algorithm>
#include <cstdio>
#include <iostream>
#include <list>
#include <memory>
#include "gtest/gtest.h"
#include "ngraph/op/add.hpp"
#include "ngraph/op/broadcast.hpp"
#include "ngraph/op/constant.hpp"
#include "ngraph/op/multiply.hpp"
#include "ngraph/op/parameter.hpp"
#include "ngraph/pass/constant_to_broadcast.hpp"
#include "ngraph/pass/manager.hpp"
#include "ngraph/pass/visualize_tree.hpp"
#include "ngraph/serializer.hpp"
#include "util/test_tools.hpp"
using namespace ngraph;
using namespace std;
TEST(pass, constant_to_broadcast)
{
Shape shape{128, 256, 1, 1};
vector<float> v = {3};
auto c = make_shared<op::Constant>(element::f32, shape, v);
auto f = make_shared<Function>(c, ParameterVector{});
{
ngraph::pass::Manager pm;
pm.register_pass<pass::ConstantToBroadcast>();
EXPECT_EQ(count_ops_of_type<op::Broadcast>(f), 0);
pm.run_passes(f);
EXPECT_EQ(count_ops_of_type<op::Broadcast>(f), 1);
}
}
|
//===-- TargetLibraryInfo.cpp - Runtime library information ----------------==//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the TargetLibraryInfo class.
//
//===----------------------------------------------------------------------===//
#include "llvm/Analysis/TargetLibraryInfo.h"
#include "llvm/ADT/Triple.h"
#include "llvm/IR/Constants.h"
#include "llvm/Support/CommandLine.h"
using namespace llvm;
static cl::opt<TargetLibraryInfoImpl::VectorLibrary> ClVectorLibrary(
"vector-library", cl::Hidden, cl::desc("Vector functions library"),
cl::init(TargetLibraryInfoImpl::NoLibrary),
cl::values(clEnumValN(TargetLibraryInfoImpl::NoLibrary, "none",
"No vector functions library"),
clEnumValN(TargetLibraryInfoImpl::Accelerate, "Accelerate",
"Accelerate framework"),
clEnumValN(TargetLibraryInfoImpl::SVML, "SVML",
"Intel SVML library")));
StringRef const TargetLibraryInfoImpl::StandardNames[LibFunc::NumLibFuncs] = {
#define TLI_DEFINE_STRING
#include "llvm/Analysis/TargetLibraryInfo.def"
};
static bool hasSinCosPiStret(const Triple &T) {
// Only Darwin variants have _stret versions of combined trig functions.
if (!T.isOSDarwin())
return false;
// The ABI is rather complicated on x86, so don't do anything special there.
if (T.getArch() == Triple::x86)
return false;
if (T.isMacOSX() && T.isMacOSXVersionLT(10, 9))
return false;
if (T.isiOS() && T.isOSVersionLT(7, 0))
return false;
return true;
}
/// Initialize the set of available library functions based on the specified
/// target triple. This should be carefully written so that a missing target
/// triple gets a sane set of defaults.
static void initialize(TargetLibraryInfoImpl &TLI, const Triple &T,
ArrayRef<StringRef> StandardNames) {
// Verify that the StandardNames array is in alphabetical order.
assert(std::is_sorted(StandardNames.begin(), StandardNames.end(),
[](StringRef LHS, StringRef RHS) {
return LHS < RHS;
}) &&
"TargetLibraryInfoImpl function names must be sorted");
bool ShouldExtI32Param = false, ShouldExtI32Return = false,
ShouldSignExtI32Param = false;
// PowerPC64, Sparc64, SystemZ need signext/zeroext on i32 parameters and
// returns corresponding to C-level ints and unsigned ints.
if (T.getArch() == Triple::ppc64 || T.getArch() == Triple::ppc64le ||
T.getArch() == Triple::sparcv9 || T.getArch() == Triple::systemz) {
ShouldExtI32Param = true;
ShouldExtI32Return = true;
}
// Mips, on the other hand, needs signext on i32 parameters corresponding
// to both signed and unsigned ints.
if (T.getArch() == Triple::mips || T.getArch() == Triple::mipsel ||
T.getArch() == Triple::mips64 || T.getArch() == Triple::mips64el) {
ShouldSignExtI32Param = true;
}
TLI.setShouldExtI32Param(ShouldExtI32Param);
TLI.setShouldExtI32Return(ShouldExtI32Return);
TLI.setShouldSignExtI32Param(ShouldSignExtI32Param);
if (T.getArch() == Triple::r600 ||
T.getArch() == Triple::amdgcn) {
TLI.setUnavailable(LibFunc_ldexp);
TLI.setUnavailable(LibFunc_ldexpf);
TLI.setUnavailable(LibFunc_ldexpl);
TLI.setUnavailable(LibFunc_exp10);
TLI.setUnavailable(LibFunc_exp10f);
TLI.setUnavailable(LibFunc_exp10l);
TLI.setUnavailable(LibFunc_log10);
TLI.setUnavailable(LibFunc_log10f);
TLI.setUnavailable(LibFunc_log10l);
}
// There are no library implementations of mempcy and memset for AMD gpus and
// these can be difficult to lower in the backend.
if (T.getArch() == Triple::r600 ||
T.getArch() == Triple::amdgcn) {
TLI.setUnavailable(LibFunc_memcpy);
TLI.setUnavailable(LibFunc_memset);
TLI.setUnavailable(LibFunc_memset_pattern16);
return;
}
// memset_pattern16 is only available on iOS 3.0 and Mac OS X 10.5 and later.
// All versions of watchOS support it.
if (T.isMacOSX()) {
if (T.isMacOSXVersionLT(10, 5))
TLI.setUnavailable(LibFunc_memset_pattern16);
} else if (T.isiOS()) {
if (T.isOSVersionLT(3, 0))
TLI.setUnavailable(LibFunc_memset_pattern16);
} else if (!T.isWatchOS()) {
TLI.setUnavailable(LibFunc_memset_pattern16);
}
if (!hasSinCosPiStret(T)) {
TLI.setUnavailable(LibFunc_sinpi);
TLI.setUnavailable(LibFunc_sinpif);
TLI.setUnavailable(LibFunc_cospi);
TLI.setUnavailable(LibFunc_cospif);
TLI.setUnavailable(LibFunc_sincospi_stret);
TLI.setUnavailable(LibFunc_sincospif_stret);
}
if (T.isMacOSX() && T.getArch() == Triple::x86 &&
!T.isMacOSXVersionLT(10, 7)) {
// x86-32 OSX has a scheme where fwrite and fputs (and some other functions
// we don't care about) have two versions; on recent OSX, the one we want
// has a $UNIX2003 suffix. The two implementations are identical except
// for the return value in some edge cases. However, we don't want to
// generate code that depends on the old symbols.
TLI.setAvailableWithName(LibFunc_fwrite, "fwrite$UNIX2003");
TLI.setAvailableWithName(LibFunc_fputs, "fputs$UNIX2003");
}
// iprintf and friends are only available on XCore and TCE.
if (T.getArch() != Triple::xcore && T.getArch() != Triple::tce) {
TLI.setUnavailable(LibFunc_iprintf);
TLI.setUnavailable(LibFunc_siprintf);
TLI.setUnavailable(LibFunc_fiprintf);
}
if (T.isOSWindows() && !T.isOSCygMing()) {
// Win32 does not support long double
TLI.setUnavailable(LibFunc_acosl);
TLI.setUnavailable(LibFunc_asinl);
TLI.setUnavailable(LibFunc_atanl);
TLI.setUnavailable(LibFunc_atan2l);
TLI.setUnavailable(LibFunc_ceill);
TLI.setUnavailable(LibFunc_copysignl);
TLI.setUnavailable(LibFunc_cosl);
TLI.setUnavailable(LibFunc_coshl);
TLI.setUnavailable(LibFunc_expl);
TLI.setUnavailable(LibFunc_fabsf); // Win32 and Win64 both lack fabsf
TLI.setUnavailable(LibFunc_fabsl);
TLI.setUnavailable(LibFunc_floorl);
TLI.setUnavailable(LibFunc_fmaxl);
TLI.setUnavailable(LibFunc_fminl);
TLI.setUnavailable(LibFunc_fmodl);
TLI.setUnavailable(LibFunc_frexpl);
TLI.setUnavailable(LibFunc_ldexpf);
TLI.setUnavailable(LibFunc_ldexpl);
TLI.setUnavailable(LibFunc_logl);
TLI.setUnavailable(LibFunc_modfl);
TLI.setUnavailable(LibFunc_powl);
TLI.setUnavailable(LibFunc_sinl);
TLI.setUnavailable(LibFunc_sinhl);
TLI.setUnavailable(LibFunc_sqrtl);
TLI.setUnavailable(LibFunc_tanl);
TLI.setUnavailable(LibFunc_tanhl);
// Win32 only has C89 math
TLI.setUnavailable(LibFunc_acosh);
TLI.setUnavailable(LibFunc_acoshf);
TLI.setUnavailable(LibFunc_acoshl);
TLI.setUnavailable(LibFunc_asinh);
TLI.setUnavailable(LibFunc_asinhf);
TLI.setUnavailable(LibFunc_asinhl);
TLI.setUnavailable(LibFunc_atanh);
TLI.setUnavailable(LibFunc_atanhf);
TLI.setUnavailable(LibFunc_atanhl);
TLI.setUnavailable(LibFunc_cabs);
TLI.setUnavailable(LibFunc_cabsf);
TLI.setUnavailable(LibFunc_cabsl);
TLI.setUnavailable(LibFunc_cbrt);
TLI.setUnavailable(LibFunc_cbrtf);
TLI.setUnavailable(LibFunc_cbrtl);
TLI.setUnavailable(LibFunc_exp2);
TLI.setUnavailable(LibFunc_exp2f);
TLI.setUnavailable(LibFunc_exp2l);
TLI.setUnavailable(LibFunc_expm1);
TLI.setUnavailable(LibFunc_expm1f);
TLI.setUnavailable(LibFunc_expm1l);
TLI.setUnavailable(LibFunc_log2);
TLI.setUnavailable(LibFunc_log2f);
TLI.setUnavailable(LibFunc_log2l);
TLI.setUnavailable(LibFunc_log1p);
TLI.setUnavailable(LibFunc_log1pf);
TLI.setUnavailable(LibFunc_log1pl);
TLI.setUnavailable(LibFunc_logb);
TLI.setUnavailable(LibFunc_logbf);
TLI.setUnavailable(LibFunc_logbl);
TLI.setUnavailable(LibFunc_nearbyint);
TLI.setUnavailable(LibFunc_nearbyintf);
TLI.setUnavailable(LibFunc_nearbyintl);
TLI.setUnavailable(LibFunc_rint);
TLI.setUnavailable(LibFunc_rintf);
TLI.setUnavailable(LibFunc_rintl);
TLI.setUnavailable(LibFunc_round);
TLI.setUnavailable(LibFunc_roundf);
TLI.setUnavailable(LibFunc_roundl);
TLI.setUnavailable(LibFunc_trunc);
TLI.setUnavailable(LibFunc_truncf);
TLI.setUnavailable(LibFunc_truncl);
// Win32 provides some C99 math with mangled names
TLI.setAvailableWithName(LibFunc_copysign, "_copysign");
if (T.getArch() == Triple::x86) {
// Win32 on x86 implements single-precision math functions as macros
TLI.setUnavailable(LibFunc_acosf);
TLI.setUnavailable(LibFunc_asinf);
TLI.setUnavailable(LibFunc_atanf);
TLI.setUnavailable(LibFunc_atan2f);
TLI.setUnavailable(LibFunc_ceilf);
TLI.setUnavailable(LibFunc_copysignf);
TLI.setUnavailable(LibFunc_cosf);
TLI.setUnavailable(LibFunc_coshf);
TLI.setUnavailable(LibFunc_expf);
TLI.setUnavailable(LibFunc_floorf);
TLI.setUnavailable(LibFunc_fminf);
TLI.setUnavailable(LibFunc_fmaxf);
TLI.setUnavailable(LibFunc_fmodf);
TLI.setUnavailable(LibFunc_logf);
TLI.setUnavailable(LibFunc_log10f);
TLI.setUnavailable(LibFunc_modff);
TLI.setUnavailable(LibFunc_powf);
TLI.setUnavailable(LibFunc_sinf);
TLI.setUnavailable(LibFunc_sinhf);
TLI.setUnavailable(LibFunc_sqrtf);
TLI.setUnavailable(LibFunc_tanf);
TLI.setUnavailable(LibFunc_tanhf);
}
// Win32 does *not* provide these functions, but they are
// generally available on POSIX-compliant systems:
TLI.setUnavailable(LibFunc_access);
TLI.setUnavailable(LibFunc_bcmp);
TLI.setUnavailable(LibFunc_bcopy);
TLI.setUnavailable(LibFunc_bzero);
TLI.setUnavailable(LibFunc_chmod);
TLI.setUnavailable(LibFunc_chown);
TLI.setUnavailable(LibFunc_closedir);
TLI.setUnavailable(LibFunc_ctermid);
TLI.setUnavailable(LibFunc_fdopen);
TLI.setUnavailable(LibFunc_ffs);
TLI.setUnavailable(LibFunc_fileno);
TLI.setUnavailable(LibFunc_flockfile);
TLI.setUnavailable(LibFunc_fseeko);
TLI.setUnavailable(LibFunc_fstat);
TLI.setUnavailable(LibFunc_fstatvfs);
TLI.setUnavailable(LibFunc_ftello);
TLI.setUnavailable(LibFunc_ftrylockfile);
TLI.setUnavailable(LibFunc_funlockfile);
TLI.setUnavailable(LibFunc_getc_unlocked);
TLI.setUnavailable(LibFunc_getitimer);
TLI.setUnavailable(LibFunc_getlogin_r);
TLI.setUnavailable(LibFunc_getpwnam);
TLI.setUnavailable(LibFunc_gettimeofday);
TLI.setUnavailable(LibFunc_htonl);
TLI.setUnavailable(LibFunc_htons);
TLI.setUnavailable(LibFunc_lchown);
TLI.setUnavailable(LibFunc_lstat);
TLI.setUnavailable(LibFunc_memccpy);
TLI.setUnavailable(LibFunc_mkdir);
TLI.setUnavailable(LibFunc_ntohl);
TLI.setUnavailable(LibFunc_ntohs);
TLI.setUnavailable(LibFunc_open);
TLI.setUnavailable(LibFunc_opendir);
TLI.setUnavailable(LibFunc_pclose);
TLI.setUnavailable(LibFunc_popen);
TLI.setUnavailable(LibFunc_pread);
TLI.setUnavailable(LibFunc_pwrite);
TLI.setUnavailable(LibFunc_read);
TLI.setUnavailable(LibFunc_readlink);
TLI.setUnavailable(LibFunc_realpath);
TLI.setUnavailable(LibFunc_rmdir);
TLI.setUnavailable(LibFunc_setitimer);
TLI.setUnavailable(LibFunc_stat);
TLI.setUnavailable(LibFunc_statvfs);
TLI.setUnavailable(LibFunc_stpcpy);
TLI.setUnavailable(LibFunc_stpncpy);
TLI.setUnavailable(LibFunc_strcasecmp);
TLI.setUnavailable(LibFunc_strncasecmp);
TLI.setUnavailable(LibFunc_times);
TLI.setUnavailable(LibFunc_uname);
TLI.setUnavailable(LibFunc_unlink);
TLI.setUnavailable(LibFunc_unsetenv);
TLI.setUnavailable(LibFunc_utime);
TLI.setUnavailable(LibFunc_utimes);
TLI.setUnavailable(LibFunc_write);
// Win32 does *not* provide provide these functions, but they are
// specified by C99:
TLI.setUnavailable(LibFunc_atoll);
TLI.setUnavailable(LibFunc_frexpf);
TLI.setUnavailable(LibFunc_llabs);
}
switch (T.getOS()) {
case Triple::MacOSX:
// exp10 and exp10f are not available on OS X until 10.9 and iOS until 7.0
// and their names are __exp10 and __exp10f. exp10l is not available on
// OS X or iOS.
TLI.setUnavailable(LibFunc_exp10l);
if (T.isMacOSXVersionLT(10, 9)) {
TLI.setUnavailable(LibFunc_exp10);
TLI.setUnavailable(LibFunc_exp10f);
} else {
TLI.setAvailableWithName(LibFunc_exp10, "__exp10");
TLI.setAvailableWithName(LibFunc_exp10f, "__exp10f");
}
break;
case Triple::IOS:
case Triple::TvOS:
case Triple::WatchOS:
TLI.setUnavailable(LibFunc_exp10l);
if (!T.isWatchOS() && (T.isOSVersionLT(7, 0) ||
(T.isOSVersionLT(9, 0) &&
(T.getArch() == Triple::x86 ||
T.getArch() == Triple::x86_64)))) {
TLI.setUnavailable(LibFunc_exp10);
TLI.setUnavailable(LibFunc_exp10f);
} else {
TLI.setAvailableWithName(LibFunc_exp10, "__exp10");
TLI.setAvailableWithName(LibFunc_exp10f, "__exp10f");
}
break;
case Triple::Linux:
// exp10, exp10f, exp10l is available on Linux (GLIBC) but are extremely
// buggy prior to glibc version 2.18. Until this version is widely deployed
// or we have a reasonable detection strategy, we cannot use exp10 reliably
// on Linux.
//
// Fall through to disable all of them.
LLVM_FALLTHROUGH;
default:
TLI.setUnavailable(LibFunc_exp10);
TLI.setUnavailable(LibFunc_exp10f);
TLI.setUnavailable(LibFunc_exp10l);
}
// ffsl is available on at least Darwin, Mac OS X, iOS, FreeBSD, and
// Linux (GLIBC):
// http://developer.apple.com/library/mac/#documentation/Darwin/Reference/ManPages/man3/ffsl.3.html
// http://svn.freebsd.org/base/head/lib/libc/string/ffsl.c
// http://www.gnu.org/software/gnulib/manual/html_node/ffsl.html
switch (T.getOS()) {
case Triple::Darwin:
case Triple::MacOSX:
case Triple::IOS:
case Triple::TvOS:
case Triple::WatchOS:
case Triple::FreeBSD:
case Triple::Linux:
break;
default:
TLI.setUnavailable(LibFunc_ffsl);
}
// ffsll is available on at least FreeBSD and Linux (GLIBC):
// http://svn.freebsd.org/base/head/lib/libc/string/ffsll.c
// http://www.gnu.org/software/gnulib/manual/html_node/ffsll.html
switch (T.getOS()) {
case Triple::Darwin:
case Triple::MacOSX:
case Triple::IOS:
case Triple::TvOS:
case Triple::WatchOS:
case Triple::FreeBSD:
case Triple::Linux:
break;
default:
TLI.setUnavailable(LibFunc_ffsll);
}
// The following functions are available on at least FreeBSD:
// http://svn.freebsd.org/base/head/lib/libc/string/fls.c
// http://svn.freebsd.org/base/head/lib/libc/string/flsl.c
// http://svn.freebsd.org/base/head/lib/libc/string/flsll.c
if (!T.isOSFreeBSD()) {
TLI.setUnavailable(LibFunc_fls);
TLI.setUnavailable(LibFunc_flsl);
TLI.setUnavailable(LibFunc_flsll);
}
// The following functions are available on Linux,
// but Android uses bionic instead of glibc.
if (!T.isOSLinux() || T.isAndroid()) {
TLI.setUnavailable(LibFunc_dunder_strdup);
TLI.setUnavailable(LibFunc_dunder_strtok_r);
TLI.setUnavailable(LibFunc_dunder_isoc99_scanf);
TLI.setUnavailable(LibFunc_dunder_isoc99_sscanf);
TLI.setUnavailable(LibFunc_under_IO_getc);
TLI.setUnavailable(LibFunc_under_IO_putc);
// But, Android has memalign.
if (!T.isAndroid())
TLI.setUnavailable(LibFunc_memalign);
TLI.setUnavailable(LibFunc_fopen64);
TLI.setUnavailable(LibFunc_fseeko64);
TLI.setUnavailable(LibFunc_fstat64);
TLI.setUnavailable(LibFunc_fstatvfs64);
TLI.setUnavailable(LibFunc_ftello64);
TLI.setUnavailable(LibFunc_lstat64);
TLI.setUnavailable(LibFunc_open64);
TLI.setUnavailable(LibFunc_stat64);
TLI.setUnavailable(LibFunc_statvfs64);
TLI.setUnavailable(LibFunc_tmpfile64);
// Relaxed math functions are included in math-finite.h on Linux (GLIBC).
TLI.setUnavailable(LibFunc_acos_finite);
TLI.setUnavailable(LibFunc_acosf_finite);
TLI.setUnavailable(LibFunc_acosl_finite);
TLI.setUnavailable(LibFunc_acosh_finite);
TLI.setUnavailable(LibFunc_acoshf_finite);
TLI.setUnavailable(LibFunc_acoshl_finite);
TLI.setUnavailable(LibFunc_asin_finite);
TLI.setUnavailable(LibFunc_asinf_finite);
TLI.setUnavailable(LibFunc_asinl_finite);
TLI.setUnavailable(LibFunc_atan2_finite);
TLI.setUnavailable(LibFunc_atan2f_finite);
TLI.setUnavailable(LibFunc_atan2l_finite);
TLI.setUnavailable(LibFunc_atanh_finite);
TLI.setUnavailable(LibFunc_atanhf_finite);
TLI.setUnavailable(LibFunc_atanhl_finite);
TLI.setUnavailable(LibFunc_cosh_finite);
TLI.setUnavailable(LibFunc_coshf_finite);
TLI.setUnavailable(LibFunc_coshl_finite);
TLI.setUnavailable(LibFunc_exp10_finite);
TLI.setUnavailable(LibFunc_exp10f_finite);
TLI.setUnavailable(LibFunc_exp10l_finite);
TLI.setUnavailable(LibFunc_exp2_finite);
TLI.setUnavailable(LibFunc_exp2f_finite);
TLI.setUnavailable(LibFunc_exp2l_finite);
TLI.setUnavailable(LibFunc_exp_finite);
TLI.setUnavailable(LibFunc_expf_finite);
TLI.setUnavailable(LibFunc_expl_finite);
TLI.setUnavailable(LibFunc_log10_finite);
TLI.setUnavailable(LibFunc_log10f_finite);
TLI.setUnavailable(LibFunc_log10l_finite);
TLI.setUnavailable(LibFunc_log2_finite);
TLI.setUnavailable(LibFunc_log2f_finite);
TLI.setUnavailable(LibFunc_log2l_finite);
TLI.setUnavailable(LibFunc_log_finite);
TLI.setUnavailable(LibFunc_logf_finite);
TLI.setUnavailable(LibFunc_logl_finite);
TLI.setUnavailable(LibFunc_pow_finite);
TLI.setUnavailable(LibFunc_powf_finite);
TLI.setUnavailable(LibFunc_powl_finite);
TLI.setUnavailable(LibFunc_sinh_finite);
TLI.setUnavailable(LibFunc_sinhf_finite);
TLI.setUnavailable(LibFunc_sinhl_finite);
}
// As currently implemented in clang, NVPTX code has no standard library to
// speak of. Headers provide a standard-ish library implementation, but many
// of the signatures are wrong -- for example, many libm functions are not
// extern "C".
//
// libdevice, an IR library provided by nvidia, is linked in by the front-end,
// but only used functions are provided to llvm. Moreover, most of the
// functions in libdevice don't map precisely to standard library functions.
//
// FIXME: Having no standard library prevents e.g. many fastmath
// optimizations, so this situation should be fixed.
if (T.isNVPTX()) {
TLI.disableAllFunctions();
TLI.setAvailable(LibFunc_nvvm_reflect);
} else {
TLI.setUnavailable(LibFunc_nvvm_reflect);
}
TLI.addVectorizableFunctionsFromVecLib(ClVectorLibrary);
}
TargetLibraryInfoImpl::TargetLibraryInfoImpl() {
// Default to everything being available.
memset(AvailableArray, -1, sizeof(AvailableArray));
initialize(*this, Triple(), StandardNames);
}
TargetLibraryInfoImpl::TargetLibraryInfoImpl(const Triple &T) {
// Default to everything being available.
memset(AvailableArray, -1, sizeof(AvailableArray));
initialize(*this, T, StandardNames);
}
TargetLibraryInfoImpl::TargetLibraryInfoImpl(const TargetLibraryInfoImpl &TLI)
: CustomNames(TLI.CustomNames), ShouldExtI32Param(TLI.ShouldExtI32Param),
ShouldExtI32Return(TLI.ShouldExtI32Return),
ShouldSignExtI32Param(TLI.ShouldSignExtI32Param) {
memcpy(AvailableArray, TLI.AvailableArray, sizeof(AvailableArray));
VectorDescs = TLI.VectorDescs;
ScalarDescs = TLI.ScalarDescs;
}
TargetLibraryInfoImpl::TargetLibraryInfoImpl(TargetLibraryInfoImpl &&TLI)
: CustomNames(std::move(TLI.CustomNames)),
ShouldExtI32Param(TLI.ShouldExtI32Param),
ShouldExtI32Return(TLI.ShouldExtI32Return),
ShouldSignExtI32Param(TLI.ShouldSignExtI32Param) {
std::move(std::begin(TLI.AvailableArray), std::end(TLI.AvailableArray),
AvailableArray);
VectorDescs = TLI.VectorDescs;
ScalarDescs = TLI.ScalarDescs;
}
TargetLibraryInfoImpl &TargetLibraryInfoImpl::operator=(const TargetLibraryInfoImpl &TLI) {
CustomNames = TLI.CustomNames;
ShouldExtI32Param = TLI.ShouldExtI32Param;
ShouldExtI32Return = TLI.ShouldExtI32Return;
ShouldSignExtI32Param = TLI.ShouldSignExtI32Param;
memcpy(AvailableArray, TLI.AvailableArray, sizeof(AvailableArray));
return *this;
}
TargetLibraryInfoImpl &TargetLibraryInfoImpl::operator=(TargetLibraryInfoImpl &&TLI) {
CustomNames = std::move(TLI.CustomNames);
ShouldExtI32Param = TLI.ShouldExtI32Param;
ShouldExtI32Return = TLI.ShouldExtI32Return;
ShouldSignExtI32Param = TLI.ShouldSignExtI32Param;
std::move(std::begin(TLI.AvailableArray), std::end(TLI.AvailableArray),
AvailableArray);
return *this;
}
static StringRef sanitizeFunctionName(StringRef funcName) {
// Filter out empty names and names containing null bytes, those can't be in
// our table.
if (funcName.empty() || funcName.find('\0') != StringRef::npos)
return StringRef();
// Check for \01 prefix that is used to mangle __asm declarations and
// strip it if present.
return GlobalValue::dropLLVMManglingEscape(funcName);
}
bool TargetLibraryInfoImpl::getLibFunc(StringRef funcName,
LibFunc &F) const {
StringRef const *Start = &StandardNames[0];
StringRef const *End = &StandardNames[NumLibFuncs];
funcName = sanitizeFunctionName(funcName);
if (funcName.empty())
return false;
StringRef const *I = std::lower_bound(
Start, End, funcName, [](StringRef LHS, StringRef RHS) {
return LHS < RHS;
});
if (I != End && *I == funcName) {
F = (LibFunc)(I - Start);
return true;
}
return false;
}
bool TargetLibraryInfoImpl::isValidProtoForLibFunc(const FunctionType &FTy,
LibFunc F,
const DataLayout *DL) const {
LLVMContext &Ctx = FTy.getContext();
Type *PCharTy = Type::getInt8PtrTy(Ctx);
Type *SizeTTy = DL ? DL->getIntPtrType(Ctx, /*AS=*/0) : nullptr;
auto IsSizeTTy = [SizeTTy](Type *Ty) {
return SizeTTy ? Ty == SizeTTy : Ty->isIntegerTy();
};
unsigned NumParams = FTy.getNumParams();
switch (F) {
case LibFunc_strlen:
return (NumParams == 1 && FTy.getParamType(0)->isPointerTy() &&
FTy.getReturnType()->isIntegerTy());
case LibFunc_strchr:
case LibFunc_strrchr:
return (NumParams == 2 && FTy.getReturnType()->isPointerTy() &&
FTy.getParamType(0) == FTy.getReturnType() &&
FTy.getParamType(1)->isIntegerTy());
case LibFunc_strtol:
case LibFunc_strtod:
case LibFunc_strtof:
case LibFunc_strtoul:
case LibFunc_strtoll:
case LibFunc_strtold:
case LibFunc_strtoull:
return ((NumParams == 2 || NumParams == 3) &&
FTy.getParamType(0)->isPointerTy() &&
FTy.getParamType(1)->isPointerTy());
case LibFunc_strcat:
return (NumParams == 2 && FTy.getReturnType()->isPointerTy() &&
FTy.getParamType(0) == FTy.getReturnType() &&
FTy.getParamType(1) == FTy.getReturnType());
case LibFunc_strncat:
return (NumParams == 3 && FTy.getReturnType()->isPointerTy() &&
FTy.getParamType(0) == FTy.getReturnType() &&
FTy.getParamType(1) == FTy.getReturnType() &&
IsSizeTTy(FTy.getParamType(2)));
case LibFunc_strcpy_chk:
case LibFunc_stpcpy_chk:
--NumParams;
if (!IsSizeTTy(FTy.getParamType(NumParams)))
return false;
LLVM_FALLTHROUGH;
case LibFunc_strcpy:
case LibFunc_stpcpy:
return (NumParams == 2 && FTy.getReturnType() == FTy.getParamType(0) &&
FTy.getParamType(0) == FTy.getParamType(1) &&
FTy.getParamType(0) == PCharTy);
case LibFunc_strncpy_chk:
case LibFunc_stpncpy_chk:
--NumParams;
if (!IsSizeTTy(FTy.getParamType(NumParams)))
return false;
LLVM_FALLTHROUGH;
case LibFunc_strncpy:
case LibFunc_stpncpy:
return (NumParams == 3 && FTy.getReturnType() == FTy.getParamType(0) &&
FTy.getParamType(0) == FTy.getParamType(1) &&
FTy.getParamType(0) == PCharTy &&
IsSizeTTy(FTy.getParamType(2)));
case LibFunc_strxfrm:
return (NumParams == 3 && FTy.getParamType(0)->isPointerTy() &&
FTy.getParamType(1)->isPointerTy());
case LibFunc_strcmp:
return (NumParams == 2 && FTy.getReturnType()->isIntegerTy(32) &&
FTy.getParamType(0)->isPointerTy() &&
FTy.getParamType(0) == FTy.getParamType(1));
case LibFunc_strncmp:
return (NumParams == 3 && FTy.getReturnType()->isIntegerTy(32) &&
FTy.getParamType(0)->isPointerTy() &&
FTy.getParamType(0) == FTy.getParamType(1) &&
IsSizeTTy(FTy.getParamType(2)));
case LibFunc_strspn:
case LibFunc_strcspn:
return (NumParams == 2 && FTy.getParamType(0)->isPointerTy() &&
FTy.getParamType(0) == FTy.getParamType(1) &&
FTy.getReturnType()->isIntegerTy());
case LibFunc_strcoll:
case LibFunc_strcasecmp:
case LibFunc_strncasecmp:
return (NumParams >= 2 && FTy.getParamType(0)->isPointerTy() &&
FTy.getParamType(1)->isPointerTy());
case LibFunc_strstr:
return (NumParams == 2 && FTy.getReturnType()->isPointerTy() &&
FTy.getParamType(0)->isPointerTy() &&
FTy.getParamType(1)->isPointerTy());
case LibFunc_strpbrk:
return (NumParams == 2 && FTy.getParamType(0)->isPointerTy() &&
FTy.getReturnType() == FTy.getParamType(0) &&
FTy.getParamType(0) == FTy.getParamType(1));
case LibFunc_strtok:
case LibFunc_strtok_r:
return (NumParams >= 2 && FTy.getParamType(1)->isPointerTy());
case LibFunc_scanf:
case LibFunc_setbuf:
case LibFunc_setvbuf:
return (NumParams >= 1 && FTy.getParamType(0)->isPointerTy());
case LibFunc_strdup:
case LibFunc_strndup:
return (NumParams >= 1 && FTy.getReturnType()->isPointerTy() &&
FTy.getParamType(0)->isPointerTy());
case LibFunc_sscanf:
case LibFunc_stat:
case LibFunc_statvfs:
case LibFunc_siprintf:
case LibFunc_sprintf:
return (NumParams >= 2 && FTy.getParamType(0)->isPointerTy() &&
FTy.getParamType(1)->isPointerTy());
case LibFunc_snprintf:
return (NumParams == 3 && FTy.getParamType(0)->isPointerTy() &&
FTy.getParamType(2)->isPointerTy());
case LibFunc_setitimer:
return (NumParams == 3 && FTy.getParamType(1)->isPointerTy() &&
FTy.getParamType(2)->isPointerTy());
case LibFunc_system:
return (NumParams == 1 && FTy.getParamType(0)->isPointerTy());
case LibFunc_malloc:
return (NumParams == 1 && FTy.getReturnType()->isPointerTy());
case LibFunc_memcmp:
return (NumParams == 3 && FTy.getReturnType()->isIntegerTy(32) &&
FTy.getParamType(0)->isPointerTy() &&
FTy.getParamType(1)->isPointerTy());
case LibFunc_memchr:
case LibFunc_memrchr:
return (NumParams == 3 && FTy.getReturnType()->isPointerTy() &&
FTy.getReturnType() == FTy.getParamType(0) &&
FTy.getParamType(1)->isIntegerTy(32) &&
IsSizeTTy(FTy.getParamType(2)));
case LibFunc_modf:
case LibFunc_modff:
case LibFunc_modfl:
return (NumParams >= 2 && FTy.getParamType(1)->isPointerTy());
case LibFunc_memcpy_chk:
case LibFunc_memmove_chk:
--NumParams;
if (!IsSizeTTy(FTy.getParamType(NumParams)))
return false;
LLVM_FALLTHROUGH;
case LibFunc_memcpy:
case LibFunc_mempcpy:
case LibFunc_memmove:
return (NumParams == 3 && FTy.getReturnType() == FTy.getParamType(0) &&
FTy.getParamType(0)->isPointerTy() &&
FTy.getParamType(1)->isPointerTy() &&
IsSizeTTy(FTy.getParamType(2)));
case LibFunc_memset_chk:
--NumParams;
if (!IsSizeTTy(FTy.getParamType(NumParams)))
return false;
LLVM_FALLTHROUGH;
case LibFunc_memset:
return (NumParams == 3 && FTy.getReturnType() == FTy.getParamType(0) &&
FTy.getParamType(0)->isPointerTy() &&
FTy.getParamType(1)->isIntegerTy() &&
IsSizeTTy(FTy.getParamType(2)));
case LibFunc_memccpy:
return (NumParams >= 2 && FTy.getParamType(1)->isPointerTy());
case LibFunc_memalign:
return (FTy.getReturnType()->isPointerTy());
case LibFunc_realloc:
case LibFunc_reallocf:
return (NumParams == 2 && FTy.getReturnType() == PCharTy &&
FTy.getParamType(0) == FTy.getReturnType() &&
IsSizeTTy(FTy.getParamType(1)));
case LibFunc_read:
return (NumParams == 3 && FTy.getParamType(1)->isPointerTy());
case LibFunc_rewind:
case LibFunc_rmdir:
case LibFunc_remove:
case LibFunc_realpath:
return (NumParams >= 1 && FTy.getParamType(0)->isPointerTy());
case LibFunc_rename:
return (NumParams >= 2 && FTy.getParamType(0)->isPointerTy() &&
FTy.getParamType(1)->isPointerTy());
case LibFunc_readlink:
return (NumParams >= 2 && FTy.getParamType(0)->isPointerTy() &&
FTy.getParamType(1)->isPointerTy());
case LibFunc_write:
return (NumParams == 3 && FTy.getParamType(1)->isPointerTy());
case LibFunc_bcopy:
case LibFunc_bcmp:
return (NumParams == 3 && FTy.getParamType(0)->isPointerTy() &&
FTy.getParamType(1)->isPointerTy());
case LibFunc_bzero:
return (NumParams == 2 && FTy.getParamType(0)->isPointerTy());
case LibFunc_calloc:
return (NumParams == 2 && FTy.getReturnType()->isPointerTy());
case LibFunc_atof:
case LibFunc_atoi:
case LibFunc_atol:
case LibFunc_atoll:
case LibFunc_ferror:
case LibFunc_getenv:
case LibFunc_getpwnam:
case LibFunc_iprintf:
case LibFunc_pclose:
case LibFunc_perror:
case LibFunc_printf:
case LibFunc_puts:
case LibFunc_uname:
case LibFunc_under_IO_getc:
case LibFunc_unlink:
case LibFunc_unsetenv:
return (NumParams == 1 && FTy.getParamType(0)->isPointerTy());
case LibFunc_access:
case LibFunc_chmod:
case LibFunc_chown:
case LibFunc_clearerr:
case LibFunc_closedir:
case LibFunc_ctermid:
case LibFunc_fclose:
case LibFunc_feof:
case LibFunc_fflush:
case LibFunc_fgetc:
case LibFunc_fileno:
case LibFunc_flockfile:
case LibFunc_free:
case LibFunc_fseek:
case LibFunc_fseeko64:
case LibFunc_fseeko:
case LibFunc_fsetpos:
case LibFunc_ftell:
case LibFunc_ftello64:
case LibFunc_ftello:
case LibFunc_ftrylockfile:
case LibFunc_funlockfile:
case LibFunc_getc:
case LibFunc_getc_unlocked:
case LibFunc_getlogin_r:
case LibFunc_mkdir:
case LibFunc_mktime:
case LibFunc_times:
return (NumParams != 0 && FTy.getParamType(0)->isPointerTy());
case LibFunc_fopen:
return (NumParams == 2 && FTy.getReturnType()->isPointerTy() &&
FTy.getParamType(0)->isPointerTy() &&
FTy.getParamType(1)->isPointerTy());
case LibFunc_fdopen:
return (NumParams == 2 && FTy.getReturnType()->isPointerTy() &&
FTy.getParamType(1)->isPointerTy());
case LibFunc_fputc:
case LibFunc_fstat:
case LibFunc_frexp:
case LibFunc_frexpf:
case LibFunc_frexpl:
case LibFunc_fstatvfs:
return (NumParams == 2 && FTy.getParamType(1)->isPointerTy());
case LibFunc_fgets:
return (NumParams == 3 && FTy.getParamType(0)->isPointerTy() &&
FTy.getParamType(2)->isPointerTy());
case LibFunc_fread:
return (NumParams == 4 && FTy.getParamType(0)->isPointerTy() &&
FTy.getParamType(3)->isPointerTy());
case LibFunc_fwrite:
return (NumParams == 4 && FTy.getReturnType()->isIntegerTy() &&
FTy.getParamType(0)->isPointerTy() &&
FTy.getParamType(1)->isIntegerTy() &&
FTy.getParamType(2)->isIntegerTy() &&
FTy.getParamType(3)->isPointerTy());
case LibFunc_fputs:
return (NumParams >= 2 && FTy.getParamType(0)->isPointerTy() &&
FTy.getParamType(1)->isPointerTy());
case LibFunc_fscanf:
case LibFunc_fiprintf:
case LibFunc_fprintf:
return (NumParams >= 2 && FTy.getReturnType()->isIntegerTy() &&
FTy.getParamType(0)->isPointerTy() &&
FTy.getParamType(1)->isPointerTy());
case LibFunc_fgetpos:
return (NumParams >= 2 && FTy.getParamType(0)->isPointerTy() &&
FTy.getParamType(1)->isPointerTy());
case LibFunc_getchar:
return (NumParams == 0 && FTy.getReturnType()->isIntegerTy());
case LibFunc_gets:
return (NumParams == 1 && FTy.getParamType(0) == PCharTy);
case LibFunc_getitimer:
return (NumParams == 2 && FTy.getParamType(1)->isPointerTy());
case LibFunc_ungetc:
return (NumParams == 2 && FTy.getParamType(1)->isPointerTy());
case LibFunc_utime:
case LibFunc_utimes:
return (NumParams == 2 && FTy.getParamType(0)->isPointerTy() &&
FTy.getParamType(1)->isPointerTy());
case LibFunc_putc:
return (NumParams == 2 && FTy.getParamType(1)->isPointerTy());
case LibFunc_pread:
case LibFunc_pwrite:
return (NumParams == 4 && FTy.getParamType(1)->isPointerTy());
case LibFunc_popen:
return (NumParams == 2 && FTy.getReturnType()->isPointerTy() &&
FTy.getParamType(0)->isPointerTy() &&
FTy.getParamType(1)->isPointerTy());
case LibFunc_vscanf:
return (NumParams == 2 && FTy.getParamType(1)->isPointerTy());
case LibFunc_vsscanf:
return (NumParams == 3 && FTy.getParamType(1)->isPointerTy() &&
FTy.getParamType(2)->isPointerTy());
case LibFunc_vfscanf:
return (NumParams == 3 && FTy.getParamType(1)->isPointerTy() &&
FTy.getParamType(2)->isPointerTy());
case LibFunc_valloc:
return (FTy.getReturnType()->isPointerTy());
case LibFunc_vprintf:
return (NumParams == 2 && FTy.getParamType(0)->isPointerTy());
case LibFunc_vfprintf:
case LibFunc_vsprintf:
return (NumParams == 3 && FTy.getParamType(0)->isPointerTy() &&
FTy.getParamType(1)->isPointerTy());
case LibFunc_vsnprintf:
return (NumParams == 4 && FTy.getParamType(0)->isPointerTy() &&
FTy.getParamType(2)->isPointerTy());
case LibFunc_open:
return (NumParams >= 2 && FTy.getParamType(0)->isPointerTy());
case LibFunc_opendir:
return (NumParams == 1 && FTy.getReturnType()->isPointerTy() &&
FTy.getParamType(0)->isPointerTy());
case LibFunc_tmpfile:
return (FTy.getReturnType()->isPointerTy());
case LibFunc_htonl:
case LibFunc_ntohl:
return (NumParams == 1 && FTy.getReturnType()->isIntegerTy(32) &&
FTy.getReturnType() == FTy.getParamType(0));
case LibFunc_htons:
case LibFunc_ntohs:
return (NumParams == 1 && FTy.getReturnType()->isIntegerTy(16) &&
FTy.getReturnType() == FTy.getParamType(0));
case LibFunc_lstat:
return (NumParams == 2 && FTy.getParamType(0)->isPointerTy() &&
FTy.getParamType(1)->isPointerTy());
case LibFunc_lchown:
return (NumParams == 3 && FTy.getParamType(0)->isPointerTy());
case LibFunc_qsort:
return (NumParams == 4 && FTy.getParamType(3)->isPointerTy());
case LibFunc_dunder_strdup:
case LibFunc_dunder_strndup:
return (NumParams >= 1 && FTy.getReturnType()->isPointerTy() &&
FTy.getParamType(0)->isPointerTy());
case LibFunc_dunder_strtok_r:
return (NumParams == 3 && FTy.getParamType(1)->isPointerTy());
case LibFunc_under_IO_putc:
return (NumParams == 2 && FTy.getParamType(1)->isPointerTy());
case LibFunc_dunder_isoc99_scanf:
return (NumParams >= 1 && FTy.getParamType(0)->isPointerTy());
case LibFunc_stat64:
case LibFunc_lstat64:
case LibFunc_statvfs64:
return (NumParams == 2 && FTy.getParamType(0)->isPointerTy() &&
FTy.getParamType(1)->isPointerTy());
case LibFunc_dunder_isoc99_sscanf:
return (NumParams >= 2 && FTy.getParamType(0)->isPointerTy() &&
FTy.getParamType(1)->isPointerTy());
case LibFunc_fopen64:
return (NumParams == 2 && FTy.getReturnType()->isPointerTy() &&
FTy.getParamType(0)->isPointerTy() &&
FTy.getParamType(1)->isPointerTy());
case LibFunc_tmpfile64:
return (FTy.getReturnType()->isPointerTy());
case LibFunc_fstat64:
case LibFunc_fstatvfs64:
return (NumParams == 2 && FTy.getParamType(1)->isPointerTy());
case LibFunc_open64:
return (NumParams >= 2 && FTy.getParamType(0)->isPointerTy());
case LibFunc_gettimeofday:
return (NumParams == 2 && FTy.getParamType(0)->isPointerTy() &&
FTy.getParamType(1)->isPointerTy());
// new(unsigned int);
case LibFunc_Znwj:
// new(unsigned long);
case LibFunc_Znwm:
// new[](unsigned int);
case LibFunc_Znaj:
// new[](unsigned long);
case LibFunc_Znam:
// new(unsigned int);
case LibFunc_msvc_new_int:
// new(unsigned long long);
case LibFunc_msvc_new_longlong:
// new[](unsigned int);
case LibFunc_msvc_new_array_int:
// new[](unsigned long long);
case LibFunc_msvc_new_array_longlong:
return (NumParams == 1 && FTy.getReturnType()->isPointerTy());
// new(unsigned int, nothrow);
case LibFunc_ZnwjRKSt9nothrow_t:
// new(unsigned long, nothrow);
case LibFunc_ZnwmRKSt9nothrow_t:
// new[](unsigned int, nothrow);
case LibFunc_ZnajRKSt9nothrow_t:
// new[](unsigned long, nothrow);
case LibFunc_ZnamRKSt9nothrow_t:
// new(unsigned int, nothrow);
case LibFunc_msvc_new_int_nothrow:
// new(unsigned long long, nothrow);
case LibFunc_msvc_new_longlong_nothrow:
// new[](unsigned int, nothrow);
case LibFunc_msvc_new_array_int_nothrow:
// new[](unsigned long long, nothrow);
case LibFunc_msvc_new_array_longlong_nothrow:
// new(unsigned int, align_val_t)
case LibFunc_ZnwjSt11align_val_t:
// new(unsigned long, align_val_t)
case LibFunc_ZnwmSt11align_val_t:
// new[](unsigned int, align_val_t)
case LibFunc_ZnajSt11align_val_t:
// new[](unsigned long, align_val_t)
case LibFunc_ZnamSt11align_val_t:
return (NumParams == 2 && FTy.getReturnType()->isPointerTy());
// new(unsigned int, align_val_t, nothrow)
case LibFunc_ZnwjSt11align_val_tRKSt9nothrow_t:
// new(unsigned long, align_val_t, nothrow)
case LibFunc_ZnwmSt11align_val_tRKSt9nothrow_t:
// new[](unsigned int, align_val_t, nothrow)
case LibFunc_ZnajSt11align_val_tRKSt9nothrow_t:
// new[](unsigned long, align_val_t, nothrow)
case LibFunc_ZnamSt11align_val_tRKSt9nothrow_t:
return (NumParams == 3 && FTy.getReturnType()->isPointerTy());
// void operator delete[](void*);
case LibFunc_ZdaPv:
// void operator delete(void*);
case LibFunc_ZdlPv:
// void operator delete[](void*);
case LibFunc_msvc_delete_array_ptr32:
// void operator delete[](void*);
case LibFunc_msvc_delete_array_ptr64:
// void operator delete(void*);
case LibFunc_msvc_delete_ptr32:
// void operator delete(void*);
case LibFunc_msvc_delete_ptr64:
return (NumParams == 1 && FTy.getParamType(0)->isPointerTy());
// void operator delete[](void*, nothrow);
case LibFunc_ZdaPvRKSt9nothrow_t:
// void operator delete[](void*, unsigned int);
case LibFunc_ZdaPvj:
// void operator delete[](void*, unsigned long);
case LibFunc_ZdaPvm:
// void operator delete(void*, nothrow);
case LibFunc_ZdlPvRKSt9nothrow_t:
// void operator delete(void*, unsigned int);
case LibFunc_ZdlPvj:
// void operator delete(void*, unsigned long);
case LibFunc_ZdlPvm:
// void operator delete(void*, align_val_t)
case LibFunc_ZdlPvSt11align_val_t:
// void operator delete[](void*, align_val_t)
case LibFunc_ZdaPvSt11align_val_t:
// void operator delete[](void*, unsigned int);
case LibFunc_msvc_delete_array_ptr32_int:
// void operator delete[](void*, nothrow);
case LibFunc_msvc_delete_array_ptr32_nothrow:
// void operator delete[](void*, unsigned long long);
case LibFunc_msvc_delete_array_ptr64_longlong:
// void operator delete[](void*, nothrow);
case LibFunc_msvc_delete_array_ptr64_nothrow:
// void operator delete(void*, unsigned int);
case LibFunc_msvc_delete_ptr32_int:
// void operator delete(void*, nothrow);
case LibFunc_msvc_delete_ptr32_nothrow:
// void operator delete(void*, unsigned long long);
case LibFunc_msvc_delete_ptr64_longlong:
// void operator delete(void*, nothrow);
case LibFunc_msvc_delete_ptr64_nothrow:
return (NumParams == 2 && FTy.getParamType(0)->isPointerTy());
// void operator delete(void*, align_val_t, nothrow)
case LibFunc_ZdlPvSt11align_val_tRKSt9nothrow_t:
// void operator delete[](void*, align_val_t, nothrow)
case LibFunc_ZdaPvSt11align_val_tRKSt9nothrow_t:
return (NumParams == 3 && FTy.getParamType(0)->isPointerTy());
case LibFunc_memset_pattern16:
return (!FTy.isVarArg() && NumParams == 3 &&
FTy.getParamType(0)->isPointerTy() &&
FTy.getParamType(1)->isPointerTy() &&
FTy.getParamType(2)->isIntegerTy());
case LibFunc_cxa_guard_abort:
case LibFunc_cxa_guard_acquire:
case LibFunc_cxa_guard_release:
case LibFunc_nvvm_reflect:
return (NumParams == 1 && FTy.getParamType(0)->isPointerTy());
case LibFunc_sincospi_stret:
case LibFunc_sincospif_stret:
return (NumParams == 1 && FTy.getParamType(0)->isFloatingPointTy());
case LibFunc_acos:
case LibFunc_acos_finite:
case LibFunc_acosf:
case LibFunc_acosf_finite:
case LibFunc_acosh:
case LibFunc_acosh_finite:
case LibFunc_acoshf:
case LibFunc_acoshf_finite:
case LibFunc_acoshl:
case LibFunc_acoshl_finite:
case LibFunc_acosl:
case LibFunc_acosl_finite:
case LibFunc_asin:
case LibFunc_asin_finite:
case LibFunc_asinf:
case LibFunc_asinf_finite:
case LibFunc_asinh:
case LibFunc_asinhf:
case LibFunc_asinhl:
case LibFunc_asinl:
case LibFunc_asinl_finite:
case LibFunc_atan:
case LibFunc_atanf:
case LibFunc_atanh:
case LibFunc_atanh_finite:
case LibFunc_atanhf:
case LibFunc_atanhf_finite:
case LibFunc_atanhl:
case LibFunc_atanhl_finite:
case LibFunc_atanl:
case LibFunc_cbrt:
case LibFunc_cbrtf:
case LibFunc_cbrtl:
case LibFunc_ceil:
case LibFunc_ceilf:
case LibFunc_ceill:
case LibFunc_cos:
case LibFunc_cosf:
case LibFunc_cosh:
case LibFunc_cosh_finite:
case LibFunc_coshf:
case LibFunc_coshf_finite:
case LibFunc_coshl:
case LibFunc_coshl_finite:
case LibFunc_cosl:
case LibFunc_exp10:
case LibFunc_exp10_finite:
case LibFunc_exp10f:
case LibFunc_exp10f_finite:
case LibFunc_exp10l:
case LibFunc_exp10l_finite:
case LibFunc_exp2:
case LibFunc_exp2_finite:
case LibFunc_exp2f:
case LibFunc_exp2f_finite:
case LibFunc_exp2l:
case LibFunc_exp2l_finite:
case LibFunc_exp:
case LibFunc_exp_finite:
case LibFunc_expf:
case LibFunc_expf_finite:
case LibFunc_expl:
case LibFunc_expl_finite:
case LibFunc_expm1:
case LibFunc_expm1f:
case LibFunc_expm1l:
case LibFunc_fabs:
case LibFunc_fabsf:
case LibFunc_fabsl:
case LibFunc_floor:
case LibFunc_floorf:
case LibFunc_floorl:
case LibFunc_log10:
case LibFunc_log10_finite:
case LibFunc_log10f:
case LibFunc_log10f_finite:
case LibFunc_log10l:
case LibFunc_log10l_finite:
case LibFunc_log1p:
case LibFunc_log1pf:
case LibFunc_log1pl:
case LibFunc_log2:
case LibFunc_log2_finite:
case LibFunc_log2f:
case LibFunc_log2f_finite:
case LibFunc_log2l:
case LibFunc_log2l_finite:
case LibFunc_log:
case LibFunc_log_finite:
case LibFunc_logb:
case LibFunc_logbf:
case LibFunc_logbl:
case LibFunc_logf:
case LibFunc_logf_finite:
case LibFunc_logl:
case LibFunc_logl_finite:
case LibFunc_nearbyint:
case LibFunc_nearbyintf:
case LibFunc_nearbyintl:
case LibFunc_rint:
case LibFunc_rintf:
case LibFunc_rintl:
case LibFunc_round:
case LibFunc_roundf:
case LibFunc_roundl:
case LibFunc_sin:
case LibFunc_sinf:
case LibFunc_sinh:
case LibFunc_sinh_finite:
case LibFunc_sinhf:
case LibFunc_sinhf_finite:
case LibFunc_sinhl:
case LibFunc_sinhl_finite:
case LibFunc_sinl:
case LibFunc_sqrt:
case LibFunc_sqrt_finite:
case LibFunc_sqrtf:
case LibFunc_sqrtf_finite:
case LibFunc_sqrtl:
case LibFunc_sqrtl_finite:
case LibFunc_tan:
case LibFunc_tanf:
case LibFunc_tanh:
case LibFunc_tanhf:
case LibFunc_tanhl:
case LibFunc_tanl:
case LibFunc_trunc:
case LibFunc_truncf:
case LibFunc_truncl:
return (NumParams == 1 && FTy.getReturnType()->isFloatingPointTy() &&
FTy.getReturnType() == FTy.getParamType(0));
case LibFunc_atan2:
case LibFunc_atan2_finite:
case LibFunc_atan2f:
case LibFunc_atan2f_finite:
case LibFunc_atan2l:
case LibFunc_atan2l_finite:
case LibFunc_fmin:
case LibFunc_fminf:
case LibFunc_fminl:
case LibFunc_fmax:
case LibFunc_fmaxf:
case LibFunc_fmaxl:
case LibFunc_fmod:
case LibFunc_fmodf:
case LibFunc_fmodl:
case LibFunc_copysign:
case LibFunc_copysignf:
case LibFunc_copysignl:
case LibFunc_pow:
case LibFunc_pow_finite:
case LibFunc_powf:
case LibFunc_powf_finite:
case LibFunc_powl:
case LibFunc_powl_finite:
return (NumParams == 2 && FTy.getReturnType()->isFloatingPointTy() &&
FTy.getReturnType() == FTy.getParamType(0) &&
FTy.getReturnType() == FTy.getParamType(1));
case LibFunc_ldexp:
case LibFunc_ldexpf:
case LibFunc_ldexpl:
return (NumParams == 2 && FTy.getReturnType()->isFloatingPointTy() &&
FTy.getReturnType() == FTy.getParamType(0) &&
FTy.getParamType(1)->isIntegerTy(32));
case LibFunc_ffs:
case LibFunc_ffsl:
case LibFunc_ffsll:
case LibFunc_fls:
case LibFunc_flsl:
case LibFunc_flsll:
return (NumParams == 1 && FTy.getReturnType()->isIntegerTy(32) &&
FTy.getParamType(0)->isIntegerTy());
case LibFunc_isdigit:
case LibFunc_isascii:
case LibFunc_toascii:
case LibFunc_putchar:
return (NumParams == 1 && FTy.getReturnType()->isIntegerTy(32) &&
FTy.getReturnType() == FTy.getParamType(0));
case LibFunc_abs:
case LibFunc_labs:
case LibFunc_llabs:
return (NumParams == 1 && FTy.getReturnType()->isIntegerTy() &&
FTy.getReturnType() == FTy.getParamType(0));
case LibFunc_cxa_atexit:
return (NumParams == 3 && FTy.getReturnType()->isIntegerTy() &&
FTy.getParamType(0)->isPointerTy() &&
FTy.getParamType(1)->isPointerTy() &&
FTy.getParamType(2)->isPointerTy());
case LibFunc_sinpi:
case LibFunc_cospi:
return (NumParams == 1 && FTy.getReturnType()->isDoubleTy() &&
FTy.getReturnType() == FTy.getParamType(0));
case LibFunc_sinpif:
case LibFunc_cospif:
return (NumParams == 1 && FTy.getReturnType()->isFloatTy() &&
FTy.getReturnType() == FTy.getParamType(0));
case LibFunc_strnlen:
return (NumParams == 2 && FTy.getReturnType() == FTy.getParamType(1) &&
FTy.getParamType(0) == PCharTy &&
FTy.getParamType(1) == SizeTTy);
case LibFunc_posix_memalign:
return (NumParams == 3 && FTy.getReturnType()->isIntegerTy(32) &&
FTy.getParamType(0)->isPointerTy() &&
FTy.getParamType(1) == SizeTTy && FTy.getParamType(2) == SizeTTy);
case LibFunc_wcslen:
return (NumParams == 1 && FTy.getParamType(0)->isPointerTy() &&
FTy.getReturnType()->isIntegerTy());
case LibFunc_cabs:
case LibFunc_cabsf:
case LibFunc_cabsl: {
Type* RetTy = FTy.getReturnType();
if (!RetTy->isFloatingPointTy())
return false;
// NOTE: These prototypes are target specific and currently support
// "complex" passed as an array or discrete real & imaginary parameters.
// Add other calling conventions to enable libcall optimizations.
if (NumParams == 1)
return (FTy.getParamType(0)->isArrayTy() &&
FTy.getParamType(0)->getArrayNumElements() == 2 &&
FTy.getParamType(0)->getArrayElementType() == RetTy);
else if (NumParams == 2)
return (FTy.getParamType(0) == RetTy && FTy.getParamType(1) == RetTy);
else
return false;
}
case LibFunc::NumLibFuncs:
break;
}
llvm_unreachable("Invalid libfunc");
}
bool TargetLibraryInfoImpl::getLibFunc(const Function &FDecl,
LibFunc &F) const {
const DataLayout *DL =
FDecl.getParent() ? &FDecl.getParent()->getDataLayout() : nullptr;
return getLibFunc(FDecl.getName(), F) &&
isValidProtoForLibFunc(*FDecl.getFunctionType(), F, DL);
}
void TargetLibraryInfoImpl::disableAllFunctions() {
memset(AvailableArray, 0, sizeof(AvailableArray));
}
static bool compareByScalarFnName(const VecDesc &LHS, const VecDesc &RHS) {
return LHS.ScalarFnName < RHS.ScalarFnName;
}
static bool compareByVectorFnName(const VecDesc &LHS, const VecDesc &RHS) {
return LHS.VectorFnName < RHS.VectorFnName;
}
static bool compareWithScalarFnName(const VecDesc &LHS, StringRef S) {
return LHS.ScalarFnName < S;
}
static bool compareWithVectorFnName(const VecDesc &LHS, StringRef S) {
return LHS.VectorFnName < S;
}
void TargetLibraryInfoImpl::addVectorizableFunctions(ArrayRef<VecDesc> Fns) {
VectorDescs.insert(VectorDescs.end(), Fns.begin(), Fns.end());
llvm::sort(VectorDescs.begin(), VectorDescs.end(), compareByScalarFnName);
ScalarDescs.insert(ScalarDescs.end(), Fns.begin(), Fns.end());
llvm::sort(ScalarDescs.begin(), ScalarDescs.end(), compareByVectorFnName);
}
void TargetLibraryInfoImpl::addVectorizableFunctionsFromVecLib(
enum VectorLibrary VecLib) {
switch (VecLib) {
case Accelerate: {
const VecDesc VecFuncs[] = {
// Floating-Point Arithmetic and Auxiliary Functions
{"ceilf", "vceilf", 4},
{"fabsf", "vfabsf", 4},
{"llvm.fabs.f32", "vfabsf", 4},
{"floorf", "vfloorf", 4},
{"sqrtf", "vsqrtf", 4},
{"llvm.sqrt.f32", "vsqrtf", 4},
// Exponential and Logarithmic Functions
{"expf", "vexpf", 4},
{"llvm.exp.f32", "vexpf", 4},
{"expm1f", "vexpm1f", 4},
{"logf", "vlogf", 4},
{"llvm.log.f32", "vlogf", 4},
{"log1pf", "vlog1pf", 4},
{"log10f", "vlog10f", 4},
{"llvm.log10.f32", "vlog10f", 4},
{"logbf", "vlogbf", 4},
// Trigonometric Functions
{"sinf", "vsinf", 4},
{"llvm.sin.f32", "vsinf", 4},
{"cosf", "vcosf", 4},
{"llvm.cos.f32", "vcosf", 4},
{"tanf", "vtanf", 4},
{"asinf", "vasinf", 4},
{"acosf", "vacosf", 4},
{"atanf", "vatanf", 4},
// Hyperbolic Functions
{"sinhf", "vsinhf", 4},
{"coshf", "vcoshf", 4},
{"tanhf", "vtanhf", 4},
{"asinhf", "vasinhf", 4},
{"acoshf", "vacoshf", 4},
{"atanhf", "vatanhf", 4},
};
addVectorizableFunctions(VecFuncs);
break;
}
case SVML: {
const VecDesc VecFuncs[] = {
{"sin", "__svml_sin2", 2},
{"sin", "__svml_sin4", 4},
{"sin", "__svml_sin8", 8},
{"sinf", "__svml_sinf4", 4},
{"sinf", "__svml_sinf8", 8},
{"sinf", "__svml_sinf16", 16},
{"cos", "__svml_cos2", 2},
{"cos", "__svml_cos4", 4},
{"cos", "__svml_cos8", 8},
{"cosf", "__svml_cosf4", 4},
{"cosf", "__svml_cosf8", 8},
{"cosf", "__svml_cosf16", 16},
{"pow", "__svml_pow2", 2},
{"pow", "__svml_pow4", 4},
{"pow", "__svml_pow8", 8},
{"powf", "__svml_powf4", 4},
{"powf", "__svml_powf8", 8},
{"powf", "__svml_powf16", 16},
{ "__pow_finite", "__svml_pow2", 2 },
{ "__pow_finite", "__svml_pow4", 4 },
{ "__pow_finite", "__svml_pow8", 8 },
{ "__powf_finite", "__svml_powf4", 4 },
{ "__powf_finite", "__svml_powf8", 8 },
{ "__powf_finite", "__svml_powf16", 16 },
{"llvm.pow.f64", "__svml_pow2", 2},
{"llvm.pow.f64", "__svml_pow4", 4},
{"llvm.pow.f64", "__svml_pow8", 8},
{"llvm.pow.f32", "__svml_powf4", 4},
{"llvm.pow.f32", "__svml_powf8", 8},
{"llvm.pow.f32", "__svml_powf16", 16},
{"exp", "__svml_exp2", 2},
{"exp", "__svml_exp4", 4},
{"exp", "__svml_exp8", 8},
{"expf", "__svml_expf4", 4},
{"expf", "__svml_expf8", 8},
{"expf", "__svml_expf16", 16},
{ "__exp_finite", "__svml_exp2", 2 },
{ "__exp_finite", "__svml_exp4", 4 },
{ "__exp_finite", "__svml_exp8", 8 },
{ "__expf_finite", "__svml_expf4", 4 },
{ "__expf_finite", "__svml_expf8", 8 },
{ "__expf_finite", "__svml_expf16", 16 },
{"llvm.exp.f64", "__svml_exp2", 2},
{"llvm.exp.f64", "__svml_exp4", 4},
{"llvm.exp.f64", "__svml_exp8", 8},
{"llvm.exp.f32", "__svml_expf4", 4},
{"llvm.exp.f32", "__svml_expf8", 8},
{"llvm.exp.f32", "__svml_expf16", 16},
{"log", "__svml_log2", 2},
{"log", "__svml_log4", 4},
{"log", "__svml_log8", 8},
{"logf", "__svml_logf4", 4},
{"logf", "__svml_logf8", 8},
{"logf", "__svml_logf16", 16},
{ "__log_finite", "__svml_log2", 2 },
{ "__log_finite", "__svml_log4", 4 },
{ "__log_finite", "__svml_log8", 8 },
{ "__logf_finite", "__svml_logf4", 4 },
{ "__logf_finite", "__svml_logf8", 8 },
{ "__logf_finite", "__svml_logf16", 16 },
{"llvm.log.f64", "__svml_log2", 2},
{"llvm.log.f64", "__svml_log4", 4},
{"llvm.log.f64", "__svml_log8", 8},
{"llvm.log.f32", "__svml_logf4", 4},
{"llvm.log.f32", "__svml_logf8", 8},
{"llvm.log.f32", "__svml_logf16", 16},
};
addVectorizableFunctions(VecFuncs);
break;
}
case NoLibrary:
break;
}
}
bool TargetLibraryInfoImpl::isFunctionVectorizable(StringRef funcName) const {
funcName = sanitizeFunctionName(funcName);
if (funcName.empty())
return false;
std::vector<VecDesc>::const_iterator I = std::lower_bound(
VectorDescs.begin(), VectorDescs.end(), funcName,
compareWithScalarFnName);
return I != VectorDescs.end() && StringRef(I->ScalarFnName) == funcName;
}
StringRef TargetLibraryInfoImpl::getVectorizedFunction(StringRef F,
unsigned VF) const {
F = sanitizeFunctionName(F);
if (F.empty())
return F;
std::vector<VecDesc>::const_iterator I = std::lower_bound(
VectorDescs.begin(), VectorDescs.end(), F, compareWithScalarFnName);
while (I != VectorDescs.end() && StringRef(I->ScalarFnName) == F) {
if (I->VectorizationFactor == VF)
return I->VectorFnName;
++I;
}
return StringRef();
}
StringRef TargetLibraryInfoImpl::getScalarizedFunction(StringRef F,
unsigned &VF) const {
F = sanitizeFunctionName(F);
if (F.empty())
return F;
std::vector<VecDesc>::const_iterator I = std::lower_bound(
ScalarDescs.begin(), ScalarDescs.end(), F, compareWithVectorFnName);
if (I == VectorDescs.end() || StringRef(I->VectorFnName) != F)
return StringRef();
VF = I->VectorizationFactor;
return I->ScalarFnName;
}
TargetLibraryInfo TargetLibraryAnalysis::run(Module &M,
ModuleAnalysisManager &) {
if (PresetInfoImpl)
return TargetLibraryInfo(*PresetInfoImpl);
return TargetLibraryInfo(lookupInfoImpl(Triple(M.getTargetTriple())));
}
TargetLibraryInfo TargetLibraryAnalysis::run(Function &F,
FunctionAnalysisManager &) {
if (PresetInfoImpl)
return TargetLibraryInfo(*PresetInfoImpl);
return TargetLibraryInfo(
lookupInfoImpl(Triple(F.getParent()->getTargetTriple())));
}
TargetLibraryInfoImpl &TargetLibraryAnalysis::lookupInfoImpl(const Triple &T) {
std::unique_ptr<TargetLibraryInfoImpl> &Impl =
Impls[T.normalize()];
if (!Impl)
Impl.reset(new TargetLibraryInfoImpl(T));
return *Impl;
}
unsigned TargetLibraryInfoImpl::getWCharSize(const Module &M) const {
if (auto *ShortWChar = cast_or_null<ConstantAsMetadata>(
M.getModuleFlag("wchar_size")))
return cast<ConstantInt>(ShortWChar->getValue())->getZExtValue();
return 0;
}
TargetLibraryInfoWrapperPass::TargetLibraryInfoWrapperPass()
: ImmutablePass(ID), TLIImpl(), TLI(TLIImpl) {
initializeTargetLibraryInfoWrapperPassPass(*PassRegistry::getPassRegistry());
}
TargetLibraryInfoWrapperPass::TargetLibraryInfoWrapperPass(const Triple &T)
: ImmutablePass(ID), TLIImpl(T), TLI(TLIImpl) {
initializeTargetLibraryInfoWrapperPassPass(*PassRegistry::getPassRegistry());
}
TargetLibraryInfoWrapperPass::TargetLibraryInfoWrapperPass(
const TargetLibraryInfoImpl &TLIImpl)
: ImmutablePass(ID), TLIImpl(TLIImpl), TLI(this->TLIImpl) {
initializeTargetLibraryInfoWrapperPassPass(*PassRegistry::getPassRegistry());
}
AnalysisKey TargetLibraryAnalysis::Key;
// Register the basic pass.
INITIALIZE_PASS(TargetLibraryInfoWrapperPass, "targetlibinfo",
"Target Library Information", false, true)
char TargetLibraryInfoWrapperPass::ID = 0;
void TargetLibraryInfoWrapperPass::anchor() {}
|
/*=============================================================================
Library: CTK
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics
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 "ctkCMPluginManager_p.h"
#include <ctkServiceTracker.h>
#include <service/cm/ctkConfigurationPlugin.h>
#include <QStringList>
#include <set>
struct _PluginTrackerCompare
{
bool operator() (const ctkServiceReference& l, const ctkServiceReference& r) const
{
return getRank(l) < getRank(r);
}
int getRank(const ctkServiceReference& ref) const
{
QVariant ranking = ref.getProperty(ctkConfigurationPlugin::CM_RANKING);
if (!ranking.isValid() || !(ranking.canConvert<int>()))
return 0;
return ranking.toInt();
}
};
class _PluginTracker : public ctkServiceTracker<ctkConfigurationPlugin*>
{
mutable QMutex mutex;
typedef std::set<ctkServiceReference, _PluginTrackerCompare> ServiceRefContainer;
ServiceRefContainer serviceReferences;
ctkPluginContext* context;
public:
_PluginTracker(ctkPluginContext* context)
: ctkServiceTracker<ctkConfigurationPlugin*>(context),
context(context)
{
}
QList<ctkServiceReference> getServiceReferences() const
{
QMutexLocker lock(&mutex);
QList<ctkServiceReference> refs;
ServiceRefContainer::const_iterator refEnd = serviceReferences.end();
for (ServiceRefContainer::const_iterator it = serviceReferences.begin();
it != refEnd; ++it)
{
refs.push_back(*it);
}
return refs;
}
ctkConfigurationPlugin* addingService(const ctkServiceReference& reference)
{
QMutexLocker lock(&mutex);
serviceReferences.insert(reference);
return context->getService<ctkConfigurationPlugin>(reference);
}
void modifiedService(const ctkServiceReference& reference, ctkConfigurationPlugin* service)
{
Q_UNUSED(reference)
Q_UNUSED(service)
// nothing to do
}
void removedService(const ctkServiceReference& reference, ctkConfigurationPlugin* service)
{
Q_UNUSED(service)
QMutexLocker lock(&mutex);
serviceReferences.erase(reference);
context->ungetService(reference);
}
};
ctkCMPluginManager::ctkCMPluginManager(ctkPluginContext* context)
{
pluginTracker.reset(new _PluginTracker(context));
}
ctkCMPluginManager::~ctkCMPluginManager()
{
}
void ctkCMPluginManager::start()
{
pluginTracker->open();
}
void ctkCMPluginManager::stop()
{
pluginTracker->close();
}
void ctkCMPluginManager::modifyConfiguration(const ctkServiceReference& managedReference, ctkDictionary& properties)
{
if (properties.empty())
return;
QList<ctkServiceReference> references = pluginTracker->getServiceReferences();
foreach(ctkServiceReference ref, references)
{
QVariant pids = ref.getProperty(ctkConfigurationPlugin::CM_TARGET);
if (pids.isValid() && pids.canConvert<QStringList>())
{
QString pid = properties.value(ctkPluginConstants::SERVICE_PID).toString();
if (!pids.toStringList().contains(pid))
continue;
}
ctkConfigurationPlugin* plugin = pluginTracker->getService(ref);
if (plugin != 0)
plugin->modifyConfiguration(managedReference, properties);
}
}
|
/*
Source File : PDFStreamInput.cpp
Copyright 2011 Gal Kahana PDFWriter
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 "objects/PDFStreamInput.h"
#include "objects/PDFDictionary.h"
#include "objects/PDFName.h"
#include <utility>
charta::PDFStreamInput::PDFStreamInput(std::shared_ptr<charta::PDFDictionary> inStreamDictionary,
long long inStreamContentStart)
: PDFObject(eType)
{
mDictionary = std::move(inStreamDictionary);
mStreamContentStart = inStreamContentStart;
}
std::shared_ptr<charta::PDFDictionary> charta::PDFStreamInput::QueryStreamDictionary()
{
return mDictionary;
}
long long charta::PDFStreamInput::GetStreamContentStart() const
{
return mStreamContentStart;
}
|
/*
* Author : Siddhant Khare
*/
#include <bits/stdc++.h>
using namespace std;
/******* All Required define Pre-Processors and typedef Constants *******/
#define ll long long
#define ld long double
#define arr array
#define si(t) scanf("%d", &t)
#define sl(t) scanf("%ld", &t)
#define sll(t) scanf("%lld", &t)
#define sc(t) scanf("%c", &t)
#define ss(t) scanf("%s", &t)
#define sf(t) scanf("%f", &t)
#define slf(t) scanf("%lf", &t)
#define pi(x) printf("%d\n", x)
#define pl(x) printf("%ld\n", x)
#define pll(x) printf("%lld\n", x)
#define pf(x) printf("%f")
#define sz(x) (int)(x).size()
#define mem(a, b) memset(a, (b), sizeof(a))
#define FOR(i, j, k, in) for (int i = j; i < k; i += in)
#define RFOR(i, j, k, in) for (int i = j; i >= k; i -= in)
#define REP(i, j) FOR(i, 0, j, 1)
#define RREP(i, j) RFOR(i, j, 0, 1)
#define all(x) x.begin(), x.end()
#define rall(cont) cont.end(), cont.begin()
#define FOREACH(it, l) for (auto it = l.begin(); it != l.end(); it++)
#define IN(A, B, C) assert(B <= A && A <= C)
#define sortall(x) sort(all(x))
#define mp make_pair
#define pb push_back
#define INF (int)1e9
#define EPS 1e-9
#define PI 3.1415926535897932384626433832795
#define MOD 1000000007
#define read(type) readInt<type>()
const double pi = acos(-1.0);
typedef pair<int, int> PII;
typedef vector<int> VI;
typedef vector<string> VS;
typedef vector<PII> VII;
typedef vector<VI> VVI;
typedef map<int, int> MPII;
typedef set<int> SETI;
typedef multiset<int> MSETI;
/**************************************/
/******** User-defined Function *******/
void solve()
{
ll a, b, c, d;
scanf("%lld%lld%lld%lld", &a, &b, &c, &d);
// Algorithm
// Output
// pll(ans) // long long print
}
/**************************************/
/********** Main() function **********/
int main()
{
// freopen("input.txt","r",stdin);
// freopen("output.txt","w",stdout);
int x;
cin >> x;
if (x == 0) {
cout << "1";
} else {
cout << "0";
}
}
/******** Main() Ends Here *************/
|
// Copyright 2018 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 "third_party/blink/renderer/modules/webgpu/gpu_device.h"
#include "gpu/command_buffer/client/webgpu_interface.h"
#include "third_party/blink/public/platform/platform.h"
#include "third_party/blink/renderer/bindings/core/v8/script_promise_resolver.h"
#include "third_party/blink/renderer/bindings/modules/v8/v8_gpu_compute_pipeline_descriptor.h"
#include "third_party/blink/renderer/bindings/modules/v8/v8_gpu_device_descriptor.h"
#include "third_party/blink/renderer/bindings/modules/v8/v8_gpu_external_texture_descriptor.h"
#include "third_party/blink/renderer/bindings/modules/v8/v8_gpu_feature_name.h"
#include "third_party/blink/renderer/bindings/modules/v8/v8_gpu_render_pipeline_descriptor.h"
#include "third_party/blink/renderer/bindings/modules/v8/v8_gpu_uncaptured_error_event_init.h"
#include "third_party/blink/renderer/bindings/modules/v8/v8_union_gpuoutofmemoryerror_gpuvalidationerror.h"
#include "third_party/blink/renderer/core/dom/dom_exception.h"
#include "third_party/blink/renderer/core/inspector/console_message.h"
#include "third_party/blink/renderer/modules/event_target_modules.h"
#include "third_party/blink/renderer/modules/webgpu/dawn_conversions.h"
#include "third_party/blink/renderer/modules/webgpu/gpu_adapter.h"
#include "third_party/blink/renderer/modules/webgpu/gpu_bind_group.h"
#include "third_party/blink/renderer/modules/webgpu/gpu_bind_group_layout.h"
#include "third_party/blink/renderer/modules/webgpu/gpu_buffer.h"
#include "third_party/blink/renderer/modules/webgpu/gpu_command_encoder.h"
#include "third_party/blink/renderer/modules/webgpu/gpu_compute_pipeline.h"
#include "third_party/blink/renderer/modules/webgpu/gpu_device_lost_info.h"
#include "third_party/blink/renderer/modules/webgpu/gpu_external_texture.h"
#include "third_party/blink/renderer/modules/webgpu/gpu_out_of_memory_error.h"
#include "third_party/blink/renderer/modules/webgpu/gpu_pipeline_layout.h"
#include "third_party/blink/renderer/modules/webgpu/gpu_query_set.h"
#include "third_party/blink/renderer/modules/webgpu/gpu_queue.h"
#include "third_party/blink/renderer/modules/webgpu/gpu_render_bundle_encoder.h"
#include "third_party/blink/renderer/modules/webgpu/gpu_render_pipeline.h"
#include "third_party/blink/renderer/modules/webgpu/gpu_sampler.h"
#include "third_party/blink/renderer/modules/webgpu/gpu_shader_module.h"
#include "third_party/blink/renderer/modules/webgpu/gpu_supported_features.h"
#include "third_party/blink/renderer/modules/webgpu/gpu_supported_limits.h"
#include "third_party/blink/renderer/modules/webgpu/gpu_texture.h"
#include "third_party/blink/renderer/modules/webgpu/gpu_uncaptured_error_event.h"
#include "third_party/blink/renderer/modules/webgpu/gpu_validation_error.h"
#include "third_party/blink/renderer/platform/bindings/microtask.h"
#include "third_party/blink/renderer/platform/graphics/gpu/webgpu_image_bitmap_handler.h"
namespace blink {
namespace {
Vector<String> ToStringVector(const Vector<V8GPUFeatureName>& features) {
Vector<String> str_features;
for (auto&& feature : features)
str_features.push_back(IDLEnumAsString(feature));
return str_features;
}
} // anonymous namespace
// TODO(enga): Handle adapter options and device descriptor
GPUDevice::GPUDevice(ExecutionContext* execution_context,
scoped_refptr<DawnControlClientHolder> dawn_control_client,
GPUAdapter* adapter,
WGPUDevice dawn_device,
const WGPUSupportedLimits* limits,
const GPUDeviceDescriptor* descriptor)
: ExecutionContextClient(execution_context),
DawnObject(dawn_control_client, dawn_device),
adapter_(adapter),
features_(MakeGarbageCollected<GPUSupportedFeatures>(
ToStringVector(descriptor->requiredFeatures()))),
queue_(MakeGarbageCollected<GPUQueue>(
this,
GetProcs().deviceGetQueue(GetHandle()))),
lost_property_(MakeGarbageCollected<LostProperty>(execution_context)),
error_callback_(BindDawnRepeatingCallback(&GPUDevice::OnUncapturedError,
WrapWeakPersistent(this))),
logging_callback_(BindDawnRepeatingCallback(&GPUDevice::OnLogging,
WrapWeakPersistent(this))),
// Note: This is a *repeating* callback even though we expect it to only
// be called once. This is because it may be called *zero* times.
// Because it might never be called, the GPUDevice needs to own the
// allocation so it can be appropriately freed on destruction. Thus, the
// callback should not be a OnceCallback which self-deletes after it is
// called.
lost_callback_(BindDawnRepeatingCallback(&GPUDevice::OnDeviceLostError,
WrapWeakPersistent(this))) {
DCHECK(dawn_device);
DCHECK(limits);
limits_ = MakeGarbageCollected<GPUSupportedLimits>(*limits);
GetProcs().deviceSetUncapturedErrorCallback(
GetHandle(), error_callback_->UnboundCallback(),
error_callback_->AsUserdata());
GetProcs().deviceSetLoggingCallback(GetHandle(),
logging_callback_->UnboundCallback(),
logging_callback_->AsUserdata());
GetProcs().deviceSetDeviceLostCallback(GetHandle(),
lost_callback_->UnboundCallback(),
lost_callback_->AsUserdata());
if (descriptor->hasLabel())
setLabel(descriptor->label());
}
GPUDevice::~GPUDevice() {
// Clear the callbacks since we can't handle callbacks after finalization.
// error_callback_, logging_callback_, and lost_callback_ will be deleted.
GetProcs().deviceSetUncapturedErrorCallback(GetHandle(), nullptr, nullptr);
GetProcs().deviceSetLoggingCallback(GetHandle(), nullptr, nullptr);
GetProcs().deviceSetDeviceLostCallback(GetHandle(), nullptr, nullptr);
}
void GPUDevice::InjectError(WGPUErrorType type, const char* message) {
GetProcs().deviceInjectError(GetHandle(), type, message);
}
void GPUDevice::AddConsoleWarning(const char* message) {
ExecutionContext* execution_context = GetExecutionContext();
if (execution_context && allowed_console_warnings_remaining_ > 0) {
auto* console_message = MakeGarbageCollected<ConsoleMessage>(
mojom::blink::ConsoleMessageSource::kRendering,
mojom::blink::ConsoleMessageLevel::kWarning, message);
execution_context->AddConsoleMessage(console_message);
allowed_console_warnings_remaining_--;
if (allowed_console_warnings_remaining_ == 0) {
auto* final_message = MakeGarbageCollected<ConsoleMessage>(
mojom::blink::ConsoleMessageSource::kRendering,
mojom::blink::ConsoleMessageLevel::kWarning,
"WebGPU: too many warnings, no more warnings will be reported to the "
"console for this GPUDevice.");
execution_context->AddConsoleMessage(final_message);
}
}
}
void GPUDevice::OnUncapturedError(WGPUErrorType errorType,
const char* message) {
DCHECK_NE(errorType, WGPUErrorType_NoError);
DCHECK_NE(errorType, WGPUErrorType_DeviceLost);
LOG(ERROR) << "GPUDevice: " << message;
AddConsoleWarning(message);
GPUUncapturedErrorEventInit* init = GPUUncapturedErrorEventInit::Create();
if (errorType == WGPUErrorType_Validation) {
init->setError(
MakeGarbageCollected<V8UnionGPUOutOfMemoryErrorOrGPUValidationError>(
MakeGarbageCollected<GPUValidationError>(message)));
} else if (errorType == WGPUErrorType_OutOfMemory) {
init->setError(
MakeGarbageCollected<V8UnionGPUOutOfMemoryErrorOrGPUValidationError>(
GPUOutOfMemoryError::Create()));
} else {
return;
}
DispatchEvent(*GPUUncapturedErrorEvent::Create(
event_type_names::kUncapturederror, init));
}
void GPUDevice::OnLogging(WGPULoggingType loggingType, const char* message) {
// Callback function for WebGPU logging return command
mojom::blink::ConsoleMessageLevel level;
switch (loggingType) {
case (WGPULoggingType_Verbose): {
level = mojom::blink::ConsoleMessageLevel::kVerbose;
break;
}
case (WGPULoggingType_Info): {
level = mojom::blink::ConsoleMessageLevel::kInfo;
break;
}
case (WGPULoggingType_Warning): {
level = mojom::blink::ConsoleMessageLevel::kWarning;
break;
}
case (WGPULoggingType_Error): {
level = mojom::blink::ConsoleMessageLevel::kError;
break;
}
default: {
level = mojom::blink::ConsoleMessageLevel::kError;
break;
}
}
ExecutionContext* execution_context = GetExecutionContext();
if (execution_context) {
auto* console_message = MakeGarbageCollected<ConsoleMessage>(
mojom::blink::ConsoleMessageSource::kRendering, level, message);
execution_context->AddConsoleMessage(console_message);
}
}
void GPUDevice::OnDeviceLostError(WGPUDeviceLostReason, const char* message) {
if (!GetExecutionContext())
return;
AddConsoleWarning(message);
if (lost_property_->GetState() == LostProperty::kPending) {
// TODO(crbug.com/1253721): Add the `reason` attribute to GPUDeviceLostInfo.
auto* device_lost_info = MakeGarbageCollected<GPUDeviceLostInfo>(message);
lost_property_->Resolve(device_lost_info);
}
}
void GPUDevice::OnCreateRenderPipelineAsyncCallback(
ScriptPromiseResolver* resolver,
WGPUCreatePipelineAsyncStatus status,
WGPURenderPipeline render_pipeline,
const char* message) {
switch (status) {
case WGPUCreatePipelineAsyncStatus_Success: {
resolver->Resolve(
MakeGarbageCollected<GPURenderPipeline>(this, render_pipeline));
break;
}
case WGPUCreatePipelineAsyncStatus_Error:
case WGPUCreatePipelineAsyncStatus_DeviceLost:
case WGPUCreatePipelineAsyncStatus_DeviceDestroyed:
case WGPUCreatePipelineAsyncStatus_Unknown: {
resolver->Reject(MakeGarbageCollected<DOMException>(
DOMExceptionCode::kOperationError, message));
break;
}
default: {
NOTREACHED();
}
}
}
void GPUDevice::OnCreateComputePipelineAsyncCallback(
ScriptPromiseResolver* resolver,
WGPUCreatePipelineAsyncStatus status,
WGPUComputePipeline compute_pipeline,
const char* message) {
switch (status) {
case WGPUCreatePipelineAsyncStatus_Success: {
resolver->Resolve(
MakeGarbageCollected<GPUComputePipeline>(this, compute_pipeline));
break;
}
case WGPUCreatePipelineAsyncStatus_Error:
case WGPUCreatePipelineAsyncStatus_DeviceLost:
case WGPUCreatePipelineAsyncStatus_DeviceDestroyed:
case WGPUCreatePipelineAsyncStatus_Unknown: {
resolver->Reject(MakeGarbageCollected<DOMException>(
DOMExceptionCode::kOperationError, message));
break;
}
default: {
NOTREACHED();
}
}
}
GPUAdapter* GPUDevice::adapter() const {
return adapter_;
}
GPUSupportedFeatures* GPUDevice::features() const {
return features_;
}
ScriptPromise GPUDevice::lost(ScriptState* script_state) {
return lost_property_->Promise(script_state->World());
}
GPUQueue* GPUDevice::queue() {
return queue_;
}
GPUBuffer* GPUDevice::createBuffer(const GPUBufferDescriptor* descriptor) {
return GPUBuffer::Create(this, descriptor);
}
GPUTexture* GPUDevice::createTexture(const GPUTextureDescriptor* descriptor,
ExceptionState& exception_state) {
return GPUTexture::Create(this, descriptor, exception_state);
}
GPUTexture* GPUDevice::experimentalImportTexture(
HTMLCanvasElement* canvas,
unsigned int usage_flags,
ExceptionState& exception_state) {
return GPUTexture::FromCanvas(this, canvas,
static_cast<WGPUTextureUsage>(usage_flags),
exception_state);
}
GPUSampler* GPUDevice::createSampler(const GPUSamplerDescriptor* descriptor) {
return GPUSampler::Create(this, descriptor);
}
GPUExternalTexture* GPUDevice::importExternalTexture(
const GPUExternalTextureDescriptor* descriptor,
ExceptionState& exception_state) {
GPUExternalTexture* externalTexture =
GPUExternalTexture::FromVideo(this, descriptor, exception_state);
if (externalTexture)
EnsureExternalTextureDestroyed(externalTexture);
return externalTexture;
}
GPUBindGroup* GPUDevice::createBindGroup(
const GPUBindGroupDescriptor* descriptor,
ExceptionState& exception_state) {
return GPUBindGroup::Create(this, descriptor, exception_state);
}
GPUBindGroupLayout* GPUDevice::createBindGroupLayout(
const GPUBindGroupLayoutDescriptor* descriptor,
ExceptionState& exception_state) {
return GPUBindGroupLayout::Create(this, descriptor, exception_state);
}
GPUPipelineLayout* GPUDevice::createPipelineLayout(
const GPUPipelineLayoutDescriptor* descriptor) {
return GPUPipelineLayout::Create(this, descriptor);
}
GPUShaderModule* GPUDevice::createShaderModule(
const GPUShaderModuleDescriptor* descriptor,
ExceptionState& exception_state) {
return GPUShaderModule::Create(this, descriptor, exception_state);
}
GPURenderPipeline* GPUDevice::createRenderPipeline(
ScriptState* script_state,
const GPURenderPipelineDescriptor* descriptor) {
return GPURenderPipeline::Create(script_state, this, descriptor);
}
GPUComputePipeline* GPUDevice::createComputePipeline(
const GPUComputePipelineDescriptor* descriptor,
ExceptionState& exception_state) {
return GPUComputePipeline::Create(this, descriptor);
}
ScriptPromise GPUDevice::createRenderPipelineAsync(
ScriptState* script_state,
const GPURenderPipelineDescriptor* descriptor) {
auto* resolver = MakeGarbageCollected<ScriptPromiseResolver>(script_state);
ScriptPromise promise = resolver->Promise();
v8::Isolate* isolate = script_state->GetIsolate();
ExceptionState exception_state(isolate, ExceptionState::kExecutionContext,
"GPUDevice", "createRenderPipelineAsync");
OwnedRenderPipelineDescriptor dawn_desc_info;
ConvertToDawnType(isolate, this, descriptor, &dawn_desc_info,
exception_state);
if (exception_state.HadException()) {
resolver->Reject(exception_state);
} else {
auto* callback =
BindDawnOnceCallback(&GPUDevice::OnCreateRenderPipelineAsyncCallback,
WrapPersistent(this), WrapPersistent(resolver));
GetProcs().deviceCreateRenderPipelineAsync(
GetHandle(), &dawn_desc_info.dawn_desc, callback->UnboundCallback(),
callback->AsUserdata());
}
// WebGPU guarantees that promises are resolved in finite time so we need to
// ensure commands are flushed.
EnsureFlush();
return promise;
}
ScriptPromise GPUDevice::createComputePipelineAsync(
ScriptState* script_state,
const GPUComputePipelineDescriptor* descriptor) {
auto* resolver = MakeGarbageCollected<ScriptPromiseResolver>(script_state);
ScriptPromise promise = resolver->Promise();
std::string label;
OwnedProgrammableStageDescriptor computeStageDescriptor;
WGPUComputePipelineDescriptor dawn_desc =
AsDawnType(descriptor, &label, &computeStageDescriptor, this);
auto* callback =
BindDawnOnceCallback(&GPUDevice::OnCreateComputePipelineAsyncCallback,
WrapPersistent(this), WrapPersistent(resolver));
GetProcs().deviceCreateComputePipelineAsync(GetHandle(), &dawn_desc,
callback->UnboundCallback(),
callback->AsUserdata());
// WebGPU guarantees that promises are resolved in finite time so we need to
// ensure commands are flushed.
EnsureFlush();
return promise;
}
GPUCommandEncoder* GPUDevice::createCommandEncoder(
const GPUCommandEncoderDescriptor* descriptor) {
return GPUCommandEncoder::Create(this, descriptor);
}
GPURenderBundleEncoder* GPUDevice::createRenderBundleEncoder(
const GPURenderBundleEncoderDescriptor* descriptor) {
return GPURenderBundleEncoder::Create(this, descriptor);
}
GPUQuerySet* GPUDevice::createQuerySet(
const GPUQuerySetDescriptor* descriptor) {
return GPUQuerySet::Create(this, descriptor);
}
void GPUDevice::pushErrorScope(const WTF::String& filter) {
GetProcs().devicePushErrorScope(GetHandle(),
AsDawnEnum<WGPUErrorFilter>(filter));
}
ScriptPromise GPUDevice::popErrorScope(ScriptState* script_state) {
ScriptPromiseResolver* resolver =
MakeGarbageCollected<ScriptPromiseResolver>(script_state);
ScriptPromise promise = resolver->Promise();
auto* callback =
BindDawnOnceCallback(&GPUDevice::OnPopErrorScopeCallback,
WrapPersistent(this), WrapPersistent(resolver));
if (!GetProcs().devicePopErrorScope(GetHandle(), callback->UnboundCallback(),
callback->AsUserdata())) {
resolver->Reject(MakeGarbageCollected<DOMException>(
DOMExceptionCode::kOperationError, "No error scopes to pop."));
delete callback;
return promise;
}
// WebGPU guarantees that promises are resolved in finite time so we
// need to ensure commands are flushed.
EnsureFlush();
return promise;
}
void GPUDevice::OnPopErrorScopeCallback(ScriptPromiseResolver* resolver,
WGPUErrorType type,
const char* message) {
v8::Isolate* isolate = resolver->GetScriptState()->GetIsolate();
switch (type) {
case WGPUErrorType_NoError:
resolver->Resolve(v8::Null(isolate));
break;
case WGPUErrorType_OutOfMemory:
resolver->Resolve(GPUOutOfMemoryError::Create());
break;
case WGPUErrorType_Validation:
resolver->Resolve(MakeGarbageCollected<GPUValidationError>(message));
break;
case WGPUErrorType_Unknown:
case WGPUErrorType_DeviceLost:
resolver->Reject(MakeGarbageCollected<DOMException>(
DOMExceptionCode::kOperationError));
break;
default:
NOTREACHED();
}
}
ExecutionContext* GPUDevice::GetExecutionContext() const {
return ExecutionContextClient::GetExecutionContext();
}
const AtomicString& GPUDevice::InterfaceName() const {
return event_target_names::kGPUDevice;
}
void GPUDevice::Trace(Visitor* visitor) const {
visitor->Trace(adapter_);
visitor->Trace(features_);
visitor->Trace(limits_);
visitor->Trace(queue_);
visitor->Trace(lost_property_);
visitor->Trace(external_textures_pending_destroy_);
ExecutionContextClient::Trace(visitor);
EventTargetWithInlineData::Trace(visitor);
}
void GPUDevice::EnsureExternalTextureDestroyed(
GPUExternalTexture* externalTexture) {
DCHECK(externalTexture);
external_textures_pending_destroy_.push_back(externalTexture);
if (has_pending_microtask_)
return;
Microtask::EnqueueMicrotask(WTF::Bind(
&GPUDevice::DestroyExternalTexturesMicrotask, WrapWeakPersistent(this)));
has_pending_microtask_ = true;
}
void GPUDevice::DestroyExternalTexturesMicrotask() {
has_pending_microtask_ = false;
auto externalTextures = std::move(external_textures_pending_destroy_);
for (Member<GPUExternalTexture> externalTexture : externalTextures) {
externalTexture->Destroy();
}
}
} // namespace blink
|
/************************************************************************
*
* Copyright: 2020
* Owner: Aditya Khopkar
*
* @brief: This file is the main file. The main function begins and ends here.
* This program is responsible in storing an inline input in a vector and subsequently,
* find the word count as well as number of occurrences of each word.
************************************************************************/
#include <iostream>
#include <vector>
#include <string>
#include <sstream>
#include <map>
/**
* @brief: Stores a bag of words from a given input.
* @param: void.
* @return: vector of type string.
*/
std::vector<std::string> WordStorage();
int main() {
// an ordered STL map initialized to keep track of the unique words.
std::map<std::string, int> dictionary;
// iterator object of the map instantiated.
std::map<std::string, int>::iterator it;
// bag of word from method WordStorage()
std::vector < std::string > word_bag = WordStorage();
std::cout << "The total number of words in input: " << word_bag.size()
<< std::endl;
// store the words in the map, keep count of all the words.
for (auto &word : word_bag)
dictionary[word]++;
// iterate through the map to print the word count.
for (it = dictionary.begin(); it != dictionary.end(); it++) {
std::cout << "The word '" << it->first << "' occurs " << it->second
<< " times." << std::endl;
}
}
std::vector<std::string> WordStorage() {
std::string input;
std::string word;
std::vector < std::string > word_bag;
std::cout << "Please Enter your input: " << std::endl;
std::getline(std::cin, input);
// sstream used to store entries from the input.
std::istringstream stream(input);
while (stream >> word)
word_bag.push_back(word);
return word_bag;
}
|
//
// RSACipherImpl.cpp
//
// $Id$
//
// Library: Crypto_Win
// Package: RSA
// Module: RSACipherImpl
//
// Copyright (c) 2006-2014, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier: BSL-1.0
//
#include "Poco/Crypto/RSACipherImpl.h"
#include "Poco/Crypto/CryptoTransform.h"
#include "Poco/Error.h"
#include "Poco/Exception.h"
namespace Poco {
namespace Crypto {
namespace
{
std::size_t rsaBlockSize(RSAKeyImpl::Ptr pKey)
{
DWORD blockLen = 0;
DWORD dataLen = sizeof(DWORD);
if (!CryptGetKeyParam(pKey->privateKey(), KP_BLOCKLEN, reinterpret_cast<LPBYTE>(&blockLen), &dataLen, 0))
{
error("Cannot obtain RSA block length");
}
poco_assert_dbg(dataLen = blockLen);
return static_cast<std::size_t>(blockLen / 8);
}
class RSAEncryptImpl: public CryptoTransform
{
public:
RSAEncryptImpl(const ServiceProvider& sp, RSAKeyImpl::Ptr pKey, RSAPaddingMode paddingMode);
~RSAEncryptImpl();
std::size_t blockSize() const;
std::size_t maxDataSize() const;
std::streamsize transform(
const unsigned char* input,
std::streamsize inputLength,
unsigned char* output,
std::streamsize outputLength);
std::streamsize finalize(unsigned char* output, std::streamsize length);
private:
DWORD encrypt(unsigned char* output, std::streamsize outputLength, BOOL isFinal);
RSAKeyImpl::Ptr _pKey;
const ServiceProvider& _sp;
RSAPaddingMode _paddingMode;
std::streamsize _pos;
unsigned char* _pBuf;
};
RSAEncryptImpl::RSAEncryptImpl(const ServiceProvider& sp, RSAKeyImpl::Ptr pKey, RSAPaddingMode paddingMode) :
_pKey(pKey),
_sp(sp),
_paddingMode(paddingMode),
_pos(0),
_pBuf(0)
{
_pBuf = new unsigned char[blockSize()];
}
RSAEncryptImpl::~RSAEncryptImpl()
{
delete [] _pBuf;
}
std::size_t RSAEncryptImpl::blockSize() const
{
return rsaBlockSize(_pKey);
}
std::size_t RSAEncryptImpl::maxDataSize() const
{
std::size_t size = blockSize();
switch (_paddingMode)
{
case RSA_PADDING_PKCS1:
case RSA_PADDING_SSLV23:
size -= 11;
break;
case RSA_PADDING_PKCS1_OAEP:
size -= 41;
break;
default:
break;
}
return size;
}
DWORD RSAEncryptImpl::encrypt(unsigned char* output, std::streamsize outputLength, BOOL isFinal)
{
DWORD flags = _paddingMode == RSA_PADDING_PKCS1_OAEP ? CRYPT_OAEP : 0;
DWORD n = static_cast<DWORD>(_pos);
if (!CryptEncrypt(_pKey->publicKey(), NULL, isFinal, flags, NULL, &n, 0))
error("RSACipher cannot obtain length of encrypted data");
poco_assert(n > _pos);
std::vector<BYTE> data(n);
n = static_cast<DWORD>(_pos /*+ 1*/);
std::memcpy(&data[0], _pBuf, n);
if (!CryptEncrypt(_pKey->publicKey(), NULL, isFinal, flags, &data[0], &n, static_cast<DWORD>(data.size())))
error("RSACipher cannot encrypt data");
poco_assert(n <= outputLength);
std::memcpy(output, &data[0], n);
return n;
}
std::streamsize RSAEncryptImpl::transform(const unsigned char* input,
std::streamsize inputLength,
unsigned char* output,
std::streamsize outputLength)
{
// always fill up the buffer before writing!
std::streamsize maxSize = static_cast<std::streamsize>(maxDataSize());
std::streamsize rsaSize = static_cast<std::streamsize>(blockSize());
poco_assert_dbg(_pos <= maxSize);
poco_assert (outputLength >= rsaSize);
int rc = 0;
while (inputLength > 0)
{
// check how many data bytes we are missing to get the buffer full
poco_assert_dbg (maxSize >= _pos);
std::streamsize missing = maxSize - _pos;
if (missing == 0)
{
poco_assert (outputLength >= rsaSize);
DWORD n = encrypt(output, outputLength, FALSE);
rc += n;
output += n;
outputLength -= n;
_pos = 0;
}
else
{
if (missing > inputLength)
missing = inputLength;
std::memcpy(_pBuf + _pos, input, static_cast<std::size_t>(missing));
input += missing;
_pos += missing;
inputLength -= missing;
}
}
return rc;
}
std::streamsize RSAEncryptImpl::finalize(unsigned char* output, std::streamsize length)
{
poco_assert (length >= blockSize());
poco_assert (_pos <= maxDataSize());
int rc = 0;
if (_pos > 0)
{
rc = encrypt(output, length, TRUE);
}
return rc;
}
class RSADecryptImpl: public CryptoTransform
{
public:
RSADecryptImpl(const ServiceProvider& sp, RSAKeyImpl::Ptr pKey, RSAPaddingMode paddingMode);
~RSADecryptImpl();
std::size_t blockSize() const;
std::streamsize transform(const unsigned char* input,
std::streamsize inputLength,
unsigned char* output,
std::streamsize outputLength);
std::streamsize finalize(
unsigned char* output,
std::streamsize length);
private:
DWORD decrypt(unsigned char* output, std::streamsize outputLength, BOOL isFinal);
const ServiceProvider& _sp;
RSAKeyImpl::Ptr _pKey;
RSAPaddingMode _paddingMode;
std::streamsize _pos;
unsigned char* _pBuf;
};
RSADecryptImpl::RSADecryptImpl(const ServiceProvider& sp, RSAKeyImpl::Ptr pKey, RSAPaddingMode paddingMode) :
_pKey(pKey),
_sp(sp),
_paddingMode(paddingMode),
_pos(0),
_pBuf(0)
{
_pBuf = new unsigned char[blockSize()];
}
RSADecryptImpl::~RSADecryptImpl()
{
delete [] _pBuf;
}
std::size_t RSADecryptImpl::blockSize() const
{
return rsaBlockSize(_pKey);
}
DWORD RSADecryptImpl::decrypt(unsigned char* output, std::streamsize outputLength, BOOL isFinal)
{
DWORD n = static_cast<DWORD>(_pos);
DWORD flags = _paddingMode == RSA_PADDING_PKCS1_OAEP ? CRYPT_OAEP : 0;
std::vector<BYTE> data(n);
std::memcpy(&data[0], _pBuf, n);
if (!CryptDecrypt(_pKey->privateKey(), NULL, isFinal, flags, &data[0], &n))
error("RSACipher cannot decrypt data");
poco_assert(n <= outputLength);
std::memcpy(output, &data[0], n);
return n;
}
std::streamsize RSADecryptImpl::transform(const unsigned char* input,
std::streamsize inputLength,
unsigned char* output,
std::streamsize outputLength)
{
// always fill up the buffer before decrypting!
std::streamsize rsaSize = static_cast<std::streamsize>(blockSize());
poco_assert_dbg(_pos <= rsaSize);
poco_assert (outputLength >= rsaSize);
int rc = 0;
while (inputLength > 0)
{
// check how many data bytes we are missing to get the buffer full
poco_assert_dbg (rsaSize >= _pos);
std::streamsize missing = rsaSize - _pos;
if (missing == 0)
{
DWORD tmp = decrypt(output, outputLength, FALSE);
if (tmp == -1) error("RSACipher cannot transform data");
rc += tmp;
output += tmp;
outputLength -= tmp;
_pos = 0;
}
else
{
if (missing > inputLength)
missing = inputLength;
std::memcpy(_pBuf + _pos, input, static_cast<std::size_t>(missing));
input += missing;
_pos += missing;
inputLength -= missing;
}
}
return rc;
}
std::streamsize RSADecryptImpl::finalize(unsigned char* output, std::streamsize length)
{
poco_assert (length >= blockSize());
int rc = 0;
if (_pos > 0)
{
rc = decrypt(output, length, TRUE);
if (rc == -1) error("RSACipher cannot transform data");
}
return rc;
}
}
RSACipherImpl::RSACipherImpl(const RSAKey& key, RSAPaddingMode paddingMode):
_key(key),
_paddingMode(paddingMode)
{
}
RSACipherImpl::~RSACipherImpl()
{
}
CryptoTransform* RSACipherImpl::createEncryptor()
{
return new RSAEncryptImpl(_key.impl()->serviceProvider(), _key.impl(), _paddingMode);
}
CryptoTransform* RSACipherImpl::createDecryptor()
{
return new RSADecryptImpl(_key.impl()->serviceProvider(), _key.impl(), _paddingMode);
}
} } // namespace Poco::Crypto
|
/*
* Copyright (c) 2012 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 "modules/video_coding/codecs/test/stats.h"
#include <algorithm>
#include <cmath>
#include <numeric>
#include "modules/rtp_rtcp/include/rtp_rtcp_defines.h"
#include "rtc_base/checks.h"
#include "test/statistics.h"
namespace webrtc {
namespace test {
namespace {
const int kMaxBitrateMismatchPercent = 20;
}
std::string FrameStatistics::ToString() const {
std::stringstream ss;
ss << "frame_number " << frame_number;
ss << " decoded_width " << decoded_width;
ss << " decoded_height " << decoded_height;
ss << " spatial_idx " << spatial_idx;
ss << " temporal_idx " << temporal_idx;
ss << " inter_layer_predicted " << inter_layer_predicted;
ss << " frame_type " << frame_type;
ss << " length_bytes " << length_bytes;
ss << " qp " << qp;
ss << " psnr " << psnr;
ss << " psnr_y " << psnr_y;
ss << " psnr_u " << psnr_u;
ss << " psnr_v " << psnr_v;
ss << " ssim " << ssim;
ss << " encode_time_us " << encode_time_us;
ss << " decode_time_us " << decode_time_us;
ss << " rtp_timestamp " << rtp_timestamp;
ss << " target_bitrate_kbps " << target_bitrate_kbps;
return ss.str();
}
std::string VideoStatistics::ToString(std::string prefix) const {
std::stringstream ss;
ss << prefix << "target_bitrate_kbps: " << target_bitrate_kbps;
ss << "\n" << prefix << "input_framerate_fps: " << input_framerate_fps;
ss << "\n" << prefix << "spatial_idx: " << spatial_idx;
ss << "\n" << prefix << "temporal_idx: " << temporal_idx;
ss << "\n" << prefix << "width: " << width;
ss << "\n" << prefix << "height: " << height;
ss << "\n" << prefix << "length_bytes: " << length_bytes;
ss << "\n" << prefix << "bitrate_kbps: " << bitrate_kbps;
ss << "\n" << prefix << "framerate_fps: " << framerate_fps;
ss << "\n" << prefix << "enc_speed_fps: " << enc_speed_fps;
ss << "\n" << prefix << "dec_speed_fps: " << dec_speed_fps;
ss << "\n" << prefix << "avg_delay_sec: " << avg_delay_sec;
ss << "\n"
<< prefix << "max_key_frame_delay_sec: " << max_key_frame_delay_sec;
ss << "\n"
<< prefix << "max_delta_frame_delay_sec: " << max_delta_frame_delay_sec;
ss << "\n"
<< prefix << "time_to_reach_target_bitrate_sec: "
<< time_to_reach_target_bitrate_sec;
ss << "\n"
<< prefix << "avg_key_frame_size_bytes: " << avg_key_frame_size_bytes;
ss << "\n"
<< prefix << "avg_delta_frame_size_bytes: " << avg_delta_frame_size_bytes;
ss << "\n" << prefix << "avg_qp: " << avg_qp;
ss << "\n" << prefix << "avg_psnr: " << avg_psnr;
ss << "\n" << prefix << "min_psnr: " << min_psnr;
ss << "\n" << prefix << "avg_ssim: " << avg_ssim;
ss << "\n" << prefix << "min_ssim: " << min_ssim;
ss << "\n" << prefix << "num_input_frames: " << num_input_frames;
ss << "\n" << prefix << "num_encoded_frames: " << num_encoded_frames;
ss << "\n" << prefix << "num_decoded_frames: " << num_decoded_frames;
ss << "\n"
<< prefix
<< "num_dropped_frames: " << num_input_frames - num_encoded_frames;
ss << "\n" << prefix << "num_key_frames: " << num_key_frames;
ss << "\n" << prefix << "num_spatial_resizes: " << num_spatial_resizes;
ss << "\n" << prefix << "max_nalu_size_bytes: " << max_nalu_size_bytes;
return ss.str();
}
FrameStatistics* Stats::AddFrame(size_t timestamp, size_t layer_idx) {
RTC_DCHECK(rtp_timestamp_to_frame_num_[layer_idx].find(timestamp) ==
rtp_timestamp_to_frame_num_[layer_idx].end());
const size_t frame_num = layer_stats_[layer_idx].size();
rtp_timestamp_to_frame_num_[layer_idx][timestamp] = frame_num;
layer_stats_[layer_idx].emplace_back(frame_num, timestamp);
return &layer_stats_[layer_idx].back();
}
FrameStatistics* Stats::GetFrame(size_t frame_num, size_t layer_idx) {
RTC_CHECK_LT(frame_num, layer_stats_[layer_idx].size());
return &layer_stats_[layer_idx][frame_num];
}
FrameStatistics* Stats::GetFrameWithTimestamp(size_t timestamp,
size_t layer_idx) {
RTC_DCHECK(rtp_timestamp_to_frame_num_[layer_idx].find(timestamp) !=
rtp_timestamp_to_frame_num_[layer_idx].end());
return GetFrame(rtp_timestamp_to_frame_num_[layer_idx][timestamp], layer_idx);
}
std::vector<VideoStatistics> Stats::SliceAndCalcLayerVideoStatistic(
size_t first_frame_num,
size_t last_frame_num) {
std::vector<VideoStatistics> layer_stats;
size_t num_spatial_layers = 0;
size_t num_temporal_layers = 0;
GetNumberOfEncodedLayers(first_frame_num, last_frame_num, &num_spatial_layers,
&num_temporal_layers);
RTC_CHECK_GT(num_spatial_layers, 0);
RTC_CHECK_GT(num_temporal_layers, 0);
for (size_t spatial_idx = 0; spatial_idx < num_spatial_layers;
++spatial_idx) {
for (size_t temporal_idx = 0; temporal_idx < num_temporal_layers;
++temporal_idx) {
VideoStatistics layer_stat = SliceAndCalcVideoStatistic(
first_frame_num, last_frame_num, spatial_idx, temporal_idx, false);
layer_stats.push_back(layer_stat);
}
}
return layer_stats;
}
VideoStatistics Stats::SliceAndCalcAggregatedVideoStatistic(
size_t first_frame_num,
size_t last_frame_num) {
size_t num_spatial_layers = 0;
size_t num_temporal_layers = 0;
GetNumberOfEncodedLayers(first_frame_num, last_frame_num, &num_spatial_layers,
&num_temporal_layers);
RTC_CHECK_GT(num_spatial_layers, 0);
RTC_CHECK_GT(num_temporal_layers, 0);
return SliceAndCalcVideoStatistic(first_frame_num, last_frame_num,
num_spatial_layers - 1,
num_temporal_layers - 1, true);
}
void Stats::PrintFrameStatistics() {
for (size_t frame_num = 0; frame_num < layer_stats_[0].size(); ++frame_num) {
for (const auto& it : layer_stats_) {
const FrameStatistics& frame_stat = it.second[frame_num];
printf("\n%s", frame_stat.ToString().c_str());
}
}
}
size_t Stats::Size(size_t spatial_idx) {
return layer_stats_[spatial_idx].size();
}
void Stats::Clear() {
layer_stats_.clear();
rtp_timestamp_to_frame_num_.clear();
}
FrameStatistics Stats::AggregateFrameStatistic(
size_t frame_num,
size_t spatial_idx,
bool aggregate_independent_layers) {
FrameStatistics frame_stat = *GetFrame(frame_num, spatial_idx);
bool inter_layer_predicted = frame_stat.inter_layer_predicted;
while (spatial_idx-- > 0) {
if (aggregate_independent_layers || inter_layer_predicted) {
FrameStatistics* base_frame_stat = GetFrame(frame_num, spatial_idx);
frame_stat.length_bytes += base_frame_stat->length_bytes;
frame_stat.target_bitrate_kbps += base_frame_stat->target_bitrate_kbps;
inter_layer_predicted = base_frame_stat->inter_layer_predicted;
}
}
return frame_stat;
}
size_t Stats::CalcLayerTargetBitrateKbps(size_t first_frame_num,
size_t last_frame_num,
size_t spatial_idx,
size_t temporal_idx,
bool aggregate_independent_layers) {
size_t target_bitrate_kbps = 0;
// We don't know if superframe includes all required spatial layers because
// of possible frame drops. Run through all frames in specified range, find
// and return maximum target bitrate. Assume that target bitrate in frame
// statistic is specified per temporal layer.
for (size_t frame_num = first_frame_num; frame_num <= last_frame_num;
++frame_num) {
FrameStatistics superframe = AggregateFrameStatistic(
frame_num, spatial_idx, aggregate_independent_layers);
if (superframe.temporal_idx <= temporal_idx) {
target_bitrate_kbps =
std::max(target_bitrate_kbps, superframe.target_bitrate_kbps);
}
}
RTC_DCHECK_GT(target_bitrate_kbps, 0);
return target_bitrate_kbps;
}
VideoStatistics Stats::SliceAndCalcVideoStatistic(
size_t first_frame_num,
size_t last_frame_num,
size_t spatial_idx,
size_t temporal_idx,
bool aggregate_independent_layers) {
VideoStatistics video_stat;
float buffer_level_bits = 0.0f;
Statistics buffer_level_sec;
Statistics key_frame_size_bytes;
Statistics delta_frame_size_bytes;
Statistics frame_encoding_time_us;
Statistics frame_decoding_time_us;
Statistics psnr_y;
Statistics psnr_u;
Statistics psnr_v;
Statistics psnr;
Statistics ssim;
Statistics qp;
size_t rtp_timestamp_first_frame = 0;
size_t rtp_timestamp_prev_frame = 0;
FrameStatistics last_successfully_decoded_frame(0, 0);
const size_t target_bitrate_kbps =
CalcLayerTargetBitrateKbps(first_frame_num, last_frame_num, spatial_idx,
temporal_idx, aggregate_independent_layers);
for (size_t frame_num = first_frame_num; frame_num <= last_frame_num;
++frame_num) {
FrameStatistics frame_stat = AggregateFrameStatistic(
frame_num, spatial_idx, aggregate_independent_layers);
float time_since_first_frame_sec =
1.0f * (frame_stat.rtp_timestamp - rtp_timestamp_first_frame) /
kVideoPayloadTypeFrequency;
float time_since_prev_frame_sec =
1.0f * (frame_stat.rtp_timestamp - rtp_timestamp_prev_frame) /
kVideoPayloadTypeFrequency;
if (frame_stat.temporal_idx > temporal_idx) {
continue;
}
buffer_level_bits -= time_since_prev_frame_sec * 1000 * target_bitrate_kbps;
buffer_level_bits = std::max(0.0f, buffer_level_bits);
buffer_level_bits += 8.0 * frame_stat.length_bytes;
buffer_level_sec.AddSample(buffer_level_bits /
(1000 * target_bitrate_kbps));
video_stat.length_bytes += frame_stat.length_bytes;
if (frame_stat.encoding_successful) {
++video_stat.num_encoded_frames;
if (frame_stat.frame_type == kVideoFrameKey) {
key_frame_size_bytes.AddSample(frame_stat.length_bytes);
++video_stat.num_key_frames;
} else {
delta_frame_size_bytes.AddSample(frame_stat.length_bytes);
}
frame_encoding_time_us.AddSample(frame_stat.encode_time_us);
qp.AddSample(frame_stat.qp);
video_stat.max_nalu_size_bytes = std::max(video_stat.max_nalu_size_bytes,
frame_stat.max_nalu_size_bytes);
}
if (frame_stat.decoding_successful) {
++video_stat.num_decoded_frames;
video_stat.width = std::max(video_stat.width, frame_stat.decoded_width);
video_stat.height =
std::max(video_stat.height, frame_stat.decoded_height);
psnr_y.AddSample(frame_stat.psnr_y);
psnr_u.AddSample(frame_stat.psnr_u);
psnr_v.AddSample(frame_stat.psnr_v);
psnr.AddSample(frame_stat.psnr);
ssim.AddSample(frame_stat.ssim);
if (video_stat.num_decoded_frames > 1) {
if (last_successfully_decoded_frame.decoded_width !=
frame_stat.decoded_width ||
last_successfully_decoded_frame.decoded_height !=
frame_stat.decoded_height) {
++video_stat.num_spatial_resizes;
}
}
frame_decoding_time_us.AddSample(frame_stat.decode_time_us);
last_successfully_decoded_frame = frame_stat;
}
if (video_stat.num_input_frames > 0) {
if (video_stat.time_to_reach_target_bitrate_sec == 0.0f) {
const float curr_kbps =
8.0 * video_stat.length_bytes / 1000 / time_since_first_frame_sec;
const float bitrate_mismatch_percent =
100 * std::fabs(curr_kbps - target_bitrate_kbps) /
target_bitrate_kbps;
if (bitrate_mismatch_percent < kMaxBitrateMismatchPercent) {
video_stat.time_to_reach_target_bitrate_sec =
time_since_first_frame_sec;
}
}
}
rtp_timestamp_prev_frame = frame_stat.rtp_timestamp;
if (video_stat.num_input_frames == 0) {
rtp_timestamp_first_frame = frame_stat.rtp_timestamp;
}
++video_stat.num_input_frames;
}
const size_t num_frames = last_frame_num - first_frame_num + 1;
const size_t timestamp_delta =
GetFrame(first_frame_num + 1, spatial_idx)->rtp_timestamp -
GetFrame(first_frame_num, spatial_idx)->rtp_timestamp;
const float input_framerate_fps =
1.0 * kVideoPayloadTypeFrequency / timestamp_delta;
const float duration_sec = num_frames / input_framerate_fps;
video_stat.target_bitrate_kbps = target_bitrate_kbps;
video_stat.input_framerate_fps = input_framerate_fps;
video_stat.spatial_idx = spatial_idx;
video_stat.temporal_idx = temporal_idx;
video_stat.bitrate_kbps =
static_cast<size_t>(8 * video_stat.length_bytes / 1000 / duration_sec);
video_stat.framerate_fps = video_stat.num_encoded_frames / duration_sec;
video_stat.enc_speed_fps = 1000000 / frame_encoding_time_us.Mean();
video_stat.dec_speed_fps = 1000000 / frame_decoding_time_us.Mean();
video_stat.avg_delay_sec = buffer_level_sec.Mean();
video_stat.max_key_frame_delay_sec =
8 * key_frame_size_bytes.Max() / 1000 / target_bitrate_kbps;
video_stat.max_delta_frame_delay_sec =
8 * delta_frame_size_bytes.Max() / 1000 / target_bitrate_kbps;
video_stat.avg_key_frame_size_bytes = key_frame_size_bytes.Mean();
video_stat.avg_delta_frame_size_bytes = delta_frame_size_bytes.Mean();
video_stat.avg_qp = qp.Mean();
video_stat.avg_psnr_y = psnr_y.Mean();
video_stat.avg_psnr_u = psnr_u.Mean();
video_stat.avg_psnr_v = psnr_v.Mean();
video_stat.avg_psnr = psnr.Mean();
video_stat.min_psnr = psnr.Min();
video_stat.avg_ssim = ssim.Mean();
video_stat.min_ssim = ssim.Min();
return video_stat;
}
void Stats::GetNumberOfEncodedLayers(size_t first_frame_num,
size_t last_frame_num,
size_t* num_encoded_spatial_layers,
size_t* num_encoded_temporal_layers) {
*num_encoded_spatial_layers = 0;
*num_encoded_temporal_layers = 0;
const size_t num_spatial_layers = layer_stats_.size();
for (size_t frame_num = first_frame_num; frame_num <= last_frame_num;
++frame_num) {
for (size_t spatial_idx = 0; spatial_idx < num_spatial_layers;
++spatial_idx) {
FrameStatistics* frame_stat = GetFrame(frame_num, spatial_idx);
if (frame_stat->encoding_successful) {
*num_encoded_spatial_layers =
std::max(*num_encoded_spatial_layers, frame_stat->spatial_idx + 1);
*num_encoded_temporal_layers = std::max(*num_encoded_temporal_layers,
frame_stat->temporal_idx + 1);
}
}
}
}
} // namespace test
} // namespace webrtc
|
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
#include "core/framework/data_types_internal.h"
#include "core/providers/cpu/math/matmul_integer.h"
#include "core/providers/cpu/math/matmul_helper.h"
#include "core/util/qmath.h"
#include "core/providers/common.h"
namespace onnxruntime {
// only register this operator if low precision computation is enabled.
ONNX_OPERATOR_TYPED_KERNEL_EX(
MatMulInteger,
kOnnxDomain,
10,
uint8_t,
kCpuExecutionProvider,
KernelDefBuilder()
.TypeConstraint("T1", DataTypeImpl::GetTensorType<uint8_t>())
.TypeConstraint("T2", DataTypeImpl::GetTensorType<uint8_t>())
.TypeConstraint("T3", DataTypeImpl::GetTensorType<int32_t>()),
MatMulInteger<uint8_t, uint8_t>);
ONNX_OPERATOR_TYPED_KERNEL_EX(
MatMulInteger,
kOnnxDomain,
10,
int8_t,
kCpuExecutionProvider,
KernelDefBuilder()
.TypeConstraint("T1", DataTypeImpl::GetTensorType<uint8_t>())
.TypeConstraint("T2", DataTypeImpl::GetTensorType<int8_t>())
.TypeConstraint("T3", DataTypeImpl::GetTensorType<int32_t>()),
MatMulInteger<uint8_t, int8_t>);
ONNX_OPERATOR_TYPED_KERNEL_EX(
MatMulInteger,
kOnnxDomain,
10,
int8_tXint8_t,
kCpuExecutionProvider,
KernelDefBuilder()
.TypeConstraint("T1", DataTypeImpl::GetTensorType<int8_t>())
.TypeConstraint("T2", DataTypeImpl::GetTensorType<int8_t>())
.TypeConstraint("T3", DataTypeImpl::GetTensorType<int32_t>()),
MatMulInteger<int8_t, int8_t>);
template <>
Status MatMulInteger<uint8_t, uint8_t>::Compute(OpKernelContext* ctx) const {
concurrency::ThreadPool* thread_pool = ctx->GetOperatorThreadPool();
auto a = ctx->Input<Tensor>(0);
auto b = ctx->Input<Tensor>(1);
ORT_ENFORCE(a != nullptr && b != nullptr);
MatMulComputeHelper helper;
ORT_RETURN_IF_ERROR(helper.Compute(a->Shape(), b->Shape()));
Tensor* y = ctx->Output(0, helper.OutputShape());
// validate zero points
uint8_t a_offset = 0;
uint8_t b_offset = 0;
if (has_a_zero_point_) {
auto a_zero_point = ctx->Input<Tensor>(2);
ORT_ENFORCE(IsScalarOr1ElementVector(a_zero_point),
"MatmulInteger : input1 zero point must be a scalar or 1D tensor of size 1");
a_offset = static_cast<int32_t>(*a_zero_point->template Data<uint8_t>());
}
if (has_b_zero_point_) {
auto b_zero_point = ctx->Input<Tensor>(3);
ORT_ENFORCE(IsScalarOr1ElementVector(b_zero_point),
"MatmulInteger : input2 zero point must be a scalar or 1D tensor of size 1");
b_offset = static_cast<int32_t>(*b_zero_point->template Data<uint8_t>());
}
for (size_t i = 0; i < helper.OutputOffsets().size(); i++) {
QGemmu8u8_s32(static_cast<int>(helper.M()),
static_cast<int>(helper.N()),
static_cast<int>(helper.K()),
a->template Data<uint8_t>() + helper.LeftOffsets()[i],
static_cast<int>(helper.K()),
a_offset,
b->template Data<uint8_t>() + helper.RightOffsets()[i],
static_cast<int>(helper.N()),
b_offset,
y->template MutableData<int32_t>() + helper.OutputOffsets()[i],
static_cast<int>(helper.N()),
thread_pool);
}
return Status::OK();
}
template <>
Status MatMulInteger<uint8_t, int8_t>::Compute(OpKernelContext* ctx) const {
concurrency::ThreadPool* thread_pool = ctx->GetOperatorThreadPool();
auto a = ctx->Input<Tensor>(0);
auto b = ctx->Input<Tensor>(1);
ORT_ENFORCE(a != nullptr && b != nullptr);
MatMulComputeHelper helper;
ORT_RETURN_IF_ERROR(helper.Compute(a->Shape(), b->Shape()));
Tensor* y = ctx->Output(0, helper.OutputShape());
if (has_a_zero_point_ || has_b_zero_point_) {
// currently zero point is only supported in Gemmlowp path above
// in future, the selection of Eigen/Gemmlowp/mklml/etc. should be in a common math library like SGEMM
auto IsZeroPointTensorAllZero = [](OpKernelContext* ctx, int input_idx) -> bool {
auto t = ctx->Input<Tensor>(input_idx);
ORT_ENFORCE(t->Shape().NumDimensions() <= 1 && t->Shape().Size() == 1,
"Currently only scalar zero_point is supported. TODO: add per channel zero point support.");
ORT_ENFORCE(t->IsDataType<int8_t>() || t->IsDataType<uint8_t>());
auto data = reinterpret_cast<const int8_t*>(t->DataRaw());
auto vec = std::vector<int8_t>(data, data + t->Shape().Size());
return std::all_of(vec.begin(), vec.end(), [](int8_t v) { return v == 0; });
};
if ((has_a_zero_point_ && !IsZeroPointTensorAllZero(ctx, 2)) ||
(has_b_zero_point_ && !IsZeroPointTensorAllZero(ctx, 3))) {
ORT_NOT_IMPLEMENTED("MatMulInteger: Unsupported input types with zero point");
}
}
for (int i = 0; i < static_cast<int>(helper.OutputOffsets().size()); i++) {
QGemmu8s8_s32(static_cast<int>(helper.M()),
static_cast<int>(helper.N()),
static_cast<int>(helper.K()),
a->template Data<uint8_t>() + helper.LeftOffsets()[i],
static_cast<int>(helper.K()),
0,
b->template Data<int8_t>() + helper.RightOffsets()[i],
static_cast<int>(helper.N()),
0,
y->template MutableData<int32_t>() + helper.OutputOffsets()[i],
static_cast<int>(helper.N()),
thread_pool);
}
return Status::OK();
}
template <>
Status MatMulInteger<int8_t, int8_t>::Compute(OpKernelContext* ctx) const {
concurrency::ThreadPool* thread_pool = ctx->GetOperatorThreadPool();
auto a = ctx->Input<Tensor>(0);
auto b = ctx->Input<Tensor>(1);
ORT_ENFORCE(a != nullptr && b != nullptr);
MatMulComputeHelper helper;
ORT_RETURN_IF_ERROR(helper.Compute(a->Shape(), b->Shape()));
Tensor* y = ctx->Output(0, helper.OutputShape());
if (has_a_zero_point_ || has_b_zero_point_) {
// currently zero point is only supported in Gemmlowp path above
// in future, the selection of Eigen/Gemmlowp/mklml/etc. should be in a common math library like SGEMM
auto IsZeroPointTensorAllZero = [](OpKernelContext* ctx, int input_idx) -> bool {
auto t = ctx->Input<Tensor>(input_idx);
ORT_ENFORCE(t->Shape().NumDimensions() <= 1 && t->Shape().Size() == 1,
"Currently only scalar zero_point is supported. TODO: add per channel zero point support.");
ORT_ENFORCE(t->IsDataType<int8_t>());
auto data = reinterpret_cast<const int8_t*>(t->DataRaw());
auto vec = std::vector<int8_t>(data, data + t->Shape().Size());
return std::all_of(vec.begin(), vec.end(), [](int8_t v) { return v == 0; });
};
if ((has_a_zero_point_ && !IsZeroPointTensorAllZero(ctx, 2)) ||
(has_b_zero_point_ && !IsZeroPointTensorAllZero(ctx, 3))) {
ORT_NOT_IMPLEMENTED("MatMulInteger: Unsupported input types with zero point");
}
}
for (int i = 0; i < static_cast<int>(helper.OutputOffsets().size()); i++) {
QGemms8s8_s32(static_cast<int>(helper.M()),
static_cast<int>(helper.N()),
static_cast<int>(helper.K()),
a->template Data<int8_t>() + helper.LeftOffsets()[i],
static_cast<int>(helper.K()),
0,
b->template Data<int8_t>() + helper.RightOffsets()[i],
static_cast<int>(helper.N()),
0,
y->template MutableData<int32_t>() + helper.OutputOffsets()[i],
static_cast<int>(helper.N()),
thread_pool);
}
return Status::OK();
}
} // namespace onnxruntime
|
#include "stdafx.h"
#include "ai_biting.h"
#include "ai_biting_state.h"
///////////////////////////////////////////////////////////////////////////////////////////////////////////
// CBitingHide class
///////////////////////////////////////////////////////////////////////////////////////////////////////////
CBitingHide::CBitingHide(CAI_Biting *p)
{
pMonster = p;
}
void CBitingHide::Init()
{
inherited::Init();
}
void CBitingHide::Reset()
{
inherited::Reset();
}
void CBitingHide::Run()
{
LOG_EX("Hide state...");
pMonster->MotionMan.m_tAction = ACT_SLEEP;
}
|
/*
The OpenTRV project licenses this file to you
under the Apache Licence, Version 2.0 (the "Licence");
you may not use this file except in compliance
with the Licence. You may obtain a copy of the Licence at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the Licence is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the Licence for the
specific language governing permissions and limitations
under the Licence.
Author(s) / Copyright (s): Deniz Erbilgin 2015
Damon Hart-Davis 2015--2016
*/
#ifdef ARDUINO
#include "unitTest.h"
/**
* @brief Report an error from a unit test on Serial, and repeat so that it is not missed.
* @param expected expected value
* @param actual actual value
* @param line line error occurred at
*/
void OTUnitTest::error(int expected, int actual, int line)
{
for( ; ; )
{
Serial.print(F("***Test FAILED*** expected=\t0x"));
Serial.print(expected, HEX);
Serial.print(F(", actual = 0x"));
Serial.print(actual, HEX);
Serial.print(F(" = "));
Serial.print(actual, DEC);
if(0 != line)
{
Serial.print(F(" at line "));
Serial.print(line);
}
Serial.println();
// LED_HEATCALL_ON();
// tinyPause();
// LED_HEATCALL_OFF();
// sleepLowPowerMs(1000);
delay(1000);
}
}
#endif // ARDUINO
|
// Copyright 1996-2019 Cyberbotics 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 "WbAbstractCamera.hpp"
#include "WbBackground.hpp"
#include "WbFieldChecker.hpp"
#include "WbLens.hpp"
#include "WbLight.hpp"
#include "WbLog.hpp"
#include "WbPerformanceLog.hpp"
#include "WbPreferences.hpp"
#include "WbProtoModel.hpp"
#include "WbRgb.hpp"
#include "WbRobot.hpp"
#include "WbSFNode.hpp"
#include "WbSensor.hpp"
#include "WbSimulationState.hpp"
#include "WbViewpoint.hpp"
#include "WbWorld.hpp"
#include "WbWrenCamera.hpp"
#include "WbWrenRenderingContext.hpp"
#include "WbWrenShaders.hpp"
#include "WbWrenTextureOverlay.hpp"
#include "../../lib/Controller/api/messages.h"
#include <QtCore/QCoreApplication>
#include <QtCore/QDataStream>
#include <QtCore/QFile>
#include <QtCore/QSharedMemory>
#include <QtCore/QVector>
#include <wren/config.h>
#include <wren/material.h>
#include <wren/node.h>
#include <wren/renderable.h>
#include <wren/static_mesh.h>
#include <wren/transform.h>
#ifndef _WIN32
// include ftok needed to get QSharedMemory unix name
#include <sys/ipc.h>
#include <sys/types.h>
#endif
int WbAbstractCamera::cCameraNumber = 0;
int WbAbstractCamera::cCameraCounter = 0;
void WbAbstractCamera::init() {
mImageShm = NULL;
mWrenCamera = NULL;
mSensor = NULL;
mRefreshRate = 0;
mNeedToConfigure = false;
mHasSharedMemoryChanged = false;
mNeedToCheckShaderErrors = false;
mSharedMemoryReset = false;
mExternalWindowEnabled = false;
mCharType = 0;
mTransform = NULL;
mRenderable = NULL;
mMesh = NULL;
mMaterial = NULL;
mFrustumDisplayTransform = NULL;
mFrustumDisplayRenderable = NULL;
mFrustumDisplayMesh = NULL;
mFrustumDisplayMaterial = NULL;
// Fields initialization
mFieldOfView = findSFDouble("fieldOfView");
mSpherical = findSFBool("spherical");
mNear = findSFDouble("near");
mMotionBlur = findSFDouble("motionBlur");
mNoise = findSFDouble("noise");
mLens = findSFNode("lens");
mImageChanged = false;
mImageReady = false;
}
WbAbstractCamera::WbAbstractCamera(const QString &modelName, WbTokenizer *tokenizer) : WbRenderingDevice(modelName, tokenizer) {
init();
}
WbAbstractCamera::WbAbstractCamera(const WbAbstractCamera &other) : WbRenderingDevice(other) {
init();
}
WbAbstractCamera::WbAbstractCamera(const WbNode &other) : WbRenderingDevice(other) {
init();
}
WbAbstractCamera::~WbAbstractCamera() {
delete mImageShm;
delete mSensor;
if (areWrenObjectsInitialized())
deleteWren();
}
void WbAbstractCamera::preFinalize() {
WbRenderingDevice::preFinalize();
if (lens())
lens()->preFinalize();
mSensor = new WbSensor();
updateFieldOfView();
updateSpherical();
updateNoise();
}
void WbAbstractCamera::postFinalize() {
WbRenderingDevice::postFinalize();
if (lens()) {
lens()->postFinalize();
updateLens();
}
connect(mFieldOfView, &WbSFDouble::changed, this, &WbAbstractCamera::updateFieldOfView);
connect(mSpherical, &WbSFBool::changed, this, &WbAbstractCamera::updateSpherical);
connect(mNoise, &WbSFDouble::changed, this, &WbAbstractCamera::updateNoise);
if (mLens)
connect(mLens, &WbSFNode::changed, this, &WbAbstractCamera::updateLens);
if (mMotionBlur)
connect(mMotionBlur, &WbSFDouble::changed, this, &WbAbstractCamera::updateMotionBlur);
connect(mSensor, &WbSensor::stateChanged, this, &WbAbstractCamera::applyFrustumToWren);
connect(WbWrenRenderingContext::instance(), &WbWrenRenderingContext::optionalRenderingChanged, this,
&WbAbstractCamera::updateOptionalRendering);
}
void WbAbstractCamera::updateOptionalRendering(int option) {
if (areWrenObjectsInitialized() && ((isRangeFinder() && option == WbWrenRenderingContext::VF_RANGE_FINDER_FRUSTUMS) ||
(!isRangeFinder() && option == WbWrenRenderingContext::VF_CAMERA_FRUSTUMS)))
applyFrustumToWren();
}
WbLens *WbAbstractCamera::lens() const {
if (mLens)
return dynamic_cast<WbLens *>(mLens->value());
else
return NULL;
}
void WbAbstractCamera::deleteWren() {
if (mWrenCamera) {
disconnect(mWrenCamera, &WbWrenCamera::cameraInitialized, this, &WbAbstractCamera::applyCameraSettingsToWren);
delete mWrenCamera;
mWrenCamera = NULL;
}
if (areWrenObjectsInitialized()) {
wr_static_mesh_delete(mMesh);
wr_node_delete(WR_NODE(mRenderable));
wr_node_delete(WR_NODE(mTransform));
wr_material_delete(mMaterial);
wr_static_mesh_delete(mFrustumDisplayMesh);
wr_node_delete(WR_NODE(mFrustumDisplayRenderable));
wr_node_delete(WR_NODE(mFrustumDisplayTransform));
wr_material_delete(mFrustumDisplayMaterial);
}
cCameraCounter--;
if (cCameraCounter == 0)
resetStaticCounters();
}
void WbAbstractCamera::initializeSharedMemory() {
mHasSharedMemoryChanged = true;
delete mImageShm;
QString sharedMemoryName =
QString("Webots_Camera_Image_%1_%2").arg((long)QCoreApplication::applicationPid()).arg(cCameraNumber);
mImageShm = new QSharedMemory(sharedMemoryName);
// qDebug() << "key: " << mImageShm->key();
// qDebug() << "nativekey: " << mImageShm->nativeKey();
// A controller of the previous simulation may have not released cleanly the shared memory (e.g. when the controller crashes).
// This can be detected by trying to attach, and the shared memory may be cleaned by detaching.
if (mImageShm->attach())
mImageShm->detach();
if (!mImageShm->create(size())) {
QString message = tr("Cannot allocate shared memory. The shared memory is required for the cameras. The shared memory of "
"your OS is probably full. Please check your shared memory setup.");
#ifdef __APPLE__
message += QString(" ") + tr("The shared memory can be extended by modifying the '/etc/sysctl.conf' file and rebooting.");
#endif
warn(message);
delete mImageShm;
mImageShm = NULL;
return;
}
}
void WbAbstractCamera::setup() {
cCameraNumber++;
cCameraCounter++;
initializeSharedMemory();
if (!mImageShm)
return;
WbRenderingDevice::setup();
createWrenCamera();
createWrenOverlay();
if (!spherical()) {
updateFrustumDisplay();
connect(mWrenCamera, &WbWrenCamera::cameraInitialized, this, &WbAbstractCamera::updateFrustumDisplay);
connect(WbWrenRenderingContext::instance(), &WbWrenRenderingContext::optionalRenderingChanged, this,
&WbAbstractCamera::updateFrustumDisplayIfNeeded);
}
}
void WbAbstractCamera::updateCameraTexture() {
if (isPowerOn() && mSensor->needToRefresh()) {
// update camera overlay before main rendering
computeValue();
mSensor->updateTimer();
mImageChanged = true;
} else if (mSensor->isRemoteModeEnabled() && mOverlay)
// keep updating the overlay in remote mode
mOverlay->requestUpdateTexture();
}
// Generally, computeValue() acquires the data from the RTT
// handle and copies the resulting value in the shared memory
void WbAbstractCamera::computeValue() {
if (!hasBeenSetup())
return;
WbPerformanceLog *log = WbPerformanceLog::instance();
if (log)
log->startMeasure(WbPerformanceLog::DEVICE_RENDERING, deviceName());
// enable viewpoint's invisible nodes
// they will be re-disabled after the controller step
WbViewpoint *viewpoint = WbWorld::instance()->viewpoint();
viewpoint->enableNodeVisibility(true);
const int invisibleNodesCount = mInvisibleNodes.size();
for (int i = 0; i < invisibleNodesCount; ++i)
wr_node_set_visible(WR_NODE(mInvisibleNodes.at(i)->wrenNode()), false);
mWrenCamera->render();
for (int i = 0; i < invisibleNodesCount; ++i)
wr_node_set_visible(WR_NODE(mInvisibleNodes.at(i)->wrenNode()), true);
if (log)
log->stopMeasure(WbPerformanceLog::DEVICE_RENDERING, deviceName());
}
void WbAbstractCamera::copyImageToSharedMemory() {
unsigned char *data = image();
if (mWrenCamera) {
mWrenCamera->enableCopying(true);
mWrenCamera->copyContentsToMemory(data);
}
mImageChanged = false;
}
void WbAbstractCamera::reset() {
WbRenderingDevice::reset();
if (mLens) {
WbNode *const l = mLens->value();
if (l)
l->reset();
}
for (int i = 0; i < mInvisibleNodes.size(); ++i)
disconnect(mInvisibleNodes.at(i), &QObject::destroyed, this, &WbAbstractCamera::removeInvisibleNodeFromList);
mInvisibleNodes.clear();
}
void WbAbstractCamera::resetSharedMemory() {
if (hasBeenSetup()) {
// the previous shared memory will be released by the new controller start
cCameraNumber++;
initializeSharedMemory();
mSharedMemoryReset = true;
}
}
void WbAbstractCamera::writeConfigure(QDataStream &stream) {
mSensor->connectToRobotSignal(robot());
addConfigureToStream(stream);
}
void WbAbstractCamera::writeAnswer(QDataStream &stream) {
if (mNeedToConfigure)
addConfigureToStream(stream, true);
if (mHasSharedMemoryChanged && mImageShm) {
stream << (short unsigned int)tag();
stream << (unsigned char)C_CAMERA_SHARED_MEMORY;
#ifdef _WIN32
QByteArray n = QFile::encodeName(mImageShm ? mImageShm->nativeKey() : "");
stream.writeRawData(n.constData(), n.size() + 1);
#else
stream << (int)ftok(QFile::encodeName(mImageShm->nativeKey()), 'Q');
#endif
mHasSharedMemoryChanged = false;
}
if (mImageReady) {
stream << (short unsigned int)tag();
stream << (unsigned char)C_CAMERA_GET_IMAGE;
mImageReady = false;
mSensor->resetPendingValue();
}
}
void WbAbstractCamera::addConfigureToStream(QDataStream &stream, bool reconfigure) {
stream << (short unsigned int)tag();
if (reconfigure)
stream << (unsigned char)C_CAMERA_RECONFIGURE;
else {
stream << (unsigned char)C_CONFIGURE;
stream << (unsigned int)uniqueId();
stream << (unsigned short)width();
stream << (unsigned short)height();
}
stream << (double)fieldOfView();
stream << (double)minRange();
stream << (unsigned char)mSpherical->value();
mNeedToConfigure = false;
if (!reconfigure && !mSharedMemoryReset)
mHasSharedMemoryChanged = false;
mSharedMemoryReset = false;
}
bool WbAbstractCamera::handleCommand(QDataStream &stream, unsigned char command) {
bool commandHandled = true;
switch (command) {
case C_SET_SAMPLING_PERIOD:
stream >> mRefreshRate;
mSensor->setRefreshRate(mRefreshRate);
// update motion blur factor
applyMotionBlurToWren();
if (mSensor->isEnabled())
connect(WbSimulationState::instance(), &WbSimulationState::cameraRenderingStarted, this,
&WbAbstractCamera::updateCameraTexture, Qt::UniqueConnection);
else
disconnect(WbSimulationState::instance(), &WbSimulationState::cameraRenderingStarted, this,
&WbAbstractCamera::updateCameraTexture);
if (!hasBeenSetup()) {
setup();
mHasSharedMemoryChanged = true;
}
break;
case C_CAMERA_GET_IMAGE:
if (mImageChanged)
copyImageToSharedMemory();
mImageReady = true;
break;
default:
commandHandled = false;
}
return commandHandled;
}
void WbAbstractCamera::setNodeVisibility(WbBaseNode *node, bool visible) {
if (visible)
mInvisibleNodes.removeAll(node);
else if (!mInvisibleNodes.contains(node)) {
mInvisibleNodes.append(node);
connect(node, &QObject::destroyed, this, &WbAbstractCamera::removeInvisibleNodeFromList, Qt::UniqueConnection);
}
}
void WbAbstractCamera::removeInvisibleNodeFromList(QObject *node) {
WbBaseNode *const baseNode = static_cast<WbBaseNode *>(node);
mInvisibleNodes.removeAll(baseNode);
}
unsigned char *WbAbstractCamera::image() const {
if (mImageShm == NULL)
return NULL;
return (unsigned char *)mImageShm->data();
}
void WbAbstractCamera::createWrenObjects() {
WbRenderingDevice::createWrenObjects();
// Frustum
mMaterial = wr_phong_material_new();
wr_material_set_default_program(mMaterial, WbWrenShaders::lineSetShader());
wr_phong_material_set_color_per_vertex(mMaterial, true);
mRenderable = wr_renderable_new();
wr_renderable_set_cast_shadows(mRenderable, false);
wr_renderable_set_receive_shadows(mRenderable, false);
wr_renderable_set_material(mRenderable, mMaterial, NULL);
wr_renderable_set_drawing_mode(mRenderable, WR_RENDERABLE_DRAWING_MODE_LINES);
mTransform = wr_transform_new();
wr_transform_attach_child(mTransform, WR_NODE(mRenderable));
wr_transform_attach_child(wrenNode(), WR_NODE(mTransform));
applyFrustumToWren();
// Frustum display
mFrustumDisplayTransform = wr_transform_new();
mFrustumDisplayRenderable = wr_renderable_new();
mFrustumDisplayMesh = wr_static_mesh_unit_rectangle_new(false);
mFrustumDisplayMaterial = wr_phong_material_new();
wr_material_set_default_program(mFrustumDisplayMaterial, WbWrenShaders::simpleShader());
wr_phong_material_set_transparency(mFrustumDisplayMaterial, 0.5f);
wr_renderable_set_material(mFrustumDisplayRenderable, mFrustumDisplayMaterial, NULL);
wr_renderable_set_mesh(mFrustumDisplayRenderable, WR_MESH(mFrustumDisplayMesh));
wr_renderable_set_face_culling(mFrustumDisplayRenderable, false);
if (isRangeFinder())
wr_renderable_set_visibility_flags(mFrustumDisplayRenderable, WbWrenRenderingContext::VF_RANGE_FINDER_FRUSTUMS);
else
wr_renderable_set_visibility_flags(mFrustumDisplayRenderable, WbWrenRenderingContext::VF_CAMERA_FRUSTUMS);
wr_node_set_visible(WR_NODE(mFrustumDisplayTransform), false);
wr_transform_attach_child(mFrustumDisplayTransform, WR_NODE(mFrustumDisplayRenderable));
wr_transform_attach_child(wrenNode(), WR_NODE(mFrustumDisplayTransform));
createWrenOverlay();
}
void WbAbstractCamera::createWrenCamera() {
if (mWrenCamera)
disconnect(mWrenCamera, &WbWrenCamera::cameraInitialized, this, &WbAbstractCamera::applyCameraSettingsToWren);
delete mWrenCamera;
// Assumption: Qt ensure that the following slots are calling sequentially.
connect(WbWrenRenderingContext::instance(), &WbWrenRenderingContext::backgroundColorChanged, this,
&WbAbstractCamera::updateBackground, Qt::UniqueConnection);
connect(WbWrenRenderingContext::instance(), &WbWrenRenderingContext::backgroundColorChanged, this,
&WbAbstractCamera::updatePostProcessingEffect, Qt::UniqueConnection);
// create the camera
bool enableAntiAliasing = antiAliasing() && !WbPreferences::instance()->value("OpenGL/disableAntiAliasing", true).toBool();
mWrenCamera = new WbWrenCamera(wrenNode(), width(), height(), nearValue(), minRange(), maxRange(), fieldOfView(), mCharType,
enableAntiAliasing, mSpherical->value());
updateBackground();
connect(mWrenCamera, &WbWrenCamera::cameraInitialized, this, &WbAbstractCamera::applyCameraSettingsToWren);
applyNearToWren();
applyFieldOfViewToWren();
applyMotionBlurToWren();
applyLensToWren();
applyNoiseToWren();
if (mExternalWindowEnabled)
updateTextureUpdateNotifications();
}
void WbAbstractCamera::updateBackground() {
if (!mWrenCamera)
return;
WbBackground *background = WbBackground::firstInstance();
if (background)
mWrenCamera->setBackgroundColor(background->skyColor());
else
mWrenCamera->setBackgroundColor(WbRgb());
}
void WbAbstractCamera::updatePostProcessingEffect() {
applyCameraSettingsToWren();
computeValue();
}
void WbAbstractCamera::applyCameraSettingsToWren() {
createWrenOverlay();
applyMotionBlurToWren();
applyLensToWren();
applyNoiseToWren();
}
void WbAbstractCamera::createWrenOverlay() {
QStringList previousSettings;
if (mOverlay)
previousSettings = mOverlay->perspective();
delete mOverlay;
mOverlay = NULL;
if (mWrenCamera) {
mWrenCamera->setSize(width(), height());
if (mCharType == 'r')
mOverlay = new WbWrenTextureOverlay(image(), width(), height(), WbWrenTextureOverlay::TEXTURE_TYPE_DEPTH,
WbWrenTextureOverlay::OVERLAY_TYPE_RANGE_FINDER, mWrenCamera->getWrenTexture(),
maxRange(), true, false);
else if (mCharType == 'c')
mOverlay =
new WbWrenTextureOverlay(image(), width(), height(), WbWrenTextureOverlay::TEXTURE_TYPE_BGRA,
WbWrenTextureOverlay::OVERLAY_TYPE_CAMERA, mWrenCamera->getWrenTexture(), 1.0, false, false);
} else {
if (mCharType == 'r')
mOverlay = new WbWrenTextureOverlay(image(), width(), height(), WbWrenTextureOverlay::TEXTURE_TYPE_DEPTH,
WbWrenTextureOverlay::OVERLAY_TYPE_RANGE_FINDER);
else if (mCharType == 'c')
mOverlay = new WbWrenTextureOverlay(image(), width(), height(), WbWrenTextureOverlay::TEXTURE_TYPE_BGRA,
WbWrenTextureOverlay::OVERLAY_TYPE_CAMERA, NULL, 1.0, false, false);
}
if (!mOverlay)
return;
if (mCharType == 'r')
mOverlay->setMaxRange(maxRange());
applyWorldSettings();
if (!previousSettings.isEmpty())
mOverlay->restorePerspective(previousSettings, areOverlaysEnabled());
else
mOverlay->setVisible(true, areOverlaysEnabled());
emit textureIdUpdated(textureGLId());
}
/////////////////////
// Update methods //
/////////////////////
void WbAbstractCamera::updateWidth() {
WbRenderingDevice::updateWidth();
if (areWrenObjectsInitialized() && !hasBeenSetup()) {
createWrenOverlay();
applyFrustumToWren();
}
}
void WbAbstractCamera::updateHeight() {
WbRenderingDevice::updateHeight();
if (areWrenObjectsInitialized() && !hasBeenSetup()) {
createWrenOverlay();
applyFrustumToWren();
}
}
void WbAbstractCamera::updateLens() {
if (lens()) {
connect(lens(), &WbLens::centerChanged, this, &WbAbstractCamera::applyLensToWren);
connect(lens(), &WbLens::radialCoefficientsChanged, this, &WbAbstractCamera::applyLensToWren);
connect(lens(), &WbLens::tangentialCoefficientsChanged, this, &WbAbstractCamera::applyLensToWren);
}
if (hasBeenSetup())
applyLensToWren();
}
void WbAbstractCamera::updateFieldOfView() {
if (WbFieldChecker::resetDoubleIfNonPositive(this, mFieldOfView, 0.7854))
return;
if (!mSpherical->value() && fieldOfView() > M_PI) {
warn(tr("Invalid 'fieldOfView' changed to 0.7854. The field of view is limited to pi if the 'spherical' field is FALSE."));
mFieldOfView->setValue(0.7854);
return;
}
mNeedToConfigure = true;
if (hasBeenSetup())
applyFieldOfViewToWren();
if (areWrenObjectsInitialized()) {
applyFrustumToWren();
if (!spherical() && hasBeenSetup())
updateFrustumDisplay();
}
}
void WbAbstractCamera::updateSpherical() {
mNeedToConfigure = true;
if (hasBeenSetup()) {
wr_node_set_visible(WR_NODE(mFrustumDisplayTransform), false);
setup();
}
if (areWrenObjectsInitialized())
applyFrustumToWren();
updateFieldOfView();
}
void WbAbstractCamera::updateAntiAliasing() {
if (hasBeenSetup())
setup();
}
void WbAbstractCamera::updateMotionBlur() {
if (!mMotionBlur || WbFieldChecker::resetDoubleIfNegative(this, mMotionBlur, 0.0))
return;
if (hasBeenSetup())
applyMotionBlurToWren();
}
void WbAbstractCamera::updateNoise() {
if (WbFieldChecker::resetDoubleIfNegative(this, mNoise, 0.0))
return;
if (hasBeenSetup())
applyNoiseToWren();
}
/////////////////////
// Apply methods //
/////////////////////
void WbAbstractCamera::applyNearToWren() {
mWrenCamera->setNear(nearValue());
}
void WbAbstractCamera::applyFieldOfViewToWren() {
mWrenCamera->setFieldOfView(mFieldOfView->value());
}
void WbAbstractCamera::applyMotionBlurToWren() {
if (mMotionBlur && hasBeenSetup()) {
if (mRefreshRate > 0) {
// 0.005 because the threshold is 99.5%
double factor = pow(0.005, (double)mRefreshRate / mMotionBlur->value());
mWrenCamera->setMotionBlur(factor);
}
}
}
void WbAbstractCamera::applyLensToWren() {
if (hasBeenSetup()) {
if (lens()) {
mWrenCamera->enableLensDistortion();
mWrenCamera->setLensDistortionCenter(lens()->center());
mWrenCamera->setRadialLensDistortionCoefficients(lens()->radialCoefficients());
mWrenCamera->setTangentialLensDistortionCoefficients(lens()->tangentialCoefficients());
} else
mWrenCamera->disableLensDistortion();
}
}
void WbAbstractCamera::applyNoiseToWren() {
if (mCharType == 'c')
mWrenCamera->setColorNoise(mNoise->value());
else
mWrenCamera->setRangeNoise(mNoise->value());
}
///////////////////////
// Drawing methods //
///////////////////////
static void addVertex(QVector<float> &vertices, QVector<float> &colors, const float *vertex, const float *color) {
vertices.push_back(vertex[0]);
vertices.push_back(vertex[1]);
vertices.push_back(vertex[2]);
colors.push_back(color[0]);
colors.push_back(color[1]);
colors.push_back(color[2]);
}
static void drawCube(QVector<float> &vertices, QVector<float> &colors, float n, const float *color) {
const float cubeVertices[8][3] = {{n, n, n}, {-n, n, n}, {-n, n, -n}, {n, n, -n},
{n, -n, n}, {-n, -n, n}, {-n, -n, -n}, {n, -n, -n}};
for (int i = 0; i < 4; ++i) {
// Top edge
addVertex(vertices, colors, cubeVertices[i], color);
addVertex(vertices, colors, cubeVertices[(i + 1) % 4], color);
// Bottom edge
addVertex(vertices, colors, cubeVertices[i + 4], color);
addVertex(vertices, colors, cubeVertices[((i + 1) % 4) + 4], color);
// Side edge
addVertex(vertices, colors, cubeVertices[i], color);
addVertex(vertices, colors, cubeVertices[i + 4], color);
}
}
static void drawRectangle(QVector<float> &vertices, QVector<float> &colors, const float v[4][3], const float *color) {
for (int i = 0; i < 4; ++i) {
addVertex(vertices, colors, v[i], color);
addVertex(vertices, colors, v[(i + 1) % 4], color);
}
}
void WbAbstractCamera::applyFrustumToWren() {
wr_node_set_visible(WR_NODE(mTransform), false);
wr_static_mesh_delete(mMesh);
mMesh = NULL;
if (!isFrustumEnabled())
return;
WbRgb frustumColorRgb;
if (mSensor->isEnabled() && mSensor->isFirstValueReady())
frustumColorRgb = enabledCameraFrustrumColor();
else
frustumColorRgb = disabledCameraFrustrumColor();
const float frustumColor[] = {static_cast<float>(frustumColorRgb.red()), static_cast<float>(frustumColorRgb.green()),
static_cast<float>(frustumColorRgb.blue())};
wr_phong_material_set_color(mMaterial, frustumColor);
bool drawFarPlane;
float f;
const float n = minRange();
// if the far is set to 0 it means the far clipping plane is set to infinity
// so, the far distance of the colored frustum should be set arbitrarily
if (mCharType == 'c' && maxRange() == 0.0f) {
f = n + 2.0f * wr_config_get_line_scale();
drawFarPlane = false;
} else {
f = maxRange();
drawFarPlane = true;
}
const float w = width();
const float h = height();
const float fovX = mFieldOfView->value();
const float fovY = WbWrenCamera::computeFieldOfViewY(fovX, w / h); // fovX -> fovY
const float t = tanf(fovX / 2.0f);
const float dw1 = n * t;
const float dh1 = dw1 * h / w;
const float n1 = -n;
const float dw2 = f * t;
const float dh2 = dw2 * h / w;
const float n2 = -f;
QVector<float> vertices;
QVector<float> colors;
float vertex[3] = {0.0f, 0.0f, 0.0f};
addVertex(vertices, colors, vertex, frustumColor);
vertex[2] = -n;
addVertex(vertices, colors, vertex, frustumColor);
// creation of the near plane
if (hasBeenSetup() && mWrenCamera->isSpherical()) {
const float cubeColor[3] = {0.0f, 0.0f, 0.0f};
drawCube(vertices, colors, n, cubeColor);
const float n95 = 0.95f * n;
if (mWrenCamera->isSubCameraActive(WbWrenCamera::CAMERA_ORIENTATION_FRONT)) {
const float pos[4][3] = {{n95, n95, -n}, {n95, -n95, -n}, {-n95, -n95, -n}, {-n95, n95, -n}};
drawRectangle(vertices, colors, pos, frustumColor);
}
if (mWrenCamera->isSubCameraActive(WbWrenCamera::CAMERA_ORIENTATION_DOWN)) {
const float pos0[4][3] = {{n95, -n, n95}, {n95, -n, -n95}, {-n95, -n, -n95}, {-n95, -n, n95}};
const float pos1[4][3] = {{n95, n, n95}, {n95, n, -n95}, {-n95, n, -n95}, {-n95, n, n95}};
drawRectangle(vertices, colors, pos0, frustumColor);
drawRectangle(vertices, colors, pos1, frustumColor);
}
if (mWrenCamera->isSubCameraActive(WbWrenCamera::CAMERA_ORIENTATION_LEFT)) {
const float pos0[4][3] = {{-n, n95, n95}, {-n, n95, -n95}, {-n, -n95, -n95}, {-n, -n95, n95}};
const float pos1[4][3] = {{n, n95, n95}, {n, n95, -n95}, {n, -n95, -n95}, {n, -n95, n95}};
drawRectangle(vertices, colors, pos0, frustumColor);
drawRectangle(vertices, colors, pos1, frustumColor);
}
if (mWrenCamera->isSubCameraActive(WbWrenCamera::CAMERA_ORIENTATION_BACK)) {
const float pos[4][3] = {{n95, n95, n}, {n95, -n95, n}, {-n95, -n95, n}, {-n95, n95, n}};
drawRectangle(vertices, colors, pos, frustumColor);
}
} else {
const float pos[4][3] = {{dw1, dh1, n1}, {dw1, -dh1, n1}, {-dw1, -dh1, n1}, {-dw1, dh1, n1}};
drawRectangle(vertices, colors, pos, frustumColor);
}
// Creation of the far plane
// if the camera is not of the range-finder type, the far is set to infinity
// so, the far rectangle of the colored frustum shouldn't be set
if (drawFarPlane && !mSpherical->value()) {
const float pos[4][3] = {{dw2, dh2, n2}, {dw2, -dh2, n2}, {-dw2, -dh2, n2}, {-dw2, dh2, n2}};
drawRectangle(vertices, colors, pos, frustumColor);
}
const float zero[3] = {0.0f, 0.0f, 0.0f};
// Creation of the external outline of the frustum (4 lines)
if (mSpherical->value()) {
const float angleY[4] = {-fovY / 2.0f, -fovY / 2.0f, fovY / 2.0f, fovY / 2.0f};
const float angleX[4] = {fovX / 2.0f, -fovX / 2.0f, -fovX / 2.0f, fovX / 2.0f};
for (int k = 0; k < 4; ++k) {
const float helper = cosf(angleY[k]);
// get x, y and z from the spherical coordinates
float x = 0.0f;
if (angleY[k] > M_PI_4 || angleY[k] < -M_PI_4)
x = f * cosf(angleY[k] + M_PI_2) * sinf(angleX[k]);
else
x = f * helper * sinf(angleX[k]);
const float y = f * sinf(angleY[k]);
const float z = -f * helper * cosf(angleX[k]);
addVertex(vertices, colors, zero, frustumColor);
const float outlineVertex[3] = {x, y, z};
addVertex(vertices, colors, outlineVertex, frustumColor);
}
} else {
const float frustumOutline[8][3] = {{dw1, dh1, n1}, {dw2, dh2, n2}, {-dw1, dh1, n1}, {-dw2, dh2, n2},
{dw1, -dh1, n1}, {dw2, -dh2, n2}, {-dw1, -dh1, n1}, {-dw2, -dh2, n2}};
for (int i = 0; i < 8; ++i)
addVertex(vertices, colors, frustumOutline[i], frustumColor);
}
mMesh = wr_static_mesh_line_set_new(vertices.size() / 3, &vertices[0], &colors[0]);
wr_renderable_set_mesh(mRenderable, WR_MESH(mMesh));
if (isRangeFinder())
wr_renderable_set_visibility_flags(mRenderable, WbWrenRenderingContext::VF_RANGE_FINDER_FRUSTUMS);
else
wr_renderable_set_visibility_flags(mRenderable, WbWrenRenderingContext::VF_CAMERA_FRUSTUMS);
wr_node_set_visible(WR_NODE(mTransform), true);
}
void WbAbstractCamera::updateFrustumDisplay() {
wr_node_set_visible(WR_NODE(mFrustumDisplayTransform), false);
if (!mWrenCamera || !isFrustumEnabled())
return;
const float n = minRange();
const float quadWidth = 2.0f * n * tanf(mFieldOfView->value() / 2.0f);
const float translation[3] = {0.0f, 0.0f, -n};
const float orientation[4] = {M_PI / 2.0f, 1.0f, 0.0f, 0.0f};
const float scale[3] = {quadWidth, 1.0f, (quadWidth * height()) / width()};
wr_transform_set_position(mFrustumDisplayTransform, translation);
wr_transform_set_orientation(mFrustumDisplayTransform, orientation);
wr_transform_set_scale(mFrustumDisplayTransform, scale);
wr_material_set_texture(mFrustumDisplayMaterial, mWrenCamera->getWrenTexture(), 0);
wr_node_set_visible(WR_NODE(mFrustumDisplayTransform), true);
}
void WbAbstractCamera::updateTextureUpdateNotifications() {
assert(mWrenCamera);
if (mExternalWindowEnabled)
connect(mWrenCamera, &WbWrenCamera::textureUpdated, this, &WbRenderingDevice::textureUpdated, Qt::UniqueConnection);
else
disconnect(mWrenCamera, &WbWrenCamera::textureUpdated, this, &WbRenderingDevice::textureUpdated);
mWrenCamera->enableTextureUpdateNotifications(mExternalWindowEnabled);
}
void WbAbstractCamera::enableExternalWindow(bool enabled) {
WbRenderingDevice::enableExternalWindow(enabled);
mExternalWindowEnabled = enabled;
if (mWrenCamera)
updateTextureUpdateNotifications();
}
|
// no-networkit-format
/*
* CommunityDetectionAlgorithm.hpp
*
* Created on: 30.10.2012
* Author: Christian Staudt
*/
#ifndef NETWORKIT_COMMUNITY_COMMUNITY_DETECTION_ALGORITHM_HPP_
#define NETWORKIT_COMMUNITY_COMMUNITY_DETECTION_ALGORITHM_HPP_
#include <networkit/base/Algorithm.hpp>
#include <networkit/graph/Graph.hpp>
#include <networkit/structures/Partition.hpp>
namespace NetworKit {
/**
* @ingroup community
* Abstract base class for community detection/graph clustering algorithms.
*/
class CommunityDetectionAlgorithm : public Algorithm {
public:
/**
* A community detection algorithm operates on a graph, so the constructor expects a graph.
*
* @param[in] G input graph
*/
CommunityDetectionAlgorithm(const Graph& G);
/**
* A community detection algorithm operates on a graph, so the constructor expects a graph.
*
* @param[in] G input graph
* @param[in] baseClustering optional; the algorithm will start from the given clustering.
*/
CommunityDetectionAlgorithm(const Graph &G, Partition baseClustering);
/** Default destructor */
~CommunityDetectionAlgorithm() override = default;
/**
* Apply algorithm to graph
*/
void run() override = 0;
/**
* Returns the result of the run method or throws an error, if the algorithm hasn't run yet.
* @return partition of the node set
*/
virtual Partition getPartition();
/**
* @return string representation of algorithm and parameters.
*/
std::string TLX_DEPRECATED(toString() const override);
protected:
const Graph* G;
Partition result;
};
} /* namespace NetworKit */
#endif // NETWORKIT_COMMUNITY_COMMUNITY_DETECTION_ALGORITHM_HPP_
|
/* Copyright © 2020 Apple Inc. All rights reserved.
*
* Use of this source code is governed by a BSD-3-clause license that can
* be found in the LICENSE.txt file or at
* https://opensource.org/licenses/BSD-3-Clause
*/
#ifndef ML_NEURAL_NET_COMBINE_HPP_
#define ML_NEURAL_NET_COMBINE_HPP_
/**
* \file combine.hpp
*
* Defines a reactive-streams library inspired by the Swift Combine
* framework. Its intent is to simplify reasoning about and testing of NN
* model-training pipelines.
*/
#include <ml/neural_net/combine_base.hpp>
#include <ml/neural_net/combine_futures_subscriber.hpp>
#include <ml/neural_net/combine_iterator.hpp>
#include <ml/neural_net/combine_map.hpp>
#endif // ML_NEURAL_NET_COMBINE_HPP_
|
/**
* Copyright 2011-2015 Quickstep Technologies LLC.
* Copyright 2015 Pivotal Software, 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.
**/
#ifndef QUICKSTEP_PARSER_PARSE_LITERAL_VALUE_HPP_
#define QUICKSTEP_PARSER_PARSE_LITERAL_VALUE_HPP_
#include <cstdint>
#include <memory>
#include <string>
#include <vector>
#include "parser/ParseString.hpp"
#include "parser/ParseTreeNode.hpp"
#include "types/TypedValue.hpp"
#include "utility/Macros.hpp"
#include "glog/logging.h"
namespace quickstep {
class Type;
/** \addtogroup Parser
* @{
*/
/**
* @brief The parsed representation of a literal data value.
**/
class ParseLiteralValue : public ParseTreeNode {
public:
/**
* @brief Virtual destructor.
**/
~ParseLiteralValue() override {
}
/**
* @brief Obtain this value as a literal TypedValue in the quickstep type
* system.
*
* @param type_hint A hint of what Type is expected. This may be used to give
* NULL values the correct Type, or to disambiguate between types that
* have similar human-readable text formats. type_hint may be NULL, in
* which case the most sensible guess for the value's Type is used
* (for a NULL literal, the special type NullType is used).
* @param concretized_type After the call, *concretized_type will point to
* the actual Type that the returned TypedValue belongs to.
* @return The concrete version of this literal value.
**/
virtual TypedValue concretize(const Type *type_hint,
const Type **concretized_type) const = 0;
/**
* @brief Obtain an exact, deep copy of this ParseLiteralValue.
*
* @return A copy of this ParseLiteralValue.
**/
virtual ParseLiteralValue* clone() const = 0;
/**
* @brief Get a human-readable representation of this value.
*
* @return The human-readable form of this value.
**/
virtual std::string generateName() const = 0;
protected:
/**
* @brief Constructor.
*
* @param line_number Line number of the first token of this node in the SQL statement.
* @param column_number Column number of the first token of this node in the SQL statement.
**/
ParseLiteralValue(const int line_number, const int column_number)
: ParseTreeNode(line_number, column_number) {
}
private:
DISALLOW_COPY_AND_ASSIGN(ParseLiteralValue);
};
/**
* @brief The parsed representation of a NULL literal.
**/
class NullParseLiteralValue: public ParseLiteralValue {
public:
/**
* @brief Constructor.
*
* @param line_number Line number of the first token of this node in the SQL statement.
* @param column_number Column number of the first token of this node in the SQL statement.
**/
NullParseLiteralValue(const int line_number, const int column_number)
: ParseLiteralValue(line_number, column_number) {
}
std::string getName() const override {
return "NullLiteral";
}
TypedValue concretize(const Type *type_hint,
const Type **concretized_type) const override;
ParseLiteralValue* clone() const override {
return new NullParseLiteralValue(line_number(), column_number());
}
std::string generateName() const override {
return "NULL";
}
protected:
void getFieldStringItems(
std::vector<std::string> *inline_field_names,
std::vector<std::string> *inline_field_values,
std::vector<std::string> *non_container_child_field_names,
std::vector<const ParseTreeNode*> *non_container_child_fields,
std::vector<std::string> *container_child_field_names,
std::vector<std::vector<const ParseTreeNode*>> *container_child_fields) const override {
}
private:
DISALLOW_COPY_AND_ASSIGN(NullParseLiteralValue);
};
/**
* @brief The parsed representation of an unquoted numeric literal.
**/
class NumericParseLiteralValue : public ParseLiteralValue {
public:
/**
* @brief Constructor.
*
* @param line_number Line number of the first token of this node in the SQL statement.
* @param column_number Column number of the first token of this node in the SQL statement.
* @param numstring The C-string form of the numeric value.
**/
NumericParseLiteralValue(const int line_number,
const int column_number,
const char *numstring);
/**
* @brief Destructor.
**/
~NumericParseLiteralValue() override {
}
std::string getName() const override {
return "NumericLiteral";
}
/**
* @brief Prepend a minus sign to this numeric value, negating it.
* @note This exists to work around a quirk in our Bison SQL grammar, since
* a minus sign can be the leading character in a negative number OR
* can represent the unary negation operation applied to a numeric
* value. Our solution is to have the Lexer scan all numeric literals
* as unsigned values, while the parser has a rule that calls this
* method when a minus-sign token occurs in front of a numeric literal.
**/
void prependMinus();
/**
* @brief Determine whether this numeric value looks like a floating-point
* value.
*
* @return True if the value is "float-like", false otherwise.
**/
bool float_like() const {
return float_like_;
}
/**
* @brief Get this numeric value as a long.
*
* @return This numeric value as a long.
**/
std::int64_t long_value() const {
DCHECK(!float_like_)
<< "Attempted to read integer value from float-like "
<< "NumericParseLiteralValue";
return long_value_;
}
/**
* @note This implementation of concretize() always tries to honor the given
* type_hint first. If resolution with the supplied type_hint fails, or
* if no type_hint is given, then the following rules apply:
* 1. If the literal contains a decimal point or exponent, resolve as
* DoubleType (unless FloatType is hinted, we always use
* DoubleType for more precision).
* 2. Otherwise, if the literal is in-range for a 32-bit signed
* integer, resolve as IntType.
* 3. Otherwise, resolve as LongType.
**/
TypedValue concretize(const Type *type_hint,
const Type **concretized_type) const override;
ParseLiteralValue* clone() const override {
return new NumericParseLiteralValue(line_number(),
column_number(),
numeric_string_.c_str());
}
std::string generateName() const override {
return numeric_string_;
}
protected:
void getFieldStringItems(
std::vector<std::string> *inline_field_names,
std::vector<std::string> *inline_field_values,
std::vector<std::string> *non_container_child_field_names,
std::vector<const ParseTreeNode*> *non_container_child_fields,
std::vector<std::string> *container_child_field_names,
std::vector<std::vector<const ParseTreeNode*>> *container_child_fields) const override;
private:
std::int64_t long_value_;
bool float_like_;
std::string numeric_string_;
DISALLOW_COPY_AND_ASSIGN(NumericParseLiteralValue);
};
/**
* @brief The parsed representation of a quoted string value. This includes
* explicitly typed literals of the form "TYPE 'literal value'".
**/
class StringParseLiteralValue : public ParseLiteralValue {
public:
/**
* @brief Constructor.
*
* @param value The string.
* @param explicit_type If non-NULL, indicates an explicit Type that appeared
* immediately before a quoted string in the SQL syntax. If NULL, then
* value appeared by itself as a quoted string without an explicit
* Type.
**/
explicit StringParseLiteralValue(ParseString *value,
const Type *explicit_type)
: ParseLiteralValue(value->line_number(), value->column_number()),
value_(value),
explicit_type_(explicit_type) {
}
~StringParseLiteralValue() override {
}
/**
* @brief Attempt to parse an interval literal that was specified
* in the form "INTERVAL 'value string'" in SQL syntax.
* @note There are two distinct INTERVAL Types in Quickstep:
* DatetimeInterval ("DATETIME INTERVAL" in SQL) and YearMonthInterval
* ("YEARMONTH INTERVAL" in SQL). The INTERVAL keyword by itself is
* ambiguous and does not name a Type, however the text formats for
* literals of the two different interval Types are distinct and
* non-overlapping, so if a valid interval literal string follows the
* INTERVAL keyword, the Type can be determined unambiguously. This
* method does just that, allowing the SQL parser to be more forgiving
* when interval literals don't specify the flavor of interval
* up-front.
*
* @param value A string literal that followed an INTERVAL keyword in SQL
* syntax. On successful parse, this becomes owned by the parsed
* StringParseLiteralValue. On failure, it is deleted.
* @param output On successful parse, *output is overwritten to point to a
* new heap-allocated StringParseLiteralValue representing the parsed
* interval literal.
* @return true if value was successfully parsed as either of the interval
* types, false otherwise.
**/
static bool ParseAmbiguousInterval(ParseString *value,
StringParseLiteralValue **output);
/**
* @note The rules for what type this literal is resolved as depend on
* whether an explicit_type_ from the SQL context exists, and whether
* a type_hint is provided. Specifically, they are:
* 1. If there is an explicit_type_:
* a. If there is a type_hint and it is safely coercible from
* explicit_type_, do the coercion and resolve as type_hint.
* b. Otherwise resolve as explicit_type_.
* 2. If there is no explicit_type_:
* a. If there is a type_hint and it can successfully parse the
* string value, resolve as the hinted type.
* b. Otherwise, resolve as a non-nullable VarCharType that is
* exactly long enough for this string literal.
**/
TypedValue concretize(const Type *type_hint,
const Type **concretized_type) const override;
std::string getName() const override {
return "StringLiteral";
}
ParseLiteralValue* clone() const override {
return new StringParseLiteralValue(value_->clone(), explicit_type_);
}
std::string generateName() const override;
/**
* @brief Attempt to parse this string literal as an instance of the
* explicit Type provided to the constructor. This should ALWAYS be
* called by the parser immediately after creating a
* StringParseLiteralValue with an explicit Type.
*
* @return true if parse was successful, false if the string was not in a
* valid format for the specified explicit Type.
**/
bool tryExplicitTypeParse();
protected:
void getFieldStringItems(
std::vector<std::string> *inline_field_names,
std::vector<std::string> *inline_field_values,
std::vector<std::string> *non_container_child_field_names,
std::vector<const ParseTreeNode*> *non_container_child_fields,
std::vector<std::string> *container_child_field_names,
std::vector<std::vector<const ParseTreeNode*>> *container_child_fields) const override;
private:
std::unique_ptr<ParseString> value_;
const Type *explicit_type_;
TypedValue explicit_parsed_value_;
DISALLOW_COPY_AND_ASSIGN(StringParseLiteralValue);
};
/** @} */
} // namespace quickstep
#endif // QUICKSTEP_PARSER_PARSE_LITERAL_VALUE_HPP_
|
#define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers
#include <windows.h>
#include <BWAPI.h>
#include "BlueBlueSkyModule.h"
extern "C" __declspec(dllexport) void gameInit(BWAPI::Game* game) { BWAPI::BroodwarPtr = game; }
BOOL APIENTRY DllMain( HANDLE hModule, DWORD ul_reason_for_call, LPVOID lpReserved )
{
switch (ul_reason_for_call)
{
case DLL_PROCESS_ATTACH:
break;
case DLL_PROCESS_DETACH:
break;
}
return TRUE;
}
extern "C" __declspec(dllexport) BWAPI::AIModule* newAIModule()
{
return new BlueBlueSky::BlueBlueSkyModule();
}
|
// This file is made available under Elastic License 2.0.
// This file is based on code available under the Apache license here:
// https://github.com/apache/incubator-doris/blob/master/be/src/olap/rowset/beta_rowset_writer.cpp
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you 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 "storage/rowset/beta_rowset_writer.h"
#include <fmt/format.h>
#include <ctime>
#include <memory>
#include "column/chunk.h"
#include "common/config.h"
#include "common/logging.h"
#include "common/tracer.h"
#include "fs/fs.h"
#include "runtime/exec_env.h"
#include "segment_options.h"
#include "serde/column_array_serde.h"
#include "storage/aggregate_iterator.h"
#include "storage/chunk_helper.h"
#include "storage/merge_iterator.h"
#include "storage/olap_define.h"
#include "storage/rowset/beta_rowset.h"
#include "storage/rowset/rowset_factory.h"
#include "storage/storage_engine.h"
#include "storage/type_utils.h"
#include "util/pretty_printer.h"
namespace starrocks {
BetaRowsetWriter::BetaRowsetWriter(const RowsetWriterContext& context)
: _context(context),
_rowset_meta(nullptr),
_num_rows_written(0),
_total_row_size(0),
_total_data_size(0),
_total_index_size(0) {}
Status BetaRowsetWriter::init() {
DCHECK(!(_context.tablet_schema->contains_format_v1_column() &&
_context.tablet_schema->contains_format_v2_column()));
auto real_data_format = _context.storage_format_version;
auto tablet_format = real_data_format;
if (_context.tablet_schema->contains_format_v1_column()) {
tablet_format = kDataFormatV1;
} else if (_context.tablet_schema->contains_format_v2_column()) {
tablet_format = kDataFormatV2;
}
// StarRocks is built on earlier work on Apache Doris and is compatible with its data format but
// has newly designed storage formats for DATA/DATETIME/DECIMAL for better performance.
// When loading data into a tablet created by Apache Doris, the real data format will
// be different from the tablet schema, so here we create a new schema matched with the
// real data format to init `SegmentWriter`.
if (real_data_format != tablet_format) {
_rowset_schema = _context.tablet_schema->convert_to_format(real_data_format);
}
_rowset_meta = std::make_shared<RowsetMeta>();
_rowset_meta->set_rowset_id(_context.rowset_id);
_rowset_meta->set_partition_id(_context.partition_id);
_rowset_meta->set_tablet_id(_context.tablet_id);
_rowset_meta->set_tablet_schema_hash(_context.tablet_schema_hash);
_rowset_meta->set_rowset_type(_context.rowset_type);
_rowset_meta->set_rowset_state(_context.rowset_state);
_rowset_meta->set_segments_overlap(_context.segments_overlap);
if (_context.rowset_state == PREPARED || _context.rowset_state == COMMITTED) {
_is_pending = true;
_rowset_meta->set_txn_id(_context.txn_id);
_rowset_meta->set_load_id(_context.load_id);
} else {
_rowset_meta->set_version(_context.version);
}
_rowset_meta->set_tablet_uid(_context.tablet_uid);
_writer_options.storage_format_version = _context.storage_format_version;
_writer_options.global_dicts = _context.global_dicts != nullptr ? _context.global_dicts : nullptr;
_writer_options.referenced_column_ids = _context.referenced_column_ids;
if (_context.tablet_schema->keys_type() == KeysType::PRIMARY_KEYS && _context.partial_update_tablet_schema) {
_rowset_txn_meta_pb = std::make_unique<RowsetTxnMetaPB>();
}
ASSIGN_OR_RETURN(_fs, FileSystem::CreateSharedFromString(_context.rowset_path_prefix));
return Status::OK();
}
StatusOr<RowsetSharedPtr> BetaRowsetWriter::build() {
if (_num_rows_written > 0) {
RETURN_IF_ERROR(_fs->sync_dir(_context.rowset_path_prefix));
}
_rowset_meta->set_num_rows(_num_rows_written);
_rowset_meta->set_total_row_size(_total_row_size);
_rowset_meta->set_total_disk_size(_total_data_size);
_rowset_meta->set_data_disk_size(_total_data_size);
_rowset_meta->set_index_disk_size(_total_index_size);
// TODO write zonemap to meta
_rowset_meta->set_empty(_num_rows_written == 0);
_rowset_meta->set_creation_time(time(nullptr));
_rowset_meta->set_num_segments(_num_segment);
// newly created rowset do not have rowset_id yet, use 0 instead
_rowset_meta->set_rowset_seg_id(0);
// updatable tablet require extra processing
if (_context.tablet_schema->keys_type() == KeysType::PRIMARY_KEYS) {
_rowset_meta->set_num_delete_files(_num_delfile);
_rowset_meta->set_segments_overlap(NONOVERLAPPING);
// if load only has delete, we can skip the partial update logic
if (_context.partial_update_tablet_schema && _flush_chunk_state != FlushChunkState::DELETE) {
DCHECK(_context.referenced_column_ids.size() == _context.partial_update_tablet_schema->columns().size());
for (auto i = 0; i < _context.partial_update_tablet_schema->columns().size(); ++i) {
const auto& tablet_column = _context.partial_update_tablet_schema->column(i);
_rowset_txn_meta_pb->add_partial_update_column_ids(_context.referenced_column_ids[i]);
_rowset_txn_meta_pb->add_partial_update_column_unique_ids(tablet_column.unique_id());
}
_rowset_meta->set_txn_meta(*_rowset_txn_meta_pb);
}
} else {
if (_num_segment <= 1) {
_rowset_meta->set_segments_overlap(NONOVERLAPPING);
}
}
if (_is_pending) {
_rowset_meta->set_rowset_state(COMMITTED);
} else {
_rowset_meta->set_rowset_state(VISIBLE);
}
RowsetSharedPtr rowset;
RETURN_IF_ERROR(
RowsetFactory::create_rowset(_context.tablet_schema, _context.rowset_path_prefix, _rowset_meta, &rowset));
_already_built = true;
return rowset;
}
Status BetaRowsetWriter::flush_src_rssids(uint32_t segment_id) {
auto path = BetaRowset::segment_srcrssid_file_path(_context.rowset_path_prefix, _context.rowset_id,
static_cast<int>(segment_id));
ASSIGN_OR_RETURN(auto wfile, _fs->new_writable_file(path));
RETURN_IF_ERROR(wfile->append(Slice((const char*)(_src_rssids->data()), _src_rssids->size() * sizeof(uint32_t))));
RETURN_IF_ERROR(wfile->close());
_src_rssids->clear();
_src_rssids.reset();
return Status::OK();
}
HorizontalBetaRowsetWriter::HorizontalBetaRowsetWriter(const RowsetWriterContext& context)
: BetaRowsetWriter(context), _segment_writer(nullptr) {}
HorizontalBetaRowsetWriter::~HorizontalBetaRowsetWriter() {
// TODO(lingbin): Should wrapper exception logic, no need to know file ops directly.
if (!_already_built) { // abnormal exit, remove all files generated
_segment_writer.reset(); // ensure all files are closed
if (_context.tablet_schema->keys_type() == KeysType::PRIMARY_KEYS) {
for (const auto& tmp_segment_file : _tmp_segment_files) {
// these files will be cleaned up with error handling by the GC background even though
// they have not been deleted here after an error occurred, so we just go ahead here and
// print the error message only when we encounter an error except Status::NotFound().
// The following similar scenarios are same.
auto st = _fs->delete_file(tmp_segment_file);
LOG_IF(WARNING, !(st.ok() || st.is_not_found()))
<< "Fail to delete file=" << tmp_segment_file << ", " << st.to_string();
}
_tmp_segment_files.clear();
for (auto i = 0; i < _num_segment; ++i) {
auto path = BetaRowset::segment_file_path(_context.rowset_path_prefix, _context.rowset_id, i);
auto st = _fs->delete_file(path);
LOG_IF(WARNING, !(st.ok() || st.is_not_found()))
<< "Fail to delete file=" << path << ", " << st.to_string();
}
for (auto i = 0; i < _num_delfile; ++i) {
auto path = BetaRowset::segment_del_file_path(_context.rowset_path_prefix, _context.rowset_id, i);
auto st = _fs->delete_file(path);
LOG_IF(WARNING, !(st.ok() || st.is_not_found()))
<< "Fail to delete file=" << path << ", " << st.to_string();
}
//// only deleting segment files may not delete all delete files or temporary files
//// during final merge, should iterate directory and delete all files with rowset_id prefix
//std::vector<std::string> files;
//Status st = _context.env->get_children(_context.rowset_path_prefix, &files);
//if (!st.ok()) {
// LOG(WARNING) << "list dir failed: " << _context.rowset_path_prefix << " "
// << st.to_string();
//}
//string prefix = _context.rowset_id.to_string();
//for (auto& f : files) {
// if (strncmp(f.c_str(), prefix.c_str(), prefix.size()) == 0) {
// string path = _context.rowset_path_prefix + "/" + f;
// // Even if an error is encountered, these files that have not been cleaned up
// // will be cleaned up by the GC background. So here we only print the error
// // message when we encounter an error.
// Status st = _context.env->delete_file(path);
// LOG_IF(WARNING, !st.ok())
// << "Fail to delete file=" << path << ", " << st.to_string();
// }
//}
} else {
for (int i = 0; i < _num_segment; ++i) {
auto path = BetaRowset::segment_file_path(_context.rowset_path_prefix, _context.rowset_id, i);
auto st = _fs->delete_file(path);
LOG_IF(WARNING, !(st.ok() || st.is_not_found()))
<< "Fail to delete file=" << path << ", " << st.to_string();
}
}
// if _already_built is false, we need to release rowset_id to avoid rowset_id leak
StorageEngine::instance()->release_rowset_id(_context.rowset_id);
}
}
StatusOr<std::unique_ptr<SegmentWriter>> HorizontalBetaRowsetWriter::_create_segment_writer() {
std::lock_guard<std::mutex> l(_lock);
std::string path;
if ((_context.tablet_schema->keys_type() == KeysType::PRIMARY_KEYS &&
_context.segments_overlap != NONOVERLAPPING) ||
_context.write_tmp) {
path = BetaRowset::segment_temp_file_path(_context.rowset_path_prefix, _context.rowset_id, _num_segment);
_tmp_segment_files.emplace_back(path);
} else {
// for update final merge scenario, we marked segments_overlap to NONOVERLAPPING in
// function _final_merge, so we create segment data file here, rather than
// temporary segment files.
path = BetaRowset::segment_file_path(_context.rowset_path_prefix, _context.rowset_id, _num_segment);
}
ASSIGN_OR_RETURN(auto wfile, _fs->new_writable_file(path));
const auto* schema = _rowset_schema != nullptr ? _rowset_schema.get() : _context.tablet_schema;
auto segment_writer = std::make_unique<SegmentWriter>(std::move(wfile), _num_segment, schema, _writer_options);
RETURN_IF_ERROR(segment_writer->init());
++_num_segment;
return std::move(segment_writer);
}
Status HorizontalBetaRowsetWriter::add_chunk(const vectorized::Chunk& chunk) {
if (_segment_writer == nullptr) {
ASSIGN_OR_RETURN(_segment_writer, _create_segment_writer());
} else if (_segment_writer->estimate_segment_size() >= config::max_segment_file_size ||
_segment_writer->num_rows_written() + chunk.num_rows() >= _context.max_rows_per_segment) {
RETURN_IF_ERROR(_flush_segment_writer(&_segment_writer));
ASSIGN_OR_RETURN(_segment_writer, _create_segment_writer());
}
RETURN_IF_ERROR(_segment_writer->append_chunk(chunk));
_num_rows_written += static_cast<int64_t>(chunk.num_rows());
_total_row_size += static_cast<int64_t>(chunk.bytes_usage());
return Status::OK();
}
Status HorizontalBetaRowsetWriter::add_chunk_with_rssid(const vectorized::Chunk& chunk, const vector<uint32_t>& rssid) {
if (_segment_writer == nullptr) {
ASSIGN_OR_RETURN(_segment_writer, _create_segment_writer());
} else if (_segment_writer->estimate_segment_size() >= config::max_segment_file_size ||
_segment_writer->num_rows_written() + chunk.num_rows() >= _context.max_rows_per_segment) {
RETURN_IF_ERROR(_flush_segment_writer(&_segment_writer));
ASSIGN_OR_RETURN(_segment_writer, _create_segment_writer());
}
RETURN_IF_ERROR(_segment_writer->append_chunk(chunk));
if (!_src_rssids) {
_src_rssids = std::make_unique<vector<uint32_t>>();
}
_src_rssids->insert(_src_rssids->end(), rssid.begin(), rssid.end());
_num_rows_written += static_cast<int64_t>(chunk.num_rows());
_total_row_size += static_cast<int64_t>(chunk.bytes_usage());
return Status::OK();
}
std::string HorizontalBetaRowsetWriter::_dump_mixed_segment_delfile_not_supported() {
std::string msg = strings::Substitute(
"multi-segment rowset do not support mixing upsert and delete tablet:$0 txn:$1 #seg:$2 #delfile:$3 "
"#upsert:$4 #del:$5",
_context.tablet_id, _context.txn_id, _num_segment, _num_delfile, _num_rows_written, _num_rows_del);
LOG(WARNING) << msg;
return msg;
}
Status HorizontalBetaRowsetWriter::flush_chunk(const vectorized::Chunk& chunk) {
// 1. pure upsert
// once upsert, subsequent flush can only do upsert
switch (_flush_chunk_state) {
case FlushChunkState::UNKNOWN:
_flush_chunk_state = FlushChunkState::UPSERT;
break;
case FlushChunkState::UPSERT:
break;
default:
return Status::Cancelled(_dump_mixed_segment_delfile_not_supported());
}
return _flush_chunk(chunk);
}
Status HorizontalBetaRowsetWriter::_flush_chunk(const vectorized::Chunk& chunk) {
auto segment_writer = _create_segment_writer();
if (!segment_writer.ok()) {
return segment_writer.status();
}
RETURN_IF_ERROR((*segment_writer)->append_chunk(chunk));
{
std::lock_guard<std::mutex> l(_lock);
_num_rows_written += static_cast<int64_t>(chunk.num_rows());
_total_row_size += static_cast<int64_t>(chunk.bytes_usage());
}
return _flush_segment_writer(&segment_writer.value());
}
Status HorizontalBetaRowsetWriter::flush_chunk_with_deletes(const vectorized::Chunk& upserts,
const vectorized::Column& deletes) {
auto flush_del_file = [&](const vectorized::Column& deletes) {
auto path = BetaRowset::segment_del_file_path(_context.rowset_path_prefix, _context.rowset_id, _num_delfile);
ASSIGN_OR_RETURN(auto wfile, _fs->new_writable_file(path));
size_t sz = serde::ColumnArraySerde::max_serialized_size(deletes);
std::vector<uint8_t> content(sz);
if (serde::ColumnArraySerde::serialize(deletes, content.data()) == nullptr) {
return Status::InternalError("deletes column serialize failed");
}
RETURN_IF_ERROR(wfile->append(Slice(content.data(), content.size())));
RETURN_IF_ERROR(wfile->close());
_num_delfile++;
_num_rows_del += deletes.size();
return Status::OK();
};
// three flush states
// 1. pure upsert, support multi-segment
// 2. pure delete, support multi-segment
// 3. mixed upsert/delete, do not support multi-segment
if (!upserts.is_empty() && deletes.empty()) {
return flush_chunk(upserts);
} else if (upserts.is_empty() && !deletes.empty()) {
// 2. pure delete
// once delete, subsequent flush can only do delete
switch (_flush_chunk_state) {
case FlushChunkState::UNKNOWN:
_flush_chunk_state = FlushChunkState::DELETE;
break;
case FlushChunkState::DELETE:
break;
default:
return Status::Cancelled(_dump_mixed_segment_delfile_not_supported());
}
RETURN_IF_ERROR(flush_del_file(deletes));
return Status::OK();
} else if (!upserts.is_empty() && !deletes.empty()) {
// 3. mixed upsert/delete, do not support multi-segment, check will there be multi-segment in the following _final_merge
switch (_flush_chunk_state) {
case FlushChunkState::UNKNOWN:
_flush_chunk_state = FlushChunkState::MIXED;
break;
default:
return Status::Cancelled(_dump_mixed_segment_delfile_not_supported());
}
RETURN_IF_ERROR(flush_del_file(deletes));
return _flush_chunk(upserts);
} else {
return flush_chunk(upserts);
}
}
Status HorizontalBetaRowsetWriter::add_rowset(RowsetSharedPtr rowset) {
assert(rowset->rowset_meta()->rowset_type() == BETA_ROWSET);
RETURN_IF_ERROR(rowset->link_files_to(_context.rowset_path_prefix, _context.rowset_id));
_num_rows_written += rowset->num_rows();
_total_row_size += static_cast<int64_t>(rowset->total_row_size());
_total_data_size += static_cast<int64_t>(rowset->rowset_meta()->data_disk_size());
_total_index_size += static_cast<int64_t>(rowset->rowset_meta()->index_disk_size());
_num_segment += static_cast<int>(rowset->num_segments());
// TODO update zonemap
if (rowset->rowset_meta()->has_delete_predicate()) {
_rowset_meta->set_delete_predicate(rowset->rowset_meta()->delete_predicate());
}
return Status::OK();
}
Status HorizontalBetaRowsetWriter::add_rowset_for_linked_schema_change(RowsetSharedPtr rowset,
const SchemaMapping& schema_mapping) {
// TODO use schema_mapping to transfer zonemap
return add_rowset(rowset);
}
Status HorizontalBetaRowsetWriter::flush() {
if (_segment_writer != nullptr) {
return _flush_segment_writer(&_segment_writer);
}
return Status::OK();
}
StatusOr<RowsetSharedPtr> HorizontalBetaRowsetWriter::build() {
if (!_tmp_segment_files.empty()) {
RETURN_IF_ERROR(_final_merge());
}
// When building a rowset, we must ensure that the current _segment_writer has been
// flushed, that is, the current _segment_wirter is nullptr
DCHECK(_segment_writer == nullptr) << "segment must be null when build rowset";
return BetaRowsetWriter::build();
}
// why: when the data is large, multi segment files created, may be OVERLAPPINGed.
// what: do final merge for NONOVERLAPPING state among segment files
// when: segment files number larger than one, no delete files(for now, ignore it when just one segment)
// how: for final merge scenario, temporary files created at first, merge them, create final segment files.
Status HorizontalBetaRowsetWriter::_final_merge() {
if (_num_segment == 1) {
auto old_path = BetaRowset::segment_temp_file_path(_context.rowset_path_prefix, _context.rowset_id, 0);
auto new_path = BetaRowset::segment_file_path(_context.rowset_path_prefix, _context.rowset_id, 0);
auto st = _fs->rename_file(old_path, new_path);
RETURN_IF_ERROR_WITH_WARN(st, "Fail to rename file");
return Status::OK();
}
auto span = Tracer::Instance().start_trace_txn_tablet("final_merge", _context.txn_id, _context.tablet_id);
auto scoped = trace::Scope(span);
MonotonicStopWatch timer;
timer.start();
auto schema = vectorized::ChunkHelper::convert_schema_to_format_v2(*_context.tablet_schema);
std::vector<vectorized::ChunkIteratorPtr> seg_iterators;
seg_iterators.reserve(_num_segment);
vectorized::SegmentReadOptions seg_options;
seg_options.fs = _fs;
OlapReaderStatistics stats;
seg_options.stats = &stats;
for (int seg_id = 0; seg_id < _num_segment; ++seg_id) {
std::string tmp_segment_file =
BetaRowset::segment_temp_file_path(_context.rowset_path_prefix, _context.rowset_id, seg_id);
auto segment_ptr = Segment::open(ExecEnv::GetInstance()->tablet_meta_mem_tracker(), _fs, tmp_segment_file,
seg_id, _context.tablet_schema);
if (!segment_ptr.ok()) {
LOG(WARNING) << "Fail to open " << tmp_segment_file << ": " << segment_ptr.status();
return segment_ptr.status();
}
if ((*segment_ptr)->num_rows() == 0) {
continue;
}
auto res = (*segment_ptr)->new_iterator(schema, seg_options);
if (res.status().is_end_of_file()) {
continue;
} else if (!res.ok()) {
return res.status();
} else if (res.value() == nullptr) {
continue;
} else {
seg_iterators.emplace_back(res.value());
}
}
ChunkIteratorPtr itr = nullptr;
// schema change vectorized
// schema change with sorting create temporary segment files first
// merge them and create final segment files if _context.write_tmp is true
if (_context.write_tmp) {
if (_context.tablet_schema->keys_type() == KeysType::DUP_KEYS) {
itr = new_heap_merge_iterator(seg_iterators);
} else if (_context.tablet_schema->keys_type() == KeysType::UNIQUE_KEYS ||
_context.tablet_schema->keys_type() == KeysType::AGG_KEYS) {
itr = new_aggregate_iterator(new_heap_merge_iterator(seg_iterators), 0);
} else {
return Status::NotSupported(fmt::format("HorizontalBetaRowsetWriter not support {} key type final merge",
_context.tablet_schema->keys_type()));
}
_context.write_tmp = false;
} else {
itr = new_aggregate_iterator(new_heap_merge_iterator(seg_iterators), 0);
}
itr->init_encoded_schema(vectorized::EMPTY_GLOBAL_DICTMAPS);
auto chunk_shared_ptr = vectorized::ChunkHelper::new_chunk(schema, config::vector_chunk_size);
auto chunk = chunk_shared_ptr.get();
_num_segment = 0;
_num_delfile = 0;
_num_rows_written = 0;
_num_rows_del = 0;
_total_data_size = 0;
_total_index_size = 0;
if (_rowset_txn_meta_pb) {
_rowset_txn_meta_pb->clear_partial_rowset_footers();
}
// since the segment already NONOVERLAPPING here, make the _create_segment_writer
// method to create segment data files, rather than temporary segment files.
_context.segments_overlap = NONOVERLAPPING;
auto char_field_indexes = vectorized::ChunkHelper::get_char_field_indexes(schema);
size_t total_rows = 0;
size_t total_chunk = 0;
while (true) {
chunk->reset();
auto st = itr->get_next(chunk);
if (st.is_end_of_file()) {
break;
} else if (st.ok()) {
vectorized::ChunkHelper::padding_char_columns(char_field_indexes, schema, *_context.tablet_schema, chunk);
total_rows += chunk->num_rows();
total_chunk++;
add_chunk(*chunk);
} else {
return st;
}
}
itr->close();
flush();
timer.stop();
LOG(INFO) << "rowset writer final merge finished. tablet:" << _context.tablet_id
<< " #key:" << schema.num_key_fields() << " input("
<< "entry=" << seg_iterators.size() << " rows=" << stats.raw_rows_read
<< " bytes=" << PrettyPrinter::print(stats.bytes_read, TUnit::UNIT) << ") output(rows=" << total_rows
<< " chunk=" << total_chunk << " bytes=" << PrettyPrinter::print(total_data_size(), TUnit::UNIT)
<< ") duration: " << timer.elapsed_time() / 1000000 << "ms";
span->SetAttribute("output_bytes", total_data_size());
for (const auto& tmp_segment_file : _tmp_segment_files) {
auto st = _fs->delete_file(tmp_segment_file);
LOG_IF(WARNING, !(st.ok() || st.is_not_found()))
<< "Fail to delete segment temp file=" << tmp_segment_file << ", " << st.to_string();
}
_tmp_segment_files.clear();
return Status::OK();
}
Status HorizontalBetaRowsetWriter::_flush_segment_writer(std::unique_ptr<SegmentWriter>* segment_writer) {
uint64_t segment_size;
uint64_t index_size;
uint64_t footer_position;
RETURN_IF_ERROR((*segment_writer)->finalize(&segment_size, &index_size, &footer_position));
if (_context.tablet_schema->keys_type() == KeysType::PRIMARY_KEYS && _context.partial_update_tablet_schema) {
uint64_t footer_size = segment_size - footer_position;
auto* partial_rowset_footer = _rowset_txn_meta_pb->add_partial_rowset_footers();
partial_rowset_footer->set_position(footer_position);
partial_rowset_footer->set_size(footer_size);
}
{
std::lock_guard<std::mutex> l(_lock);
_total_data_size += static_cast<int64_t>(segment_size);
_total_index_size += static_cast<int64_t>(index_size);
}
if (_src_rssids) {
RETURN_IF_ERROR(flush_src_rssids(_segment_writer->segment_id()));
}
// check global_dict efficacy
const auto& seg_global_dict_columns_valid_info = (*segment_writer)->global_dict_columns_valid_info();
for (const auto& it : seg_global_dict_columns_valid_info) {
if (!it.second) {
_global_dict_columns_valid_info[it.first] = false;
} else {
if (const auto& iter = _global_dict_columns_valid_info.find(it.first);
iter == _global_dict_columns_valid_info.end()) {
_global_dict_columns_valid_info[it.first] = true;
}
}
}
(*segment_writer).reset();
return Status::OK();
}
VerticalBetaRowsetWriter::VerticalBetaRowsetWriter(const RowsetWriterContext& context) : BetaRowsetWriter(context) {}
VerticalBetaRowsetWriter::~VerticalBetaRowsetWriter() {
if (!_already_built) {
for (auto& segment_writer : _segment_writers) {
segment_writer.reset();
}
for (int i = 0; i < _num_segment; ++i) {
auto path = BetaRowset::segment_file_path(_context.rowset_path_prefix, _context.rowset_id, i);
auto st = _fs->delete_file(path);
LOG_IF(WARNING, !(st.ok() || st.is_not_found()))
<< "Fail to delete file=" << path << ", " << st.to_string();
}
// if _already_built is false, we need to release rowset_id to avoid rowset_id leak
StorageEngine::instance()->release_rowset_id(_context.rowset_id);
}
}
Status VerticalBetaRowsetWriter::add_columns(const vectorized::Chunk& chunk,
const std::vector<uint32_t>& column_indexes, bool is_key) {
size_t chunk_num_rows = chunk.num_rows();
if (_segment_writers.empty()) {
DCHECK(is_key);
auto segment_writer = _create_segment_writer(column_indexes, is_key);
if (!segment_writer.ok()) return segment_writer.status();
_segment_writers.emplace_back(std::move(segment_writer).value());
_current_writer_index = 0;
RETURN_IF_ERROR(_segment_writers[_current_writer_index]->append_chunk(chunk));
} else if (is_key) {
// key columns
if (_segment_writers[_current_writer_index]->num_rows_written() + chunk_num_rows >=
_context.max_rows_per_segment) {
RETURN_IF_ERROR(_flush_columns(&_segment_writers[_current_writer_index]));
auto segment_writer = _create_segment_writer(column_indexes, is_key);
if (!segment_writer.ok()) return segment_writer.status();
_segment_writers.emplace_back(std::move(segment_writer).value());
++_current_writer_index;
}
RETURN_IF_ERROR(_segment_writers[_current_writer_index]->append_chunk(chunk));
} else {
// non key columns
uint32_t num_rows_written = _segment_writers[_current_writer_index]->num_rows_written();
uint32_t segment_num_rows = _segment_writers[_current_writer_index]->num_rows();
DCHECK_LE(num_rows_written, segment_num_rows);
// init segment writer
if (_current_writer_index == 0 && num_rows_written == 0) {
RETURN_IF_ERROR(_segment_writers[_current_writer_index]->init(column_indexes, is_key));
}
if (num_rows_written + chunk_num_rows <= segment_num_rows) {
RETURN_IF_ERROR(_segment_writers[_current_writer_index]->append_chunk(chunk));
} else {
// split into multi chunks and write into multi segments
auto write_chunk = chunk.clone_empty();
size_t num_left_rows = chunk_num_rows;
size_t offset = 0;
while (num_left_rows > 0) {
if (segment_num_rows == num_rows_written) {
RETURN_IF_ERROR(_flush_columns(&_segment_writers[_current_writer_index]));
++_current_writer_index;
RETURN_IF_ERROR(_segment_writers[_current_writer_index]->init(column_indexes, is_key));
num_rows_written = _segment_writers[_current_writer_index]->num_rows_written();
segment_num_rows = _segment_writers[_current_writer_index]->num_rows();
}
size_t write_size = segment_num_rows - num_rows_written;
if (write_size > num_left_rows) {
write_size = num_left_rows;
}
write_chunk->append(chunk, offset, write_size);
RETURN_IF_ERROR(_segment_writers[_current_writer_index]->append_chunk(*write_chunk));
write_chunk->reset();
num_left_rows -= write_size;
offset += write_size;
num_rows_written = _segment_writers[_current_writer_index]->num_rows_written();
}
DCHECK_EQ(0, num_left_rows);
DCHECK_EQ(offset, chunk_num_rows);
}
}
if (is_key) {
_num_rows_written += static_cast<int64_t>(chunk_num_rows);
}
_total_row_size += static_cast<int64_t>(chunk.bytes_usage());
return Status::OK();
}
Status VerticalBetaRowsetWriter::add_columns_with_rssid(const vectorized::Chunk& chunk,
const std::vector<uint32_t>& column_indexes,
const std::vector<uint32_t>& rssid) {
RETURN_IF_ERROR(add_columns(chunk, column_indexes, true));
if (!_src_rssids) {
_src_rssids = std::make_unique<std::vector<uint32_t>>();
}
_src_rssids->insert(_src_rssids->end(), rssid.begin(), rssid.end());
return Status::OK();
}
Status VerticalBetaRowsetWriter::flush_columns() {
if (_segment_writers.empty()) {
return Status::OK();
}
DCHECK(_segment_writers[_current_writer_index]);
RETURN_IF_ERROR(_flush_columns(&_segment_writers[_current_writer_index]));
_current_writer_index = 0;
return Status::OK();
}
Status VerticalBetaRowsetWriter::final_flush() {
for (auto& segment_writer : _segment_writers) {
uint64_t segment_size = 0;
if (auto st = segment_writer->finalize_footer(&segment_size); !st.ok()) {
LOG(WARNING) << "Fail to finalize segment footer, " << st;
return st;
}
{
std::lock_guard<std::mutex> l(_lock);
_total_data_size += static_cast<int64_t>(segment_size);
}
// check global_dict efficacy
const auto& seg_global_dict_columns_valid_info = segment_writer->global_dict_columns_valid_info();
for (const auto& it : seg_global_dict_columns_valid_info) {
if (!it.second) {
_global_dict_columns_valid_info[it.first] = false;
} else {
if (const auto& iter = _global_dict_columns_valid_info.find(it.first);
iter == _global_dict_columns_valid_info.end()) {
_global_dict_columns_valid_info[it.first] = true;
}
}
}
segment_writer.reset();
}
return Status::OK();
}
StatusOr<std::unique_ptr<SegmentWriter>> VerticalBetaRowsetWriter::_create_segment_writer(
const std::vector<uint32_t>& column_indexes, bool is_key) {
std::lock_guard<std::mutex> l(_lock);
std::string path = BetaRowset::segment_file_path(_context.rowset_path_prefix, _context.rowset_id, _num_segment);
ASSIGN_OR_RETURN(auto wfile, _fs->new_writable_file(path));
const auto* schema = _rowset_schema != nullptr ? _rowset_schema.get() : _context.tablet_schema;
auto segment_writer = std::make_unique<SegmentWriter>(std::move(wfile), _num_segment, schema, _writer_options);
RETURN_IF_ERROR(segment_writer->init(column_indexes, is_key));
++_num_segment;
return std::move(segment_writer);
}
Status VerticalBetaRowsetWriter::_flush_columns(std::unique_ptr<SegmentWriter>* segment_writer) {
uint64_t index_size = 0;
RETURN_IF_ERROR((*segment_writer)->finalize_columns(&index_size));
{
std::lock_guard<std::mutex> l(_lock);
_total_index_size += static_cast<int64_t>(index_size);
}
if (_src_rssids) {
return flush_src_rssids((*segment_writer)->segment_id());
}
return Status::OK();
}
} // namespace starrocks
|
#include "ModuleCameraWUP.h"
#include "CameraWUP.h"
#include "ShrinkerWUP.h"
ModuleCameraWUP* gInstanceModuleCameraWUP=0;
IMPLEMENT_CLASS_INFO(ModuleCameraWUP)
//! constructor
ModuleCameraWUP::ModuleCameraWUP(const kstl::string& name,CLASS_NAME_TREE_ARG) : ModuleBase(name,PASS_CLASS_NAME_TREE_ARG)
{
}
//! destructor
ModuleCameraWUP::~ModuleCameraWUP()
{
}
//! module init, register FilePathManager
void ModuleCameraWUP::Init(KigsCore* core, const kstl::vector<CoreModifiableAttribute*>* params)
{
BaseInit(core,"ModuleCameraWUP",params);
DECLARE_FULL_CLASS_INFO(core, CameraWUP,WebCamera,CameraModule)
DECLARE_FULL_CLASS_INFO(core, ShrinkerWUP, Shrinker, CameraModule)
// DECLARE_FULL_CLASS_INFO(core, BodyTracking, BodyTracking, CameraModule)
// DECLARE_FULL_CLASS_INFO(core, DrawBody, DrawBody, CameraModule)
}
//! module close
void ModuleCameraWUP::Close()
{
BaseClose();
}
//! module update
void ModuleCameraWUP::Update(const Timer& timer, void* addParam)
{
BaseUpdate(timer,addParam);
}
ModuleBase* MODULEINITFUNC(KigsCore* core, const kstl::vector<CoreModifiableAttribute*>* params)
{
KigsCore::ModuleStaticInit(core);
DECLARE_CLASS_INFO_WITHOUT_FACTORY(ModuleCameraWUP,"ModuleCameraWUP");
gInstanceModuleCameraWUP=new ModuleCameraWUP("ModuleCameraWUP");
gInstanceModuleCameraWUP->Init(core,params);
return gInstanceModuleCameraWUP;
}
|
#include<iostream>
#include<iomanip>
#include<string>
#include<stdio.h>
#include<sqlite3.h>
#include<sstream>
#include<exception>
#include<stdlib.h>
#include <bits/stdc++.h>
#include "Library.h"
using namespace std;
int Book::add_book()
{
cout<<"\nNEW BOOK ENTRY...\n";
cout<<"Enter The Book Identity number:\n";//should this be generated
cin>>book_id;
cin.ignore();
cout<<"Enter The Name of The Book:\n";
getline(cin,book_name);
cout<<"Enter The Name of The Author:\n";
getline(cin,author);
cout<<"Enter The Number of Copies:\n";
cin>>number_of_copies;
cin.ignore();
if(number_of_copies>0)
availability=1;
cout<<"Enter Description:\n";
getline(cin,description);
sqlite3 *db;
char *zErrMsg = 0;
int rc;
std::ostringstream sql;
std::string command;
/* Open database */
rc = sqlite3_open("../book.db", &db);
if( rc )
{
fprintf(stderr, "Can't open database: %s\n", sqlite3_errmsg(db));
return(0);
}
else
fprintf(stderr, "Opened database successfully\n");
/* Create SQL statement */
sql<<"INSERT INTO BOOKS VALUES (" <<book_id<< ", '"
<<book_name<<"','"
<<author<<"','"
<<description<<"',"
<<number_of_copies<<")";
command=sql.str();
/* Execute SQL statement */
rc = sqlite3_exec(db, command.c_str(), callback, 0, &zErrMsg);
if( rc != SQLITE_OK )
{
fprintf(stderr, "SQL error: %s\n", zErrMsg);
sqlite3_free(zErrMsg);
}
else
fprintf(stdout, "Records created successfully\n");
sqlite3_close(db);
return 0;//add other codes for error handling
}
int Book::remove_book()
{
//cout<<"\nDELETE A BOOK ENTRY...\n";
//cout<<"Enter The Book name:\n";//should this be generated
//cin>>book_name;
//cin.ignore();
sqlite3 *db;
char *zErrMsg = 0;
int rc;
std::ostringstream sql;
std::string command;
/* Open database */
rc = sqlite3_open("../book.db", &db);
if( rc )
{
fprintf(stderr, "Can't open database: %s\n", sqlite3_errmsg(db));
return(0);
}
else
fprintf(stderr, "Opened database successfully\n");
/* Create SQL statement */
sql<<"DELETE FROM BOOKS WHERE Book_id ="<<book_id<<" And Book_name='"<<book_name<<"';";
command=sql.str();
/* Execute SQL statement */
rc = sqlite3_exec(db, command.c_str(), callback, 0, &zErrMsg);
if( rc != SQLITE_OK )
{
fprintf(stderr, "SQL error: %s\n", zErrMsg);
sqlite3_free(zErrMsg);
}
sqlite3_close(db);
return 0;
}
int Book::modify_book()
{
cout<<"\nMODIFY BOOK INFORMATION...\n";
cout<<"Enter The Book Identity number:\n";//should this be generated
cin>>book_id;
cin.ignore();
sqlite3 *db;
char *zErrMsg = 0;
int rc;
std::ostringstream sql;
std::string command;
/* Open database */
rc = sqlite3_open("book.db", &db);
if( rc )
{
fprintf(stderr, "Can't open database: %s\n", sqlite3_errmsg(db));
return(0);
}
else
fprintf(stderr, "Opened database successfully\n");
/* Create SQL statement */
int choice;
cout<<"Which Detail must be modified:\n";
cout<<"1. Name of the Book 2. Author 3. Description 4. Number of Copies\n";
cin>>choice;
cin.ignore();
switch(choice)
{
case 1:
cout<<"Modified name:\n";
getline(cin,book_name);
sql<<"UPDATE BOOKS SET Book_name='"<<book_name<<"' WHERE Book_Id="<<book_id;
break;
case 2:
cout<<"Modified name:\n";
getline(cin,author);
sql<<"UPDATE BOOKS SET Author='"<<author<<"' WHERE Book_Id="<<book_id;
break;
case 3:
cout<<"Modified description:\n";
getline(cin,description);
sql<<"UPDATE BOOKS SET Description='"<<description<<"' WHERE Book_Id="<<book_id;
break;
case 4:
cout<<"Modified number of copies:\n";
cin>>number_of_copies;
cin.ignore();
sql<<"UPDATE BOOKS SET Copies="<<number_of_copies<<" WHERE Book_Id="<<book_id;
break;
default:
break;
}
command=sql.str();
/* Execute SQL statement */
rc = sqlite3_exec(db, command.c_str(), callback, 0, &zErrMsg);
if( rc != SQLITE_OK )
{
fprintf(stderr, "SQL error: %s\n", zErrMsg);
sqlite3_free(zErrMsg);
}
sqlite3_close(db);
return 0;
}
int Book::print_info()
{
cout<<"\nPRINT BOOK INFORMATION...\n";
cout<<"Enter The Book Identity number:\n";//should this be generated
cin>>book_id;
cin.ignore();
sqlite3 *db;
char *zErrMsg = 0;
int rc;
std::ostringstream sql;
std::string command;
/* Open database */
rc = sqlite3_open("book.db", &db);
if( rc )
{
fprintf(stderr, "Can't open database: %s\n", sqlite3_errmsg(db));
return(0);
}
else
fprintf(stderr, "Opened database successfully\n");
/* Create SQL statement */
sql<<"SELECT * FROM BOOKS WHERE Book_Id="<<book_id;
command=sql.str();
/* Execute SQL statement */
rc = sqlite3_exec(db, command.c_str(), callback, 0, &zErrMsg);
if( rc != SQLITE_OK )
{
fprintf(stderr, "SQL error: %s\n", zErrMsg);
sqlite3_free(zErrMsg);
}
sqlite3_close(db);
return 0;
}
|
/***********************************************************************************************************************
* OpenStudio(R), Copyright (c) 2008-2019, Alliance for Sustainable Energy, LLC, and other contributors. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
* following conditions are met:
*
* (1) Redistributions of source code must retain the above copyright notice, this list of conditions and the following
* disclaimer.
*
* (2) 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.
*
* (3) Neither the name of the copyright holder nor the names of any contributors may be used to endorse or promote products
* derived from this software without specific prior written permission from the respective party.
*
* (4) Other than as required in clauses (1) and (2), distributions in any form of modifications or other derivative works
* may not use the "OpenStudio" trademark, "OS", "os", or any other confusingly similar designation without specific prior
* written permission from Alliance for Sustainable Energy, LLC.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER(S) AND ANY 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(S), ANY CONTRIBUTORS, THE UNITED STATES GOVERNMENT, OR THE UNITED
* STATES DEPARTMENT OF ENERGY, NOR ANY OF THEIR EMPLOYEES, 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 "RefrigerationGridView.hpp"
#include "../shared_gui_components/OSGridView.hpp"
#include "ModelObjectItem.hpp"
#include "OSAppBase.hpp"
#include "OSDocument.hpp"
#include "../model/ModelObject.hpp"
#include "../model/ModelObject_Impl.hpp"
#include "../model/RefrigerationCase.hpp"
#include "../model/RefrigerationCase_Impl.hpp"
#include "../model/RefrigerationSystem.hpp"
#include "../model/RefrigerationSystem_Impl.hpp"
#include "../model/RefrigerationWalkIn.hpp"
#include "../model/RefrigerationWalkIn_Impl.hpp"
#include "../model/Schedule.hpp"
#include "../model/Schedule_Impl.hpp"
#include "../model/ScheduleTypeRegistry.hpp"
#include "../model/ThermalZone.hpp"
#include "../model/ThermalZone_Impl.hpp"
#include "../model/Model.hpp"
#include "../model/Model_Impl.hpp"
#include "../utilities/idd/IddEnums.hxx"
#include "../utilities/idd/Refrigeration_Case_FieldEnums.hxx"
#include "../utilities/idd/Refrigeration_WalkIn_FieldEnums.hxx"
#include <QBoxLayout>
#include <QCheckBox>
#include <QLabel>
#include <QScrollArea>
#include <QSettings>
#include <QTimer>
// These defines provide a common area for field display names
// used on column headers, and other grid widgets
#define SELECTED "All"
// Display Case Fields
#define ANTISWEATHEATERCONTROLTYPE "Anti Sweat Heater Control Type"
#define AVAILABILITYSCHEDULE "Availability Schedule" // TODO this has not yet been implemented
#define AVERAGEREFRIGERANTCHARGEINVENTORY "Average Refrigerant Charge Inventory" // TODO this has not yet been implemented
#define CASEANTISWEATHEATERPOWERPERUNITLENGTH "Case Anti Sweat Heater Power\nper Unit Length"
#define CASECREDITFRACTIONSCHEDULE "Case Credit Fraction Schedule"
#define CASEDEFROSTDRIPDOWNSCHEDULE "Case Defrost Drip Down Schedule" // TODO this has not yet been implemented
#define CASEDEFROSTPOWERPERUNITLENGTH "Case Defrost Power\nper Unit Length"
#define CASEDEFROSTSCHEDULE "Case Defrost Schedule" // TODO this has not yet been implemented
#define CASEDEFROSTTYPE "Case Defrost Type" // TODO this has not yet been implemented
#define CASEHEIGHT "Case Height" // TODO this has not yet been implemented
#define CASELENGTH "Case Length"
#define CASELIGHTINGSCHEDULE "Case Lighting Schedule"
#define CASEOPERATINGTEMPERATURE "Case Operating Temperature"
#define DEFROSTENERGYCORRECTIONCURVE "Defrost Energy Correction Curve" // TODO this has not yet been implemented
#define DEFROSTENERGYCORRECTIONCURVETYPE "Defrost Energy Correction Curve Type" // TODO ***************************************** AVAILABLE, but this has not yet been called
#define DESIGNEVAPORATORTEMPERATUREORBRINEINLETTEMPERATURE "Design Evaporator Temperature\nor Brine Inlet Temperature"
#define FRACTIONOFANTISWEATHEATERENERGYTOCASE "Fraction of Anti Sweat\nHeater Energy to Case"
#define FRACTIONOFLIGHTINGENERGYTOCASE "Fraction of Lighting Energy to Case"
#define HUMIDITYATZEROANTISWEATHEATERENERGY "Humidity at Zero Anti Sweat\nHeater Energy"
#define INSTALLEDCASELIGHTINGPOWERPERUNITLENGTH "Installed Case Lighting Power\nper Unit Length"
#define LATENTCASECREDITCURVETYPE "Latent Case Credit Curve Type" // TODO this has not yet been implemented
#define MINIMUMANTISWEATHEATERPOWERPERUNITLENGTH "Minimum Anti Sweat Heater Power\nper Unit Length"
#define NAME "Name"
#define OPERATINGCASEFANPOWERPERUNITLENGTH "Operating Case Fan Power\nper Unit Length"
#define RATEDAMBIENTRELATIVEHUMIDITY "Rated Ambient Relative Humidity" // TODO this has not yet been implemented
#define RATEDAMBIENTTEMPERATURE "Rated Ambient Temperature" // ************************************************************* TODO AVAILABLE, but this has not yet been called
#define RATEDLATENTHEATRATIO "Rated Latent Heat Ratio"
#define RATEDRUNTIMEFRACTION "Rated Runtime Fraction"
#define RATEDTOTALCOOLINGCAPACITYPERUNITLENGTH "Rated Total Cooling Capacity\nper Unit Length"
#define REFRIGERATEDCASERESTOCKINGSCHEDULE "Refrigerated Case Restocking Schedule"
#define STANDARDCASEFANPOWERPERUNITLENGTH "Standard Case Fan Power\nper Unit Length"
#define STANDARDCASELIGHTINGPOWERPERUNITLENGTH "Standard Case Lighting Power\nper Unit Length"
#define THERMALZONE "Thermal Zone"
#define RACK "Rack"
#define UNDERCASEHVACRETURNAIRFRACTION "Under Case HVAC Return Air Fraction"
// Walk In Fields
#define AVAILABILITYSCHEDULE "Availability Schedule"
#define AVERAGEREFRIGERANTCHARGEINVENTORY "Average Refrigerant Charge Inventory" // TODO this has not yet been implemented
#define DEFROSTCONTROLTYPE "Defrost Control Type"
#define DEFROSTDRIPDOWNSCHEDULE "Defrost Drip Down Schedule" // TODO this has not yet been implemented
#define DEFROSTPOWER "Defrost Power"
#define DEFROSTSCHEDULE "Defrost Schedule" // TODO this has not yet been implemented
#define DEFROSTTYPE "Defrost Type" // TODO this has not yet been implemented
#define HEATINGPOWERSCHEDULE "Heating Power Schedule"
#define INSULATEDFLOORSURFACEAREA "Insulated Floor Surface Area" // TODO this has not yet been implemented
#define INSULATEDFLOORUVALUE "Insulated Floor U Value"
#define LIGHTINGSCHEDULE "Lighting Schedule" // TODO this has not yet been implemented
#define NAME "Name"
#define OPERATINGTEMPERATURE "Operating Temperature" // TODO this has not yet been implemented
#define RATEDCIRCULATIONFANPOWER "Rated Circulation Fan Power" // TODO this has not yet been implemented
#define RATEDCOILCOOLINGCAPACITY "Rated Coil Cooling Capacity" // TODO this has not yet been implemented
#define RATEDCOOLINGCOILFANPOWER "Rated Cooling Coil Fan Power" // TODO this has not yet been implemented
#define RATEDCOOLINGSOURCETEMPERATURE "Rated Cooling Source Temperature" // TODO this has not yet been implemented
#define RATEDTOTALHEATINGPOWER "Rated Total Heating Power" // TODO this has not yet been implemented
#define RATEDTOTALLIGHTINGPOWER "Rated Total Lighting Power" // TODO this has not yet been implemented
#define RESTOCKINGSCHEDULE "Restocking Schedule"
#define TEMPERATURETERMINATIONDEFROSTFRACTIONTOICE "Temperature Termination\nDefrost Fraction to Ice"
#define ZONEBOUNDARIES "Zone Boundaries" // TODO this has not yet been implemented
#define ZONEBOUNDARYTHERMALZONE "Thermal Zone"
#define ZONEBOUNDARYTOTALINSULATEDSURFACEAREAFACINGZONE "Total Insulated Surface\nArea Facing Zone"
#define ZONEBOUNDARYAREAOFGLASSREACHINDOORSFACINGZONE "Area of Glass Reach In\nDoors Facing Zone"
#define ZONEBOUNDARYHEIGHTOFGLASSREACHINDOORSFACINGZONE "Height of Glass Reach In\nDoors Facing Zone"
#define ZONEBOUNDARYAREAOFSTOCKINGDOORSFACINGZONE "Area of Stocking Doors Facing Zone"
#define ZONEBOUNDARYHEIGHTOFSTOCKINGDOORSFACINGZONE "Height of Stocking Doors Facing Zone"
#define ZONEBOUNDARYINSULATEDSURFACEUVALUEFACINGZONE "Insulated Surface U\nValue Facing Zone"
#define ZONEBOUNDARYGLASSREACHINDOORUVALUEFACINGZONE "Glass Reach In Door U\nValue Facing Zone"
#define ZONEBOUNDARYSTOCKINGDOORUVALUEFACINGZONE "Stocking Door U\nValue Facing Zone"
#define ZONEBOUNDARYSTOCKINGDOOROPENINGSCHEDULEFACINGZONE "Stocking Door Opening\nSchedule Facing Zone"
namespace openstudio {
struct ModelObjectNameSorter{
// sort by name
bool operator()(const model::ModelObject & lhs, const model::ModelObject & rhs){
return (lhs.name() < rhs.name());
}
};
RefrigerationGridView::RefrigerationGridView(bool isIP, const model::Model & model, QWidget * parent)
: QWidget(parent),
m_isIP(isIP)
{
QVBoxLayout * layout = nullptr;
layout = new QVBoxLayout();
layout->setSpacing(0);
layout->setContentsMargins(0,0,0,0);
setLayout(layout);
auto scrollLayout = new QVBoxLayout();
scrollLayout->setSpacing(0);
scrollLayout->setContentsMargins(0,0,0,0);
auto scrollWidget = new QWidget();
scrollWidget->setObjectName("ScrollWidget");
scrollWidget->setStyleSheet("QWidget#ScrollWidget { background: transparent; }");
scrollWidget->setLayout(scrollLayout);
auto scrollArea = new QScrollArea();
scrollArea->setContentsMargins(0,0,0,0);
scrollArea->setFrameStyle(QFrame::NoFrame);
scrollArea->setWidget(scrollWidget);
scrollArea->setWidgetResizable(true);
scrollArea->setBackgroundRole(QPalette::NoRole);
layout->addWidget(scrollArea);
std::vector<model::RefrigerationCase> refrigerationCases = model.getConcreteModelObjects<model::RefrigerationCase>();
std::vector<model::ModelObject> caseModelObjects = subsetCastVector<model::ModelObject>(refrigerationCases);
RefrigerationCaseGridController * refrigerationCaseGridController = new RefrigerationCaseGridController(m_isIP, "Display Cases", IddObjectType::OS_Refrigeration_Case, model, caseModelObjects);
OSGridView * caseGridView = new OSGridView(refrigerationCaseGridController, "Display Cases", "Drop\nCase", true, parent);
bool isConnected = false;
isConnected = connect(caseGridView, SIGNAL(dropZoneItemClicked(OSItem*)), this, SIGNAL(dropZoneItemClicked(OSItem*)));
OS_ASSERT(isConnected);
scrollLayout->addWidget(caseGridView,0,Qt::AlignTop);
std::vector<model::RefrigerationWalkIn> refrigerationWalkIns = model.getConcreteModelObjects<model::RefrigerationWalkIn>();
std::vector<model::ModelObject> walkInModelObjects = subsetCastVector<model::ModelObject>(refrigerationWalkIns);
RefrigerationWalkInGridController * refrigerationWalkInGridController = new RefrigerationWalkInGridController(m_isIP, "Walk Ins", IddObjectType::OS_Refrigeration_WalkIn, model, walkInModelObjects);
OSGridView * walkInView = new OSGridView(refrigerationWalkInGridController, "Walk Ins", "Drop\nWalk In", true, parent);
isConnected = connect(walkInView, SIGNAL(dropZoneItemClicked(OSItem*)), this, SIGNAL(dropZoneItemClicked(OSItem*)));
OS_ASSERT(isConnected);
scrollLayout->addWidget(walkInView,0,Qt::AlignTop);
scrollLayout->addStretch(1);
connect(this, &RefrigerationGridView::toggleUnitsClicked, refrigerationCaseGridController, &RefrigerationCaseGridController::toggleUnitsClicked);
connect(this, &RefrigerationGridView::toggleUnitsClicked, refrigerationWalkInGridController, &RefrigerationWalkInGridController::toggleUnitsClicked);
connect(this, &RefrigerationGridView::toggleUnitsClicked, refrigerationCaseGridController, &RefrigerationCaseGridController::toggleUnits);
connect(this, &RefrigerationGridView::toggleUnitsClicked, refrigerationWalkInGridController, &RefrigerationWalkInGridController::toggleUnits);
std::vector<model::RefrigerationSystem> refrigerationSystems = model.getConcreteModelObjects<model::RefrigerationSystem>(); // NOTE for horizontal system list
}
RefrigerationCaseGridController::RefrigerationCaseGridController(bool isIP,
const QString & headerText,
IddObjectType iddObjectType,
model::Model model,
std::vector<model::ModelObject> modelObjects) :
OSGridController(isIP, headerText, iddObjectType, model, modelObjects)
{
setCategoriesAndFields();
}
void RefrigerationCaseGridController::setCategoriesAndFields()
{
{
std::vector<QString> fields;
fields.push_back(RACK);
fields.push_back(THERMALZONE);
fields.push_back(CASELENGTH);
std::pair<QString,std::vector<QString> > categoryAndFields = std::make_pair(QString("General"),fields);
m_categoriesAndFields.push_back(categoryAndFields);
}
{
std::vector<QString> fields;
fields.push_back(UNDERCASEHVACRETURNAIRFRACTION);
fields.push_back(CASEOPERATINGTEMPERATURE);
fields.push_back(DESIGNEVAPORATORTEMPERATUREORBRINEINLETTEMPERATURE);
fields.push_back(RATEDRUNTIMEFRACTION);
std::pair<QString,std::vector<QString> > categoryAndFields = std::make_pair(QString("Operation"),fields);
m_categoriesAndFields.push_back(categoryAndFields);
}
{
std::vector<QString> fields;
fields.push_back(RATEDTOTALCOOLINGCAPACITYPERUNITLENGTH);
fields.push_back(CASECREDITFRACTIONSCHEDULE);
fields.push_back(RATEDLATENTHEATRATIO);
std::pair<QString,std::vector<QString> > categoryAndFields = std::make_pair(QString("Cooling\nCapacity"),fields);
m_categoriesAndFields.push_back(categoryAndFields);
}
{
std::vector<QString> fields;
fields.push_back(STANDARDCASEFANPOWERPERUNITLENGTH);
fields.push_back(OPERATINGCASEFANPOWERPERUNITLENGTH);
std::pair<QString,std::vector<QString> > categoryAndFields = std::make_pair(QString("Fan"),fields);
m_categoriesAndFields.push_back(categoryAndFields);
}
{
std::vector<QString> fields;
fields.push_back(STANDARDCASELIGHTINGPOWERPERUNITLENGTH);
fields.push_back(INSTALLEDCASELIGHTINGPOWERPERUNITLENGTH);
fields.push_back(FRACTIONOFLIGHTINGENERGYTOCASE);
fields.push_back(CASELIGHTINGSCHEDULE);
std::pair<QString,std::vector<QString> > categoryAndFields = std::make_pair(QString("Lighting"),fields);
m_categoriesAndFields.push_back(categoryAndFields);
}
{
std::vector<QString> fields;
fields.push_back(CASEANTISWEATHEATERPOWERPERUNITLENGTH);
fields.push_back(ANTISWEATHEATERCONTROLTYPE);
fields.push_back(MINIMUMANTISWEATHEATERPOWERPERUNITLENGTH);
fields.push_back(HUMIDITYATZEROANTISWEATHEATERENERGY);
fields.push_back(FRACTIONOFANTISWEATHEATERENERGYTOCASE);
std::pair<QString,std::vector<QString> > categoryAndFields = std::make_pair(QString("Case\nAnti-Sweat\nHeaters"),fields);
m_categoriesAndFields.push_back(categoryAndFields);
}
{
std::vector<QString> fields;
fields.push_back(CASEDEFROSTPOWERPERUNITLENGTH);
fields.push_back(REFRIGERATEDCASERESTOCKINGSCHEDULE);
std::pair<QString,std::vector<QString> > categoryAndFields = std::make_pair(QString("Defrost\nAnd\nRestocking"),fields);
m_categoriesAndFields.push_back(categoryAndFields);
}
OSGridController::setCategoriesAndFields();
}
void RefrigerationCaseGridController::addColumns(const QString &/*category*/, std::vector<QString> & fields)
{
// always show name column
fields.insert(fields.begin(), {NAME, SELECTED});
m_baseConcepts.clear();
for (const QString& field : fields) {
if(field == RATEDAMBIENTTEMPERATURE){
addQuantityEditColumn(Heading(QString(RATEDAMBIENTTEMPERATURE)),
QString("C"),
QString("C"),
QString("F"),
m_isIP,
NullAdapter(&model::RefrigerationCase::ratedAmbientTemperature),
NullAdapter(&model::RefrigerationCase::setRatedAmbientTemperature));
}else if(field == SELECTED){
auto checkbox = QSharedPointer<QCheckBox>(new QCheckBox());
checkbox->setToolTip("Check to select all rows");
connect(checkbox.data(), &QCheckBox::stateChanged, this, &RefrigerationCaseGridController::selectAllStateChanged);
connect(checkbox.data(), &QCheckBox::stateChanged, this->gridView(), &OSGridView::gridRowSelectionChanged);
addSelectColumn(Heading(QString(SELECTED), false, false, checkbox), "Check to select this row");
}else if(field == RATEDAMBIENTRELATIVEHUMIDITY){
addValueEditColumn(Heading(QString(RATEDAMBIENTRELATIVEHUMIDITY)),
NullAdapter(&model::RefrigerationCase::ratedAmbientRelativeHumidity),
NullAdapter(&model::RefrigerationCase::setRatedAmbientRelativeHumidity));
}else if(field == RATEDTOTALCOOLINGCAPACITYPERUNITLENGTH){
addQuantityEditColumn(Heading(QString(RATEDTOTALCOOLINGCAPACITYPERUNITLENGTH)),
QString("W/m"),
QString("W/m"),
QString("Btu/hr*ft"),
m_isIP,
NullAdapter(&model::RefrigerationCase::ratedTotalCoolingCapacityperUnitLength),
NullAdapter(&model::RefrigerationCase::setRatedTotalCoolingCapacityperUnitLength));
}else if(field == RATEDLATENTHEATRATIO){
addValueEditColumn(Heading(QString(RATEDLATENTHEATRATIO)),
NullAdapter(&model::RefrigerationCase::ratedLatentHeatRatio),
NullAdapter(&model::RefrigerationCase::setRatedLatentHeatRatio));
}else if(field == RATEDRUNTIMEFRACTION){
addValueEditColumn(Heading(QString(RATEDRUNTIMEFRACTION)),
NullAdapter(&model::RefrigerationCase::ratedRuntimeFraction),
NullAdapter(&model::RefrigerationCase::setRatedRuntimeFraction));
}else if(field == CASELENGTH){
addQuantityEditColumn(Heading(QString(CASELENGTH)),
QString("m"),
QString("m"),
QString("ft"),
m_isIP,
NullAdapter(&model::RefrigerationCase::caseLength),
NullAdapter(&model::RefrigerationCase::setCaseLength));
}else if(field == CASEOPERATINGTEMPERATURE){
addQuantityEditColumn(Heading(QString(CASEOPERATINGTEMPERATURE)),
QString("C"),
QString("C"),
QString("F"),
m_isIP,
NullAdapter(&model::RefrigerationCase::caseOperatingTemperature),
NullAdapter(&model::RefrigerationCase::setCaseOperatingTemperature));
}else if(field == STANDARDCASEFANPOWERPERUNITLENGTH){
addQuantityEditColumn(Heading(QString(STANDARDCASEFANPOWERPERUNITLENGTH)),
QString("W/m"),
QString("W/m"),
QString("W/ft"),
m_isIP,
NullAdapter(&model::RefrigerationCase::standardCaseFanPowerperUnitLength),
NullAdapter(&model::RefrigerationCase::setStandardCaseFanPowerperUnitLength));
}else if(field == OPERATINGCASEFANPOWERPERUNITLENGTH){
addQuantityEditColumn(Heading(QString(OPERATINGCASEFANPOWERPERUNITLENGTH)),
QString("W/m"),
QString("W/m"),
QString("W/ft"),
m_isIP,
NullAdapter(&model::RefrigerationCase::operatingCaseFanPowerperUnitLength),
NullAdapter(&model::RefrigerationCase::setOperatingCaseFanPowerperUnitLength));
}else if(field == FRACTIONOFLIGHTINGENERGYTOCASE){
addValueEditColumn(Heading(QString(FRACTIONOFLIGHTINGENERGYTOCASE)),
NullAdapter(&model::RefrigerationCase::fractionofLightingEnergytoCase),
NullAdapter(&model::RefrigerationCase::setFractionofLightingEnergytoCase));
}else if(field == CASEANTISWEATHEATERPOWERPERUNITLENGTH){
addQuantityEditColumn(Heading(QString(CASEANTISWEATHEATERPOWERPERUNITLENGTH)),
QString("W/m"),
QString("W/m"),
QString("W/ft"),
m_isIP,
NullAdapter(&model::RefrigerationCase::caseAntiSweatHeaterPowerperUnitLength),
NullAdapter(&model::RefrigerationCase::setCaseAntiSweatHeaterPowerperUnitLength));
}else if(field == MINIMUMANTISWEATHEATERPOWERPERUNITLENGTH){
addQuantityEditColumn(Heading(QString(MINIMUMANTISWEATHEATERPOWERPERUNITLENGTH)),
QString("W/m"),
QString("W/m"),
QString("W/ft"),
m_isIP,
NullAdapter(&model::RefrigerationCase::minimumAntiSweatHeaterPowerperUnitLength),
NullAdapter(&model::RefrigerationCase::setMinimumAntiSweatHeaterPowerperUnitLength));
}else if(field == CASEHEIGHT){
addQuantityEditColumn(Heading(QString(CASEHEIGHT)),
QString("m"),
QString("m"),
QString("ft"),
m_isIP,
NullAdapter(&model::RefrigerationCase::caseHeight),
NullAdapter(&model::RefrigerationCase::setCaseHeight));
}else if(field == FRACTIONOFANTISWEATHEATERENERGYTOCASE){
addValueEditColumn(Heading(QString(FRACTIONOFANTISWEATHEATERENERGYTOCASE)),
NullAdapter(&model::RefrigerationCase::fractionofAntiSweatHeaterEnergytoCase),
NullAdapter(&model::RefrigerationCase::setFractionofAntiSweatHeaterEnergytoCase));
}else if(field == CASEDEFROSTPOWERPERUNITLENGTH){
addQuantityEditColumn(Heading(QString(CASEDEFROSTPOWERPERUNITLENGTH)),
QString("W/m"),
QString("W/m"),
QString("W/ft"),
m_isIP,
NullAdapter(&model::RefrigerationCase::caseDefrostPowerperUnitLength),
NullAdapter(&model::RefrigerationCase::setCaseDefrostPowerperUnitLength));
}else if(field == UNDERCASEHVACRETURNAIRFRACTION){
addValueEditColumn(Heading(QString(UNDERCASEHVACRETURNAIRFRACTION)),
NullAdapter(&model::RefrigerationCase::underCaseHVACReturnAirFraction),
NullAdapter(&model::RefrigerationCase::setUnderCaseHVACReturnAirFraction));
}else if(field == STANDARDCASELIGHTINGPOWERPERUNITLENGTH){
addQuantityEditColumn(Heading(QString(STANDARDCASELIGHTINGPOWERPERUNITLENGTH)),
QString("W/m"),
QString("W/m"),
QString("W/ft"),
m_isIP,
NullAdapter(&model::RefrigerationCase::standardCaseLightingPowerperUnitLength),
NullAdapter(&model::RefrigerationCase::setStandardCaseLightingPowerperUnitLength));
}else if(field == HUMIDITYATZEROANTISWEATHEATERENERGY){
addValueEditColumn(Heading(QString(HUMIDITYATZEROANTISWEATHEATERENERGY)),
NullAdapter(&model::RefrigerationCase::humidityatZeroAntiSweatHeaterEnergy),
NullAdapter(&model::RefrigerationCase::setHumidityatZeroAntiSweatHeaterEnergy));
}else if(field == AVERAGEREFRIGERANTCHARGEINVENTORY){
addQuantityEditColumn(Heading(QString(AVERAGEREFRIGERANTCHARGEINVENTORY)),
QString("kg/m"),
QString("kg/m"),
QString("lb/ft"),
m_isIP,
NullAdapter(&model::RefrigerationCase::averageRefrigerantChargeInventory),
NullAdapter(&model::RefrigerationCase::setAverageRefrigerantChargeInventory));
}else if(field == LATENTCASECREDITCURVETYPE){
addComboBoxColumn<std::string, model::RefrigerationCase>(
Heading(QString(LATENTCASECREDITCURVETYPE)),
static_cast<std::string(*)(const std::string&)>(&openstudio::toString),
std::function<std::vector<std::string> ()>(&model::RefrigerationCase::latentCaseCreditCurveTypeValues),
CastNullAdapter<model::RefrigerationCase>(&model::RefrigerationCase::latentCaseCreditCurveType),
CastNullAdapter<model::RefrigerationCase>(&model::RefrigerationCase::setLatentCaseCreditCurveType),
boost::optional<std::function<void(model::RefrigerationCase *)> >(),
boost::optional<DataSource>());
}else if(field == ANTISWEATHEATERCONTROLTYPE){
addComboBoxColumn<std::string,model::RefrigerationCase>(
Heading(QString(ANTISWEATHEATERCONTROLTYPE)),
static_cast<std::string (*)(const std::string&)>(&openstudio::toString),
std::function<std::vector<std::string> ()>(&model::RefrigerationCase::antiSweatHeaterControlTypeValues),
CastNullAdapter<model::RefrigerationCase>(&model::RefrigerationCase::antiSweatHeaterControlType),
CastNullAdapter<model::RefrigerationCase>(&model::RefrigerationCase::setAntiSweatHeaterControlType),
boost::optional<std::function<void(model::RefrigerationCase *)> >(),
boost::optional<DataSource>());
}else if(field == CASEDEFROSTTYPE){
addComboBoxColumn<std::string,model::RefrigerationCase>(
Heading(QString(CASEDEFROSTTYPE)),
static_cast<std::string (*)(const std::string&)>(&openstudio::toString),
std::function<std::vector<std::string> ()>(&model::RefrigerationCase::caseDefrostTypeValues),
CastNullAdapter<model::RefrigerationCase>(&model::RefrigerationCase::caseDefrostType),
CastNullAdapter<model::RefrigerationCase>(&model::RefrigerationCase::setCaseDefrostType),
boost::optional<std::function<void(model::RefrigerationCase *)> >(),
boost::optional<DataSource>());
}else if(field == DEFROSTENERGYCORRECTIONCURVETYPE){
addComboBoxColumn<std::string,model::RefrigerationCase>(
Heading(QString(DEFROSTENERGYCORRECTIONCURVETYPE)),
static_cast<std::string (*)(const std::string&)>(&openstudio::toString),
std::function<std::vector<std::string> ()>(&model::RefrigerationCase::defrostEnergyCorrectionCurveTypeValues),
CastNullAdapter<model::RefrigerationCase>(&model::RefrigerationCase::defrostEnergyCorrectionCurveType),
CastNullAdapter<model::RefrigerationCase>(&model::RefrigerationCase::setDefrostEnergyCorrectionCurveType),
boost::optional<std::function<void(model::RefrigerationCase *)> >(),
boost::optional<DataSource>());
}else if(field == INSTALLEDCASELIGHTINGPOWERPERUNITLENGTH){
addQuantityEditColumn(Heading(QString(INSTALLEDCASELIGHTINGPOWERPERUNITLENGTH)),
QString("W/m"),
QString("W/m"),
QString("W/ft"),
m_isIP,
NullAdapter(&model::RefrigerationCase::installedCaseLightingPowerperUnitLength),
NullAdapter(&model::RefrigerationCase::setInstalledCaseLightingPowerperUnitLength));
}else if(field == DESIGNEVAPORATORTEMPERATUREORBRINEINLETTEMPERATURE){
addQuantityEditColumn(Heading(QString(DESIGNEVAPORATORTEMPERATUREORBRINEINLETTEMPERATURE)),
QString("C"),
QString("C"),
QString("F"),
m_isIP,
NullAdapter(&model::RefrigerationCase::designEvaporatorTemperatureorBrineInletTemperature),
NullAdapter(&model::RefrigerationCase::setDesignEvaporatorTemperatureorBrineInletTemperature));
}else if(field == CASELIGHTINGSCHEDULE){
addComboBoxColumn<model::Schedule,model::RefrigerationCase>(
Heading(QString(CASELIGHTINGSCHEDULE)),
&openstudio::objectName,
std::function<std::vector<model::Schedule> ()>(std::bind(&openstudio::sortByObjectName<model::Schedule>,
std::bind(&openstudio::model::getCompatibleSchedules,
m_model,
"RefrigerationCase",
"Case Lighting"))), // NOTE these strings found in ScheduleTypeRegistry.cpp
NullAdapter(&model::RefrigerationCase::caseLightingSchedule),
NullAdapter(&model::RefrigerationCase::setCaseLightingSchedule),
NullAdapter(&model::RefrigerationCase::resetCaseLightingSchedule));
}else if(field == CASEDEFROSTSCHEDULE){
addComboBoxColumn<model::Schedule,model::RefrigerationCase>(
Heading(QString(CASEDEFROSTSCHEDULE)),
&openstudio::objectName,
std::function<std::vector<model::Schedule> ()>(std::bind(&openstudio::sortByObjectName<model::Schedule>,
std::bind(&openstudio::model::getCompatibleSchedules,
m_model,
"RefrigerationCase",
"Case Defrost"))),
NullAdapter(&model::RefrigerationCase::caseDefrostSchedule),
NullAdapter(&model::RefrigerationCase::setCaseDefrostSchedule),
NullAdapter(&model::RefrigerationCase::resetCaseDefrostSchedule));
}else if(field == CASEDEFROSTDRIPDOWNSCHEDULE){
addComboBoxColumn<model::Schedule,model::RefrigerationCase>(
Heading(QString(CASEDEFROSTDRIPDOWNSCHEDULE)),
&openstudio::objectName,
std::function<std::vector<model::Schedule> ()>(std::bind(&openstudio::sortByObjectName<model::Schedule>,
std::bind(&openstudio::model::getCompatibleSchedules,
m_model,
"RefrigerationCase",
"Case Defrost Drip-Down"))),
NullAdapter(&model::RefrigerationCase::caseDefrostDripDownSchedule),
NullAdapter(&model::RefrigerationCase::setCaseDefrostDripDownSchedule),
NullAdapter(&model::RefrigerationCase::resetCaseDefrostDripDownSchedule));
}else if(field == REFRIGERATEDCASERESTOCKINGSCHEDULE){
addComboBoxColumn<model::Schedule,model::RefrigerationCase>(
Heading(QString(REFRIGERATEDCASERESTOCKINGSCHEDULE)),
&openstudio::objectName,
std::function<std::vector<model::Schedule> ()>(std::bind(&openstudio::sortByObjectName<model::Schedule>,
std::bind(&openstudio::model::getCompatibleSchedules,
m_model,
"RefrigerationCase",
"Refrigerated Case Restocking"))),
NullAdapter(&model::RefrigerationCase::refrigeratedCaseRestockingSchedule),
NullAdapter(&model::RefrigerationCase::setRefrigeratedCaseRestockingSchedule),
NullAdapter(&model::RefrigerationCase::resetRefrigeratedCaseRestockingSchedule));
}else if(field == CASECREDITFRACTIONSCHEDULE){
addComboBoxColumn<model::Schedule,model::RefrigerationCase>(
Heading(QString(CASECREDITFRACTIONSCHEDULE)),
&openstudio::objectName,
std::function<std::vector<model::Schedule> ()>(std::bind(&openstudio::sortByObjectName<model::Schedule>,
std::bind(&openstudio::model::getCompatibleSchedules,
m_model,
"RefrigerationCase",
"Case Credit Fraction"))),
NullAdapter(&model::RefrigerationCase::caseCreditFractionSchedule),
NullAdapter(&model::RefrigerationCase::setCaseCreditFractionSchedule),
NullAdapter(&model::RefrigerationCase::resetCaseCreditFractionSchedule));
}else if(field == AVAILABILITYSCHEDULE){
addComboBoxColumn<model::Schedule,model::RefrigerationCase>(
Heading(QString(AVAILABILITYSCHEDULE)),
&openstudio::objectName,
std::function<std::vector<model::Schedule> ()>(std::bind(&openstudio::sortByObjectName<model::Schedule>,
std::bind(&openstudio::model::getCompatibleSchedules,
m_model,
"RefrigerationCase",
"Availability"))),
NullAdapter(&model::RefrigerationCase::availabilitySchedule),
NullAdapter(&model::RefrigerationCase::setAvailabilitySchedule),
NullAdapter(&model::RefrigerationCase::resetAvailabilitySchedule));
}else if(field == THERMALZONE){
addComboBoxColumn<model::ThermalZone,model::RefrigerationCase>(
Heading(QString(THERMALZONE)),
std::function<std::string (const openstudio::model::ThermalZone &)>(&openstudio::objectName),
std::function<std::vector<model::ThermalZone> ()>(std::bind(&openstudio::sortByObjectName<model::ThermalZone>,
std::bind(&model::Model::getConcreteModelObjects<model::ThermalZone>, m_model))),
CastNullAdapter<model::RefrigerationCase>(&model::RefrigerationCase::thermalZone),
CastNullAdapter<model::RefrigerationCase>(&model::RefrigerationCase::setThermalZone),
boost::optional<std::function<void(openstudio::model::RefrigerationCase *)>>(NullAdapter(&model::RefrigerationCase::resetThermalZone)),
boost::optional<openstudio::DataSource>());
}else if(field == RACK){
addComboBoxColumn<model::RefrigerationSystem,model::RefrigerationCase>(
Heading(QString(RACK)),
&openstudio::objectName,
std::function<std::vector<model::RefrigerationSystem> ()>(
std::bind(&openstudio::sortByObjectName<model::RefrigerationSystem>,
std::bind(&model::Model::getConcreteModelObjects<model::RefrigerationSystem>,m_model))),
NullAdapter(&model::RefrigerationCase::system),
NullAdapter(&model::RefrigerationCase::addToSystem),
NullAdapter(&model::RefrigerationCase::removeFromSystem));
}else if(field == DEFROSTENERGYCORRECTIONCURVE){
//boost::optional<CurveCubic> defrostEnergyCorrectionCurve() const; TODO
}else if(field == NAME){
addNameLineEditColumn(Heading(QString(NAME), false, false),
false,
false,
CastNullAdapter<model::RefrigerationCase>(&model::RefrigerationCase::name),
CastNullAdapter<model::RefrigerationCase>(&model::RefrigerationCase::setName));
}else{
// unhandled
OS_ASSERT(false);
}
}
}
QString RefrigerationCaseGridController::getColor(const model:: ModelObject & modelObject)
{
QColor defaultColor(Qt::lightGray);
QString color(defaultColor.name());
// TODO: The code below is currently commented out because a refresh crash bug is precluding rack color
// updates due to rack assignments to cases and walk-ins. No colors are better than wrong colors.
//std::vector<model::RefrigerationSystem> refrigerationSystems = m_model.getConcreteModelObjects<model::RefrigerationSystem>();
//boost::optional<model::RefrigerationCase> refrigerationCase = modelObject.optionalCast<model::RefrigerationCase>();
//OS_ASSERT(refrigerationCase);
//boost::optional<model::RefrigerationSystem> refrigerationSystem = refrigerationCase->system();
//if(!refrigerationSystem){
// return color;
//}
//std::vector<model::RefrigerationSystem>::iterator it;
//it = std::find(refrigerationSystems.begin(), refrigerationSystems.end(), refrigerationSystem.get());
//if(it != refrigerationSystems.end()){
// int index = std::distance(refrigerationSystems.begin(), it);
// if(index >= static_cast<int>(m_colors.size())){
// index = m_colors.size() - 1; // similar to scheduleView's approach
// }
// color = this->m_colors.at(index).name();
//}
return color;
}
void RefrigerationCaseGridController::checkSelectedFields()
{
if(!this->m_hasHorizontalHeader) return;
OSGridController::checkSelectedFields();
}
void RefrigerationCaseGridController::onItemDropped(const OSItemId& itemId)
{
boost::optional<model::ModelObject> modelObject = OSAppBase::instance()->currentDocument()->getModelObject(itemId);
if (modelObject){
if (modelObject->optionalCast<model::RefrigerationCase>()){
modelObject->clone(m_model);
emit modelReset();
}
}
}
void RefrigerationCaseGridController::refreshModelObjects()
{
std::vector<model::RefrigerationCase> refrigerationCases = m_model.getConcreteModelObjects<model::RefrigerationCase>();
m_modelObjects = subsetCastVector<model::ModelObject>(refrigerationCases);
std::sort(m_modelObjects.begin(), m_modelObjects.end(), ModelObjectNameSorter());
}
void RefrigerationCaseGridController::onComboBoxIndexChanged(int index)
{
// Note: find the correct system color on RACK change,
// but currently unable to know which row changed.
for(unsigned index = 0; index < m_horizontalHeader.size(); index++){
HorizontalHeaderWidget * horizontalHeaderWidget = qobject_cast<HorizontalHeaderWidget *>(m_horizontalHeader.at(index));
if(horizontalHeaderWidget->m_label->text() == RACK){
// NOTE required due to a race condition
// Code below commented out due to a very infrequent crash in the bowels of Qt appears to be exasperated by this refresh.
// A new refresh scheme with finer granularity may eliminate the problem, and restore rack colors.
//QTimer::singleShot(0, this, SLOT(reset())); TODO
break;
}
}
}
RefrigerationWalkInGridController::RefrigerationWalkInGridController(bool isIP,
const QString & headerText,
IddObjectType iddObjectType,
model::Model model,
std::vector<model::ModelObject> modelObjects) :
OSGridController(isIP, headerText, iddObjectType, model, modelObjects)
{
setCategoriesAndFields();
}
void RefrigerationWalkInGridController::setCategoriesAndFields()
{
{
std::vector<QString> fields;
fields.push_back(RACK);
fields.push_back(ZONEBOUNDARYTHERMALZONE);
std::pair<QString,std::vector<QString> > categoryAndFields = std::make_pair(QString("General"),fields);
m_categoriesAndFields.push_back(categoryAndFields);
}
{
std::vector<QString> fields;
fields.push_back(ZONEBOUNDARYTOTALINSULATEDSURFACEAREAFACINGZONE);
fields.push_back(ZONEBOUNDARYAREAOFGLASSREACHINDOORSFACINGZONE);
fields.push_back(ZONEBOUNDARYHEIGHTOFGLASSREACHINDOORSFACINGZONE);
fields.push_back(ZONEBOUNDARYAREAOFSTOCKINGDOORSFACINGZONE);
fields.push_back(ZONEBOUNDARYHEIGHTOFSTOCKINGDOORSFACINGZONE);
std::pair<QString,std::vector<QString> > categoryAndFields = std::make_pair(QString("Dimensions"),fields);
m_categoriesAndFields.push_back(categoryAndFields);
}
{
std::vector<QString> fields;
fields.push_back(INSULATEDFLOORUVALUE);
fields.push_back(ZONEBOUNDARYINSULATEDSURFACEUVALUEFACINGZONE);
fields.push_back(ZONEBOUNDARYGLASSREACHINDOORUVALUEFACINGZONE);
fields.push_back(ZONEBOUNDARYSTOCKINGDOORUVALUEFACINGZONE);
std::pair<QString,std::vector<QString> > categoryAndFields = std::make_pair(QString("Construction"),fields);
m_categoriesAndFields.push_back(categoryAndFields);
}
{
std::vector<QString> fields;
fields.push_back(AVAILABILITYSCHEDULE);
fields.push_back(OPERATINGTEMPERATURE);
fields.push_back(RATEDCOOLINGSOURCETEMPERATURE);
fields.push_back(RATEDCOILCOOLINGCAPACITY);
std::pair<QString,std::vector<QString> > categoryAndFields = std::make_pair(QString("Operation"),fields);
m_categoriesAndFields.push_back(categoryAndFields);
}
{
std::vector<QString> fields;
fields.push_back(RATEDCOOLINGCOILFANPOWER);
fields.push_back(RATEDCIRCULATIONFANPOWER);
std::pair<QString,std::vector<QString> > categoryAndFields = std::make_pair(QString("Fans"),fields);
m_categoriesAndFields.push_back(categoryAndFields);
}
{
std::vector<QString> fields;
fields.push_back(RATEDTOTALLIGHTINGPOWER);
fields.push_back(LIGHTINGSCHEDULE);
std::pair<QString,std::vector<QString> > categoryAndFields = std::make_pair(QString("Lighting"),fields);
m_categoriesAndFields.push_back(categoryAndFields);
}
{
std::vector<QString> fields;
fields.push_back(RATEDTOTALHEATINGPOWER);
fields.push_back(HEATINGPOWERSCHEDULE);
std::pair<QString,std::vector<QString> > categoryAndFields = std::make_pair(QString("Heating"),fields);
m_categoriesAndFields.push_back(categoryAndFields);
}
{
std::vector<QString> fields;
fields.push_back(DEFROSTTYPE);
fields.push_back(DEFROSTCONTROLTYPE);
fields.push_back(DEFROSTPOWER);
fields.push_back(TEMPERATURETERMINATIONDEFROSTFRACTIONTOICE);
std::pair<QString,std::vector<QString> > categoryAndFields = std::make_pair(QString("Defrost"),fields);
m_categoriesAndFields.push_back(categoryAndFields);
}
{
std::vector<QString> fields;
fields.push_back(RESTOCKINGSCHEDULE);
fields.push_back(ZONEBOUNDARYSTOCKINGDOOROPENINGSCHEDULEFACINGZONE);
std::pair<QString,std::vector<QString> > categoryAndFields = std::make_pair(QString("Restocking"),fields);
m_categoriesAndFields.push_back(categoryAndFields);
}
OSGridController::setCategoriesAndFields();
}
void RefrigerationWalkInGridController::addColumns(const QString &/*category*/, std::vector<QString> & fields)
{
// always show name column
fields.insert(fields.begin(), {NAME, SELECTED});
m_baseConcepts.clear();
for (const QString& field : fields) {
if(field == DEFROSTTYPE){
addComboBoxColumn<std::string,model::RefrigerationWalkIn>(
Heading(QString(DEFROSTTYPE)),
static_cast<std::string (*)(const std::string&)>(&openstudio::toString),
std::function<std::vector<std::string> ()>(&model::RefrigerationWalkIn::defrostTypeValues),
CastNullAdapter<model::RefrigerationWalkIn>(&model::RefrigerationWalkIn::defrostType),
CastNullAdapter<model::RefrigerationWalkIn>(&model::RefrigerationWalkIn::setDefrostType),
boost::optional<std::function<void(model::RefrigerationWalkIn *)> >(),
boost::optional<DataSource>());
}else if(field == SELECTED){
auto checkbox = QSharedPointer<QCheckBox>(new QCheckBox());
checkbox->setToolTip("Check to select all rows");
connect(checkbox.data(), &QCheckBox::stateChanged, this, &RefrigerationWalkInGridController::selectAllStateChanged);
connect(checkbox.data(), &QCheckBox::stateChanged, this->gridView(), &OSGridView::gridRowSelectionChanged);
addSelectColumn(Heading(QString(SELECTED), false, false, checkbox), "Check to select this row");
}else if(field == DEFROSTCONTROLTYPE){
addComboBoxColumn<std::string,model::RefrigerationWalkIn>(
Heading(QString(DEFROSTCONTROLTYPE)),
static_cast<std::string (*)(const std::string&)>(&openstudio::toString),
std::function<std::vector<std::string> ()>(&model::RefrigerationWalkIn::defrostControlTypeValues),
CastNullAdapter<model::RefrigerationWalkIn>(&model::RefrigerationWalkIn::defrostControlType),
CastNullAdapter<model::RefrigerationWalkIn>(&model::RefrigerationWalkIn::setDefrostControlType),
boost::optional<std::function<void(model::RefrigerationWalkIn *)> >(),
boost::optional<DataSource>());
}else if(field == OPERATINGTEMPERATURE){
addQuantityEditColumn(Heading(QString(OPERATINGTEMPERATURE)),
QString("C"),
QString("C"),
QString("F"),
m_isIP,
NullAdapter(&model::RefrigerationWalkIn::operatingTemperature),
NullAdapter(&model::RefrigerationWalkIn::setOperatingTemperature));
}else if(field == RATEDCOOLINGSOURCETEMPERATURE){
addQuantityEditColumn(Heading(QString(RATEDCOOLINGSOURCETEMPERATURE)),
QString("C"),
QString("C"),
QString("F"),
m_isIP,
NullAdapter(&model::RefrigerationWalkIn::ratedCoolingSourceTemperature),
NullAdapter(&model::RefrigerationWalkIn::setRatedCoolingSourceTemperature));
}else if(field == RATEDCOOLINGCOILFANPOWER){
addQuantityEditColumn(Heading(QString(RATEDCOOLINGCOILFANPOWER)),
QString("W"),
QString("W"),
QString("W"),
m_isIP,
NullAdapter(&model::RefrigerationWalkIn::ratedCoolingCoilFanPower),
NullAdapter(&model::RefrigerationWalkIn::setRatedCoolingCoilFanPower));
}else if(field == RATEDCIRCULATIONFANPOWER){
addQuantityEditColumn(Heading(QString(RATEDCIRCULATIONFANPOWER)),
QString("W"),
QString("W"),
QString("W"),
m_isIP,
NullAdapter(&model::RefrigerationWalkIn::ratedCirculationFanPower),
NullAdapter(&model::RefrigerationWalkIn::setRatedCirculationFanPower));
}else if(field == INSULATEDFLOORSURFACEAREA){
addQuantityEditColumn(Heading(QString(INSULATEDFLOORSURFACEAREA)),
QString("m2"),
QString("m2"),
QString("ft^2"),
m_isIP,
NullAdapter(&model::RefrigerationWalkIn::insulatedFloorSurfaceArea),
NullAdapter(&model::RefrigerationWalkIn::setInsulatedFloorSurfaceArea));
}else if(field == INSULATEDFLOORUVALUE){
addQuantityEditColumn(Heading(QString(INSULATEDFLOORUVALUE)),
QString("W/m^2*K"),
QString("W/m^2*K"),
QString("Btu/ft^2*hr*R"),
m_isIP,
NullAdapter(&model::RefrigerationWalkIn::insulatedFloorUValue),
NullAdapter(&model::RefrigerationWalkIn::setInsulatedFloorUValue));
}else if(field == RATEDCOILCOOLINGCAPACITY){
addQuantityEditColumn(Heading(QString(RATEDCOILCOOLINGCAPACITY)),
QString("W"),
QString("W"),
QString("Btu/hr"),
m_isIP,
NullAdapter(&model::RefrigerationWalkIn::ratedCoilCoolingCapacity),
NullAdapter(&model::RefrigerationWalkIn::setRatedCoilCoolingCapacity));
}else if(field == RATEDTOTALHEATINGPOWER){
addQuantityEditColumn(Heading(QString(RATEDTOTALHEATINGPOWER)),
QString("W"),
QString("W"),
QString("W"),
m_isIP,
NullAdapter(&model::RefrigerationWalkIn::ratedTotalHeatingPower),
NullAdapter(&model::RefrigerationWalkIn::setRatedTotalHeatingPower));
}else if(field == RATEDTOTALLIGHTINGPOWER){
addQuantityEditColumn(Heading(QString(RATEDTOTALLIGHTINGPOWER)),
QString("W"),
QString("W"),
QString("W"),
m_isIP,
NullAdapter(&model::RefrigerationWalkIn::ratedTotalLightingPower),
NullAdapter(&model::RefrigerationWalkIn::setRatedTotalLightingPower));
}else if(field == AVERAGEREFRIGERANTCHARGEINVENTORY){
addQuantityEditColumn(Heading(QString(AVERAGEREFRIGERANTCHARGEINVENTORY)),
QString("kg"),
QString("kg"),
QString("lb"),
m_isIP,
NullAdapter(&model::RefrigerationWalkIn::averageRefrigerantChargeInventory),
NullAdapter(&model::RefrigerationWalkIn::setAverageRefrigerantChargeInventory));
}else if(field == DEFROSTSCHEDULE){
addComboBoxColumn<model::Schedule, model::RefrigerationWalkIn>(
Heading(QString(DEFROSTSCHEDULE)),
std::function<std::string (const model::Schedule &)>(&openstudio::objectName),
std::function<std::vector<model::Schedule> ()>(std::bind(&openstudio::sortByObjectName<model::Schedule>,
std::bind(&openstudio::model::getCompatibleSchedules,
m_model,
"RefrigerationWalkIn",
"Defrost"))),
CastNullAdapter<model::RefrigerationWalkIn>(&model::RefrigerationWalkIn::defrostSchedule),
CastNullAdapter<model::RefrigerationWalkIn>(&model::RefrigerationWalkIn::setDefrostSchedule),
boost::optional<std::function<void (model::RefrigerationWalkIn *)>>(),
boost::optional<std::function<bool (model::RefrigerationWalkIn *)>>(),
boost::optional<DataSource>()
);
}else if(field == DEFROSTPOWER){
addQuantityEditColumn(Heading(QString(DEFROSTPOWER)),
QString("W"),
QString("W"),
QString("W"),
m_isIP,
NullAdapter(&model::RefrigerationWalkIn::defrostPower),
NullAdapter(&model::RefrigerationWalkIn::setDefrostPower));
}else if(field == TEMPERATURETERMINATIONDEFROSTFRACTIONTOICE){
addValueEditColumn(Heading(QString(TEMPERATURETERMINATIONDEFROSTFRACTIONTOICE)),
NullAdapter(&model::RefrigerationWalkIn::temperatureTerminationDefrostFractiontoIce),
NullAdapter(&model::RefrigerationWalkIn::setTemperatureTerminationDefrostFractiontoIce));
}else if(field == AVAILABILITYSCHEDULE){
addComboBoxColumn<model::Schedule,model::RefrigerationWalkIn>(
Heading(QString(AVAILABILITYSCHEDULE)),
&openstudio::objectName,
std::function<std::vector<model::Schedule> ()>(std::bind(&openstudio::sortByObjectName<model::Schedule>,
std::bind(&openstudio::model::getCompatibleSchedules,
m_model,
"RefrigerationWalkIn",
"Availability"))),
CastNullAdapter<model::RefrigerationWalkIn>(&model::RefrigerationWalkIn::availabilitySchedule),
CastNullAdapter<model::RefrigerationWalkIn>(&model::RefrigerationWalkIn::setAvailabilitySchedule),
boost::optional<std::function<void(model::RefrigerationWalkIn*)> >(NullAdapter(&model::RefrigerationWalkIn::resetAvailabilitySchedule)));
//boost::optional<std::function<void(model::RefrigerationWalkIn*)> >(static_cast<void (model::RefrigerationWalkIn::*)()>(&model::RefrigerationWalkIn::resetAvailabilitySchedule)));
}else if(field == HEATINGPOWERSCHEDULE){
addComboBoxColumn<model::Schedule,model::RefrigerationWalkIn>(
Heading(QString(HEATINGPOWERSCHEDULE)),
&openstudio::objectName,
std::function<std::vector<model::Schedule> ()>(std::bind(&openstudio::sortByObjectName<model::Schedule>,
std::bind(&openstudio::model::getCompatibleSchedules,
m_model,
"RefrigerationWalkIn",
"Heating Power"))),
NullAdapter(&model::RefrigerationWalkIn::heatingPowerSchedule),
NullAdapter(&model::RefrigerationWalkIn::setHeatingPowerSchedule),
boost::optional<std::function<void (model::RefrigerationWalkIn*)> >(NullAdapter(&model::RefrigerationWalkIn::resetHeatingPowerSchedule)));
}else if(field == LIGHTINGSCHEDULE){
addComboBoxColumn<model::Schedule,model::RefrigerationWalkIn>(
Heading(QString(LIGHTINGSCHEDULE)),
&openstudio::objectName,
std::function<std::vector<model::Schedule> ()>(std::bind(&openstudio::sortByObjectName<model::Schedule>,
std::bind(&openstudio::model::getCompatibleSchedules,
m_model,
"RefrigerationWalkIn",
"Lighting"))),
NullAdapter(&model::RefrigerationWalkIn::lightingSchedule),
NullAdapter(&model::RefrigerationWalkIn::setLightingSchedule),
boost::optional<std::function<void (model::RefrigerationWalkIn*)> >(NullAdapter(&model::RefrigerationWalkIn::resetLightingSchedule)));
}else if(field == DEFROSTDRIPDOWNSCHEDULE){
addComboBoxColumn<model::Schedule,model::RefrigerationWalkIn>(
Heading(QString(DEFROSTDRIPDOWNSCHEDULE)),
&openstudio::objectName,
std::function<std::vector<model::Schedule> ()>(std::bind(&openstudio::sortByObjectName<model::Schedule>,
std::bind(&openstudio::model::getCompatibleSchedules,
m_model,
"RefrigerationWalkIn",
"Defrost Drip-Down"))),
NullAdapter(&model::RefrigerationWalkIn::defrostDripDownSchedule),
NullAdapter(&model::RefrigerationWalkIn::setDefrostDripDownSchedule),
boost::optional<std::function<void (model::RefrigerationWalkIn*)> >(NullAdapter(&model::RefrigerationWalkIn::resetDefrostDripDownSchedule)));
}else if(field == RESTOCKINGSCHEDULE){
addComboBoxColumn<model::Schedule,model::RefrigerationWalkIn>(
Heading(QString(RESTOCKINGSCHEDULE)),
&openstudio::objectName,
std::function<std::vector<model::Schedule> ()>(std::bind(&openstudio::sortByObjectName<model::Schedule>,
std::bind(&openstudio::model::getCompatibleSchedules,
m_model,
"RefrigerationWalkIn",
"Restocking"))),
NullAdapter(&model::RefrigerationWalkIn::restockingSchedule),
NullAdapter(&model::RefrigerationWalkIn::setRestockingSchedule),
boost::optional<std::function<void (model::RefrigerationWalkIn*)> >(NullAdapter(&model::RefrigerationWalkIn::resetRestockingSchedule)));
}else if(field == ZONEBOUNDARIES){
//std::vector<RefrigerationWalkInZoneBoundary> zoneBoundaries() const; TODO
}else if(field == NAME){
addNameLineEditColumn(Heading(QString(NAME), false, false),
false,
false,
CastNullAdapter<model::RefrigerationWalkIn>(&model::RefrigerationWalkIn::name),
CastNullAdapter<model::RefrigerationWalkIn>(&model::RefrigerationWalkIn::setName));
}else if(field == RACK){
addComboBoxColumn<model::RefrigerationSystem,model::RefrigerationWalkIn>(
Heading(QString(RACK)),
&openstudio::objectName,
std::function<std::vector<model::RefrigerationSystem> ()>(std::bind(&openstudio::sortByObjectName<model::RefrigerationSystem>,
std::bind(&model::Model::getConcreteModelObjects<model::RefrigerationSystem>,m_model))),
NullAdapter(&model::RefrigerationWalkIn::system),
NullAdapter(&model::RefrigerationWalkIn::addToSystem),
boost::optional<std::function<void (model::RefrigerationWalkIn*)> >(NullAdapter(&model::RefrigerationWalkIn::removeFromSystem)));
}
else if (field == ZONEBOUNDARYTHERMALZONE){
addComboBoxColumn<model::ThermalZone, model::RefrigerationWalkIn>(
Heading(QString(ZONEBOUNDARYTHERMALZONE)),
&openstudio::objectName,
std::function<std::vector<model::ThermalZone>()>(std::bind(&openstudio::sortByObjectName<model::ThermalZone>,
std::bind(&model::Model::getConcreteModelObjects<model::ThermalZone>, m_model))),
CastNullAdapter<model::RefrigerationWalkIn>(&model::RefrigerationWalkIn::zoneBoundaryThermalZone),
CastNullAdapter<model::RefrigerationWalkIn>(&model::RefrigerationWalkIn::setZoneBoundaryThermalZone),
NullAdapter(&model::RefrigerationWalkIn::resetZoneBoundaryThermalZone));
}else if (field == ZONEBOUNDARYTOTALINSULATEDSURFACEAREAFACINGZONE){
addQuantityEditColumn(Heading(QString(ZONEBOUNDARYTOTALINSULATEDSURFACEAREAFACINGZONE)),
QString("m^2"),
QString("m^2"),
QString("ft^2"),
m_isIP,
NullAdapter(&model::RefrigerationWalkIn::zoneBoundaryTotalInsulatedSurfaceAreaFacingZone),
NullAdapter(&model::RefrigerationWalkIn::setZoneBoundaryTotalInsulatedSurfaceAreaFacingZone));
}else if(field == ZONEBOUNDARYAREAOFGLASSREACHINDOORSFACINGZONE){
addQuantityEditColumn(Heading(QString(ZONEBOUNDARYAREAOFGLASSREACHINDOORSFACINGZONE)),
QString("m^2"),
QString("m^2"),
QString("ft^2"),
m_isIP,
NullAdapter(&model::RefrigerationWalkIn::zoneBoundaryAreaofGlassReachInDoorsFacingZone),
NullAdapter(&model::RefrigerationWalkIn::setZoneBoundaryAreaofGlassReachInDoorsFacingZone));
}else if(field == ZONEBOUNDARYHEIGHTOFGLASSREACHINDOORSFACINGZONE){
addQuantityEditColumn(Heading(QString(ZONEBOUNDARYHEIGHTOFGLASSREACHINDOORSFACINGZONE)),
QString("m"),
QString("m"),
QString("ft"),
m_isIP,
NullAdapter(&model::RefrigerationWalkIn::zoneBoundaryHeightofGlassReachInDoorsFacingZone),
NullAdapter(&model::RefrigerationWalkIn::setZoneBoundaryHeightofGlassReachInDoorsFacingZone));
}else if(field == ZONEBOUNDARYAREAOFSTOCKINGDOORSFACINGZONE){
addQuantityEditColumn(Heading(QString(ZONEBOUNDARYAREAOFSTOCKINGDOORSFACINGZONE)),
QString("m^2"),
QString("m^2"),
QString("ft^2"),
m_isIP,
NullAdapter(&model::RefrigerationWalkIn::zoneBoundaryAreaofStockingDoorsFacingZone),
NullAdapter(&model::RefrigerationWalkIn::setZoneBoundaryAreaofStockingDoorsFacingZone));
}else if(field == ZONEBOUNDARYHEIGHTOFSTOCKINGDOORSFACINGZONE){
addQuantityEditColumn(Heading(QString(ZONEBOUNDARYHEIGHTOFSTOCKINGDOORSFACINGZONE)),
QString("m"),
QString("m"),
QString("ft"),
m_isIP,
NullAdapter(&model::RefrigerationWalkIn::zoneBoundaryHeightofStockingDoorsFacingZone),
NullAdapter(&model::RefrigerationWalkIn::setZoneBoundaryHeightofStockingDoorsFacingZone));
}else if(field == ZONEBOUNDARYINSULATEDSURFACEUVALUEFACINGZONE){
addQuantityEditColumn(Heading(QString(ZONEBOUNDARYINSULATEDSURFACEUVALUEFACINGZONE)),
QString("W/m^2*K"),
QString("W/m^2*K"),
QString("Btu/ft^2*hr*R"),
m_isIP,
NullAdapter(&model::RefrigerationWalkIn::zoneBoundaryInsulatedSurfaceUValueFacingZone),
NullAdapter(&model::RefrigerationWalkIn::setZoneBoundaryInsulatedSurfaceUValueFacingZone));
}else if(field == ZONEBOUNDARYGLASSREACHINDOORUVALUEFACINGZONE){
addQuantityEditColumn(Heading(QString(ZONEBOUNDARYGLASSREACHINDOORUVALUEFACINGZONE)),
QString("W/m^2*K"),
QString("W/m^2*K"),
QString("Btu/ft^2*hr*R"),
m_isIP,
NullAdapter(&model::RefrigerationWalkIn::zoneBoundaryGlassReachInDoorUValueFacingZone),
NullAdapter(&model::RefrigerationWalkIn::setZoneBoundaryGlassReachInDoorUValueFacingZone));
}else if(field == ZONEBOUNDARYSTOCKINGDOORUVALUEFACINGZONE){
addQuantityEditColumn(Heading(QString(ZONEBOUNDARYSTOCKINGDOORUVALUEFACINGZONE)),
QString("W/m^2*K"),
QString("W/m^2*K"),
QString("Btu/ft^2*hr*R"),
m_isIP,
NullAdapter(&model::RefrigerationWalkIn::zoneBoundaryStockingDoorUValueFacingZone),
NullAdapter(&model::RefrigerationWalkIn::setZoneBoundaryStockingDoorUValueFacingZone));
}else if(field == ZONEBOUNDARYSTOCKINGDOOROPENINGSCHEDULEFACINGZONE){
addComboBoxColumn<model::Schedule,model::RefrigerationWalkIn>(
Heading(QString(ZONEBOUNDARYSTOCKINGDOOROPENINGSCHEDULEFACINGZONE)),
&openstudio::objectName,
std::function<std::vector<model::Schedule> ()>(std::bind(&openstudio::sortByObjectName<model::Schedule>,
std::bind(&openstudio::model::getCompatibleSchedules,
m_model,
"RefrigerationWalkInZoneBoundary",
"Stocking Door Opening Facing Zone"))),
NullAdapter(&model::RefrigerationWalkIn::zoneBoundaryStockingDoorOpeningScheduleFacingZone),
NullAdapter(&model::RefrigerationWalkIn::setZoneBoundaryStockingDoorOpeningScheduleFacingZone),
NullAdapter(&model::RefrigerationWalkIn::resetZoneBoundaryStockingDoorOpeningScheduleFacingZone));
}else{
// unhandled
OS_ASSERT(false);
}
}
}
QString RefrigerationWalkInGridController::getColor(const model:: ModelObject & modelObject)
{
QColor defaultColor(Qt::lightGray);
QString color(defaultColor.name());
// TODO: The code below is currently commented out because a refresh crash bug is precluding rack color
// updates due to rack assignments to cases and walk-ins. No colors are better than wrong colors.
//std::vector<model::RefrigerationSystem> refrigerationSystems = m_model.getConcreteModelObjects<model::RefrigerationSystem>();
//boost::optional<model::RefrigerationWalkIn> refrigerationWalkIn = modelObject.optionalCast<model::RefrigerationWalkIn>();
//OS_ASSERT(refrigerationWalkIn);
//boost::optional<model::RefrigerationSystem> refrigerationSystem = refrigerationWalkIn->system();
//if(!refrigerationSystem){
// return color;
//}
//std::vector<model::RefrigerationSystem>::iterator it;
//it = std::find(refrigerationSystems.begin(), refrigerationSystems.end(), refrigerationSystem.get());
//if(it != refrigerationSystems.end()){
// int index = std::distance(refrigerationSystems.begin(), it);
// if(index >= static_cast<int>(m_colors.size())){
// index = m_colors.size() - 1; // similar to scheduleView's approach
// }
// color = this->m_colors.at(index).name();
//}
return color;
}
void RefrigerationWalkInGridController::checkSelectedFields()
{
if(!this->m_hasHorizontalHeader) return;
OSGridController::checkSelectedFields();
}
void RefrigerationWalkInGridController::onItemDropped(const OSItemId& itemId)
{
boost::optional<model::ModelObject> modelObject = OSAppBase::instance()->currentDocument()->getModelObject(itemId);
if (modelObject){
if (modelObject->optionalCast<model::RefrigerationWalkIn>()){
modelObject->clone(m_model);
emit modelReset();
}
}
}
void RefrigerationWalkInGridController::refreshModelObjects()
{
std::vector<model::RefrigerationWalkIn> refrigerationWalkIns = m_model.getConcreteModelObjects<model::RefrigerationWalkIn>();
m_modelObjects = subsetCastVector<model::ModelObject>(refrigerationWalkIns);
std::sort(m_modelObjects.begin(), m_modelObjects.end(), ModelObjectNameSorter());
}
void RefrigerationWalkInGridController::onComboBoxIndexChanged(int index)
{
// Note: find the correct system color on RACK change,
// but currently unable to know which row changed.
for(unsigned index = 0; index < m_horizontalHeader.size(); index++){
HorizontalHeaderWidget * horizontalHeaderWidget = qobject_cast<HorizontalHeaderWidget *>(m_horizontalHeader.at(index));
if(horizontalHeaderWidget->m_label->text() == RACK){
// NOTE required due to a race condition
// Code below commented out due to a very infrequent crash in the bowels of Qt appears to be exasperated by this refresh.
// A new refresh scheme with finer granularity may eliminate the problem, and restore rack colors.
//QTimer::singleShot(0, this, SLOT(reset())); TODO
break;
}
}
}
} // openstudio
|
/*
* Copyright (c) 2016 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 "modules/audio_coding/audio_network_adaptor/audio_network_adaptor_impl.h"
#include <stdint.h>
#include <utility>
#include <vector>
#include "modules/audio_coding/audio_network_adaptor/controller_manager.h"
#include "modules/audio_coding/audio_network_adaptor/debug_dump_writer.h"
#include "modules/audio_coding/audio_network_adaptor/event_log_writer.h"
#include "rtc_base/checks.h"
#include "rtc_base/time_utils.h"
#include "system_wrappers/include/field_trial.h"
namespace webrtc {
namespace {
constexpr int kEventLogMinBitrateChangeBps = 5000;
constexpr float kEventLogMinBitrateChangeFraction = 0.25;
constexpr float kEventLogMinPacketLossChangeFraction = 0.5;
} // namespace
AudioNetworkAdaptorImpl::Config::Config() : event_log(nullptr) {}
AudioNetworkAdaptorImpl::Config::~Config() = default;
AudioNetworkAdaptorImpl::AudioNetworkAdaptorImpl(
const Config& config,
std::unique_ptr<ControllerManager> controller_manager,
std::unique_ptr<DebugDumpWriter> debug_dump_writer)
: config_(config),
controller_manager_(std::move(controller_manager)),
debug_dump_writer_(std::move(debug_dump_writer)),
event_log_writer_(
config.event_log
? new EventLogWriter(config.event_log,
kEventLogMinBitrateChangeBps,
kEventLogMinBitrateChangeFraction,
kEventLogMinPacketLossChangeFraction)
: nullptr) {
RTC_DCHECK(controller_manager_);
}
AudioNetworkAdaptorImpl::~AudioNetworkAdaptorImpl() = default;
void AudioNetworkAdaptorImpl::SetUplinkBandwidth(int uplink_bandwidth_bps) {
last_metrics_.uplink_bandwidth_bps = uplink_bandwidth_bps;
DumpNetworkMetrics();
Controller::NetworkMetrics network_metrics;
network_metrics.uplink_bandwidth_bps = uplink_bandwidth_bps;
UpdateNetworkMetrics(network_metrics);
}
void AudioNetworkAdaptorImpl::SetUplinkPacketLossFraction(
float uplink_packet_loss_fraction) {
last_metrics_.uplink_packet_loss_fraction = uplink_packet_loss_fraction;
DumpNetworkMetrics();
Controller::NetworkMetrics network_metrics;
network_metrics.uplink_packet_loss_fraction = uplink_packet_loss_fraction;
UpdateNetworkMetrics(network_metrics);
}
void AudioNetworkAdaptorImpl::SetUplinkRecoverablePacketLossFraction(
float uplink_recoverable_packet_loss_fraction) {
last_metrics_.uplink_recoverable_packet_loss_fraction =
uplink_recoverable_packet_loss_fraction;
DumpNetworkMetrics();
Controller::NetworkMetrics network_metrics;
network_metrics.uplink_recoverable_packet_loss_fraction =
uplink_recoverable_packet_loss_fraction;
UpdateNetworkMetrics(network_metrics);
}
void AudioNetworkAdaptorImpl::SetRtt(int rtt_ms) {
last_metrics_.rtt_ms = rtt_ms;
DumpNetworkMetrics();
Controller::NetworkMetrics network_metrics;
network_metrics.rtt_ms = rtt_ms;
UpdateNetworkMetrics(network_metrics);
}
void AudioNetworkAdaptorImpl::SetTargetAudioBitrate(
int target_audio_bitrate_bps) {
last_metrics_.target_audio_bitrate_bps = target_audio_bitrate_bps;
DumpNetworkMetrics();
Controller::NetworkMetrics network_metrics;
network_metrics.target_audio_bitrate_bps = target_audio_bitrate_bps;
UpdateNetworkMetrics(network_metrics);
}
void AudioNetworkAdaptorImpl::SetOverhead(size_t overhead_bytes_per_packet) {
last_metrics_.overhead_bytes_per_packet = overhead_bytes_per_packet;
DumpNetworkMetrics();
Controller::NetworkMetrics network_metrics;
network_metrics.overhead_bytes_per_packet = overhead_bytes_per_packet;
UpdateNetworkMetrics(network_metrics);
}
AudioEncoderRuntimeConfig AudioNetworkAdaptorImpl::GetEncoderRuntimeConfig() {
AudioEncoderRuntimeConfig config;
for (auto& controller :
controller_manager_->GetSortedControllers(last_metrics_))
controller->MakeDecision(&config);
// Update ANA stats.
auto increment_opt = [](absl::optional<uint32_t>& a) {
a = a.value_or(0) + 1;
};
if (prev_config_) {
if (config.bitrate_bps != prev_config_->bitrate_bps) {
increment_opt(stats_.bitrate_action_counter);
}
if (config.enable_dtx != prev_config_->enable_dtx) {
increment_opt(stats_.dtx_action_counter);
}
if (config.enable_fec != prev_config_->enable_fec) {
increment_opt(stats_.fec_action_counter);
}
if (config.frame_length_ms && prev_config_->frame_length_ms) {
if (*config.frame_length_ms > *prev_config_->frame_length_ms) {
increment_opt(stats_.frame_length_increase_counter);
} else if (*config.frame_length_ms < *prev_config_->frame_length_ms) {
increment_opt(stats_.frame_length_decrease_counter);
}
}
if (config.num_channels != prev_config_->num_channels) {
increment_opt(stats_.channel_action_counter);
}
if (config.uplink_packet_loss_fraction) {
stats_.uplink_packet_loss_fraction = *config.uplink_packet_loss_fraction;
}
}
prev_config_ = config;
if (debug_dump_writer_)
debug_dump_writer_->DumpEncoderRuntimeConfig(config, rtc::TimeMillis());
if (event_log_writer_)
event_log_writer_->MaybeLogEncoderConfig(config);
return config;
}
void AudioNetworkAdaptorImpl::StartDebugDump(FILE* file_handle) {
debug_dump_writer_ = DebugDumpWriter::Create(file_handle);
}
void AudioNetworkAdaptorImpl::StopDebugDump() {
debug_dump_writer_.reset(nullptr);
}
ANAStats AudioNetworkAdaptorImpl::GetStats() const {
return stats_;
}
void AudioNetworkAdaptorImpl::DumpNetworkMetrics() {
if (debug_dump_writer_)
debug_dump_writer_->DumpNetworkMetrics(last_metrics_, rtc::TimeMillis());
}
void AudioNetworkAdaptorImpl::UpdateNetworkMetrics(
const Controller::NetworkMetrics& network_metrics) {
for (auto& controller : controller_manager_->GetControllers())
controller->UpdateNetworkMetrics(network_metrics);
}
} // namespace webrtc
|
// Copyright (C) 2021 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
#include <algorithm>
#include <bitset>
#include <cassert>
#include <filesystem>
#include <sstream>
#include "hebench/api_bridge/api.h"
#include "include/hebench_benchmark_factory.h"
namespace hebench {
namespace TestHarness {
//------------------------
// class BenchmarkFactory
//------------------------
IBenchmark::Ptr BenchmarkFactory::createBenchmark(std::shared_ptr<Engine> p_engine,
IBenchmarkDescriptor::DescriptionToken::Ptr p_token,
hebench::Utilities::TimingReportEx &out_report)
{
if (!p_engine)
throw std::invalid_argument(IL_LOG_MSG_CLASS("Invalid null pointer \"p_engine\"."));
if (!p_token)
throw std::invalid_argument(IL_LOG_MSG_CLASS("Invalid null pointer \"p_token\"."));
if (!p_token->getDescriptor())
throw std::invalid_argument(IL_LOG_MSG_CLASS("Invalid benchmark token \"p_token\" with null descriptor."));
std::vector<std::shared_ptr<IBenchmarkDescriptor>> ®istered_benchmarks = getRegisteredBenchmarks();
// make sure that the token matches to a descriptor that is registered
IBenchmarkDescriptor *p_tmp = p_token->getDescriptor();
auto found_it = std::find_if(registered_benchmarks.begin(), registered_benchmarks.end(),
[p_tmp](std::shared_ptr<IBenchmarkDescriptor> p) -> bool { return p_tmp == p.get(); });
if (found_it == registered_benchmarks.end() || !*found_it)
throw std::invalid_argument(IL_LOG_MSG_CLASS("Benchmark token \"p_token\" descriptor is invalid: not found in registered benchmark descriptors."));
std::shared_ptr<IBenchmarkDescriptor> p_bd = *found_it; // this ensures that we are keeping the smart pointer around until after destruction.
PartialBenchmark *p_retval = p_bd->createBenchmark(p_engine, *p_token);
if (!p_retval)
throw std::runtime_error(IL_LOG_MSG_CLASS("Unexpected error creating benchmark."));
try
{
// perform initialization of the benchmark
const PartialBenchmark::FriendPrivateKey key;
p_retval->init();
p_retval->initBackend(out_report, key);
p_retval->postInit();
p_retval->checkInitializationState(key);
}
catch (...)
{
try
{
p_bd->destroyBenchmark(p_retval);
}
catch (...)
{
// ignore any exceptions on destruction
}
throw;
}
return IBenchmark::Ptr(p_retval,
[p_bd](IBenchmark *p) { if (p) p_bd->destroyBenchmark(reinterpret_cast<PartialBenchmark *>(p)); });
}
std::vector<std::shared_ptr<IBenchmarkDescriptor>> &BenchmarkFactory::getRegisteredBenchmarks()
{
// ensures that the static member always exists during static initialization
static std::vector<std::shared_ptr<IBenchmarkDescriptor>> registered_benchmarks;
return registered_benchmarks;
}
IBenchmarkDescriptor::DescriptionToken::Ptr BenchmarkFactory::matchBenchmarkDescriptor(const Engine &engine,
const BenchmarkDescription::Backend &backend_desc,
const BenchmarkDescription::Configuration &config)
{
IBenchmarkDescriptor::DescriptionToken::Ptr retval;
std::vector<std::shared_ptr<IBenchmarkDescriptor>> ®istered_benchmarks =
getRegisteredBenchmarks();
for (std::size_t i = 0; !retval && i < registered_benchmarks.size(); ++i)
retval = registered_benchmarks[i]->matchDescriptor(engine, backend_desc, config);
return retval;
}
bool BenchmarkFactory::registerSupportedBenchmark(std::shared_ptr<IBenchmarkDescriptor> p_desc_obj)
{
bool retval = false;
try
{
if (p_desc_obj)
{
getRegisteredBenchmarks().push_back(p_desc_obj);
retval = true;
} // end if
}
catch (...)
{
retval = false;
}
return retval;
}
} // namespace TestHarness
} // namespace hebench
|
// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "butil/debug/alias.h"
#include "butil/build_config.h"
namespace butil {
namespace debug {
#if defined(COMPILER_MSVC)
#pragma optimize("", off)
#endif
void Alias(const void* var) {
}
#if defined(COMPILER_MSVC)
#pragma optimize("", on)
#endif
} // namespace debug
} // namespace butil
|
//
// Quantum Script Extension JSON
//
// Copyright (c) 2020-2021 Grigore Stefan <g_stefan@yahoo.com>
// Created by Grigore Stefan <g_stefan@yahoo.com>
//
// MIT License (MIT) <http://opensource.org/licenses/MIT>
//
#include "quantum-script-extension-json.cpp"
#include "quantum-script-extension-json-copyright.cpp"
#include "quantum-script-extension-json-license.cpp"
#ifndef QUANTUM_SCRIPT_EXTENSION_JSON_NO_VERSION
#include "quantum-script-extension-json-version.cpp"
#endif
|
/*=========================================================================
Program: ParaView
Module: TestImageScaleFactors.cxx
Copyright (c) Kitware, Inc.
All rights reserved.
See Copyright.txt or http://www.paraview.org/HTML/Copyright.html for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#include "vtkSMSaveScreenshotProxy.h"
#include "vtkVectorOperators.h"
#include <cassert>
namespace
{
void Test(const vtkVector2i& target, const vtkVector2i& maxsize, bool expect_approx = false)
{
bool approx;
vtkVector2i size(maxsize);
vtkVector2i mag = vtkSMSaveScreenshotProxy::GetScaleFactorsAndSize(target, size, &approx);
cout << "----------------------------------------------------" << endl;
cout << " Target: " << target << " Max size: " << maxsize << endl;
cout << " Achieved: " << (size * mag) << " Approx: " << approx << endl;
cout << " New size: " << size << " scale: " << mag << endl << endl;
if (size * mag != target && expect_approx == false)
{
throw false;
}
}
}
// Tests code in vtkSMSaveScreenshotProxy to compute scale factors when saving
// images at target resolution.
int TestImageScaleFactors(int, char* [])
{
try
{
// totally crazy sizes.
Test(vtkVector2i(2188, 1236), vtkVector2i(538, 638), true);
// preserves aspect ratio
Test(vtkVector2i(1280, 800), vtkVector2i(800, 800));
// let's try a prime target.
Test(vtkVector2i(1280, 811), vtkVector2i(800, 800), true);
// let's try a prime max.
Test(vtkVector2i(1280, 815), vtkVector2i(811, 811));
}
catch (bool)
{
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
|
// Copyright eeGeo Ltd (2012-2015), All Rights Reserved
#include "MenuScreenControl.h"
namespace ExampleApp
{
namespace Menu
{
namespace View
{
MenuScreenControl::MenuScreenControl(Eegeo::Helpers::TIdentity identity)
: ScreenControl::View::ScreenControlViewModelBase(false)
, m_identity(identity)
{
}
Eegeo::Helpers::TIdentity MenuScreenControl::GetIdentity() const
{
return m_identity;
}
}
}
}
|
//
// ASN1Types.cpp
//
// $Id: //poco/1.4/Foundation/src/ASN1Types.cpp#1 $
//
// Library: Foundation
// Package: Streams
// Module: ASN1Types
//
// Copyright (c) 2010, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier: BSL-1.0
//
#include "Poco/ASN1Types.h"
#include "Poco/Format.h"
#include "Poco/StringTokenizer.h"
#include "Poco/NumberParser.h"
#include "Poco/NumberFormatter.h"
#include <sstream>
#include <assert.h>
#define HIGH_BIT 0x80
namespace Poco {
namespace ASN1Types {
struct Whitespace
{
Whitespace(int n)
: n(n)
{
}
int n;
};
std::ostream& operator<<(std::ostream& stream, const Whitespace &ws)
{
for(int i = 0; i < ws.n; i++)
{
stream << " ";
}
return stream;
}
///
/// Unknown
///
Unknown::Unknown(ASN1Type type) : ASN1(type)
{
}
Unknown::Unknown(ASN1Type type, const std::string &value) : ASN1(type), _value(value)
{
}
std::string Unknown::toString() const
{
return Poco::format("[unknown type 0x%s size %?d]", Poco::NumberFormatter::formatHex(getType().rawValue()), _value.size());
}
std::string Unknown::typeName() const
{
return Poco::format("UNKNOWN-0x%s", Poco::NumberFormatter::formatHex(getType().rawValue()));
}
const std::string &Unknown::getValue() const
{
return _value;
}
Poco::UInt32 Unknown::getDataLength() const
{
return _value.size();
}
void Unknown::encodeData(Poco::BinaryWriter &stream) const
{
stream.writeRaw(_value);
}
void Unknown::decodeData(Poco::SharedPtr<ASN1Factory> factory, Poco::BinaryReader &stream, Poco::UInt32 length)
{
if (length > 0)
stream.readRaw(length, _value);
}
void Unknown::dump(std::ostream &stream, int ident) const
{
stream << Whitespace(ident) << "UNKNOWN TYPE 0x" << Poco::NumberFormatter::formatHex(getType().rawValue()) << " " << _value.size() << " BYTES" << std::endl;
}
///
/// Null
///
Null::Null() : ASN1(ASN1Type(ASN1Type::Null, true))
{
}
std::string Null::toString() const
{
return "null";
}
std::string Null::typeName() const
{
return "NULL";
}
Poco::UInt32 Null::getDataLength() const
{
return 0;
}
void Null::encodeData(Poco::BinaryWriter &stream) const
{
}
void Null::decodeData(Poco::SharedPtr<ASN1Factory> factory, Poco::BinaryReader &stream, Poco::UInt32 length)
{
}
void Null::dump(std::ostream &stream, int ident) const
{
stream << Whitespace(ident) << "NULL " << std::endl;
}
///
/// Boolean
///
Boolean::Boolean() : ASN1(ASN1Type(ASN1Type::Boolean, true)), _value(false)
{
}
Boolean::Boolean(bool value) : ASN1(ASN1Type(ASN1Type::Boolean, true)), _value(value)
{
}
bool Boolean::getValue() const
{
return _value;
}
std::string Boolean::toString() const
{
return _value?"true":"false";
}
std::string Boolean::typeName() const
{
return "BOOLEAN";
}
Poco::UInt32 Boolean::getDataLength() const
{
return 1;
}
void Boolean::encodeData(Poco::BinaryWriter &stream) const
{
if (_value)
stream << (Poco::UInt8)0xff;
else
stream << (Poco::UInt8)0x00;
}
void Boolean::decodeData(Poco::SharedPtr<ASN1Factory> factory, Poco::BinaryReader &stream, Poco::UInt32 length)
{
Poco::UInt8 byte = 0;
if (length > 0)
stream >> byte;
_value = byte != 0;
}
void Boolean::dump(std::ostream &stream, int ident) const
{
stream << Whitespace(ident) << "BOOLEAN " << toString() << std::endl;
}
///
/// Integer
///
Integer::Integer() : ASN1(ASN1Type(ASN1Type::Integer, true)), _value(0)
{
}
Integer::Integer(Poco::UInt32 value) : ASN1(ASN1Type(ASN1Type::Integer, true)), _value(value)
{
}
Integer::Integer(ASN1Type type, Poco::UInt32 value) : ASN1(type), _value(value)
{
}
Poco::UInt32 Integer::getValue() const
{
return _value;
}
std::string Integer::toString() const
{
return Poco::format("%?d", _value);
}
std::string Integer::typeName() const
{
std::string seqtype;
if (getType().universalValue() != ASN1Type::Integer)
seqtype = Poco::format("-0x%s", Poco::NumberFormatter::formatHex(getType().rawValue()));
return Poco::format("INTEGER%s", seqtype);
}
Poco::UInt32 Integer::getDataLength() const
{
int value = _value;
int valueSize = 0;
do {
value >>= 7;
valueSize++;
} while (value != 0);
return valueSize;
}
void Integer::encodeData(Poco::BinaryWriter &stream) const
{
int integer = _value;
int mask;
int intsize = 4;
/*
* Truncate "unnecessary" bytes off of the most significant end of this
* 2's complement integer. There should be no sequence of 9
* consecutive 1's or 0's at the most significant end of the
* integer.
*/
mask = 0x1FF << ((8 * 3) - 1);
/* mask is 0xFF800000 on a big-endian machine */
while ((((integer & mask) == 0) || ((integer & mask) == mask))
&& intsize > 1){
intsize--;
integer <<= 8;
}
//encodeHeader(os, type, intsize);
mask = 0xFF << (8 * 3);
/* mask is 0xFF000000 on a big-endian machine */
while ((intsize--) > 0){
stream << (char)( ((integer & mask) >> (8 * 3)) );
integer <<= 8;
}
}
void Integer::decodeData(Poco::SharedPtr<ASN1Factory> factory, Poco::BinaryReader &stream, Poco::UInt32 length)
{
Poco::UInt8 bytesRead = 0;
Poco::UInt8 byte = 0;
stream >> byte;
bytesRead++;
_value = (byte & HIGH_BIT) == 0 ? 0 : -1;
for (;;) {
_value <<= 8;
_value |= byte;
if (bytesRead >= length)
break;
stream >> byte;
bytesRead++;
}
}
void Integer::dump(std::ostream &stream, int ident) const
{
stream << Whitespace(ident) << "INTEGER " << _value << std::endl;
}
#ifdef POCO_HAVE_INT64
///
/// Integer64
///
Integer64::Integer64() : ASN1(ASN1Type(ASN1Type::Integer, true)), _value(0)
{
}
Integer64::Integer64(Poco::UInt64 value) : ASN1(ASN1Type(ASN1Type::Integer, true)), _value(value)
{
}
Integer64::Integer64(ASN1Type type, Poco::UInt64 value) : ASN1(type), _value(value)
{
}
Poco::UInt64 Integer64::getValue() const
{
return _value;
}
std::string Integer64::toString() const
{
return Poco::format("%?d", _value);
}
std::string Integer64::typeName() const
{
std::string seqtype;
if (getType().universalValue() != ASN1Type::Integer)
seqtype = Poco::format("-0x%s", Poco::NumberFormatter::formatHex(getType().rawValue()));
return Poco::format("INTEGER64%s", seqtype);
}
Poco::UInt32 Integer64::getDataLength() const
{
Poco::Int64 value = _value;
int valueSize = 0;
do {
value >>= 7;
valueSize++;
} while (value != 0);
return valueSize;
}
void Integer64::encodeData(Poco::BinaryWriter &stream) const
{
Poco::UInt64 integer = _value;
int mask;
int intsize = 4;
/*
* Truncate "unnecessary" bytes off of the most significant end of this
* 2's complement integer. There should be no sequence of 9
* consecutive 1's or 0's at the most significant end of the
* integer.
*/
mask = 0x1FF << ((8 * 3) - 1);
/* mask is 0xFF800000 on a big-endian machine */
while ((((integer & mask) == 0) || ((integer & mask) == mask))
&& intsize > 1){
intsize--;
integer <<= 8;
}
//encodeHeader(os, type, intsize);
mask = 0xFF << (8 * 3);
/* mask is 0xFF000000 on a big-endian machine */
while ((intsize--) > 0){
stream << (char)( ((integer & mask) >> (8 * 3)) );
integer <<= 8;
}
}
void Integer64::decodeData(Poco::SharedPtr<ASN1Factory> factory, Poco::BinaryReader &stream, Poco::UInt32 length)
{
Poco::UInt8 bytesRead = 0;
Poco::UInt8 byte = 0;
stream >> byte;
bytesRead++;
_value = (byte & HIGH_BIT) == 0 ? 0 : -1;
for (;;) {
_value <<= 8;
_value |= byte;
if (bytesRead >= length)
break;
stream >> byte;
bytesRead++;
}
}
void Integer64::dump(std::ostream &stream, int ident) const
{
stream << Whitespace(ident) << "INTEGER64 " << _value << std::endl;
}
#endif // POCO_HAVE_INT64
///
/// OctetString
///
OctetString::OctetString() : ASN1(ASN1Type(ASN1Type::OctetString, true)), _value()
{
}
OctetString::OctetString(const std::string &value) : ASN1(ASN1Type(ASN1Type::OctetString, true)), _value(value)
{
}
OctetString::OctetString(ASN1Type type, const std::string &value) : ASN1(type), _value(value)
{
}
std::string OctetString::getValue() const
{
return _value;
}
std::string OctetString::toString() const
{
return _value;
}
std::string OctetString::typeName() const
{
std::string seqtype;
if (getType().universalValue() != ASN1Type::OctetString)
seqtype = Poco::format("-0x%s", Poco::NumberFormatter::formatHex(getType().rawValue()));
return Poco::format("OCTETSTRING%s", seqtype);
}
Poco::UInt32 OctetString::getDataLength() const
{
return _value.size();
}
void OctetString::encodeData(Poco::BinaryWriter &stream) const
{
stream.writeRaw(_value);
}
void OctetString::decodeData(Poco::SharedPtr<ASN1Factory> factory, Poco::BinaryReader &stream, Poco::UInt32 length)
{
stream.readRaw(length, _value);
}
void OctetString::dump(std::ostream &stream, int ident) const
{
stream << Whitespace(ident) << "OCTETSTRING '" << _value << "'" << std::endl;
}
///
/// ObjectIdentifier
///
ObjectIdentifier::ObjectIdentifier() : ASN1(ASN1Type(ASN1Type::ObjectIdentifier, true)), _value()
{
}
ObjectIdentifier::ObjectIdentifier(const std::string &value) : ASN1(ASN1Type(ASN1Type::ObjectIdentifier, true)), _value()
{
Poco::StringTokenizer tok(value, ".", Poco::StringTokenizer::TOK_IGNORE_EMPTY|Poco::StringTokenizer::TOK_TRIM);
for (Poco::StringTokenizer::Iterator i=tok.begin(); i!=tok.end(); i++)
{
_value.push_back(Poco::NumberParser::parseUnsigned(*i));
}
}
std::string ObjectIdentifier::toString() const
{
std::stringstream str;
for (std::vector<Poco::UInt32>::const_iterator i = _value.begin(); i!=_value.end(); i++)
{
if (i != _value.begin())
str << ".";
str << *i;
}
return str.str();
}
std::string ObjectIdentifier::typeName() const
{
return "OBJECTIDENTIFIER";
}
Poco::UInt32 ObjectIdentifier::getDataLength() const
{
Poco::UInt32 totalLength = 1;
for (int i = 2; i < _value.size(); ++i) {
Poco::UInt32 value = _value.at(i);
do {
value >>= 7;
totalLength++;
} while (value != 0);
}
return totalLength;
}
void ObjectIdentifier::encodeData(Poco::BinaryWriter &stream) const
{
if (_value.size() < 2)
throw DataException("Invalid Object Identifier");
stream << (Poco::UInt8)(_value.at(0) * 40 + _value.at(1));
for (int i = 2; i < _value.size(); ++i) {
std::string result;
std::string tmp;
Poco::UInt32 value = _value.at(i);
if (value < 128) {
result.push_back((char)value);
} else {
Poco::UInt32 val = value;
while (val != 0) {
Poco::UInt8 bval = (Poco::UInt8)(val & 0xFF);
if ((bval & HIGH_BIT) != 0) {
bval = (Poco::UInt8)(bval & ~HIGH_BIT);
}
val >>= 7;
tmp.push_back(bval);
}
// Now we need to reverse the bytes for the final encoding
for (int i = tmp.length() - 1; i >= 0; i--) {
if (i > 0)
result.push_back(tmp[i] | HIGH_BIT);
else
result.push_back(tmp[i]);
}
}
stream.writeRaw(result);
}
}
void ObjectIdentifier::decodeData(Poco::SharedPtr<ASN1Factory> factory, Poco::BinaryReader &stream, Poco::UInt32 length)
{
Poco::UInt8 byte = 0;
stream >> byte;
_value.push_back(byte / 40);
_value.push_back(byte % 40);
Poco::UInt8 bytesRead = 1;
while (bytesRead++ < length) {
Poco::UInt8 buffer = 0;
Poco::UInt32 value = 0;
stream >> buffer;
if ((buffer & HIGH_BIT) == 0) {
value = buffer;
} else {
std::string tmp;
for (;;) {
tmp.push_back(buffer & ~HIGH_BIT);
if ((buffer & HIGH_BIT) == 0)
break;
stream >> buffer;
bytesRead++;
}
for (int i = 0; i < tmp.size(); i++) {
value <<= 7;
value |= tmp[i];
}
}
_value.push_back(value);
}
}
void ObjectIdentifier::dump(std::ostream &stream, int ident) const
{
stream << Whitespace(ident) << "OID '" << toString() << "'" << std::endl;
}
///
/// SequenceData
///
SequenceData::SequenceData()
{
}
SequenceData::SequenceData(ASN1::Ptr v1, ASN1::Ptr v2, ASN1::Ptr v3)
{
push_back(v1);
if (!v2.isNull()) push_back(v2);
if (!v3.isNull()) push_back(v3);
}
///
/// Sequence
///
Sequence::Sequence() : ASN1(ASN1Type(ASN1Type::Sequence, true))
{
}
Sequence::Sequence(ASN1Type type) : ASN1(type)
{
}
Sequence::Sequence(const SequenceData &value) : ASN1(ASN1Type(ASN1Type::Sequence, true))
{
for (SequenceData::const_iterator i=value.begin(); i!=value.end(); i++)
{
_value.push_back(*i);
}
}
Sequence::Sequence(ASN1Type type, const SequenceData &value) : ASN1(type)
{
for (SequenceData::const_iterator i=value.begin(); i!=value.end(); i++)
{
_value.push_back(*i);
}
}
const SequenceData &Sequence::getSequenceData() const
{
return _value;
}
ASN1::Ptr Sequence::getDataType(int pos) const
{
if (_value.size() < pos + 1)
throw InvalidAccessException("No such element");
return _value.at(pos);
}
Poco::UInt32 Sequence::getDataLength() const
{
Poco::UInt32 totalDataLength = 0;
for (SequenceData::const_iterator i=_value.begin(); i!=_value.end(); i++)
{
totalDataLength += (*i)->getLength();
}
return totalDataLength;
}
void Sequence::encodeData(Poco::BinaryWriter &stream) const
{
for (SequenceData::const_iterator i=_value.begin(); i!=_value.end(); i++)
{
(*i)->encode(stream);
}
}
void Sequence::decodeData(Poco::SharedPtr<ASN1Factory> factory, Poco::BinaryReader &stream, Poco::UInt32 length)
{
Poco::UInt32 bytesRead = 0;
while (!stream.eof() && bytesRead < length) {
ASN1Type tp;
Poco::UInt8 typelen = tp.decodeData(stream);
bytesRead += typelen;
ASN1::Ptr asnType = factory->create(tp);
Poco::UInt32 curBytesRead = asnType->decode(factory, stream);
bytesRead += curBytesRead;
_value.push_back(asnType);
}
}
void Sequence::dump(std::ostream &stream, int ident) const
{
std::string seqtype;
if (getType().universalValue() != ASN1Type::Sequence)
seqtype = Poco::format(" TYPE 0x%s", Poco::NumberFormatter::formatHex(getType().rawValue()));
stream << Whitespace(ident) << "SEQUENCE BEGIN" << seqtype << " " << _value.size() << " ITEMS - SIZE " << getDataLength() << std::endl;
for (SequenceData::const_iterator i=_value.begin(); i!=_value.end(); i++)
{
(*i)->dump(stream, ident+1);
}
stream << Whitespace(ident) << "SEQUENCE END" << seqtype << " " << _value.size() << " ITEMS" << std::endl;
}
std::string Sequence::typeName() const
{
std::string seqtype;
if (getType().universalValue() != ASN1Type::Sequence)
seqtype = Poco::format("-0x%s", Poco::NumberFormatter::formatHex(getType().rawValue()));
return Poco::format("SEQUENCE%s", seqtype);
}
} } // namespace Poco::ASN1Types
|
// Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2009-2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "main.h"
#include "db.h"
#include "txdb.h"
#include "init.h"
#include "miner.h"
#include "bitcoinrpc.h"
using namespace json_spirit;
using namespace std;
Value getsubsidy(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 1)
throw runtime_error(
"getsubsidy [nTarget]\n"
"Returns proof-of-work subsidy value for the specified value of target.");
return (uint64_t)GetProofOfWorkReward(0);
}
Value getmininginfo(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
"getmininginfo\n"
"Returns an object containing mining-related information.");
uint64_t nMinWeight = 0, nMaxWeight = 0, nWeight = 0;
pwalletMain->GetStakeWeight(*pwalletMain, nMinWeight, nMaxWeight, nWeight);
Object obj, diff, weight;
obj.push_back(Pair("blocks", (int)nBestHeight));
obj.push_back(Pair("currentblocksize",(uint64_t)nLastBlockSize));
obj.push_back(Pair("currentblocktx",(uint64_t)nLastBlockTx));
diff.push_back(Pair("proof-of-work", GetDifficulty()));
diff.push_back(Pair("proof-of-stake", GetDifficulty(GetLastBlockIndex(pindexBest, true))));
diff.push_back(Pair("search-interval", (int)nLastCoinStakeSearchInterval));
obj.push_back(Pair("difficulty", diff));
obj.push_back(Pair("blockvalue", (uint64_t)GetProofOfWorkReward(0)));
obj.push_back(Pair("netmhashps", GetPoWMHashPS()));
obj.push_back(Pair("netstakeweight", GetPoSKernelPS()));
obj.push_back(Pair("errors", GetWarnings("statusbar")));
obj.push_back(Pair("pooledtx", (uint64_t)mempool.size()));
weight.push_back(Pair("minimum", (uint64_t)nMinWeight));
weight.push_back(Pair("maximum", (uint64_t)nMaxWeight));
weight.push_back(Pair("combined", (uint64_t)nWeight));
obj.push_back(Pair("stakeweight", weight));
obj.push_back(Pair("stakeinterest", (uint64_t)COIN_YEAR_REWARD));
obj.push_back(Pair("testnet", fTestNet));
return obj;
}
Value getstakinginfo(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
"getstakinginfo\n"
"Returns an object containing staking-related information.");
uint64_t nMinWeight = 0, nMaxWeight = 0, nWeight = 0;
pwalletMain->GetStakeWeight(*pwalletMain, nMinWeight, nMaxWeight, nWeight);
uint64_t nNetworkWeight = GetPoSKernelPS();
bool staking = nLastCoinStakeSearchInterval && nWeight;
int nExpectedTime = staking ? (nTargetSpacing * nNetworkWeight / nWeight) : -1;
Object obj;
obj.push_back(Pair("enabled", GetBoolArg("-staking", true)));
obj.push_back(Pair("staking", staking));
obj.push_back(Pair("errors", GetWarnings("statusbar")));
obj.push_back(Pair("currentblocksize", (uint64_t)nLastBlockSize));
obj.push_back(Pair("currentblocktx", (uint64_t)nLastBlockTx));
obj.push_back(Pair("pooledtx", (uint64_t)mempool.size()));
obj.push_back(Pair("difficulty", GetDifficulty(GetLastBlockIndex(pindexBest, true))));
obj.push_back(Pair("search-interval", (int)nLastCoinStakeSearchInterval));
obj.push_back(Pair("weight", (uint64_t)nWeight));
obj.push_back(Pair("netstakeweight", (uint64_t)nNetworkWeight));
obj.push_back(Pair("expectedtime", nExpectedTime));
return obj;
}
Value getworkex(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 2)
throw runtime_error(
"getworkex [data, coinbase]\n"
"If [data, coinbase] is not specified, returns extended work data.\n"
);
if (vNodes.empty())
throw JSONRPCError(-9, "404coin is not connected!");
if (IsInitialBlockDownload())
throw JSONRPCError(-10, "404coin is downloading blocks...");
if (pindexBest->nHeight >= LAST_POW_BLOCK)
throw JSONRPCError(RPC_MISC_ERROR, "No more PoW blocks");
typedef map<uint256, pair<CBlock*, CScript> > mapNewBlock_t;
static mapNewBlock_t mapNewBlock;
static vector<CBlock*> vNewBlock;
static CReserveKey reservekey(pwalletMain);
if (params.size() == 0)
{
// Update block
static unsigned int nTransactionsUpdatedLast;
static CBlockIndex* pindexPrev;
static int64_t nStart;
static CBlock* pblock;
if (pindexPrev != pindexBest ||
(nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60))
{
if (pindexPrev != pindexBest)
{
// Deallocate old blocks since they're obsolete now
mapNewBlock.clear();
BOOST_FOREACH(CBlock* pblock, vNewBlock)
delete pblock;
vNewBlock.clear();
}
nTransactionsUpdatedLast = nTransactionsUpdated;
pindexPrev = pindexBest;
nStart = GetTime();
// Create new block
pblock = CreateNewBlock(pwalletMain);
if (!pblock)
throw JSONRPCError(-7, "Out of memory");
vNewBlock.push_back(pblock);
}
// Update nTime
pblock->nTime = max(pindexPrev->GetPastTimeLimit()+1, GetAdjustedTime());
pblock->nNonce = 0;
// Update nExtraNonce
static unsigned int nExtraNonce = 0;
IncrementExtraNonce(pblock, pindexPrev, nExtraNonce);
// Save
mapNewBlock[pblock->hashMerkleRoot] = make_pair(pblock, pblock->vtx[0].vin[0].scriptSig);
// Prebuild hash buffers
char pmidstate[32];
char pdata[128];
char phash1[64];
FormatHashBuffers(pblock, pmidstate, pdata, phash1);
uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
CTransaction coinbaseTx = pblock->vtx[0];
std::vector<uint256> merkle = pblock->GetMerkleBranch(0);
Object result;
result.push_back(Pair("data", HexStr(BEGIN(pdata), END(pdata))));
result.push_back(Pair("target", HexStr(BEGIN(hashTarget), END(hashTarget))));
CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION);
ssTx << coinbaseTx;
result.push_back(Pair("coinbase", HexStr(ssTx.begin(), ssTx.end())));
Array merkle_arr;
BOOST_FOREACH(uint256 merkleh, merkle) {
merkle_arr.push_back(HexStr(BEGIN(merkleh), END(merkleh)));
}
result.push_back(Pair("merkle", merkle_arr));
return result;
}
else
{
// Parse parameters
vector<unsigned char> vchData = ParseHex(params[0].get_str());
vector<unsigned char> coinbase;
if(params.size() == 2)
coinbase = ParseHex(params[1].get_str());
if (vchData.size() != 128)
throw JSONRPCError(-8, "Invalid parameter");
CBlock* pdata = (CBlock*)&vchData[0];
// Byte reverse
for (int i = 0; i < 128/4; i++)
((unsigned int*)pdata)[i] = ByteReverse(((unsigned int*)pdata)[i]);
// Get saved block
if (!mapNewBlock.count(pdata->hashMerkleRoot))
return false;
CBlock* pblock = mapNewBlock[pdata->hashMerkleRoot].first;
pblock->nTime = pdata->nTime;
pblock->nNonce = pdata->nNonce;
if(coinbase.size() == 0)
pblock->vtx[0].vin[0].scriptSig = mapNewBlock[pdata->hashMerkleRoot].second;
else
CDataStream(coinbase, SER_NETWORK, PROTOCOL_VERSION) >> pblock->vtx[0]; // FIXME - HACK!
pblock->hashMerkleRoot = pblock->BuildMerkleTree();
return CheckWork(pblock, *pwalletMain, reservekey);
}
}
Value getwork(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 1)
throw runtime_error(
"getwork [data]\n"
"If [data] is not specified, returns formatted hash data to work on:\n"
" \"midstate\" : precomputed hash state after hashing the first half of the data (DEPRECATED)\n" // deprecated
" \"data\" : block data\n"
" \"hash1\" : formatted hash buffer for second hash (DEPRECATED)\n" // deprecated
" \"target\" : little endian hash target\n"
"If [data] is specified, tries to solve the block and returns true if it was successful.");
if (vNodes.empty())
throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "404coin is not connected!");
if (IsInitialBlockDownload())
throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, "404coin is downloading blocks...");
if (pindexBest->nHeight >= LAST_POW_BLOCK)
throw JSONRPCError(RPC_MISC_ERROR, "No more PoW blocks");
typedef map<uint256, pair<CBlock*, CScript> > mapNewBlock_t;
static mapNewBlock_t mapNewBlock; // FIXME: thread safety
static vector<CBlock*> vNewBlock;
static CReserveKey reservekey(pwalletMain);
if (params.size() == 0)
{
// Update block
static unsigned int nTransactionsUpdatedLast;
static CBlockIndex* pindexPrev;
static int64_t nStart;
static CBlock* pblock;
if (pindexPrev != pindexBest ||
(nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60))
{
if (pindexPrev != pindexBest)
{
// Deallocate old blocks since they're obsolete now
mapNewBlock.clear();
BOOST_FOREACH(CBlock* pblock, vNewBlock)
delete pblock;
vNewBlock.clear();
}
// Clear pindexPrev so future getworks make a new block, despite any failures from here on
pindexPrev = NULL;
// Store the pindexBest used before CreateNewBlock, to avoid races
nTransactionsUpdatedLast = nTransactionsUpdated;
CBlockIndex* pindexPrevNew = pindexBest;
nStart = GetTime();
// Create new block
pblock = CreateNewBlock(pwalletMain);
if (!pblock)
throw JSONRPCError(RPC_OUT_OF_MEMORY, "Out of memory");
vNewBlock.push_back(pblock);
// Need to update only after we know CreateNewBlock succeeded
pindexPrev = pindexPrevNew;
}
// Update nTime
pblock->UpdateTime(pindexPrev);
pblock->nNonce = 0;
// Update nExtraNonce
static unsigned int nExtraNonce = 0;
IncrementExtraNonce(pblock, pindexPrev, nExtraNonce);
// Save
mapNewBlock[pblock->hashMerkleRoot] = make_pair(pblock, pblock->vtx[0].vin[0].scriptSig);
// Pre-build hash buffers
char pmidstate[32];
char pdata[128];
char phash1[64];
FormatHashBuffers(pblock, pmidstate, pdata, phash1);
uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
Object result;
result.push_back(Pair("midstate", HexStr(BEGIN(pmidstate), END(pmidstate)))); // deprecated
result.push_back(Pair("data", HexStr(BEGIN(pdata), END(pdata))));
result.push_back(Pair("hash1", HexStr(BEGIN(phash1), END(phash1)))); // deprecated
result.push_back(Pair("target", HexStr(BEGIN(hashTarget), END(hashTarget))));
return result;
}
else
{
// Parse parameters
vector<unsigned char> vchData = ParseHex(params[0].get_str());
if (vchData.size() != 128)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter");
CBlock* pdata = (CBlock*)&vchData[0];
// Byte reverse
for (int i = 0; i < 128/4; i++)
((unsigned int*)pdata)[i] = ByteReverse(((unsigned int*)pdata)[i]);
// Get saved block
if (!mapNewBlock.count(pdata->hashMerkleRoot))
return false;
CBlock* pblock = mapNewBlock[pdata->hashMerkleRoot].first;
pblock->nTime = pdata->nTime;
pblock->nNonce = pdata->nNonce;
pblock->vtx[0].vin[0].scriptSig = mapNewBlock[pdata->hashMerkleRoot].second;
pblock->hashMerkleRoot = pblock->BuildMerkleTree();
return CheckWork(pblock, *pwalletMain, reservekey);
}
}
Value getblocktemplate(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 1)
throw runtime_error(
"getblocktemplate [params]\n"
"Returns data needed to construct a block to work on:\n"
" \"version\" : block version\n"
" \"previousblockhash\" : hash of current highest block\n"
" \"transactions\" : contents of non-coinbase transactions that should be included in the next block\n"
" \"coinbaseaux\" : data that should be included in coinbase\n"
" \"coinbasevalue\" : maximum allowable input to coinbase transaction, including the generation award and transaction fees\n"
" \"target\" : hash target\n"
" \"mintime\" : minimum timestamp appropriate for next block\n"
" \"curtime\" : current timestamp\n"
" \"mutable\" : list of ways the block template may be changed\n"
" \"noncerange\" : range of valid nonces\n"
" \"sigoplimit\" : limit of sigops in blocks\n"
" \"sizelimit\" : limit of block size\n"
" \"bits\" : compressed target of next block\n"
" \"height\" : height of the next block\n"
"See https://en.bitcoin.it/wiki/BIP_0022 for full specification.");
std::string strMode = "template";
if (params.size() > 0)
{
const Object& oparam = params[0].get_obj();
const Value& modeval = find_value(oparam, "mode");
if (modeval.type() == str_type)
strMode = modeval.get_str();
else if (modeval.type() == null_type)
{
/* Do nothing */
}
else
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode");
}
if (strMode != "template")
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode");
if (vNodes.empty())
throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "404coin is not connected!");
if (IsInitialBlockDownload())
throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, "404coin is downloading blocks...");
if (pindexBest->nHeight >= LAST_POW_BLOCK)
throw JSONRPCError(RPC_MISC_ERROR, "No more PoW blocks");
static CReserveKey reservekey(pwalletMain);
// Update block
static unsigned int nTransactionsUpdatedLast;
static CBlockIndex* pindexPrev;
static int64_t nStart;
static CBlock* pblock;
if (pindexPrev != pindexBest ||
(nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 5))
{
// Clear pindexPrev so future calls make a new block, despite any failures from here on
pindexPrev = NULL;
// Store the pindexBest used before CreateNewBlock, to avoid races
nTransactionsUpdatedLast = nTransactionsUpdated;
CBlockIndex* pindexPrevNew = pindexBest;
nStart = GetTime();
// Create new block
if(pblock)
{
delete pblock;
pblock = NULL;
}
pblock = CreateNewBlock(pwalletMain);
if (!pblock)
throw JSONRPCError(RPC_OUT_OF_MEMORY, "Out of memory");
// Need to update only after we know CreateNewBlock succeeded
pindexPrev = pindexPrevNew;
}
// Update nTime
pblock->UpdateTime(pindexPrev);
pblock->nNonce = 0;
Array transactions;
map<uint256, int64_t> setTxIndex;
int i = 0;
CTxDB txdb("r");
BOOST_FOREACH (CTransaction& tx, pblock->vtx)
{
uint256 txHash = tx.GetHash();
setTxIndex[txHash] = i++;
if (tx.IsCoinBase() || tx.IsCoinStake())
continue;
Object entry;
CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION);
ssTx << tx;
entry.push_back(Pair("data", HexStr(ssTx.begin(), ssTx.end())));
entry.push_back(Pair("hash", txHash.GetHex()));
MapPrevTx mapInputs;
map<uint256, CTxIndex> mapUnused;
bool fInvalid = false;
if (tx.FetchInputs(txdb, mapUnused, false, false, mapInputs, fInvalid))
{
entry.push_back(Pair("fee", (int64_t)(tx.GetValueIn(mapInputs) - tx.GetValueOut())));
Array deps;
BOOST_FOREACH (MapPrevTx::value_type& inp, mapInputs)
{
if (setTxIndex.count(inp.first))
deps.push_back(setTxIndex[inp.first]);
}
entry.push_back(Pair("depends", deps));
int64_t nSigOps = tx.GetLegacySigOpCount();
nSigOps += tx.GetP2SHSigOpCount(mapInputs);
entry.push_back(Pair("sigops", nSigOps));
}
transactions.push_back(entry);
}
Object aux;
aux.push_back(Pair("flags", HexStr(COINBASE_FLAGS.begin(), COINBASE_FLAGS.end())));
uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
static Array aMutable;
if (aMutable.empty())
{
aMutable.push_back("time");
aMutable.push_back("transactions");
aMutable.push_back("prevblock");
}
Object result;
result.push_back(Pair("version", pblock->nVersion));
result.push_back(Pair("previousblockhash", pblock->hashPrevBlock.GetHex()));
result.push_back(Pair("transactions", transactions));
result.push_back(Pair("coinbaseaux", aux));
result.push_back(Pair("coinbasevalue", (int64_t)pblock->vtx[0].vout[0].nValue));
result.push_back(Pair("target", hashTarget.GetHex()));
result.push_back(Pair("mintime", (int64_t)pindexPrev->GetPastTimeLimit()+1));
result.push_back(Pair("mutable", aMutable));
result.push_back(Pair("noncerange", "00000000ffffffff"));
result.push_back(Pair("sigoplimit", (int64_t)MAX_BLOCK_SIGOPS));
result.push_back(Pair("sizelimit", (int64_t)MAX_BLOCK_SIZE));
result.push_back(Pair("curtime", (int64_t)pblock->nTime));
result.push_back(Pair("bits", strprintf("%08x", pblock->nBits)));
result.push_back(Pair("height", (int64_t)(pindexPrev->nHeight+1)));
return result;
}
Value submitblock(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 2)
throw runtime_error(
"submitblock <hex data> [optional-params-obj]\n"
"[optional-params-obj] parameter is currently ignored.\n"
"Attempts to submit new block to network.\n"
"See https://en.bitcoin.it/wiki/BIP_0022 for full specification.");
vector<unsigned char> blockData(ParseHex(params[0].get_str()));
CDataStream ssBlock(blockData, SER_NETWORK, PROTOCOL_VERSION);
CBlock block;
try {
ssBlock >> block;
}
catch (std::exception &e) {
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Block decode failed");
}
bool fAccepted = ProcessBlock(NULL, &block);
if (!fAccepted)
return "rejected";
return Value::null;
}
|
/*
* PFRecoTauChargedHadronFromTrackPlugin
*
* Build PFRecoTauChargedHadron objects
* using charged PFCandidates as input
*
* Author: Christian Veelken, LLR
*
*/
#include "RecoTauTag/RecoTau/interface/PFRecoTauChargedHadronPlugins.h"
#include "FWCore/MessageLogger/interface/MessageLogger.h"
#include "FWCore/Framework/interface/ESHandle.h"
#include "MagneticField/Engine/interface/MagneticField.h"
#include "MagneticField/Records/interface/IdealMagneticFieldRecord.h"
#include "DataFormats/ParticleFlowCandidate/interface/PFCandidate.h"
#include "DataFormats/ParticleFlowCandidate/interface/PFCandidateFwd.h"
#include "DataFormats/TrackReco/interface/Track.h"
#include "DataFormats/TrackReco/interface/TrackFwd.h"
#include "DataFormats/VertexReco/interface/Vertex.h"
#include "DataFormats/VertexReco/interface/VertexFwd.h"
#include "DataFormats/TauReco/interface/PFRecoTauChargedHadron.h"
#include "DataFormats/JetReco/interface/PFJet.h"
#include "DataFormats/Common/interface/AssociationMap.h"
#include "DataFormats/Common/interface/Ptr.h"
#include "DataFormats/Math/interface/deltaR.h"
#include "FastSimulation/BaseParticlePropagator/interface/BaseParticlePropagator.h"
#include "FastSimulation/BaseParticlePropagator/interface/RawParticle.h"
#include "RecoTauTag/RecoTau/interface/RecoTauCommonUtilities.h"
#include "RecoTauTag/RecoTau/interface/RecoTauQualityCuts.h"
#include "RecoTauTag/RecoTau/interface/RecoTauVertexAssociator.h"
#include "RecoTauTag/RecoTau/interface/pfRecoTauChargedHadronAuxFunctions.h"
#include <TMath.h>
#include <memory>
#include <cmath>
namespace reco { namespace tau {
class PFRecoTauChargedHadronFromTrackPlugin : public PFRecoTauChargedHadronBuilderPlugin
{
public:
explicit PFRecoTauChargedHadronFromTrackPlugin(const edm::ParameterSet&, edm::ConsumesCollector && iC);
~PFRecoTauChargedHadronFromTrackPlugin() override;
// Return type is auto_ptr<ChargedHadronVector>
return_type operator()(const reco::PFJet&) const override;
// Hook to update PV information
void beginEvent() override;
private:
typedef std::vector<reco::PFCandidatePtr> PFCandPtrs;
RecoTauVertexAssociator vertexAssociator_;
RecoTauQualityCuts* qcuts_;
edm::InputTag srcTracks_;
edm::EDGetTokenT<reco::TrackCollection> Tracks_token;
double dRcone_;
bool dRconeLimitedToJetArea_;
double dRmergeNeutralHadron_;
double dRmergePhoton_;
math::XYZVector magneticFieldStrength_;
mutable int numWarnings_;
int maxWarnings_;
int verbosity_;
};
PFRecoTauChargedHadronFromTrackPlugin::PFRecoTauChargedHadronFromTrackPlugin(const edm::ParameterSet& pset, edm::ConsumesCollector && iC)
: PFRecoTauChargedHadronBuilderPlugin(pset,std::move(iC)),
vertexAssociator_(pset.getParameter<edm::ParameterSet>("qualityCuts"),std::move(iC)),
qcuts_(nullptr)
{
edm::ParameterSet qcuts_pset = pset.getParameterSet("qualityCuts").getParameterSet("signalQualityCuts");
qcuts_ = new RecoTauQualityCuts(qcuts_pset);
srcTracks_ = pset.getParameter<edm::InputTag>("srcTracks");
Tracks_token = iC.consumes<reco::TrackCollection>(srcTracks_);
dRcone_ = pset.getParameter<double>("dRcone");
dRconeLimitedToJetArea_ = pset.getParameter<bool>("dRconeLimitedToJetArea");
dRmergeNeutralHadron_ = pset.getParameter<double>("dRmergeNeutralHadron");
dRmergePhoton_ = pset.getParameter<double>("dRmergePhoton");
numWarnings_ = 0;
maxWarnings_ = 3;
verbosity_ = ( pset.exists("verbosity") ) ?
pset.getParameter<int>("verbosity") : 0;
}
PFRecoTauChargedHadronFromTrackPlugin::~PFRecoTauChargedHadronFromTrackPlugin()
{
delete qcuts_;
}
// Update the primary vertex
void PFRecoTauChargedHadronFromTrackPlugin::beginEvent()
{
vertexAssociator_.setEvent(*this->evt());
edm::ESHandle<MagneticField> magneticField;
evtSetup()->get<IdealMagneticFieldRecord>().get(magneticField);
magneticFieldStrength_ = magneticField->inTesla(GlobalPoint(0.,0.,0.));
}
namespace
{
struct PFCandidate_withDistance
{
reco::PFCandidatePtr pfCandidate_;
double distance_;
};
bool isSmallerDistance(const PFCandidate_withDistance& cand1, const PFCandidate_withDistance& cand2)
{
return (cand1.distance_ < cand2.distance_);
}
}
PFRecoTauChargedHadronFromTrackPlugin::return_type PFRecoTauChargedHadronFromTrackPlugin::operator()(const reco::PFJet& jet) const
{
if ( verbosity_ ) {
edm::LogPrint("TauChHFromTrack") << "<PFRecoTauChargedHadronFromTrackPlugin::operator()>:" ;
edm::LogPrint("TauChHFromTrack") << " pluginName = " << name() ;
}
ChargedHadronVector output;
const edm::Event& evt = (*this->evt());
edm::Handle<reco::TrackCollection> tracks;
evt.getByToken(Tracks_token, tracks);
qcuts_->setPV(vertexAssociator_.associatedVertex(jet));
float jEta=jet.eta();
float jPhi=jet.phi();
size_t numTracks = tracks->size();
for ( size_t iTrack = 0; iTrack < numTracks; ++iTrack ) {
reco::TrackRef track(tracks, iTrack);
// consider tracks in vicinity of tau-jet candidate only
double dR = deltaR(track->eta(), track->phi(), jEta,jPhi);
double dRmatch = dRcone_;
if ( dRconeLimitedToJetArea_ ) {
double jetArea = jet.jetArea();
if ( jetArea > 0. ) {
dRmatch = TMath::Min(dRmatch, TMath::Sqrt(jetArea/TMath::Pi()));
} else {
if ( numWarnings_ < maxWarnings_ ) {
edm::LogInfo("PFRecoTauChargedHadronFromTrackPlugin::operator()")
<< "Jet: Pt = " << jet.pt() << ", eta = " << jet.eta() << ", phi = " << jet.phi() << " has area = " << jetArea << " !!" << std::endl;
++numWarnings_;
}
dRmatch = 0.1;
}
}
if ( dR > dRmatch ) continue;
// ignore tracks which fail quality cuts
if ( !qcuts_->filterTrack(track) ) continue;
reco::Candidate::Charge trackCharge_int = 0;
if ( track->charge() > 0. ) trackCharge_int = +1;
else if ( track->charge() < 0. ) trackCharge_int = -1;
const double chargedPionMass = 0.13957; // GeV
double chargedPionP = track->p();
double chargedPionEn = TMath::Sqrt(chargedPionP*chargedPionP + chargedPionMass*chargedPionMass);
reco::Candidate::LorentzVector chargedPionP4(track->px(), track->py(), track->pz(), chargedPionEn);
reco::Vertex::Point vtx(0.,0.,0.);
if ( vertexAssociator_.associatedVertex(jet).isNonnull() ) vtx = vertexAssociator_.associatedVertex(jet)->position();
std::auto_ptr<PFRecoTauChargedHadron> chargedHadron(new PFRecoTauChargedHadron(trackCharge_int, chargedPionP4, vtx, 0, true, PFRecoTauChargedHadron::kTrack));
chargedHadron->track_ = edm::Ptr<reco::Track>(tracks, iTrack);
// CV: Take code for propagating track to ECAL entrance
// from RecoParticleFlow/PFTracking/src/PFTrackTransformer.cc
// to make sure propagation is done in the same way as for charged PFCandidates.
//
// The following replacements need to be made
// outerMomentum -> momentum
// outerPosition -> referencePoint
// in order to run on AOD input
// (outerMomentum and outerPosition require access to reco::TrackExtra objects, which are available in RECO only)
//
XYZTLorentzVector chargedPionPos(track->referencePoint().x(), track->referencePoint().y(), track->referencePoint().z(), 0.);
RawParticle p(chargedPionP4, chargedPionPos);
p.setCharge(track->charge());
BaseParticlePropagator trackPropagator(p, 0., 0., magneticFieldStrength_.z());
trackPropagator.propagateToEcalEntrance(false);
if ( trackPropagator.getSuccess() != 0 ) {
chargedHadron->positionAtECALEntrance_ = trackPropagator.particle().vertex();
} else {
if ( chargedPionP4.pt() > 2. and std::abs(chargedPionP4.eta()) < 3. ) {
edm::LogWarning("PFRecoTauChargedHadronFromTrackPlugin::operator()")
<< "Failed to propagate track: Pt = " << track->pt() << ", eta = " << track->eta() << ", phi = " << track->phi() << " to ECAL entrance !!" << std::endl;
}
chargedHadron->positionAtECALEntrance_ = math::XYZPointF(0.,0.,0.);
}
std::vector<PFCandidate_withDistance> neutralJetConstituents_withDistance;
std::vector<reco::PFCandidatePtr> jetConstituents = jet.getPFConstituents();
for ( std::vector<reco::PFCandidatePtr>::const_iterator jetConstituent = jetConstituents.begin();
jetConstituent != jetConstituents.end(); ++jetConstituent ) {
reco::PFCandidate::ParticleType jetConstituentType = (*jetConstituent)->particleId();
if ( !(jetConstituentType == reco::PFCandidate::h0 || jetConstituentType == reco::PFCandidate::gamma) ) continue;
double dR = deltaR((*jetConstituent)->positionAtECALEntrance(), chargedHadron->positionAtECALEntrance_);
double dRmerge = -1.;
if ( jetConstituentType == reco::PFCandidate::h0 ) dRmerge = dRmergeNeutralHadron_;
else if ( jetConstituentType == reco::PFCandidate::gamma ) dRmerge = dRmergePhoton_;
if ( dR < dRmerge ) {
PFCandidate_withDistance jetConstituent_withDistance;
jetConstituent_withDistance.pfCandidate_ = (*jetConstituent);
jetConstituent_withDistance.distance_ = dR;
neutralJetConstituents_withDistance.push_back(jetConstituent_withDistance);
chargedHadron->addDaughter(*jetConstituent);
}
}
std::sort(neutralJetConstituents_withDistance.begin(), neutralJetConstituents_withDistance.end(), isSmallerDistance);
const double caloResolutionCoeff = 1.0; // CV: approximate ECAL + HCAL calorimeter resolution for hadrons by 100%*sqrt(E)
double resolutionTrackP = track->p()*(track->ptError()/track->pt());
double neutralEnSum = 0.;
for ( std::vector<PFCandidate_withDistance>::const_iterator nextNeutral = neutralJetConstituents_withDistance.begin();
nextNeutral != neutralJetConstituents_withDistance.end(); ++nextNeutral ) {
double nextNeutralEn = nextNeutral->pfCandidate_->energy();
double resolutionCaloEn = caloResolutionCoeff*sqrt(neutralEnSum + nextNeutralEn);
double resolution = sqrt(resolutionTrackP*resolutionTrackP + resolutionCaloEn*resolutionCaloEn);
if ( (neutralEnSum + nextNeutralEn) < (track->p() + 2.*resolution) ) {
chargedHadron->neutralPFCandidates_.push_back(nextNeutral->pfCandidate_);
neutralEnSum += nextNeutralEn;
} else {
break;
}
}
setChargedHadronP4(*chargedHadron);
if ( verbosity_ ) {
edm::LogPrint("TauChHFromTrack") << *chargedHadron;
}
output.push_back(chargedHadron);
}
return output.release();
}
}} // end namespace reco::tau
#include "FWCore/Framework/interface/MakerMacros.h"
DEFINE_EDM_PLUGIN(PFRecoTauChargedHadronBuilderPluginFactory, reco::tau::PFRecoTauChargedHadronFromTrackPlugin, "PFRecoTauChargedHadronFromTrackPlugin");
|
/***************************************************************************
# Copyright (c) 2020, NVIDIA CORPORATION. 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 NVIDIA CORPORATION 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 "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 OWNER 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 "stdafx.h"
#include "Core/API/Buffer.h"
#include "Core/API/Device.h"
#include "D3D12Resource.h"
namespace Falcor
{
ID3D12ResourcePtr createBuffer(Buffer::State initState, size_t size, const D3D12_HEAP_PROPERTIES& heapProps, Buffer::BindFlags bindFlags)
{
assert(gpDevice);
ID3D12Device* pDevice = gpDevice->getApiHandle();
// Create the buffer
D3D12_RESOURCE_DESC bufDesc = {};
bufDesc.Alignment = 0;
bufDesc.DepthOrArraySize = 1;
bufDesc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER;
bufDesc.Flags = getD3D12ResourceFlags(bindFlags);
bufDesc.Format = DXGI_FORMAT_UNKNOWN;
bufDesc.Height = 1;
bufDesc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
bufDesc.MipLevels = 1;
bufDesc.SampleDesc.Count = 1;
bufDesc.SampleDesc.Quality = 0;
bufDesc.Width = size;
assert(bufDesc.Width > 0);
D3D12_RESOURCE_STATES d3dState = getD3D12ResourceState(initState);
ID3D12ResourcePtr pApiHandle;
D3D12_HEAP_FLAGS heapFlags = is_set(bindFlags, ResourceBindFlags::Shared) ? D3D12_HEAP_FLAG_SHARED : D3D12_HEAP_FLAG_NONE;
d3d_call(pDevice->CreateCommittedResource(&heapProps, heapFlags, &bufDesc, d3dState, nullptr, IID_PPV_ARGS(&pApiHandle)));
assert(pApiHandle);
return pApiHandle;
}
size_t getBufferDataAlignment(const Buffer* pBuffer)
{
// This in order of the alignment size
const auto& bindFlags = pBuffer->getBindFlags();
if (is_set(bindFlags, Buffer::BindFlags::Constant)) return D3D12_CONSTANT_BUFFER_DATA_PLACEMENT_ALIGNMENT;
if (is_set(bindFlags, Buffer::BindFlags::Index)) return sizeof(uint32_t); // This actually depends on the size of the index, but we can handle losing 2 bytes
return D3D12_TEXTURE_DATA_PLACEMENT_ALIGNMENT;
}
void* mapBufferApi(const Buffer::ApiHandle& apiHandle, size_t size)
{
D3D12_RANGE r{ 0, size };
void* pData;
d3d_call(apiHandle->Map(0, &r, &pData));
return pData;
}
void Buffer::apiInit(bool hasInitData)
{
if (mCpuAccess != CpuAccess::None && is_set(mBindFlags, BindFlags::Shared))
{
throw std::exception("Can't create shared resource with CPU access other than 'None'.");
}
if (mBindFlags == BindFlags::Constant)
{
mSize = align_to(D3D12_CONSTANT_BUFFER_DATA_PLACEMENT_ALIGNMENT, mSize);
}
if (mCpuAccess == CpuAccess::Write)
{
mState.global = Resource::State::GenericRead;
if(hasInitData == false) // Else the allocation will happen when updating the data
{
assert(gpDevice);
mDynamicData = gpDevice->getUploadHeap()->allocate(mSize, getBufferDataAlignment(this));
mApiHandle = mDynamicData.pResourceHandle;
mGpuVaOffset = mDynamicData.offset;
}
}
else if (mCpuAccess == CpuAccess::Read && mBindFlags == BindFlags::None)
{
mState.global = Resource::State::CopyDest;
mApiHandle = createBuffer(mState.global, mSize, kReadbackHeapProps, mBindFlags);
}
else
{
mState.global = Resource::State::Common;
if (is_set(mBindFlags, BindFlags::AccelerationStructure)) mState.global = Resource::State::AccelerationStructure;
mApiHandle = createBuffer(mState.global, mSize, kDefaultHeapProps, mBindFlags);
}
}
uint64_t Buffer::getGpuAddress() const
{
return mGpuVaOffset + mApiHandle->GetGPUVirtualAddress();
}
void Buffer::unmap()
{
// Only unmap read buffers, write buffers are persistently mapped
D3D12_RANGE r{};
if (mpStagingResource)
{
mpStagingResource->mApiHandle->Unmap(0, &r);
}
else if (mCpuAccess == CpuAccess::Read)
{
mApiHandle->Unmap(0, &r);
}
}
}
|
#include "harris.h"
#include <ctime>
Harris::Harris(Mat img, float k, int filterRange, bool gauss) {
// (1) Convert to greyscalescale image
clock_t start;
start = clock();
Mat greyscaleImg = convertRgbToGrayscale(img);
std::cout << "GreyscaleImg: " << (std::clock() - start) / (double)(CLOCKS_PER_SEC / 1000) << " ms" << std::endl;
// (2) Compute Derivatives
start = clock();
Derivatives derivatives = computeDerivatives(greyscaleImg);
std::cout << "Derivatives: " << (std::clock() - start) / (double)(CLOCKS_PER_SEC / 1000) << " ms" << std::endl;
// (3) Median Filtering
start = clock();
Derivatives mDerivatives;
if(gauss) {
mDerivatives = applyGaussToDerivatives(derivatives, filterRange);
} else {
mDerivatives = applyMeanToDerivatives(derivatives, filterRange);
}
std::cout << "Median Filtering: " << (std::clock() - start) / (double)(CLOCKS_PER_SEC / 1000) << " ms" << std::endl;
// (4) Compute Harris Responses
start = clock();
Mat harrisResponses = computeHarrisResponses(k, mDerivatives);
m_harrisResponses = harrisResponses;
std::cout << "Harris Responses: " << (std::clock() - start) / (double)(CLOCKS_PER_SEC / 1000) << " ms" << std::endl;
}
//-----------------------------------------------------------------------------------------------
vector<pointData> Harris::getMaximaPoints(float percentage, int filterRange, int suppressionRadius) {
// Declare a max suppression matrix
Mat maximaSuppressionMat(m_harrisResponses.rows, m_harrisResponses.cols, CV_32F, Scalar::all(0));
// Create a vector of all Points
std::vector<pointData> points;
for (int r = 0; r < m_harrisResponses.rows; r++) {
for (int c = 0; c < m_harrisResponses.cols; c++) {
Point p(r,c);
pointData d;
d.cornerResponse = m_harrisResponses.at<float>(r,c);
d.point = p;
points.push_back(d);
}
}
// Sort points by corner Response
sort(points.begin(), points.end(), by_cornerResponse());
// Get top points, given by the percentage
int numberTopPoints = m_harrisResponses.cols * m_harrisResponses.rows * percentage;
std::vector<pointData> topPoints;
int i=0;
while(topPoints.size() < numberTopPoints) {
if(i == points.size())
break;
int supRows = maximaSuppressionMat.rows;
int supCols = maximaSuppressionMat.cols;
// Check if point marked in maximaSuppression matrix
if(maximaSuppressionMat.at<int>(points[i].point.x,points[i].point.y) == 0) {
for (int r = -suppressionRadius; r <= suppressionRadius; r++) {
for (int c = -suppressionRadius; c <= suppressionRadius; c++) {
int sx = points[i].point.x+c;
int sy = points[i].point.y+r;
// bound checking
if(sx > supRows)
sx = supRows;
if(sx < 0)
sx = 0;
if(sy > supCols)
sy = supCols;
if(sy < 0)
sy = 0;
maximaSuppressionMat.at<int>(points[i].point.x+c, points[i].point.y+r) = 1;
}
}
// Convert back to original image coordinate system
points[i].point.x += 1 + filterRange;
points[i].point.y += 1 + filterRange;
topPoints.push_back(points[i]);
}
i++;
}
return topPoints;
}
//-----------------------------------------------------------------------------------------------
Mat Harris::convertRgbToGrayscale(Mat& img) {
Mat greyscaleImg(img.rows, img.cols, CV_32F);
for (int c = 0; c < img.cols; c++) {
for (int r = 0; r < img.rows; r++) {
greyscaleImg.at<float>(r,c) =
0.2126 * img.at<cv::Vec3b>(r,c)[0] +
0.7152 * img.at<cv::Vec3b>(r,c)[1] +
0.0722 * img.at<cv::Vec3b>(r,c)[2];
}
}
return greyscaleImg;
}
//-----------------------------------------------------------------------------------------------
Derivatives Harris::applyGaussToDerivatives(Derivatives& dMats, int filterRange) {
if(filterRange == 0)
return dMats;
Derivatives mdMats;
Mat vec[3] = {mdMats.Ix, mdMats.Iy, mdMats.Ixy};
mdMats.Ix = gaussFilter(dMats.Ix, filterRange);
mdMats.Iy = gaussFilter(dMats.Iy, filterRange);
mdMats.Ixy = gaussFilter(dMats.Ixy, filterRange);
return mdMats;
}
//-----------------------------------------------------------------------------------------------
Derivatives Harris::applyMeanToDerivatives(Derivatives& dMats, int filterRange) {
if(filterRange == 0)
return dMats;
Derivatives mdMats;
Mat mIx = computeIntegralImg(dMats.Ix);
Mat mIy = computeIntegralImg(dMats.Iy);
Mat mIxy = computeIntegralImg(dMats.Ixy);
mdMats.Ix = meanFilter(mIx, filterRange);
mdMats.Iy = meanFilter(mIy, filterRange);
mdMats.Ixy = meanFilter(mIxy, filterRange);
return mdMats;
}
//-----------------------------------------------------------------------------------------------
Derivatives Harris::computeDerivatives(Mat& greyscaleImg) {
// Helper Mats for better time complexity
Mat sobelHelperV(greyscaleImg.rows-2, greyscaleImg.cols, CV_32F);
for(int r=1; r<greyscaleImg.rows-1; r++) {
for(int c=0; c<greyscaleImg.cols; c++) {
float a1 = greyscaleImg.at<float>(r-1,c);
float a2 = greyscaleImg.at<float>(r,c);
float a3 = greyscaleImg.at<float>(r+1,c);
sobelHelperV.at<float>(r-1,c) = a1 + a2 + a2 + a3;
}
}
Mat sobelHelperH(greyscaleImg.rows, greyscaleImg.cols-2, CV_32F);
for(int r=0; r<greyscaleImg.rows; r++) {
for(int c=1; c<greyscaleImg.cols-1; c++) {
float a1 = greyscaleImg.at<float>(r,c-1);
float a2 = greyscaleImg.at<float>(r,c);
float a3 = greyscaleImg.at<float>(r,c+1);
sobelHelperH.at<float>(r,c-1) = a1 + a2 + a2 + a3;
}
}
// Apply Sobel filter to compute 1st derivatives
Mat Ix(greyscaleImg.rows-2, greyscaleImg.cols-2, CV_32F);
Mat Iy(greyscaleImg.rows-2, greyscaleImg.cols-2, CV_32F);
Mat Ixy(greyscaleImg.rows-2, greyscaleImg.cols-2, CV_32F);
for(int r=0; r<greyscaleImg.rows-2; r++) {
for(int c=0; c<greyscaleImg.cols-2; c++) {
Ix.at<float>(r,c) = sobelHelperH.at<float>(r,c) - sobelHelperH.at<float>(r+2,c);
Iy.at<float>(r,c) = - sobelHelperV.at<float>(r,c) + sobelHelperV.at<float>(r,c+2);
Ixy.at<float>(r,c) = Ix.at<float>(r,c) * Iy.at<float>(r,c);
}
}
Derivatives d;
d.Ix = Ix;
d.Iy = Iy;
d.Ixy = Iy;
return d;
}
//-----------------------------------------------------------------------------------------------
Mat Harris::computeHarrisResponses(float k, Derivatives& d) {
Mat M(d.Iy.rows, d.Ix.cols, CV_32F);
for(int r=0; r<d.Iy.rows; r++) {
for(int c=0; c<d.Iy.cols; c++) {
float a11, a12,
a21, a22;
a11 = d.Ix.at<float>(r,c) * d.Ix.at<float>(r,c);
a22 = d.Iy.at<float>(r,c) * d.Iy.at<float>(r,c);
a21 = d.Ix.at<float>(r,c) * d.Iy.at<float>(r,c);
a12 = d.Ix.at<float>(r,c) * d.Iy.at<float>(r,c);
float det = a11*a22 - a12*a21;
float trace = a11 + a22;
M.at<float>(r,c) = abs(det - k * trace*trace);
}
}
return M;
}
//-----------------------------------------------------------------------------------------------
Mat Harris::computeIntegralImg(Mat& img) {
Mat integralMat(img.rows, img.cols, CV_32F);
integralMat.at<float>(0,0) = img.at<float>(0,0);
for (int i = 1; i < img.cols; i++) {
integralMat.at<float>(0,i) =
integralMat.at<float>(0,i-1)
+ img.at<float>(0,i);
}
for (int j = 1; j < img.rows; j++) {
integralMat.at<float>(j,0) =
integralMat.at<float>(j-1,0)
+ img.at<float>(j,0);
}
for (int i = 1; i < img.cols; i++) {
for (int j = 1; j < img.rows; j++) {
integralMat.at<float>(j,i) =
img.at<float>(j,i)
+ integralMat.at<float>(j-1,i)
+ integralMat.at<float>(j,i-1)
- integralMat.at<float>(j-1,i-1);
}
}
return integralMat;
}
//-----------------------------------------------------------------------------------------------
Mat Harris::meanFilter(Mat& intImg, int range) {
Mat medianFilteredMat(intImg.rows-range*2, intImg.cols-range*2, CV_32F);
for (int r = range; r < intImg.rows-range; r++) {
for (int c = range; c < intImg.cols-range; c++) {
medianFilteredMat.at<float>(r-range, c-range) =
intImg.at<float>(r+range, c+range)
+ intImg.at<float>(r-range, c-range)
- intImg.at<float>(r+range, c-range)
- intImg.at<float>(r-range, c+range);
}
}
return medianFilteredMat;
}
Mat Harris::gaussFilter(Mat& img, int range) {
// Helper Mats for better time complexity
// Mat gaussHelperV(img.rows-range*2, img.cols-range*2, CV_32F);
float* gaussHelperV = new float[(img.rows-range*2)*(img.cols-range*2)];
// float** gaussHelperV = new float*[img.rows-range*2];
// for(int i = 0; i < img.rows-range*2; i++)
// gaussHelperV[i] = new float[img.cols-range*2];
float* gauss_data = new float[(img.rows-range*2)*(img.cols-range*2)];
// float** gauss_data = new float*[img.rows-range*2];
// for(int i = 0; i < img.rows-range*2; i++)
// gauss_data[i] = new float[img.cols-range*2];
int img_row = img.rows;
int img_col = img.cols;
// float** img_data = new float*[img.rows];
// for(int i = 0; i < img.rows; i++)
// {
// img_data[i] = new float[img.cols];
// for(int j = 0; j < img.cols; j++)
// {
// img_data[i][j] = img.at<float>(i, j);
// }
// }
float* img_data = new float[img.rows*img.cols];
for(int i = 0; i < img.rows; i++)
{
for(int j = 0; j < img.cols; j++)
{
img_data[i*img_col+j] = img.at<float>(i, j);
}
}
#pragma acc data copyin(img_data[0:img.rows*img.cols], img_row, img_col,\
range, gaussHelperV[0:(img.rows-range*2)*(img.cols-range*2)]) \
copy(gauss_data[0:(img.rows-range*2)*(img.cols-range*2)])
{
#pragma acc parallel loop
for(int r=range; r<img_row-range; r++)
{
#pragma acc loop
for(int c=range; c<img_col-range; c++)
{
float res = 0;
// #pragma acc loop
for(int x = -range; x<=range; x++)
{
float m = 1/sqrt(2*M_PI)*exp(-0.5*x*x);
// res += m * img.at<float>(r-range,c-range);
// #pragma acc atomic
res += m * img_data[(r-range)*img_col + c-range];
}
// gaussHelperV.at<float>(r-range,c-range) = res;
gaussHelperV[(r-range)*(img_col-range*2) + c-range] = res;
}
}
// Mat gauss(img.rows-range*2, img.cols-range*2, CV_32F);
#pragma acc parallel loop
for(int r=range; r<img_row-range; r++)
{
#pragma acc loop
for(int c=range; c<img_col-range; c++)
{
float res = 0;
// #pragma acc loop
for(int x = -range; x<=range; x++)
{
float m = 1/sqrt(2*M_PI)*exp(-0.5*x*x);
// res += m * gaussHelperV.at<float>(r-range,c-range);
res += m * gaussHelperV[(r-range)*(img_col-range*2) + c-range];
}
gauss_data[(r-range)*(img_col-range*2) + c-range] = res;
}
}
}
Mat gauss(img.rows-range*2, img.cols-range*2, CV_32F);
for(int i = 0; i < img.rows-range*2; i++)
{
for(int j = 0; j < img.cols-range*2; j++)
{
gauss.at<float>(i, j) = gauss_data[i*(img.cols-range*2) + j];
}
}
// delete[] gaussHelperV;
// delete[] gauss_data;
return gauss;
}
|
#include "catch.hpp"
#include <SmurffCpp/Utils/Error.h>
#include <SmurffCpp/Utils/linop.h>
#include <SmurffCpp/Utils/Distribution.h>
using namespace smurff;
static NoiseConfig fixed_ncfg(NoiseTypes::fixed);
TEST_CASE( "SparseSideInfo/solve_blockcg", "BlockCG solver (1rhs)" )
{
std::vector<uint32_t> rows = { 0, 3, 3, 2, 5, 4, 1, 2, 4 };
std::vector<uint32_t> cols = { 1, 0, 2, 1, 3, 0, 1, 3, 2 };
SparseSideInfo sf(std::make_shared<MatrixConfig>(6, 4, rows, cols, fixed_ncfg, false));
Eigen::MatrixXd B(1, 4), X(1, 4), X_true(1, 4);
B << 0.56, 0.55, 0.3 , -1.78;
X_true << 0.35555556, 0.40709677, -0.16444444, -0.87483871;
int niter = smurff::linop::solve_blockcg(X, sf, 0.5, B, 1e-6);
for (int i = 0; i < X.rows(); i++) {
for (int j = 0; j < X.cols(); j++) {
REQUIRE( X(i,j) == Approx(X_true(i,j)) );
}
}
REQUIRE( niter <= 4);
}
TEST_CASE( "SparseSideInfo/solve_blockcg_1_0", "BlockCG solver (3rhs separately)" )
{
std::vector<uint32_t> rows = { 0, 3, 3, 2, 5, 4, 1, 2, 4 };
std::vector<uint32_t> cols = { 1, 0, 2, 1, 3, 0, 1, 3, 2 };
SparseSideInfo sf(std::make_shared<MatrixConfig>(6, 4, rows, cols, fixed_ncfg, false));
Eigen::MatrixXd B(3, 4), X(3, 4), X_true(3, 4);
B << 0.56, 0.55, 0.3 , -1.78,
0.34, 0.05, -1.48, 1.11,
0.09, 0.51, -0.63, 1.59;
X_true << 0.35555556, 0.40709677, -0.16444444, -0.87483871,
1.69333333, -0.12709677, -1.94666667, 0.49483871,
0.66 , -0.04064516, -0.78 , 0.65225806;
smurff::linop::solve_blockcg(X, sf, 0.5, B, 1e-6, 1, 0);
for (int i = 0; i < X.rows(); i++) {
for (int j = 0; j < X.cols(); j++) {
REQUIRE( X(i,j) == Approx(X_true(i,j)) );
}
}
}
TEST_CASE( "linop/solve_blockcg_dense/fail", "BlockCG solver for dense (3rhs separately) [!hide]" )
{
int rows[9] = { 0, 3, 3, 2, 5, 4, 1, 2, 4 };
int cols[9] = { 1, 0, 2, 1, 3, 0, 1, 3, 2 };
Eigen::MatrixXd B(3, 4), X(3, 4), X_true(3, 4), sf(6, 4);
sf = Eigen::MatrixXd::Zero(6, 4);
for (int i = 0; i < 9; i++) {
sf(rows[i], cols[i]) = 1.0;
}
B << 0.56, 0.55, 0.3 , -1.78,
0.34, 0.05, -1.48, 1.11,
0.09, 0.51, -0.63, 1.59;
// this system is unsolvable
REQUIRE_THROWS(smurff::linop::solve_blockcg(X, sf, 0.5, B, 1e-6, true));
}
TEST_CASE( "linop/solve_blockcg_dense/ok", "BlockCG solver for dense (3rhs separately)" )
{
double reg = 0.5;
Eigen::MatrixXd KK(6, 6);
KK << 1.7488399 , -1.92816395, -1.39618642, -0.2769755 , -0.52815529, 0.24624319,
-1.92816395, 3.34435465, 2.07258617, 0.4417173 , 0.84673143, -0.35075244,
-1.39618642, 2.07258617, 2.1623261 , 0.25923918, 0.64428255, -0.2329581,
-0.2769755 , 0.4417173 , 0.25923918, 0.6147927 , 0.15112057, -0.00692033,
-0.52815529, 0.84673143, 0.64428255, 0.15112057, 0.80141217, -0.19682322,
0.24624319, -0.35075244, -0.2329581 , -0.00692033, -0.19682322, 0.56240547;
Eigen::MatrixXd K = KK.llt().matrixU();
REQUIRE(((K.transpose() * K) - KK).norm() < 1e-3);
Eigen::MatrixXd X_true(3, 6);
X_true << 0.35555556, 0.40709677, -0.16444444, -0.87483871, -0.16444444, -0.87483871,
1.69333333, -0.12709677, -1.94666667, 0.49483871, -1.94666667, 0.49483871,
0.66 , -0.04064516, -0.78 , 0.65225806, -0.78 , 0.65225806;
Eigen::MatrixXd B = ((K.transpose() * K + Eigen::MatrixXd::Identity(6,6) * reg) * X_true.transpose()).transpose();
Eigen::MatrixXd X(3, 6);
//-- Solves the system (K' * K + reg * I) * X = B for X for m right-hand sides
smurff::linop::solve_blockcg(X, K, 0.5, B, 1e-6, true);
for (int i = 0; i < X.rows(); i++) {
for (int j = 0; j < X.cols(); j++) {
REQUIRE( X(i,j) == Approx(X_true(i,j)) );
}
}
}
TEST_CASE( "Eigen::MatrixFree::1", "Test smurff::linop::AtA_mulB - 1" )
{
std::vector<uint32_t> rows = {0, 3, 3, 2, 5, 4, 1, 2, 4};
std::vector<uint32_t> cols = {1, 0, 2, 1, 3, 0, 1, 3, 2};
Eigen::SparseMatrix<double> S = matrix_utils::sparse_to_eigen(MatrixConfig(6, 4, rows, cols, fixed_ncfg, false));
smurff::linop::AtA A(S, 0.5);
Eigen::MatrixXd B(3, 4), X(3, 4), X_true(3, 4);
B << 0.56, 0.55, 0.3, -1.78,
0.34, 0.05, -1.48, 1.11,
0.09, 0.51, -0.63, 1.59;
X_true << 0.35555556, 0.40709677, -0.16444444, -0.87483871,
1.69333333, -0.12709677, -1.94666667, 0.49483871,
0.66, -0.04064516, -0.78, 0.65225806;
Eigen::ConjugateGradient<smurff::linop::AtA, Eigen::Lower | Eigen::Upper, Eigen::IdentityPreconditioner> cg;
cg.compute(A);
X = cg.solve(B.transpose()).transpose();
for (int i = 0; i < X.rows(); i++)
{
for (int j = 0; j < X.cols(); j++)
{
REQUIRE(X(i, j) == Approx(X_true(i, j)));
}
}
}
|
#include <iostream>
#include <boost/asio.hpp>
#include <boost/signals2.hpp>
#include "tyfirc-msgpack.h"
#include "tyfirc-scmessage.h"
#include "tyfirc-chatrw.h"
#include "tyfirc-irclientapp.h"
int main() {
using namespace tyfirc;
client::IrcClientApp app{};
std::string prompt;
std::cout << "Write ip of chat mr client." << std::endl;
std::getline(std::cin, prompt);
std::cout << "Connect:" << app.Connect(
boost::asio::ip::address::from_string(prompt).to_v4(), 8001)
<< std::endl;
std::string username;
std::string password;
std::cout << "Username:" << std::endl;
std::getline(std::cin, username);
std::cout << "Password:" << std::endl;
std::getline(std::cin, password);
std::cout << "Login:" << app.Login(username, password) << std::endl;
app.BindHandlerOnMessage([](const Message& msg)
{ std::cout << msg.username << ": " << msg.text << std::endl; });
std::thread thr(&client::IrcClientApp::StartRead, &app);
while (true) {
std::getline(std::cin, prompt);
std::cin.clear();
app.WriteMessage(prompt);
}
}
|
/*
* ClusterController.cpp
*
* Copyright (C) 2009 - 2010 by VISUS (Universitaet Stuttgart).
* Alle Rechte vorbehalten.
*/
#include "stdafx.h"
#include "mmcore/cluster/ClusterController.h"
#include <climits>
#include "mmcore/cluster/CallRegisterAtController.h"
#include "mmcore/cluster/ClusterControllerClient.h"
#include "mmcore/CoreInstance.h"
#include "mmcore/param/BoolParam.h"
#include "mmcore/param/ButtonParam.h"
#include "mmcore/param/IntParam.h"
#include "mmcore/param/StringParam.h"
#include "mmcore/utility/Configuration.h"
#include "vislib/assert.h"
#include "vislib/sys/AutoLock.h"
#include "vislib/net/cluster/DiscoveryService.h"
#include "vislib/sys/Log.h"
#include "vislib/net/NetworkInformation.h"
#include "vislib/SmartPtr.h"
#include "vislib/net/Socket.h"
#include "vislib/StringConverter.h"
#include "vislib/sys/SystemInformation.h"
#include "vislib/Trace.h"
using namespace megamol::core;
using vislib::sys::Log;
using vislib::net::cluster::DiscoveryService;
using vislib::net::IPAgnosticAddress;
using vislib::net::IPEndPoint;
using vislib::net::NetworkInformation;
/*
* cluster::ClusterController::DEFAULT_CLUSTERNAME
*/
const char * cluster::ClusterController::DEFAULT_CLUSTERNAME = "MM04RC";
/*
* cluster::ClusterController::ClusterController
*/
cluster::ClusterController::ClusterController() : job::AbstractThreadedJob(),
Module(), vislib::net::cluster::DiscoveryListener(),
cdsNameSlot("cdsName", "Name of the rendering cluster"),
cdsPortSlot("cdsPort", "The ip port to be used by the cluster discovery service."),
cdsRunSlot("cdsRun", "Start/Stop flag for the cluster discovery"),
shutdownClusterSlot("shutdownCluster", "Shuts down the whole cluster"),
discoveryService(),
registerSlot("register", "Slot to register modules at, which wish to use this controller"),
clients(), clientsLock() {
vislib::net::Socket::Startup();
#ifdef _DEBUG
// otherwise i will die!
vislib::Trace::GetInstance().SetLevel(0);
#endif /* _DEBUG */
this->discoveryService.AddListener(this);
this->cdsNameSlot << new param::StringParam(DEFAULT_CLUSTERNAME);
this->MakeSlotAvailable(&this->cdsNameSlot);
this->cdsPortSlot << new param::IntParam(this->defaultPort(), 0, USHRT_MAX);
this->MakeSlotAvailable(&this->cdsPortSlot);
this->cdsRunSlot << new param::BoolParam(true);
this->MakeSlotAvailable(&this->cdsRunSlot);
if (this->cdsRunSlot.Param<param::BoolParam>()->Value()) {
this->cdsRunSlot.ForceSetDirty();
}
this->shutdownClusterSlot << new param::ButtonParam();
this->shutdownClusterSlot.SetUpdateCallback(&ClusterController::onShutdownCluster);
this->MakeSlotAvailable(&this->shutdownClusterSlot);
this->registerSlot.SetCallback(cluster::CallRegisterAtController::ClassName(),
cluster::CallRegisterAtController::FunctionName(cluster::CallRegisterAtController::CALL_REGISTER),
&ClusterController::registerModule);
this->registerSlot.SetCallback(cluster::CallRegisterAtController::ClassName(),
cluster::CallRegisterAtController::FunctionName(cluster::CallRegisterAtController::CALL_UNREGISTER),
&ClusterController::unregisterModule);
this->registerSlot.SetCallback(cluster::CallRegisterAtController::ClassName(),
cluster::CallRegisterAtController::FunctionName(cluster::CallRegisterAtController::CALL_GETSTATUS),
&ClusterController::queryStatus);
this->MakeSlotAvailable(&this->registerSlot);
}
/*
* cluster::ClusterController::~ClusterController
*/
cluster::ClusterController::~ClusterController() {
this->Release();
ASSERT(!this->discoveryService.IsRunning());
ASSERT(this->clients.IsEmpty());
try {
vislib::net::Socket::Cleanup();
} catch(...) {
}
}
/*
* cluster::ClusterController::SendUserMsg
*/
void cluster::ClusterController::SendUserMsg(const UINT32 msgType,
const BYTE *msgBody, const SIZE_T msgSize) {
using vislib::sys::Log;
try {
UINT rv = this->discoveryService.SendUserMessage(
msgType, msgBody, msgSize);
if (rv != 0) {
Log::DefaultLog.WriteMsg(Log::LEVEL_ERROR,
"Failed to send user message %u: failed after %u communication trails\n",
msgType, rv);
}
} catch (vislib::Exception ex) {
Log::DefaultLog.WriteMsg(Log::LEVEL_ERROR,
"Failed to send user message %u: %s\n",
msgType, ex.GetMsgA());
} catch (...) {
Log::DefaultLog.WriteMsg(Log::LEVEL_ERROR,
"Failed to send user message %u: unknown exception\n",
msgType);
}
}
/*
* cluster::ClusterController::SendUserMsg
*/
void cluster::ClusterController::SendUserMsg(
const cluster::ClusterController::PeerHandle& hPeer,
const UINT32 msgType, const BYTE *msgBody, const SIZE_T msgSize) {
using vislib::sys::Log;
try {
UINT rv = this->discoveryService.SendUserMessage(
hPeer, msgType, msgBody, msgSize);
if (rv != 0) {
Log::DefaultLog.WriteMsg(Log::LEVEL_ERROR,
"Failed to send user message %u: failed after %u communication trails\n",
msgType, rv);
}
} catch (vislib::Exception ex) {
Log::DefaultLog.WriteMsg(Log::LEVEL_ERROR,
"Failed to send user message %u: %s\n",
msgType, ex.GetMsgA());
} catch (...) {
Log::DefaultLog.WriteMsg(Log::LEVEL_ERROR,
"Failed to send user message %u: unknown exception\n",
msgType);
}
}
/*
* cluster::ClusterController::create
*/
bool cluster::ClusterController::create(void) {
const utility::Configuration& cfg
= this->GetCoreInstance()->Configuration();
if (cfg.IsConfigValueSet("cdsname")) {
this->cdsNameSlot.Param<param::StringParam>()->SetValue(
cfg.ConfigValue("cdsname").PeekBuffer());
}
if (cfg.IsConfigValueSet("cdsaddress")) { // for legacy configuration
try {
vislib::StringW port = cfg.ConfigValue("cdsaddress");
vislib::StringW::Size pos = port.FindLast(L':');
if (pos == vislib::StringW::INVALID_POS) {
throw vislib::Exception(
"cdsaddress configuration value does not seem to contain a port",
__FILE__, __LINE__);
}
this->cdsPortSlot.Param<param::IntParam>()->SetValue(
vislib::CharTraitsW::ParseInt(port.Substring(pos + 1)));
} catch(...) {
Log::DefaultLog.WriteMsg(Log::LEVEL_WARN,
"Unable to parse configuration value \"cdsaddress\" as port int. "
"Configuration value ignored.");
}
}
if (cfg.IsConfigValueSet("cdsport")) {
try {
this->cdsPortSlot.Param<param::IntParam>()->SetValue(
vislib::CharTraitsW::ParseInt(cfg.ConfigValue("cdsport")));
} catch(...) {
Log::DefaultLog.WriteMsg(Log::LEVEL_WARN,
"Unable to parse configuration value \"cdsport\" as int. "
"Configuration value ignored.");
}
}
if (cfg.IsConfigValueSet("cdsrun")) {
try {
this->cdsRunSlot.Param<param::BoolParam>()->SetValue(
vislib::CharTraitsW::ParseBool(
cfg.ConfigValue("cdsrun")));
} catch(...) {
Log::DefaultLog.WriteMsg(Log::LEVEL_WARN,
"Unable to parse configuration value \"cdsrun\" as boolean. "
"Configuration value ignored.");
}
}
if (this->cdsRunSlot.Param<param::BoolParam>()->Value()) {
this->cdsRunSlot.ForceSetDirty();
}
return true;
}
/*
* cluster::ClusterController::release
*/
void cluster::ClusterController::release(void) {
this->stopDiscoveryService();
this->clientsLock.Lock();
vislib::SingleLinkedList<ClusterControllerClient *>::Iterator iter
= this->clients.GetIterator();
while (iter.HasNext()) {
ClusterControllerClient *c = iter.Next();
if (c == NULL) continue;
c->onClusterUnavailable();
c->ctrlr = NULL; // implicitly disconnect clients
}
this->clients.Clear();
this->clientsLock.Unlock();
}
/*
* cluster::ClusterController::Run
*/
DWORD cluster::ClusterController::Run(void *userData) {
const unsigned int sleepTime = 250;
while (!this->shouldTerminate()) {
// update cluster discovery settings
if (this->cdsNameSlot.IsDirty() || this->cdsPortSlot.IsDirty() || this->cdsRunSlot.IsDirty()) {
// stop current cluster discovery service
this->stopDiscoveryService();
this->clientsLock.Lock();
vislib::SingleLinkedList<ClusterControllerClient *>::Iterator iter
= this->clients.GetIterator();
while (iter.HasNext()) {
ClusterControllerClient *c = iter.Next();
if (c == NULL) continue;
c->onClusterUnavailable();
}
this->clientsLock.Unlock();
// reset dirty flags of settings
this->cdsNameSlot.ResetDirty();
this->cdsPortSlot.ResetDirty();
this->cdsRunSlot.ResetDirty();
bool run = this->cdsRunSlot.Param<param::BoolParam>()->Value();
if (run) {
try {
vislib::StringA name(
this->cdsNameSlot.Param<param::StringParam>()->Value());
unsigned short port = static_cast<unsigned short>(this->cdsPortSlot.Param<param::IntParam>()->Value());
vislib::SmartPtr<DiscoveryService::DiscoveryConfig> cfg;
{ // choose first ethernet adapter in UP state
NetworkInformation::AdapterList adapters;
NetworkInformation::GetAdaptersForType(adapters, NetworkInformation::Adapter::TYPE_ETHERNET);
while (adapters.Count() > 0) {
if (adapters[0].GetStatus() != NetworkInformation::Adapter::OPERSTATUS_UP) {
adapters.RemoveFirst();
} else break;
}
if (adapters.Count() > 0) {
NetworkInformation::UnicastAddressList ual = adapters[0].GetUnicastAddresses();
for (SIZE_T i = 0; ual.Count(); i++) {
if (ual[i].GetAddressFamily() == IPAgnosticAddress::FAMILY_INET) {
cfg = new DiscoveryService::DiscoveryConfig(IPEndPoint(ual[i].GetAddress(), port), port);
break;
}
}
if (cfg.IsNull() && (ual.Count() > 0)) {
cfg = new DiscoveryService::DiscoveryConfig(IPEndPoint(ual[0].GetAddress(), port), port);
}
}
}
if (cfg.IsNull()) {
Log::DefaultLog.WriteMsg(Log::LEVEL_ERROR, "Unable to choose identifing network adapter.\n");
this->cdsRunSlot.Param<param::BoolParam>()->SetValue(false, false);
} else {
this->discoveryService.Start(name, cfg.operator->(), 1, 0, 0,
DiscoveryService::DEFAULT_REQUEST_INTERVAL,
DiscoveryService::DEFAULT_REQUEST_INTERVAL / 2,
2); // using 2 to ensure that slow systems have enough time
// give new theads a chance to start
vislib::sys::Thread::Sleep(125);
if (this->discoveryService.IsRunning()) {
Log::DefaultLog.WriteMsg(Log::LEVEL_INFO,
"Cluster \"%s\" discovery service is running.\n",
name.PeekBuffer());
vislib::sys::AutoLock(this->clientsLock);
vislib::SingleLinkedList<ClusterControllerClient *>::Iterator iter
= this->clients.GetIterator();
while (iter.HasNext()) {
ClusterControllerClient *c = iter.Next();
if (c == NULL) continue;
c->onClusterAvailable();
}
} else {
Log::DefaultLog.WriteMsg(Log::LEVEL_ERROR,
"Cluster \"%s\" discovery service is not running after start.\n",
name.PeekBuffer());
this->cdsRunSlot.Param<param::BoolParam>()->SetValue(false, false);
}
}
} catch(vislib::Exception ex) {
Log::DefaultLog.WriteMsg(Log::LEVEL_ERROR,
"Failed to start cluster discovery service: %s\n",
ex.GetMsgA());
this->cdsRunSlot.Param<param::BoolParam>()->SetValue(false, false);
} catch(...) {
Log::DefaultLog.WriteMsg(Log::LEVEL_ERROR,
"Failed to start cluster discovery service: unknown exception\n");
this->cdsRunSlot.Param<param::BoolParam>()->SetValue(false, false);
}
}
}
vislib::sys::Thread::Sleep(sleepTime);
}
this->stopDiscoveryService();
return 0;
}
/*
* cluster::ClusterController::OnNodeFound
*/
void cluster::ClusterController::OnNodeFound(DiscoveryService& src,
const DiscoveryService::PeerHandle& hPeer) throw() {
Log::DefaultLog.WriteMsg(Log::LEVEL_INFO, "Cluster Node found: %s\n",
src.GetDiscoveryAddress4(hPeer).ToStringA().PeekBuffer());
vislib::sys::AutoLock lock(this->clientsLock);
vislib::SingleLinkedList<ClusterControllerClient *>::Iterator iter
= this->clients.GetIterator();
while (iter.HasNext()) {
ClusterControllerClient *c = iter.Next();
if (c == NULL) continue;
c->onNodeFound(hPeer);
}
}
/*
* cluster::ClusterController::OnNodeLost
*/
void cluster::ClusterController::OnNodeLost(DiscoveryService& src,
const DiscoveryService::PeerHandle& hPeer,
const DiscoveryListener::NodeLostReason reason) throw() {
Log::DefaultLog.WriteMsg(Log::LEVEL_INFO, "Cluster Node lost: %s\n",
src.GetDiscoveryAddress4(hPeer).ToStringA().PeekBuffer());
vislib::sys::AutoLock lock(this->clientsLock);
vislib::SingleLinkedList<ClusterControllerClient *>::Iterator iter
= this->clients.GetIterator();
while (iter.HasNext()) {
ClusterControllerClient *c = iter.Next();
if (c == NULL) continue;
c->onNodeLost(hPeer);
}
}
/*
* cluster::ClusterController::OnUserMessage
*/
void cluster::ClusterController::OnUserMessage(
vislib::net::cluster::DiscoveryService& src,
const vislib::net::cluster::DiscoveryService::PeerHandle& hPeer,
const bool isClusterMember, const UINT32 msgType,
const BYTE *msgBody) throw() {
try {
//Log::DefaultLog.WriteMsg(Log::LEVEL_INFO, "Cluster User Message: from %s\n",
// src.GetDiscoveryAddress4(hPeer).ToStringA().PeekBuffer());
vislib::sys::AutoLock lock(this->clientsLock);
vislib::SingleLinkedList<ClusterControllerClient *>::Iterator iter
= this->clients.GetIterator();
while (iter.HasNext()) {
ClusterControllerClient *c = iter.Next();
if (c == NULL) continue;
c->onUserMsg(hPeer, isClusterMember, msgType, msgBody);
}
} catch(vislib::Exception ex) {
VLTRACE(VISLIB_TRCELVL_ERROR, "Illegal vislib exception in OnUserMessage \"%s\"\n", ex.GetMsgA());
} catch(...) {
VLTRACE(VISLIB_TRCELVL_ERROR, "Illegal exception in OnUserMessage\n");
}
}
/*
* cluster::ClusterController::defaultPort
*/
UINT16 cluster::ClusterController::defaultPort(void) {
return DiscoveryService::DEFAULT_PORT;
}
/*
* cluster::ClusterController::stopDiscoveryService
*/
void cluster::ClusterController::stopDiscoveryService(void) {
if (this->discoveryService.IsRunning()) {
if (this->discoveryService.Stop()) {
Log::DefaultLog.WriteMsg(Log::LEVEL_INFO, "CDS stopped");
} else {
Log::DefaultLog.WriteMsg(Log::LEVEL_WARN, "Failed to stop CDS");
}
}
}
/*
* cluster::ClusterController::registerModule
*/
bool cluster::ClusterController::registerModule(Call& call) {
CallRegisterAtController *c = dynamic_cast<CallRegisterAtController *>(&call);
if ((c == NULL) || (c->Client() == NULL)) return false;
vislib::sys::AutoLock lock(this->clientsLock);
if (this->clients.Find(c->Client()) == NULL) {
this->clients.Add(c->Client());
c->Client()->ctrlr = this;
if (this->discoveryService.IsRunning()) {
// inform client that cluster is now available
c->Client()->onClusterAvailable();
}
}
return true;
}
/*
* cluster::ClusterController::unregisterModule
*/
bool cluster::ClusterController::unregisterModule(Call& call) {
CallRegisterAtController *c = dynamic_cast<CallRegisterAtController *>(&call);
if ((c == NULL) || (c->Client() == NULL) || (c->Client()->ctrlr != this)) return false;
vislib::sys::AutoLock lock(this->clientsLock);
c->Client()->ctrlr = NULL;
this->clients.RemoveAll(c->Client());
return true;
}
/*
* cluster::ClusterController::queryStatus
*/
bool cluster::ClusterController::queryStatus(Call& call) {
CallRegisterAtController *c = dynamic_cast<CallRegisterAtController *>(&call);
if (c == NULL) return false;
c->SetStatus(
this->discoveryService.IsRunning(),
static_cast<unsigned int>(this->discoveryService.CountPeers()),
this->discoveryService.GetName());
return true;
}
/*
* cluster::ClusterController::onShutdownCluster
*/
bool cluster::ClusterController::onShutdownCluster(param::ParamSlot& slot) {
ASSERT(&slot == &this->shutdownClusterSlot);
for (unsigned int I = 0; I < 4; I++) {
this->SendUserMsg(ClusterControllerClient::USRMSG_SHUTDOWN, NULL, 0);
vislib::sys::Thread::Sleep(250);
}
return true;
}
|
#include <cstdlib>
#include <iostream>
typedef int ElemType;
typedef struct LinkNode {
ElemType data;
struct LinkNode *next;
} LinkNode, *LinkList;
void outPut(LinkList L) {
LinkNode *p = L->next;
while (p != NULL) {
std::cout << p->data << " ";
p = p->next;
}
std::cout << std::endl;
}
void rearInsert(LinkList &L, ElemType x) {
LinkNode *s = new LinkNode;
s->data = x;
L->next = s;
L = s;
}
void rearInsertCreate(LinkList &L, ElemType arr[], int length) {
L = new LinkNode;
LinkNode *p = L;
for (int i = 0; i < length; i++) {
rearInsert(p, arr[i]);
}
p->next = NULL;
}
// 题目要求根据大写、小写和数字分类,这样我还得重新定义char类型的链表,太麻烦了
// 所以我按照大写、小写、数字的ASCII码范围来分类,这样都能保证是int型
// 数字:48 ~ 57,放在A里
// 大写:65 ~ 90,放在B里
// 小写:97 ~ 122,放在C里
void SeprateByCharType(LinkList &A, LinkList &B, LinkList &C) {
LinkNode *pre = A;
LinkNode *p = A->next;
B = new LinkNode;
LinkNode *q = B;
C = new LinkNode;
LinkNode *r = C;
while (p != NULL) {
// 放在A里
if (p->data >= 48 && p->data <= 57) {
p = p->next;
pre = pre->next;
continue; //终止当前这次循环,直接进入下一次循环
}
// 放在B里
if (p->data >= 65 && p->data <= 90) {
rearInsert(q, p->data);
// 在A中删除p所指的位置,然后把p定位到下一个位置
pre->next = p->next;
delete p;
p = pre->next;
continue;
}
// 放在C里
if (p->data >= 97 && p->data <= 122) {
rearInsert(r, p->data);
pre->next = p->next;
delete p;
p = pre->next;
// 这里就不用加continue了,因为下面已经没有语句了,肯定会执行下一次循环
}
}
q->next = NULL;
r->next = NULL;
}
int main() {
ElemType arr[] = {49, 66, 98, 50, 67, 99, 51, 68, 100, 52, 69, 101};
int length = sizeof(arr) / sizeof(int);
LinkList L1 = NULL;
LinkList L2 = NULL;
LinkList L3 = NULL;
rearInsertCreate(L1, arr, length);
outPut(L1);
SeprateByCharType(L1, L2, L3);
outPut(L1);
outPut(L2);
outPut(L3);
return 0;
}
// 输出结果:
// 49 66 98 50 67 99 51 68 100 52 69 101
// 49 50 51 52
// 66 67 68 69
// 98 99 100 101
|
// Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/token.h"
#include <inttypes.h>
#include "base/pickle.h"
#include "base/rand_util.h"
#include "base/strings/stringprintf.h"
namespace base {
// static
Token Token::CreateRandom() {
Token token;
// Use base::RandBytes instead of crypto::RandBytes, because crypto calls the
// base version directly, and to prevent the dependency from base/ to crypto/.
base::RandBytes(&token, sizeof(token));
return token;
}
std::string Token::ToString() const {
return base::StringPrintf("%016" PRIX64 "%016" PRIX64, high_, low_);
}
void WriteTokenToPickle(Pickle* pickle, const Token& token) {
pickle->WriteUInt64(token.high());
pickle->WriteUInt64(token.low());
}
Optional<Token> ReadTokenFromPickle(PickleIterator* pickle_iterator) {
uint64_t high;
if (!pickle_iterator->ReadUInt64(&high))
return nullopt;
uint64_t low;
if (!pickle_iterator->ReadUInt64(&low))
return nullopt;
return Token(high, low);
}
} // namespace base
|
// Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
// Begin includes
#include "extern/beatsaber-hook/shared/utils/typedefs.h"
// Completed includes
// Begin forward declares
// Forward declaring namespace: Org::BouncyCastle::Asn1
namespace Org::BouncyCastle::Asn1 {
// Forward declaring type: DerObjectIdentifier
class DerObjectIdentifier;
}
// Completed forward declares
// Type namespace: Org.BouncyCastle.Asn1.Eac
namespace Org::BouncyCastle::Asn1::Eac {
// Size: 0x10
#pragma pack(push, 1)
// Autogenerated type: Org.BouncyCastle.Asn1.Eac.EacObjectIdentifiers
class EacObjectIdentifiers : public ::Il2CppObject {
public:
// Creating value type constructor for type: EacObjectIdentifiers
EacObjectIdentifiers() noexcept {}
// Get static field: static public readonly Org.BouncyCastle.Asn1.DerObjectIdentifier bsi_de
static Org::BouncyCastle::Asn1::DerObjectIdentifier* _get_bsi_de();
// Set static field: static public readonly Org.BouncyCastle.Asn1.DerObjectIdentifier bsi_de
static void _set_bsi_de(Org::BouncyCastle::Asn1::DerObjectIdentifier* value);
// Get static field: static public readonly Org.BouncyCastle.Asn1.DerObjectIdentifier id_PK
static Org::BouncyCastle::Asn1::DerObjectIdentifier* _get_id_PK();
// Set static field: static public readonly Org.BouncyCastle.Asn1.DerObjectIdentifier id_PK
static void _set_id_PK(Org::BouncyCastle::Asn1::DerObjectIdentifier* value);
// Get static field: static public readonly Org.BouncyCastle.Asn1.DerObjectIdentifier id_PK_DH
static Org::BouncyCastle::Asn1::DerObjectIdentifier* _get_id_PK_DH();
// Set static field: static public readonly Org.BouncyCastle.Asn1.DerObjectIdentifier id_PK_DH
static void _set_id_PK_DH(Org::BouncyCastle::Asn1::DerObjectIdentifier* value);
// Get static field: static public readonly Org.BouncyCastle.Asn1.DerObjectIdentifier id_PK_ECDH
static Org::BouncyCastle::Asn1::DerObjectIdentifier* _get_id_PK_ECDH();
// Set static field: static public readonly Org.BouncyCastle.Asn1.DerObjectIdentifier id_PK_ECDH
static void _set_id_PK_ECDH(Org::BouncyCastle::Asn1::DerObjectIdentifier* value);
// Get static field: static public readonly Org.BouncyCastle.Asn1.DerObjectIdentifier id_CA
static Org::BouncyCastle::Asn1::DerObjectIdentifier* _get_id_CA();
// Set static field: static public readonly Org.BouncyCastle.Asn1.DerObjectIdentifier id_CA
static void _set_id_CA(Org::BouncyCastle::Asn1::DerObjectIdentifier* value);
// Get static field: static public readonly Org.BouncyCastle.Asn1.DerObjectIdentifier id_CA_DH
static Org::BouncyCastle::Asn1::DerObjectIdentifier* _get_id_CA_DH();
// Set static field: static public readonly Org.BouncyCastle.Asn1.DerObjectIdentifier id_CA_DH
static void _set_id_CA_DH(Org::BouncyCastle::Asn1::DerObjectIdentifier* value);
// Get static field: static public readonly Org.BouncyCastle.Asn1.DerObjectIdentifier id_CA_DH_3DES_CBC_CBC
static Org::BouncyCastle::Asn1::DerObjectIdentifier* _get_id_CA_DH_3DES_CBC_CBC();
// Set static field: static public readonly Org.BouncyCastle.Asn1.DerObjectIdentifier id_CA_DH_3DES_CBC_CBC
static void _set_id_CA_DH_3DES_CBC_CBC(Org::BouncyCastle::Asn1::DerObjectIdentifier* value);
// Get static field: static public readonly Org.BouncyCastle.Asn1.DerObjectIdentifier id_CA_ECDH
static Org::BouncyCastle::Asn1::DerObjectIdentifier* _get_id_CA_ECDH();
// Set static field: static public readonly Org.BouncyCastle.Asn1.DerObjectIdentifier id_CA_ECDH
static void _set_id_CA_ECDH(Org::BouncyCastle::Asn1::DerObjectIdentifier* value);
// Get static field: static public readonly Org.BouncyCastle.Asn1.DerObjectIdentifier id_CA_ECDH_3DES_CBC_CBC
static Org::BouncyCastle::Asn1::DerObjectIdentifier* _get_id_CA_ECDH_3DES_CBC_CBC();
// Set static field: static public readonly Org.BouncyCastle.Asn1.DerObjectIdentifier id_CA_ECDH_3DES_CBC_CBC
static void _set_id_CA_ECDH_3DES_CBC_CBC(Org::BouncyCastle::Asn1::DerObjectIdentifier* value);
// Get static field: static public readonly Org.BouncyCastle.Asn1.DerObjectIdentifier id_TA
static Org::BouncyCastle::Asn1::DerObjectIdentifier* _get_id_TA();
// Set static field: static public readonly Org.BouncyCastle.Asn1.DerObjectIdentifier id_TA
static void _set_id_TA(Org::BouncyCastle::Asn1::DerObjectIdentifier* value);
// Get static field: static public readonly Org.BouncyCastle.Asn1.DerObjectIdentifier id_TA_RSA
static Org::BouncyCastle::Asn1::DerObjectIdentifier* _get_id_TA_RSA();
// Set static field: static public readonly Org.BouncyCastle.Asn1.DerObjectIdentifier id_TA_RSA
static void _set_id_TA_RSA(Org::BouncyCastle::Asn1::DerObjectIdentifier* value);
// Get static field: static public readonly Org.BouncyCastle.Asn1.DerObjectIdentifier id_TA_RSA_v1_5_SHA_1
static Org::BouncyCastle::Asn1::DerObjectIdentifier* _get_id_TA_RSA_v1_5_SHA_1();
// Set static field: static public readonly Org.BouncyCastle.Asn1.DerObjectIdentifier id_TA_RSA_v1_5_SHA_1
static void _set_id_TA_RSA_v1_5_SHA_1(Org::BouncyCastle::Asn1::DerObjectIdentifier* value);
// Get static field: static public readonly Org.BouncyCastle.Asn1.DerObjectIdentifier id_TA_RSA_v1_5_SHA_256
static Org::BouncyCastle::Asn1::DerObjectIdentifier* _get_id_TA_RSA_v1_5_SHA_256();
// Set static field: static public readonly Org.BouncyCastle.Asn1.DerObjectIdentifier id_TA_RSA_v1_5_SHA_256
static void _set_id_TA_RSA_v1_5_SHA_256(Org::BouncyCastle::Asn1::DerObjectIdentifier* value);
// Get static field: static public readonly Org.BouncyCastle.Asn1.DerObjectIdentifier id_TA_RSA_PSS_SHA_1
static Org::BouncyCastle::Asn1::DerObjectIdentifier* _get_id_TA_RSA_PSS_SHA_1();
// Set static field: static public readonly Org.BouncyCastle.Asn1.DerObjectIdentifier id_TA_RSA_PSS_SHA_1
static void _set_id_TA_RSA_PSS_SHA_1(Org::BouncyCastle::Asn1::DerObjectIdentifier* value);
// Get static field: static public readonly Org.BouncyCastle.Asn1.DerObjectIdentifier id_TA_RSA_PSS_SHA_256
static Org::BouncyCastle::Asn1::DerObjectIdentifier* _get_id_TA_RSA_PSS_SHA_256();
// Set static field: static public readonly Org.BouncyCastle.Asn1.DerObjectIdentifier id_TA_RSA_PSS_SHA_256
static void _set_id_TA_RSA_PSS_SHA_256(Org::BouncyCastle::Asn1::DerObjectIdentifier* value);
// Get static field: static public readonly Org.BouncyCastle.Asn1.DerObjectIdentifier id_TA_ECDSA
static Org::BouncyCastle::Asn1::DerObjectIdentifier* _get_id_TA_ECDSA();
// Set static field: static public readonly Org.BouncyCastle.Asn1.DerObjectIdentifier id_TA_ECDSA
static void _set_id_TA_ECDSA(Org::BouncyCastle::Asn1::DerObjectIdentifier* value);
// Get static field: static public readonly Org.BouncyCastle.Asn1.DerObjectIdentifier id_TA_ECDSA_SHA_1
static Org::BouncyCastle::Asn1::DerObjectIdentifier* _get_id_TA_ECDSA_SHA_1();
// Set static field: static public readonly Org.BouncyCastle.Asn1.DerObjectIdentifier id_TA_ECDSA_SHA_1
static void _set_id_TA_ECDSA_SHA_1(Org::BouncyCastle::Asn1::DerObjectIdentifier* value);
// Get static field: static public readonly Org.BouncyCastle.Asn1.DerObjectIdentifier id_TA_ECDSA_SHA_224
static Org::BouncyCastle::Asn1::DerObjectIdentifier* _get_id_TA_ECDSA_SHA_224();
// Set static field: static public readonly Org.BouncyCastle.Asn1.DerObjectIdentifier id_TA_ECDSA_SHA_224
static void _set_id_TA_ECDSA_SHA_224(Org::BouncyCastle::Asn1::DerObjectIdentifier* value);
// Get static field: static public readonly Org.BouncyCastle.Asn1.DerObjectIdentifier id_TA_ECDSA_SHA_256
static Org::BouncyCastle::Asn1::DerObjectIdentifier* _get_id_TA_ECDSA_SHA_256();
// Set static field: static public readonly Org.BouncyCastle.Asn1.DerObjectIdentifier id_TA_ECDSA_SHA_256
static void _set_id_TA_ECDSA_SHA_256(Org::BouncyCastle::Asn1::DerObjectIdentifier* value);
// Get static field: static public readonly Org.BouncyCastle.Asn1.DerObjectIdentifier id_TA_ECDSA_SHA_384
static Org::BouncyCastle::Asn1::DerObjectIdentifier* _get_id_TA_ECDSA_SHA_384();
// Set static field: static public readonly Org.BouncyCastle.Asn1.DerObjectIdentifier id_TA_ECDSA_SHA_384
static void _set_id_TA_ECDSA_SHA_384(Org::BouncyCastle::Asn1::DerObjectIdentifier* value);
// Get static field: static public readonly Org.BouncyCastle.Asn1.DerObjectIdentifier id_TA_ECDSA_SHA_512
static Org::BouncyCastle::Asn1::DerObjectIdentifier* _get_id_TA_ECDSA_SHA_512();
// Set static field: static public readonly Org.BouncyCastle.Asn1.DerObjectIdentifier id_TA_ECDSA_SHA_512
static void _set_id_TA_ECDSA_SHA_512(Org::BouncyCastle::Asn1::DerObjectIdentifier* value);
// static private System.Void .cctor()
// Offset: 0x16EDFE0
static void _cctor();
}; // Org.BouncyCastle.Asn1.Eac.EacObjectIdentifiers
#pragma pack(pop)
}
#include "extern/beatsaber-hook/shared/utils/il2cpp-type-check.hpp"
DEFINE_IL2CPP_ARG_TYPE(Org::BouncyCastle::Asn1::Eac::EacObjectIdentifiers*, "Org.BouncyCastle.Asn1.Eac", "EacObjectIdentifiers");
|
// This is a part of the Microsoft Foundation Classes C++ library.
// Copyright (C) 1992-1998 Microsoft Corporation
// All rights reserved.
//
// This source code is only intended as a supplement to the
// Microsoft Foundation Classes Reference and related
// electronic documentation provided with the library.
// See these sources for detailed information regarding the
// Microsoft Foundation Classes product.
#include "stdafx.h"
#ifdef AFX_CORE2_SEG
#pragma code_seg(AFX_CORE2_SEG)
#endif
#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
#define new DEBUG_NEW
#ifdef _DEBUG
// character strings to use for dumping CArchiveException
static const LPCSTR rgszCArchiveExceptionCause[] =
{
"none",
"generic",
"readOnly",
"endOfFile",
"writeOnly",
"badIndex",
"badClass",
"badSchema",
};
static const char szUnknown[] = "unknown";
#endif
BOOL CArchiveException::GetErrorMessage(LPTSTR lpszError, UINT nMaxError,
PUINT pnHelpContext)
{
ASSERT(lpszError != NULL && AfxIsValidString(lpszError, nMaxError));
if (pnHelpContext != NULL)
*pnHelpContext = m_cause + AFX_IDP_ARCH_NONE;
// we can use CString here; archive errors aren't caused
// by being out of memory.
CString strMessage;
CString strFileName = m_strFileName;
if (strFileName.IsEmpty())
strFileName.LoadString(AFX_IDS_UNNAMED_FILE);
AfxFormatString1(strMessage,
m_cause + AFX_IDP_ARCH_NONE, strFileName);
lstrcpyn(lpszError, strMessage, nMaxError);
return TRUE;
}
/////////////////////////////////////////////////////////////////////////////
// CArchiveException
#ifdef _DEBUG
void CArchiveException::Dump(CDumpContext& dc) const
{
CObject::Dump(dc);
dc << " m_cause = ";
if (m_cause >= 0 && m_cause < _countof(rgszCArchiveExceptionCause))
dc << rgszCArchiveExceptionCause[m_cause];
else
dc << szUnknown;
dc << "\n";
}
#endif //_DEBUG
void AFXAPI AfxThrowArchiveException(int cause,
LPCTSTR lpszArchiveName /* = NULL */)
{
#ifdef _DEBUG
LPCSTR lpsz;
if (cause >= 0 && cause < _countof(rgszCArchiveExceptionCause))
lpsz = rgszCArchiveExceptionCause[cause];
else
lpsz = szUnknown;
TRACE1("CArchive exception: %hs.\n", lpsz);
#endif //_DEBUG
THROW(new CArchiveException(cause, lpszArchiveName));
}
#ifdef AFX_INIT_SEG
#pragma code_seg(AFX_INIT_SEG)
#endif
IMPLEMENT_DYNAMIC(CArchiveException, CException)
/////////////////////////////////////////////////////////////////////////////
|
#include "PhysicsServerCommandProcessor.h"
#include "../CommonInterfaces/CommonRenderInterface.h"
#include "plugins/b3PluginCollisionInterface.h"
#include "../Importers/ImportURDFDemo/BulletUrdfImporter.h"
#include "../Importers/ImportURDFDemo/MyMultiBodyCreator.h"
#include "../Importers/ImportURDFDemo/URDF2Bullet.h"
#include "../Importers/ImportURDFDemo/UrdfFindMeshFile.h"
#include "../Extras/InverseDynamics/btMultiBodyTreeCreator.hpp"
#include "BulletCollision/CollisionDispatch/btInternalEdgeUtility.h"
#include "../Importers/ImportMeshUtility/b3ImportMeshUtility.h"
#include "BulletDynamics/MLCPSolvers/btDantzigSolver.h"
#include "BulletDynamics/MLCPSolvers/btSolveProjectedGaussSeidel.h"
#include "BulletDynamics/MLCPSolvers/btMLCPSolver.h"
#include "BulletDynamics/Featherstone/btMultiBodyMLCPConstraintSolver.h"
#include "BulletDynamics/Featherstone/btMultiBodySphericalJointMotor.h"
#include "BulletDynamics/Featherstone/btMultiBodyJointLimitConstraint.h"
//#define USE_DISCRETE_DYNAMICS_WORLD
//#define SKIP_DEFORMABLE_BODY
//#define SKIP_SOFT_BODY_MULTI_BODY_DYNAMICS_WORLD
#include "../Utils/b3BulletDefaultFileIO.h"
#include "BulletCollision/CollisionShapes/btHeightfieldTerrainShape.h"
#include "BulletDynamics/Featherstone/btMultiBodyConstraintSolver.h"
#include "BulletDynamics/Featherstone/btMultiBodyPoint2Point.h"
#include "BulletDynamics/Featherstone/btMultiBodyLinkCollider.h"
#include "BulletDynamics/Featherstone/btMultiBodyJointFeedback.h"
#include "BulletDynamics/Featherstone/btMultiBodyFixedConstraint.h"
#include "BulletDynamics/Featherstone/btMultiBodyGearConstraint.h"
#include "../Importers/ImportURDFDemo/UrdfParser.h"
#include "../Utils/b3ResourcePath.h"
#include "Bullet3Common/b3FileUtils.h"
#include "../OpenGLWindow/GLInstanceGraphicsShape.h"
#include "BulletDynamics/Featherstone/btMultiBodySliderConstraint.h"
#include "BulletDynamics/Featherstone/btMultiBodyPoint2Point.h"
#include "BulletCollision/NarrowPhaseCollision/btPersistentManifold.h"
#include "Bullet3Common/b3HashMap.h"
#include "../Utils/ChromeTraceUtil.h"
#include "SharedMemoryPublic.h"
#include "stb_image/stb_image.h"
#include "BulletInverseDynamics/MultiBodyTree.hpp"
#include "IKTrajectoryHelper.h"
#include "btBulletDynamicsCommon.h"
#include "../Utils/RobotLoggingUtil.h"
#include "LinearMath/btTransform.h"
#include "../Importers/ImportMJCFDemo/BulletMJCFImporter.h"
#include "../Importers/ImportObjDemo/LoadMeshFromObj.h"
#include "../Importers/ImportSTLDemo/LoadMeshFromSTL.h"
#include "../Extras/Serialize/BulletWorldImporter/btMultiBodyWorldImporter.h"
#include "BulletDynamics/Featherstone/btMultiBodyJointMotor.h"
#include "LinearMath/btSerializer.h"
#include "Bullet3Common/b3Logging.h"
#include "../CommonInterfaces/CommonGUIHelperInterface.h"
#include "SharedMemoryCommands.h"
#include "LinearMath/btRandom.h"
#include "Bullet3Common/b3ResizablePool.h"
#include "../Utils/b3Clock.h"
#include "b3PluginManager.h"
#include "../Extras/Serialize/BulletFileLoader/btBulletFile.h"
#include "BulletCollision/NarrowPhaseCollision/btRaycastCallback.h"
#include "LinearMath/TaskScheduler/btThreadSupportInterface.h"
#include "Wavefront/tiny_obj_loader.h"
#ifndef SKIP_COLLISION_FILTER_PLUGIN
#include "plugins/collisionFilterPlugin/collisionFilterPlugin.h"
#endif
#ifdef ENABLE_STATIC_GRPC_PLUGIN
#include "plugins/grpcPlugin/grpcPlugin.h"
#endif //ENABLE_STATIC_GRPC_PLUGIN
#ifndef SKIP_STATIC_PD_CONTROL_PLUGIN
#include "plugins/pdControlPlugin/pdControlPlugin.h"
#endif //SKIP_STATIC_PD_CONTROL_PLUGIN
#ifdef STATIC_LINK_SPD_PLUGIN
#include "plugins/stablePDPlugin/BulletConversion.h"
#include "plugins/stablePDPlugin/RBDModel.h"
#include "plugins/stablePDPlugin/RBDUtil.h"
#endif
#ifdef STATIC_LINK_VR_PLUGIN
#include "plugins/vrSyncPlugin/vrSyncPlugin.h"
#endif
#ifdef STATIC_EGLRENDERER_PLUGIN
#include "plugins/eglPlugin/eglRendererPlugin.h"
#endif //STATIC_EGLRENDERER_PLUGIN
#ifndef SKIP_STATIC_TINYRENDERER_PLUGIN
#include "plugins/tinyRendererPlugin/tinyRendererPlugin.h"
#endif
#ifdef B3_ENABLE_FILEIO_PLUGIN
#include "plugins/fileIOPlugin/fileIOPlugin.h"
#endif //B3_DISABLE_FILEIO_PLUGIN
#ifdef B3_ENABLE_TINY_AUDIO
#include "../TinyAudio/b3SoundEngine.h"
#endif
#ifdef SKIP_SOFT_BODY_MULTI_BODY_DYNAMICS_WORLD
#define SKIP_DEFORMABLE_BODY 1
#endif
#ifndef SKIP_SOFT_BODY_MULTI_BODY_DYNAMICS_WORLD
#include "BulletSoftBody/btSoftBodyRigidBodyCollisionConfiguration.h"
#include "BulletSoftBody/btSoftBodySolvers.h"
#include "BulletSoftBody/btSoftBodyHelpers.h"
#include "BulletSoftBody/btSoftMultiBodyDynamicsWorld.h"
#include "BulletSoftBody/btDeformableMultiBodyDynamicsWorld.h"
#include "BulletSoftBody/btDeformableBodySolver.h"
#include "BulletSoftBody/btDeformableMultiBodyConstraintSolver.h"
#include "../SoftDemo/BunnyMesh.h"
#endif //SKIP_SOFT_BODY_MULTI_BODY_DYNAMICS_WORLD
#ifndef SKIP_DEFORMABLE_BODY
#include "BulletSoftBody/btDeformableMultiBodyDynamicsWorld.h"
#include "BulletSoftBody/btDeformableBodySolver.h"
#include "BulletSoftBody/btDeformableMultiBodyConstraintSolver.h"
#endif //SKIP_DEFORMABLE_BODY
#include "BulletDynamics/Featherstone/btMultiBodyDynamicsWorld.h"
int gInternalSimFlags = 0;
bool gResetSimulation = 0;
int gVRTrackingObjectUniqueId = -1;
int gVRTrackingObjectFlag = VR_CAMERA_TRACK_OBJECT_ORIENTATION;
btTransform gVRTrackingObjectTr = btTransform::getIdentity();
btVector3 gVRTeleportPos1(0, 0, 0);
btQuaternion gVRTeleportOrn(0, 0, 0, 1);
btScalar simTimeScalingFactor = 1;
btScalar gRhsClamp = 1.f;
#include "../CommonInterfaces/CommonFileIOInterface.h"
class b3ThreadPool
{
public:
b3ThreadPool(const char* name = "b3ThreadPool")
{
btThreadSupportInterface::ConstructionInfo info(name, threadFunction);
m_threadSupportInterface = btThreadSupportInterface::create(info);
}
~b3ThreadPool()
{
delete m_threadSupportInterface;
}
const int numWorkers() const { return m_threadSupportInterface->getNumWorkerThreads(); }
void runTask(int threadIdx, btThreadSupportInterface::ThreadFunc func, void* arg)
{
FunctionContext& ctx = m_functionContexts[threadIdx];
ctx.func = func;
ctx.arg = arg;
m_threadSupportInterface->runTask(threadIdx, (void*)&ctx);
}
void waitForAllTasks()
{
BT_PROFILE("b3ThreadPool_waitForAllTasks");
m_threadSupportInterface->waitForAllTasks();
}
private:
struct FunctionContext
{
btThreadSupportInterface::ThreadFunc func;
void* arg;
};
static void threadFunction(void* userPtr)
{
BT_PROFILE("b3ThreadPool_threadFunction");
FunctionContext* ctx = (FunctionContext*)userPtr;
ctx->func(ctx->arg);
}
btThreadSupportInterface* m_threadSupportInterface;
FunctionContext m_functionContexts[BT_MAX_THREAD_COUNT];
};
struct SharedMemoryDebugDrawer : public btIDebugDraw
{
int m_debugMode;
btAlignedObjectArray<SharedMemLines> m_lines2;
SharedMemoryDebugDrawer()
: m_debugMode(0)
{
}
virtual void drawContactPoint(const btVector3& PointOnB, const btVector3& normalOnB, btScalar distance, int lifeTime, const btVector3& color)
{
}
virtual void reportErrorWarning(const char* warningString)
{
}
virtual void draw3dText(const btVector3& location, const char* textString)
{
}
virtual void setDebugMode(int debugMode)
{
m_debugMode = debugMode;
}
virtual int getDebugMode() const
{
return m_debugMode;
}
virtual void drawLine(const btVector3& from, const btVector3& to, const btVector3& color)
{
SharedMemLines line;
line.m_from = from;
line.m_to = to;
line.m_color = color;
m_lines2.push_back(line);
}
};
struct InternalVisualShapeData
{
int m_tinyRendererVisualShapeIndex;
int m_OpenGLGraphicsIndex;
b3AlignedObjectArray<UrdfVisual> m_visualShapes;
b3AlignedObjectArray<std::string> m_pathPrefixes;
void clear()
{
m_tinyRendererVisualShapeIndex = -1;
m_OpenGLGraphicsIndex = -1;
m_visualShapes.clear();
m_pathPrefixes.clear();
}
};
struct InternalCollisionShapeData
{
btCollisionShape* m_collisionShape;
b3AlignedObjectArray<UrdfCollision> m_urdfCollisionObjects;
int m_used;
InternalCollisionShapeData()
: m_collisionShape(0),
m_used(0)
{
}
void clear()
{
m_collisionShape = 0;
m_used = 0;
}
};
#include "SharedMemoryUserData.h"
struct InternalBodyData
{
btMultiBody* m_multiBody;
btRigidBody* m_rigidBody;
#ifndef SKIP_SOFT_BODY_MULTI_BODY_DYNAMICS_WORLD
btSoftBody* m_softBody;
#endif
int m_testData;
std::string m_bodyName;
btTransform m_rootLocalInertialFrame;
btAlignedObjectArray<btTransform> m_linkLocalInertialFrames;
btAlignedObjectArray<btGeneric6DofSpring2Constraint*> m_rigidBodyJoints;
btAlignedObjectArray<std::string> m_rigidBodyJointNames;
btAlignedObjectArray<std::string> m_rigidBodyLinkNames;
btAlignedObjectArray<int> m_userDataHandles;
#ifdef B3_ENABLE_TINY_AUDIO
b3HashMap<btHashInt, SDFAudioSource> m_audioSources;
#endif //B3_ENABLE_TINY_AUDIO
InternalBodyData()
{
clear();
}
void clear()
{
m_multiBody = 0;
m_rigidBody = 0;
#ifndef SKIP_SOFT_BODY_MULTI_BODY_DYNAMICS_WORLD
m_softBody = 0;
#endif
m_testData = 0;
m_bodyName = "";
m_rootLocalInertialFrame.setIdentity();
m_linkLocalInertialFrames.clear();
m_rigidBodyJoints.clear();
m_rigidBodyJointNames.clear();
m_rigidBodyLinkNames.clear();
m_userDataHandles.clear();
}
};
struct InteralUserConstraintData
{
btTypedConstraint* m_rbConstraint;
btMultiBodyConstraint* m_mbConstraint;
b3UserConstraint m_userConstraintData;
int m_sbHandle;
int m_sbNodeIndex;
btScalar m_sbNodeMass;
InteralUserConstraintData()
: m_rbConstraint(0),
m_mbConstraint(0),
m_sbHandle(-1),
m_sbNodeIndex(-1),
m_sbNodeMass(-1)
{
}
};
struct InternalTextureData
{
int m_tinyRendererTextureId;
int m_openglTextureId;
void clear()
{
m_tinyRendererTextureId = -1;
m_openglTextureId = -1;
}
};
typedef b3PoolBodyHandle<InternalTextureData> InternalTextureHandle;
typedef b3PoolBodyHandle<InternalBodyData> InternalBodyHandle;
typedef b3PoolBodyHandle<InternalCollisionShapeData> InternalCollisionShapeHandle;
typedef b3PoolBodyHandle<InternalVisualShapeData> InternalVisualShapeHandle;
class btCommandChunk
{
public:
int m_chunkCode;
int m_length;
void* m_oldPtr;
int m_dna_nr;
int m_number;
};
class bCommandChunkPtr4
{
public:
bCommandChunkPtr4() {}
int code;
int len;
union {
int m_uniqueInt;
};
int dna_nr;
int nr;
};
// ----------------------------------------------------- //
class bCommandChunkPtr8
{
public:
bCommandChunkPtr8() {}
int code, len;
union {
int m_uniqueInts[2];
};
int dna_nr, nr;
};
struct CommandLogger
{
FILE* m_file;
void writeHeader(unsigned char* buffer) const
{
#ifdef BT_USE_DOUBLE_PRECISION
memcpy(buffer, "BT3CMDd", 7);
#else
memcpy(buffer, "BT3CMDf", 7);
#endif //BT_USE_DOUBLE_PRECISION
int littleEndian = 1;
littleEndian = ((char*)&littleEndian)[0];
if (sizeof(void*) == 8)
{
buffer[7] = '-';
}
else
{
buffer[7] = '_';
}
if (littleEndian)
{
buffer[8] = 'v';
}
else
{
buffer[8] = 'V';
}
buffer[9] = 0;
buffer[10] = 0;
buffer[11] = 0;
int ver = btGetVersion();
if (ver >= 0 && ver < 999)
{
sprintf((char*)&buffer[9], "%d", ver);
}
}
void logCommand(const SharedMemoryCommand& command)
{
if (m_file)
{
btCommandChunk chunk;
chunk.m_chunkCode = command.m_type;
chunk.m_oldPtr = 0;
chunk.m_dna_nr = 0;
chunk.m_length = sizeof(SharedMemoryCommand);
chunk.m_number = 1;
fwrite((const char*)&chunk, sizeof(btCommandChunk), 1, m_file);
switch (command.m_type)
{
case CMD_LOAD_MJCF:
{
fwrite((const char*)&command.m_updateFlags, sizeof(int), 1, m_file);
fwrite((const char*)&command.m_mjcfArguments, sizeof(MjcfArgs), 1, m_file);
break;
}
case CMD_REQUEST_BODY_INFO:
{
fwrite((const char*)&command.m_updateFlags, sizeof(int), 1, m_file);
fwrite((const char*)&command.m_sdfRequestInfoArgs, sizeof(SdfRequestInfoArgs), 1, m_file);
break;
}
case CMD_REQUEST_VISUAL_SHAPE_INFO:
{
fwrite((const char*)&command.m_updateFlags, sizeof(int), 1, m_file);
fwrite((const char*)&command.m_requestVisualShapeDataArguments, sizeof(RequestVisualShapeDataArgs), 1, m_file);
break;
}
case CMD_LOAD_URDF:
{
fwrite((const char*)&command.m_updateFlags, sizeof(int), 1, m_file);
fwrite((const char*)&command.m_urdfArguments, sizeof(UrdfArgs), 1, m_file);
break;
}
case CMD_INIT_POSE:
{
fwrite((const char*)&command.m_updateFlags, sizeof(int), 1, m_file);
fwrite((const char*)&command.m_initPoseArgs, sizeof(InitPoseArgs), 1, m_file);
break;
};
case CMD_REQUEST_ACTUAL_STATE:
{
fwrite((const char*)&command.m_updateFlags, sizeof(int), 1, m_file);
fwrite((const char*)&command.m_requestActualStateInformationCommandArgument,
sizeof(RequestActualStateArgs), 1, m_file);
break;
};
case CMD_SEND_DESIRED_STATE:
{
fwrite((const char*)&command.m_updateFlags, sizeof(int), 1, m_file);
fwrite((const char*)&command.m_sendDesiredStateCommandArgument, sizeof(SendDesiredStateArgs), 1, m_file);
break;
}
case CMD_SEND_PHYSICS_SIMULATION_PARAMETERS:
{
fwrite((const char*)&command.m_updateFlags, sizeof(int), 1, m_file);
fwrite((const char*)&command.m_physSimParamArgs, sizeof(b3PhysicsSimulationParameters), 1, m_file);
break;
}
case CMD_REQUEST_CONTACT_POINT_INFORMATION:
{
fwrite((const char*)&command.m_updateFlags, sizeof(int), 1, m_file);
fwrite((const char*)&command.m_requestContactPointArguments, sizeof(RequestContactDataArgs), 1, m_file);
break;
}
case CMD_STEP_FORWARD_SIMULATION:
case CMD_RESET_SIMULATION:
case CMD_REQUEST_INTERNAL_DATA:
{
break;
};
default:
{
fwrite((const char*)&command, sizeof(SharedMemoryCommand), 1, m_file);
}
};
}
}
CommandLogger(const char* fileName)
{
m_file = fopen(fileName, "wb");
if (m_file)
{
unsigned char buf[15];
buf[12] = 12;
buf[13] = 13;
buf[14] = 14;
writeHeader(buf);
fwrite(buf, 12, 1, m_file);
}
}
virtual ~CommandLogger()
{
if (m_file)
{
fclose(m_file);
}
}
};
struct CommandLogPlayback
{
unsigned char m_header[12];
FILE* m_file;
bool m_bitsVary;
bool m_fileIs64bit;
CommandLogPlayback(const char* fileName)
{
m_file = fopen(fileName, "rb");
if (m_file)
{
size_t bytesRead;
bytesRead = fread(m_header, 12, 1, m_file);
}
unsigned char c = m_header[7];
m_fileIs64bit = (c == '-');
const bool VOID_IS_8 = ((sizeof(void*) == 8));
m_bitsVary = (VOID_IS_8 != m_fileIs64bit);
}
virtual ~CommandLogPlayback()
{
if (m_file)
{
fclose(m_file);
m_file = 0;
}
}
bool processNextCommand(SharedMemoryCommand* cmd)
{
//for a little while, keep this flag to be able to read 'old' log files
//#define BACKWARD_COMPAT
#if BACKWARD_COMPAT
SharedMemoryCommand unused;
#endif //BACKWARD_COMPAT
bool result = false;
size_t s = 0;
if (m_file)
{
int commandType = -1;
if (m_fileIs64bit)
{
bCommandChunkPtr8 chunk8;
s = fread((void*)&chunk8, sizeof(bCommandChunkPtr8), 1, m_file);
commandType = chunk8.code;
}
else
{
bCommandChunkPtr4 chunk4;
s = fread((void*)&chunk4, sizeof(bCommandChunkPtr4), 1, m_file);
commandType = chunk4.code;
}
if (s == 1)
{
memset(cmd, 0, sizeof(SharedMemoryCommand));
cmd->m_type = commandType;
#ifdef BACKWARD_COMPAT
s = fread(&unused, sizeof(SharedMemoryCommand), 1, m_file);
cmd->m_updateFlags = unused.m_updateFlags;
#endif
switch (commandType)
{
case CMD_LOAD_MJCF:
{
#ifdef BACKWARD_COMPAT
cmd->m_mjcfArguments = unused.m_mjcfArguments;
#else
s = fread(&cmd->m_updateFlags, sizeof(int), 1, m_file);
s = fread(&cmd->m_mjcfArguments, sizeof(MjcfArgs), 1, m_file);
#endif
result = true;
break;
}
case CMD_REQUEST_BODY_INFO:
{
#ifdef BACKWARD_COMPAT
cmd->m_sdfRequestInfoArgs = unused.m_sdfRequestInfoArgs;
#else
s = fread(&cmd->m_updateFlags, sizeof(int), 1, m_file);
s = fread(&cmd->m_sdfRequestInfoArgs, sizeof(SdfRequestInfoArgs), 1, m_file);
#endif
result = true;
break;
}
case CMD_REQUEST_VISUAL_SHAPE_INFO:
{
#ifdef BACKWARD_COMPAT
cmd->m_requestVisualShapeDataArguments = unused.m_requestVisualShapeDataArguments;
#else
s = fread(&cmd->m_updateFlags, sizeof(int), 1, m_file);
s = fread(&cmd->m_requestVisualShapeDataArguments, sizeof(RequestVisualShapeDataArgs), 1, m_file);
#endif
result = true;
break;
}
case CMD_LOAD_URDF:
{
#ifdef BACKWARD_COMPAT
cmd->m_urdfArguments = unused.m_urdfArguments;
#else
s = fread(&cmd->m_updateFlags, sizeof(int), 1, m_file);
s = fread(&cmd->m_urdfArguments, sizeof(UrdfArgs), 1, m_file);
#endif
result = true;
break;
}
case CMD_INIT_POSE:
{
#ifdef BACKWARD_COMPAT
cmd->m_initPoseArgs = unused.m_initPoseArgs;
#else
s = fread(&cmd->m_updateFlags, sizeof(int), 1, m_file);
s = fread(&cmd->m_initPoseArgs, sizeof(InitPoseArgs), 1, m_file);
#endif
result = true;
break;
};
case CMD_REQUEST_ACTUAL_STATE:
{
#ifdef BACKWARD_COMPAT
cmd->m_requestActualStateInformationCommandArgument = unused.m_requestActualStateInformationCommandArgument;
#else
s = fread(&cmd->m_updateFlags, sizeof(int), 1, m_file);
s = fread(&cmd->m_requestActualStateInformationCommandArgument, sizeof(RequestActualStateArgs), 1, m_file);
#endif
result = true;
break;
};
case CMD_SEND_DESIRED_STATE:
{
#ifdef BACKWARD_COMPAT
cmd->m_sendDesiredStateCommandArgument = unused.m_sendDesiredStateCommandArgument;
#else
s = fread(&cmd->m_updateFlags, sizeof(int), 1, m_file);
s = fread(&cmd->m_sendDesiredStateCommandArgument, sizeof(SendDesiredStateArgs), 1, m_file);
#endif
result = true;
break;
}
case CMD_SEND_PHYSICS_SIMULATION_PARAMETERS:
{
#ifdef BACKWARD_COMPAT
cmd->m_physSimParamArgs = unused.m_physSimParamArgs;
#else
s = fread(&cmd->m_updateFlags, sizeof(int), 1, m_file);
s = fread(&cmd->m_physSimParamArgs, sizeof(b3PhysicsSimulationParameters), 1, m_file);
#endif
result = true;
break;
}
case CMD_REQUEST_CONTACT_POINT_INFORMATION:
{
#ifdef BACKWARD_COMPAT
cmd->m_requestContactPointArguments = unused.m_requestContactPointArguments;
#else
s = fread(&cmd->m_updateFlags, sizeof(int), 1, m_file);
s = fread(&cmd->m_requestContactPointArguments, sizeof(RequestContactDataArgs), 1, m_file);
#endif
result = true;
break;
}
case CMD_STEP_FORWARD_SIMULATION:
case CMD_RESET_SIMULATION:
case CMD_REQUEST_INTERNAL_DATA:
{
result = true;
break;
}
default:
{
s = fread(cmd, sizeof(SharedMemoryCommand), 1, m_file);
result = (s == 1);
}
};
}
}
return result;
}
};
struct SaveWorldObjectData
{
b3AlignedObjectArray<int> m_bodyUniqueIds;
std::string m_fileName;
};
struct MyBroadphaseCallback : public btBroadphaseAabbCallback
{
b3AlignedObjectArray<int> m_bodyUniqueIds;
b3AlignedObjectArray<int> m_links;
MyBroadphaseCallback()
{
}
virtual ~MyBroadphaseCallback()
{
}
void clear()
{
m_bodyUniqueIds.clear();
m_links.clear();
}
virtual bool process(const btBroadphaseProxy* proxy)
{
btCollisionObject* colObj = (btCollisionObject*)proxy->m_clientObject;
btMultiBodyLinkCollider* mbl = btMultiBodyLinkCollider::upcast(colObj);
if (mbl)
{
int bodyUniqueId = mbl->m_multiBody->getUserIndex2();
m_bodyUniqueIds.push_back(bodyUniqueId);
m_links.push_back(mbl->m_link);
return true;
}
int bodyUniqueId = colObj->getUserIndex2();
if (bodyUniqueId >= 0)
{
m_bodyUniqueIds.push_back(bodyUniqueId);
//it is not a multibody, so use -1 otherwise
m_links.push_back(-1);
}
return true;
}
};
struct MyOverlapFilterCallback : public btOverlapFilterCallback
{
int m_filterMode;
b3PluginManager* m_pluginManager;
MyOverlapFilterCallback(b3PluginManager* pluginManager)
: m_filterMode(B3_FILTER_GROUPAMASKB_AND_GROUPBMASKA),
m_pluginManager(pluginManager)
{
}
virtual ~MyOverlapFilterCallback()
{
}
// return true when pairs need collision
virtual bool needBroadphaseCollision(btBroadphaseProxy* proxy0, btBroadphaseProxy* proxy1) const
{
b3PluginCollisionInterface* collisionInterface = m_pluginManager->getCollisionInterface();
if (collisionInterface && collisionInterface->getNumRules())
{
int objectUniqueIdB = -1, linkIndexB = -1;
btCollisionObject* colObjB = (btCollisionObject*)proxy1->m_clientObject;
btMultiBodyLinkCollider* mblB = btMultiBodyLinkCollider::upcast(colObjB);
if (mblB)
{
objectUniqueIdB = mblB->m_multiBody->getUserIndex2();
linkIndexB = mblB->m_link;
}
else
{
objectUniqueIdB = colObjB->getUserIndex2();
linkIndexB = -1;
}
int objectUniqueIdA = -1, linkIndexA = -1;
btCollisionObject* colObjA = (btCollisionObject*)proxy0->m_clientObject;
btMultiBodyLinkCollider* mblA = btMultiBodyLinkCollider::upcast(colObjA);
if (mblA)
{
objectUniqueIdA = mblA->m_multiBody->getUserIndex2();
linkIndexA = mblA->m_link;
}
else
{
objectUniqueIdA = colObjA->getUserIndex2();
linkIndexA = -1;
}
int collisionFilterGroupA = proxy0->m_collisionFilterGroup;
int collisionFilterMaskA = proxy0->m_collisionFilterMask;
int collisionFilterGroupB = proxy1->m_collisionFilterGroup;
int collisionFilterMaskB = proxy1->m_collisionFilterMask;
return collisionInterface->needsBroadphaseCollision(objectUniqueIdA, linkIndexA,
collisionFilterGroupA, collisionFilterMaskA,
objectUniqueIdB, linkIndexB, collisionFilterGroupB, collisionFilterMaskB, m_filterMode);
}
else
{
if (m_filterMode == B3_FILTER_GROUPAMASKB_AND_GROUPBMASKA)
{
bool collides = (proxy0->m_collisionFilterGroup & proxy1->m_collisionFilterMask) != 0;
collides = collides && (proxy1->m_collisionFilterGroup & proxy0->m_collisionFilterMask);
return collides;
}
if (m_filterMode == B3_FILTER_GROUPAMASKB_OR_GROUPBMASKA)
{
bool collides = (proxy0->m_collisionFilterGroup & proxy1->m_collisionFilterMask) != 0;
collides = collides || (proxy1->m_collisionFilterGroup & proxy0->m_collisionFilterMask);
return collides;
}
return false;
}
}
};
struct InternalStateLogger
{
int m_loggingUniqueId;
int m_loggingType;
InternalStateLogger()
: m_loggingUniqueId(0),
m_loggingType(0)
{
}
virtual ~InternalStateLogger() {}
virtual void stop() = 0;
virtual void logState(btScalar timeStep) = 0;
};
struct VideoMP4Loggger : public InternalStateLogger
{
struct GUIHelperInterface* m_guiHelper;
std::string m_fileName;
VideoMP4Loggger(int loggerUid, const char* fileName, GUIHelperInterface* guiHelper)
: m_guiHelper(guiHelper)
{
m_fileName = fileName;
m_loggingUniqueId = loggerUid;
m_loggingType = STATE_LOGGING_VIDEO_MP4;
m_guiHelper->dumpFramesToVideo(fileName);
}
virtual void stop()
{
m_guiHelper->dumpFramesToVideo(0);
}
virtual void logState(btScalar timeStep)
{
//dumping video frames happens in another thread
//we could add some overlay of timestamp here, if needed/wanted
}
};
struct MinitaurStateLogger : public InternalStateLogger
{
int m_loggingTimeStamp;
std::string m_fileName;
int m_minitaurBodyUniqueId;
FILE* m_logFileHandle;
std::string m_structTypes;
btMultiBody* m_minitaurMultiBody;
btAlignedObjectArray<int> m_motorIdList;
MinitaurStateLogger(int loggingUniqueId, const std::string& fileName, btMultiBody* minitaurMultiBody, btAlignedObjectArray<int>& motorIdList)
: m_loggingTimeStamp(0),
m_logFileHandle(0),
m_minitaurMultiBody(minitaurMultiBody)
{
m_loggingUniqueId = loggingUniqueId;
m_loggingType = STATE_LOGGING_MINITAUR;
m_motorIdList.resize(motorIdList.size());
for (int m = 0; m < motorIdList.size(); m++)
{
m_motorIdList[m] = motorIdList[m];
}
btAlignedObjectArray<std::string> structNames;
//'t', 'r', 'p', 'y', 'q0', 'q1', 'q2', 'q3', 'q4', 'q5', 'q6', 'q7', 'u0', 'u1', 'u2', 'u3', 'u4', 'u5', 'u6', 'u7', 'xd', 'mo'
structNames.push_back("t");
structNames.push_back("r");
structNames.push_back("p");
structNames.push_back("y");
structNames.push_back("q0");
structNames.push_back("q1");
structNames.push_back("q2");
structNames.push_back("q3");
structNames.push_back("q4");
structNames.push_back("q5");
structNames.push_back("q6");
structNames.push_back("q7");
structNames.push_back("u0");
structNames.push_back("u1");
structNames.push_back("u2");
structNames.push_back("u3");
structNames.push_back("u4");
structNames.push_back("u5");
structNames.push_back("u6");
structNames.push_back("u7");
structNames.push_back("dx");
structNames.push_back("mo");
m_structTypes = "IffffffffffffffffffffB";
const char* fileNameC = fileName.c_str();
m_logFileHandle = createMinitaurLogFile(fileNameC, structNames, m_structTypes);
}
virtual void stop()
{
if (m_logFileHandle)
{
closeMinitaurLogFile(m_logFileHandle);
m_logFileHandle = 0;
}
}
virtual void logState(btScalar timeStep)
{
if (m_logFileHandle)
{
//btVector3 pos = m_minitaurMultiBody->getBasePos();
MinitaurLogRecord logData;
//'t', 'r', 'p', 'y', 'q0', 'q1', 'q2', 'q3', 'q4', 'q5', 'q6', 'q7', 'u0', 'u1', 'u2', 'u3', 'u4', 'u5', 'u6', 'u7', 'xd', 'mo'
btScalar motorDir[8] = {1, 1, 1, 1, 1, 1, 1, 1};
btQuaternion orn = m_minitaurMultiBody->getBaseWorldTransform().getRotation();
btMatrix3x3 mat(orn);
btScalar roll = 0;
btScalar pitch = 0;
btScalar yaw = 0;
mat.getEulerZYX(yaw, pitch, roll);
logData.m_values.push_back(m_loggingTimeStamp);
logData.m_values.push_back((float)roll);
logData.m_values.push_back((float)pitch);
logData.m_values.push_back((float)yaw);
for (int i = 0; i < 8; i++)
{
float jointAngle = (float)motorDir[i] * m_minitaurMultiBody->getJointPos(m_motorIdList[i]);
logData.m_values.push_back(jointAngle);
}
for (int i = 0; i < 8; i++)
{
btMultiBodyJointMotor* motor = (btMultiBodyJointMotor*)m_minitaurMultiBody->getLink(m_motorIdList[i]).m_userPtr;
if (motor && timeStep > btScalar(0))
{
btScalar force = motor->getAppliedImpulse(0) / timeStep;
logData.m_values.push_back((float)force);
}
}
//x is forward component, estimated speed forward
float xd_speed = m_minitaurMultiBody->getBaseVel()[0];
logData.m_values.push_back(xd_speed);
char mode = 6;
logData.m_values.push_back(mode);
//at the moment, appendMinitaurLogData will directly write to disk (potential delay)
//better to fill a huge memory buffer and once in a while write it to disk
appendMinitaurLogData(m_logFileHandle, m_structTypes, logData);
fflush(m_logFileHandle);
m_loggingTimeStamp++;
}
}
};
struct b3VRControllerEvents
{
b3VRControllerEvent m_vrEvents[MAX_VR_CONTROLLERS];
b3VRControllerEvents()
{
init();
}
virtual ~b3VRControllerEvents()
{
}
void init()
{
for (int i = 0; i < MAX_VR_CONTROLLERS; i++)
{
m_vrEvents[i].m_deviceType = 0;
m_vrEvents[i].m_numButtonEvents = 0;
m_vrEvents[i].m_numMoveEvents = 0;
for (int b = 0; b < MAX_VR_BUTTONS; b++)
{
m_vrEvents[i].m_buttons[b] = 0;
}
}
}
void addNewVREvents(const struct b3VRControllerEvent* vrEvents, int numVREvents)
{
//update m_vrEvents
for (int i = 0; i < numVREvents; i++)
{
int controlledId = vrEvents[i].m_controllerId;
if (vrEvents[i].m_numMoveEvents)
{
m_vrEvents[controlledId].m_analogAxis = vrEvents[i].m_analogAxis;
for (int a = 0; a < 10; a++)
{
m_vrEvents[controlledId].m_auxAnalogAxis[a] = vrEvents[i].m_auxAnalogAxis[a];
}
}
else
{
m_vrEvents[controlledId].m_analogAxis = 0;
for (int a = 0; a < 10; a++)
{
m_vrEvents[controlledId].m_auxAnalogAxis[a] = 0;
}
}
if (vrEvents[i].m_numMoveEvents + vrEvents[i].m_numButtonEvents)
{
m_vrEvents[controlledId].m_controllerId = vrEvents[i].m_controllerId;
m_vrEvents[controlledId].m_deviceType = vrEvents[i].m_deviceType;
m_vrEvents[controlledId].m_pos[0] = vrEvents[i].m_pos[0];
m_vrEvents[controlledId].m_pos[1] = vrEvents[i].m_pos[1];
m_vrEvents[controlledId].m_pos[2] = vrEvents[i].m_pos[2];
m_vrEvents[controlledId].m_orn[0] = vrEvents[i].m_orn[0];
m_vrEvents[controlledId].m_orn[1] = vrEvents[i].m_orn[1];
m_vrEvents[controlledId].m_orn[2] = vrEvents[i].m_orn[2];
m_vrEvents[controlledId].m_orn[3] = vrEvents[i].m_orn[3];
}
m_vrEvents[controlledId].m_numButtonEvents += vrEvents[i].m_numButtonEvents;
m_vrEvents[controlledId].m_numMoveEvents += vrEvents[i].m_numMoveEvents;
for (int b = 0; b < MAX_VR_BUTTONS; b++)
{
m_vrEvents[controlledId].m_buttons[b] |= vrEvents[i].m_buttons[b];
if (vrEvents[i].m_buttons[b] & eButtonIsDown)
{
m_vrEvents[controlledId].m_buttons[b] |= eButtonIsDown;
}
else
{
m_vrEvents[controlledId].m_buttons[b] &= ~eButtonIsDown;
}
}
}
};
};
struct VRControllerStateLogger : public InternalStateLogger
{
b3VRControllerEvents m_vrEvents;
int m_loggingTimeStamp;
int m_deviceTypeFilter;
std::string m_fileName;
FILE* m_logFileHandle;
std::string m_structTypes;
VRControllerStateLogger(int loggingUniqueId, int deviceTypeFilter, const std::string& fileName)
: m_loggingTimeStamp(0),
m_deviceTypeFilter(deviceTypeFilter),
m_fileName(fileName),
m_logFileHandle(0)
{
m_loggingUniqueId = loggingUniqueId;
m_loggingType = STATE_LOGGING_VR_CONTROLLERS;
btAlignedObjectArray<std::string> structNames;
structNames.push_back("stepCount");
structNames.push_back("timeStamp");
structNames.push_back("controllerId");
structNames.push_back("numMoveEvents");
structNames.push_back("m_numButtonEvents");
structNames.push_back("posX");
structNames.push_back("posY");
structNames.push_back("posZ");
structNames.push_back("oriX");
structNames.push_back("oriY");
structNames.push_back("oriZ");
structNames.push_back("oriW");
structNames.push_back("analogAxis");
structNames.push_back("buttons0");
structNames.push_back("buttons1");
structNames.push_back("buttons2");
structNames.push_back("buttons3");
structNames.push_back("buttons4");
structNames.push_back("buttons5");
structNames.push_back("buttons6");
structNames.push_back("deviceType");
m_structTypes = "IfIIIffffffffIIIIIIII";
const char* fileNameC = fileName.c_str();
m_logFileHandle = createMinitaurLogFile(fileNameC, structNames, m_structTypes);
}
virtual void stop()
{
if (m_logFileHandle)
{
closeMinitaurLogFile(m_logFileHandle);
m_logFileHandle = 0;
}
}
virtual void logState(btScalar timeStep)
{
if (m_logFileHandle)
{
int stepCount = m_loggingTimeStamp;
float timeStamp = m_loggingTimeStamp * timeStep;
for (int i = 0; i < MAX_VR_CONTROLLERS; i++)
{
b3VRControllerEvent& event = m_vrEvents.m_vrEvents[i];
if (m_deviceTypeFilter & event.m_deviceType)
{
if (event.m_numButtonEvents + event.m_numMoveEvents)
{
MinitaurLogRecord logData;
//serverStatusOut.m_sendVREvents.m_controllerEvents[serverStatusOut.m_sendVREvents.m_numVRControllerEvents++] = event;
//log the event
logData.m_values.push_back(stepCount);
logData.m_values.push_back(timeStamp);
logData.m_values.push_back(event.m_controllerId);
logData.m_values.push_back(event.m_numMoveEvents);
logData.m_values.push_back(event.m_numButtonEvents);
logData.m_values.push_back(event.m_pos[0]);
logData.m_values.push_back(event.m_pos[1]);
logData.m_values.push_back(event.m_pos[2]);
logData.m_values.push_back(event.m_orn[0]);
logData.m_values.push_back(event.m_orn[1]);
logData.m_values.push_back(event.m_orn[2]);
logData.m_values.push_back(event.m_orn[3]);
logData.m_values.push_back(event.m_analogAxis);
int packedButtons[7] = {0, 0, 0, 0, 0, 0, 0};
int packedButtonIndex = 0;
int packedButtonShift = 0;
//encode the 64 buttons into 7 int (3 bits each), each int stores 10 buttons
for (int b = 0; b < MAX_VR_BUTTONS; b++)
{
int buttonMask = event.m_buttons[b];
buttonMask = buttonMask << (packedButtonShift * 3);
packedButtons[packedButtonIndex] |= buttonMask;
packedButtonShift++;
if (packedButtonShift >= 10)
{
packedButtonShift = 0;
packedButtonIndex++;
if (packedButtonIndex >= 7)
{
btAssert(0);
break;
}
}
}
for (int b = 0; b < 7; b++)
{
logData.m_values.push_back(packedButtons[b]);
}
logData.m_values.push_back(event.m_deviceType);
appendMinitaurLogData(m_logFileHandle, m_structTypes, logData);
event.m_numButtonEvents = 0;
event.m_numMoveEvents = 0;
for (int b = 0; b < MAX_VR_BUTTONS; b++)
{
event.m_buttons[b] = 0;
}
}
}
}
fflush(m_logFileHandle);
m_loggingTimeStamp++;
}
}
};
struct GenericRobotStateLogger : public InternalStateLogger
{
float m_loggingTimeStamp;
std::string m_fileName;
FILE* m_logFileHandle;
std::string m_structTypes;
const btMultiBodyDynamicsWorld* m_dynamicsWorld;
btAlignedObjectArray<int> m_bodyIdList;
bool m_filterObjectUniqueId;
int m_maxLogDof;
int m_logFlags;
GenericRobotStateLogger(int loggingUniqueId, const std::string& fileName, const btMultiBodyDynamicsWorld* dynamicsWorld, int maxLogDof, int logFlags)
: m_loggingTimeStamp(0),
m_logFileHandle(0),
m_dynamicsWorld(dynamicsWorld),
m_filterObjectUniqueId(false),
m_maxLogDof(maxLogDof),
m_logFlags(logFlags)
{
m_loggingUniqueId = loggingUniqueId;
m_loggingType = STATE_LOGGING_GENERIC_ROBOT;
btAlignedObjectArray<std::string> structNames;
structNames.push_back("stepCount");
structNames.push_back("timeStamp");
structNames.push_back("objectId");
structNames.push_back("posX");
structNames.push_back("posY");
structNames.push_back("posZ");
structNames.push_back("oriX");
structNames.push_back("oriY");
structNames.push_back("oriZ");
structNames.push_back("oriW");
structNames.push_back("velX");
structNames.push_back("velY");
structNames.push_back("velZ");
structNames.push_back("omegaX");
structNames.push_back("omegaY");
structNames.push_back("omegaZ");
structNames.push_back("qNum");
m_structTypes = "IfifffffffffffffI";
for (int i = 0; i < m_maxLogDof; i++)
{
m_structTypes.append("f");
char jointName[256];
sprintf(jointName, "q%d", i);
structNames.push_back(jointName);
}
for (int i = 0; i < m_maxLogDof; i++)
{
m_structTypes.append("f");
char jointName[256];
sprintf(jointName, "u%d", i);
structNames.push_back(jointName);
}
if (m_logFlags & STATE_LOG_JOINT_TORQUES)
{
for (int i = 0; i < m_maxLogDof; i++)
{
m_structTypes.append("f");
char jointName[256];
sprintf(jointName, "t%d", i);
structNames.push_back(jointName);
}
}
const char* fileNameC = fileName.c_str();
m_logFileHandle = createMinitaurLogFile(fileNameC, structNames, m_structTypes);
}
virtual void stop()
{
if (m_logFileHandle)
{
closeMinitaurLogFile(m_logFileHandle);
m_logFileHandle = 0;
}
}
virtual void logState(btScalar timeStep)
{
if (m_logFileHandle)
{
for (int i = 0; i < m_dynamicsWorld->getNumMultibodies(); i++)
{
const btMultiBody* mb = m_dynamicsWorld->getMultiBody(i);
int objectUniqueId = mb->getUserIndex2();
if (m_filterObjectUniqueId && m_bodyIdList.findLinearSearch2(objectUniqueId) < 0)
{
continue;
}
MinitaurLogRecord logData;
int stepCount = m_loggingTimeStamp;
float timeStamp = m_loggingTimeStamp * m_dynamicsWorld->getSolverInfo().m_timeStep;
logData.m_values.push_back(stepCount);
logData.m_values.push_back(timeStamp);
btVector3 pos = mb->getBasePos();
btQuaternion ori = mb->getWorldToBaseRot().inverse();
btVector3 vel = mb->getBaseVel();
btVector3 omega = mb->getBaseOmega();
float posX = pos[0];
float posY = pos[1];
float posZ = pos[2];
float oriX = ori.x();
float oriY = ori.y();
float oriZ = ori.z();
float oriW = ori.w();
float velX = vel[0];
float velY = vel[1];
float velZ = vel[2];
float omegaX = omega[0];
float omegaY = omega[1];
float omegaZ = omega[2];
logData.m_values.push_back(objectUniqueId);
logData.m_values.push_back(posX);
logData.m_values.push_back(posY);
logData.m_values.push_back(posZ);
logData.m_values.push_back(oriX);
logData.m_values.push_back(oriY);
logData.m_values.push_back(oriZ);
logData.m_values.push_back(oriW);
logData.m_values.push_back(velX);
logData.m_values.push_back(velY);
logData.m_values.push_back(velZ);
logData.m_values.push_back(omegaX);
logData.m_values.push_back(omegaY);
logData.m_values.push_back(omegaZ);
int numDofs = mb->getNumDofs();
logData.m_values.push_back(numDofs);
int numJoints = mb->getNumLinks();
for (int j = 0; j < numJoints; ++j)
{
if (mb->getLink(j).m_jointType == 0 || mb->getLink(j).m_jointType == 1)
{
float q = mb->getJointPos(j);
logData.m_values.push_back(q);
}
}
for (int j = numDofs; j < m_maxLogDof; ++j)
{
float q = 0.0;
logData.m_values.push_back(q);
}
for (int j = 0; j < numJoints; ++j)
{
if (mb->getLink(j).m_jointType == 0 || mb->getLink(j).m_jointType == 1)
{
float v = mb->getJointVel(j);
logData.m_values.push_back(v);
}
}
for (int j = numDofs; j < m_maxLogDof; ++j)
{
float v = 0.0;
logData.m_values.push_back(v);
}
if (m_logFlags & STATE_LOG_JOINT_TORQUES)
{
for (int j = 0; j < numJoints; ++j)
{
if (mb->getLink(j).m_jointType == 0 || mb->getLink(j).m_jointType == 1)
{
float jointTorque = 0;
if (m_logFlags & STATE_LOG_JOINT_MOTOR_TORQUES)
{
btMultiBodyJointMotor* motor = (btMultiBodyJointMotor*)mb->getLink(j).m_userPtr;
if (motor)
{
jointTorque += motor->getAppliedImpulse(0) / timeStep;
}
}
if (m_logFlags & STATE_LOG_JOINT_USER_TORQUES)
{
if (mb->getLink(j).m_jointType == 0 || mb->getLink(j).m_jointType == 1)
{
jointTorque += mb->getJointTorque(j); //these are the 'user' applied external torques
}
}
logData.m_values.push_back(jointTorque);
}
}
for (int j = numDofs; j < m_maxLogDof; ++j)
{
float u = 0.0;
logData.m_values.push_back(u);
}
}
//at the moment, appendMinitaurLogData will directly write to disk (potential delay)
//better to fill a huge memory buffer and once in a while write it to disk
appendMinitaurLogData(m_logFileHandle, m_structTypes, logData);
fflush(m_logFileHandle);
}
m_loggingTimeStamp++;
}
}
};
struct ContactPointsStateLogger : public InternalStateLogger
{
int m_loggingTimeStamp;
std::string m_fileName;
FILE* m_logFileHandle;
std::string m_structTypes;
btMultiBodyDynamicsWorld* m_dynamicsWorld;
bool m_filterLinkA;
bool m_filterLinkB;
int m_linkIndexA;
int m_linkIndexB;
int m_bodyUniqueIdA;
int m_bodyUniqueIdB;
ContactPointsStateLogger(int loggingUniqueId, const std::string& fileName, btMultiBodyDynamicsWorld* dynamicsWorld)
: m_loggingTimeStamp(0),
m_fileName(fileName),
m_logFileHandle(0),
m_dynamicsWorld(dynamicsWorld),
m_filterLinkA(false),
m_filterLinkB(false),
m_linkIndexA(-2),
m_linkIndexB(-2),
m_bodyUniqueIdA(-1),
m_bodyUniqueIdB(-1)
{
m_loggingUniqueId = loggingUniqueId;
m_loggingType = STATE_LOGGING_CONTACT_POINTS;
btAlignedObjectArray<std::string> structNames;
structNames.push_back("stepCount");
structNames.push_back("timeStamp");
structNames.push_back("contactFlag");
structNames.push_back("bodyUniqueIdA");
structNames.push_back("bodyUniqueIdB");
structNames.push_back("linkIndexA");
structNames.push_back("linkIndexB");
structNames.push_back("positionOnAX");
structNames.push_back("positionOnAY");
structNames.push_back("positionOnAZ");
structNames.push_back("positionOnBX");
structNames.push_back("positionOnBY");
structNames.push_back("positionOnBZ");
structNames.push_back("contactNormalOnBX");
structNames.push_back("contactNormalOnBY");
structNames.push_back("contactNormalOnBZ");
structNames.push_back("contactDistance");
structNames.push_back("normalForce");
m_structTypes = "IfIiiiifffffffffff";
const char* fileNameC = fileName.c_str();
m_logFileHandle = createMinitaurLogFile(fileNameC, structNames, m_structTypes);
}
virtual void stop()
{
if (m_logFileHandle)
{
closeMinitaurLogFile(m_logFileHandle);
m_logFileHandle = 0;
}
}
virtual void logState(btScalar timeStep)
{
if (m_logFileHandle)
{
int numContactManifolds = m_dynamicsWorld->getDispatcher()->getNumManifolds();
for (int i = 0; i < numContactManifolds; i++)
{
const btPersistentManifold* manifold = m_dynamicsWorld->getDispatcher()->getInternalManifoldPointer()[i];
int linkIndexA = -1;
int linkIndexB = -1;
int objectIndexB = -1;
const btRigidBody* bodyB = btRigidBody::upcast(manifold->getBody1());
if (bodyB)
{
objectIndexB = bodyB->getUserIndex2();
}
const btMultiBodyLinkCollider* mblB = btMultiBodyLinkCollider::upcast(manifold->getBody1());
if (mblB && mblB->m_multiBody)
{
linkIndexB = mblB->m_link;
objectIndexB = mblB->m_multiBody->getUserIndex2();
if (m_filterLinkB && (m_linkIndexB != linkIndexB))
{
continue;
}
}
int objectIndexA = -1;
const btRigidBody* bodyA = btRigidBody::upcast(manifold->getBody0());
if (bodyA)
{
objectIndexA = bodyA->getUserIndex2();
}
const btMultiBodyLinkCollider* mblA = btMultiBodyLinkCollider::upcast(manifold->getBody0());
if (mblA && mblA->m_multiBody)
{
linkIndexA = mblA->m_link;
objectIndexA = mblA->m_multiBody->getUserIndex2();
if (m_filterLinkA && (m_linkIndexA != linkIndexA))
{
continue;
}
}
btAssert(bodyA || mblA);
//apply the filter, if the user provides it
if (m_bodyUniqueIdA >= 0)
{
if ((m_bodyUniqueIdA != objectIndexA) &&
(m_bodyUniqueIdA != objectIndexB))
continue;
}
//apply the second object filter, if the user provides it
if (m_bodyUniqueIdB >= 0)
{
if ((m_bodyUniqueIdB != objectIndexA) &&
(m_bodyUniqueIdB != objectIndexB))
continue;
}
for (int p = 0; p < manifold->getNumContacts(); p++)
{
MinitaurLogRecord logData;
int stepCount = m_loggingTimeStamp;
float timeStamp = m_loggingTimeStamp * timeStep;
logData.m_values.push_back(stepCount);
logData.m_values.push_back(timeStamp);
const btManifoldPoint& srcPt = manifold->getContactPoint(p);
logData.m_values.push_back(0); // reserved contact flag
logData.m_values.push_back(objectIndexA);
logData.m_values.push_back(objectIndexB);
logData.m_values.push_back(linkIndexA);
logData.m_values.push_back(linkIndexB);
logData.m_values.push_back((float)(srcPt.getPositionWorldOnA()[0]));
logData.m_values.push_back((float)(srcPt.getPositionWorldOnA()[1]));
logData.m_values.push_back((float)(srcPt.getPositionWorldOnA()[2]));
logData.m_values.push_back((float)(srcPt.getPositionWorldOnB()[0]));
logData.m_values.push_back((float)(srcPt.getPositionWorldOnB()[1]));
logData.m_values.push_back((float)(srcPt.getPositionWorldOnB()[2]));
logData.m_values.push_back((float)(srcPt.m_normalWorldOnB[0]));
logData.m_values.push_back((float)(srcPt.m_normalWorldOnB[1]));
logData.m_values.push_back((float)(srcPt.m_normalWorldOnB[2]));
logData.m_values.push_back((float)(srcPt.getDistance()));
logData.m_values.push_back((float)(srcPt.getAppliedImpulse() / timeStep));
appendMinitaurLogData(m_logFileHandle, m_structTypes, logData);
fflush(m_logFileHandle);
}
}
m_loggingTimeStamp++;
}
}
};
struct SaveStateData
{
bParse::btBulletFile* m_bulletFile;
btSerializer* m_serializer;
};
struct PhysicsServerCommandProcessorInternalData
{
///handle management
b3ResizablePool<InternalTextureHandle> m_textureHandles;
b3ResizablePool<InternalBodyHandle> m_bodyHandles;
b3ResizablePool<InternalCollisionShapeHandle> m_userCollisionShapeHandles;
b3ResizablePool<InternalVisualShapeHandle> m_userVisualShapeHandles;
b3ResizablePool<b3PoolBodyHandle<SharedMemoryUserData> > m_userDataHandles;
btHashMap<SharedMemoryUserDataHashKey, int> m_userDataHandleLookup;
b3PluginManager m_pluginManager;
bool m_useRealTimeSimulation;
b3VRControllerEvents m_vrControllerEvents;
btAlignedObjectArray<SaveStateData> m_savedStates;
btAlignedObjectArray<b3KeyboardEvent> m_keyboardEvents;
btAlignedObjectArray<b3MouseEvent> m_mouseEvents;
CommandLogger* m_commandLogger;
int m_commandLoggingUid;
CommandLogPlayback* m_logPlayback;
int m_logPlaybackUid;
btScalar m_physicsDeltaTime;
btScalar m_numSimulationSubSteps;
btScalar m_simulationTimestamp;
btAlignedObjectArray<btMultiBodyJointFeedback*> m_multiBodyJointFeedbacks;
b3HashMap<btHashPtr, btInverseDynamics::MultiBodyTree*> m_inverseDynamicsBodies;
b3HashMap<btHashPtr, IKTrajectoryHelper*> m_inverseKinematicsHelpers;
int m_userConstraintUIDGenerator;
b3HashMap<btHashInt, InteralUserConstraintData> m_userConstraints;
b3AlignedObjectArray<SaveWorldObjectData> m_saveWorldBodyData;
#ifdef USE_DISCRETE_DYNAMICS_WORLD
btAlignedObjectArray<btWorldImporter*> m_worldImporters;
#else
btAlignedObjectArray<btMultiBodyWorldImporter*> m_worldImporters;
#endif
btAlignedObjectArray<std::string*> m_strings;
btAlignedObjectArray<btCollisionShape*> m_collisionShapes;
btAlignedObjectArray<const unsigned char*> m_heightfieldDatas;
btAlignedObjectArray<int> m_allocatedTextures;
btAlignedObjectArray<unsigned char*> m_allocatedTexturesRequireFree;
btHashMap<btHashPtr, UrdfCollision> m_bulletCollisionShape2UrdfCollision;
btAlignedObjectArray<btStridingMeshInterface*> m_meshInterfaces;
MyOverlapFilterCallback* m_broadphaseCollisionFilterCallback;
btHashedOverlappingPairCache* m_pairCache;
btBroadphaseInterface* m_broadphase;
btCollisionDispatcher* m_dispatcher;
#ifdef USE_DISCRETE_DYNAMICS_WORLD
btSequentialImpulseConstraintSolver* m_solver;
#else
btMultiBodyConstraintSolver* m_solver;
#endif
btDefaultCollisionConfiguration* m_collisionConfiguration;
#ifndef SKIP_DEFORMABLE_BODY
btSoftBody* m_pickedSoftBody;
btDeformableMousePickingForce* m_mouseForce;
btScalar m_maxPickingForce;
btDeformableBodySolver* m_deformablebodySolver;
btAlignedObjectArray<btDeformableLagrangianForce*> m_lf;
#endif
#ifdef USE_DISCRETE_DYNAMICS_WORLD
btDiscreteDynamicsWorld* m_dynamicsWorld;
#else
btMultiBodyDynamicsWorld* m_dynamicsWorld;
#endif
int m_constraintSolverType;
SharedMemoryDebugDrawer* m_remoteDebugDrawer;
btAlignedObjectArray<b3ContactPointData> m_cachedContactPoints;
MyBroadphaseCallback m_cachedOverlappingObjects;
btAlignedObjectArray<int> m_sdfRecentLoadedBodies;
btAlignedObjectArray<int> m_graphicsIndexToSegmentationMask;
btAlignedObjectArray<InternalStateLogger*> m_stateLoggers;
int m_stateLoggersUniqueId;
int m_profileTimingLoggingUid;
std::string m_profileTimingFileName;
struct GUIHelperInterface* m_guiHelper;
int m_sharedMemoryKey;
bool m_enableTinyRenderer;
bool m_verboseOutput;
//data for picking objects
class btRigidBody* m_pickedBody;
int m_savedActivationState;
class btTypedConstraint* m_pickedConstraint;
class btMultiBodyPoint2Point* m_pickingMultiBodyPoint2Point;
btVector3 m_oldPickingPos;
btVector3 m_hitPos;
btScalar m_oldPickingDist;
bool m_prevCanSleep;
int m_pdControlPlugin;
int m_collisionFilterPlugin;
int m_grpcPlugin;
#ifdef B3_ENABLE_TINY_AUDIO
b3SoundEngine m_soundEngine;
#endif
b3HashMap<b3HashString, char*> m_profileEvents;
b3HashMap<b3HashString, UrdfVisualShapeCache> m_cachedVUrdfisualShapes;
b3ThreadPool* m_threadPool;
btScalar m_defaultCollisionMargin;
double m_remoteSyncTransformTime;
double m_remoteSyncTransformInterval;
bool m_useAlternativeDeformableIndexing;
PhysicsServerCommandProcessorInternalData(PhysicsCommandProcessorInterface* proc)
: m_pluginManager(proc),
m_useRealTimeSimulation(false),
m_commandLogger(0),
m_commandLoggingUid(-1),
m_logPlayback(0),
m_logPlaybackUid(-1),
m_physicsDeltaTime(1. / 240.),
m_numSimulationSubSteps(0),
m_simulationTimestamp(0),
m_userConstraintUIDGenerator(1),
m_broadphaseCollisionFilterCallback(0),
m_pairCache(0),
m_broadphase(0),
m_dispatcher(0),
m_solver(0),
m_collisionConfiguration(0),
#ifndef SKIP_DEFORMABLE_BODY
m_pickedSoftBody(0),
m_mouseForce(0),
m_maxPickingForce(0.3),
m_deformablebodySolver(0),
#endif
m_dynamicsWorld(0),
m_constraintSolverType(-1),
m_remoteDebugDrawer(0),
m_stateLoggersUniqueId(0),
m_profileTimingLoggingUid(-1),
m_guiHelper(0),
m_sharedMemoryKey(SHARED_MEMORY_KEY),
m_enableTinyRenderer(true),
m_verboseOutput(false),
m_pickedBody(0),
m_pickedConstraint(0),
m_pickingMultiBodyPoint2Point(0),
m_pdControlPlugin(-1),
m_collisionFilterPlugin(-1),
m_grpcPlugin(-1),
m_threadPool(0),
m_defaultCollisionMargin(0.001),
m_remoteSyncTransformTime(1. / 30.),
m_remoteSyncTransformInterval(1. / 30.),
m_useAlternativeDeformableIndexing(false)
{
{
//register static plugins:
#ifdef STATIC_LINK_VR_PLUGIN
b3PluginFunctions funcs(initPlugin_vrSyncPlugin, exitPlugin_vrSyncPlugin, executePluginCommand_vrSyncPlugin);
funcs.m_preTickFunc = preTickPluginCallback_vrSyncPlugin;
m_pluginManager.registerStaticLinkedPlugin("vrSyncPlugin", funcs);
#endif //STATIC_LINK_VR_PLUGIN
}
#ifndef SKIP_STATIC_PD_CONTROL_PLUGIN
{
//int b3PluginManager::registerStaticLinkedPlugin(const char* pluginPath, PFN_INIT initFunc, PFN_EXIT exitFunc, PFN_EXECUTE executeCommandFunc, PFN_TICK preTickFunc, PFN_TICK postTickFunc, PFN_GET_RENDER_INTERFACE getRendererFunc, PFN_TICK processClientCommandsFunc, PFN_GET_COLLISION_INTERFACE getCollisionFunc, bool initPlugin)
b3PluginFunctions funcs(initPlugin_pdControlPlugin, exitPlugin_pdControlPlugin, executePluginCommand_pdControlPlugin);
funcs.m_preTickFunc = preTickPluginCallback_pdControlPlugin;
m_pdControlPlugin = m_pluginManager.registerStaticLinkedPlugin("pdControlPlugin", funcs);
}
#endif //SKIP_STATIC_PD_CONTROL_PLUGIN
#ifndef SKIP_COLLISION_FILTER_PLUGIN
{
b3PluginFunctions funcs(initPlugin_collisionFilterPlugin, exitPlugin_collisionFilterPlugin, executePluginCommand_collisionFilterPlugin);
funcs.m_getCollisionFunc = getCollisionInterface_collisionFilterPlugin;
m_collisionFilterPlugin = m_pluginManager.registerStaticLinkedPlugin("collisionFilterPlugin", funcs);
m_pluginManager.selectCollisionPlugin(m_collisionFilterPlugin);
}
#endif
#ifdef ENABLE_STATIC_GRPC_PLUGIN
{
b3PluginFunctions funcs(initPlugin_grpcPlugin, exitPlugin_grpcPlugin, executePluginCommand_grpcPlugin);
funcs.m_processClientCommandsFunc = processClientCommands_grpcPlugin;
m_grpcPlugin = m_pluginManager.registerStaticLinkedPlugin("grpcPlugin", funcs);
}
#endif //ENABLE_STATIC_GRPC_PLUGIN
#ifdef STATIC_EGLRENDERER_PLUGIN
{
bool initPlugin = false;
b3PluginFunctions funcs(initPlugin_eglRendererPlugin, exitPlugin_eglRendererPlugin, executePluginCommand_eglRendererPlugin);
funcs.m_getRendererFunc = getRenderInterface_eglRendererPlugin;
int renderPluginId = m_pluginManager.registerStaticLinkedPlugin("eglRendererPlugin", funcs, initPlugin);
m_pluginManager.selectPluginRenderer(renderPluginId);
}
#endif //STATIC_EGLRENDERER_PLUGIN
#ifndef SKIP_STATIC_TINYRENDERER_PLUGIN
{
b3PluginFunctions funcs(initPlugin_tinyRendererPlugin, exitPlugin_tinyRendererPlugin, executePluginCommand_tinyRendererPlugin);
funcs.m_getRendererFunc = getRenderInterface_tinyRendererPlugin;
int renderPluginId = m_pluginManager.registerStaticLinkedPlugin("tinyRendererPlugin", funcs);
m_pluginManager.selectPluginRenderer(renderPluginId);
}
#endif
#ifdef B3_ENABLE_FILEIO_PLUGIN
{
b3PluginFunctions funcs(initPlugin_fileIOPlugin, exitPlugin_fileIOPlugin, executePluginCommand_fileIOPlugin);
funcs.m_fileIoFunc = getFileIOFunc_fileIOPlugin;
int renderPluginId = m_pluginManager.registerStaticLinkedPlugin("fileIOPlugin", funcs);
m_pluginManager.selectFileIOPlugin(renderPluginId);
}
#endif
m_vrControllerEvents.init();
m_bodyHandles.exitHandles();
m_bodyHandles.initHandles();
m_userCollisionShapeHandles.exitHandles();
m_userCollisionShapeHandles.initHandles();
m_userVisualShapeHandles.exitHandles();
m_userVisualShapeHandles.initHandles();
}
#ifdef STATIC_LINK_SPD_PLUGIN
b3HashMap<btHashPtr, cRBDModel*> m_rbdModels;
static void convertPose(const btMultiBody* multiBody, const double* jointPositionsQ, const double* jointVelocitiesQdot, Eigen::VectorXd& pose, Eigen::VectorXd& vel)
{
int baseDofQ = multiBody->hasFixedBase() ? 0 : 7;
int baseDofQdot = multiBody->hasFixedBase() ? 0 : 6;
pose.resize(7 + multiBody->getNumPosVars());
vel.resize(7 + multiBody->getNumPosVars()); //??
btTransform tr = multiBody->getBaseWorldTransform();
int dofsrc = 0;
int velsrcdof = 0;
if (baseDofQ == 7)
{
pose[0] = jointPositionsQ[dofsrc++];
pose[1] = jointPositionsQ[dofsrc++];
pose[2] = jointPositionsQ[dofsrc++];
double quatXYZW[4];
quatXYZW[0] = jointPositionsQ[dofsrc++];
quatXYZW[1] = jointPositionsQ[dofsrc++];
quatXYZW[2] = jointPositionsQ[dofsrc++];
quatXYZW[3] = jointPositionsQ[dofsrc++];
pose[3] = quatXYZW[3];
pose[4] = quatXYZW[0];
pose[5] = quatXYZW[1];
pose[6] = quatXYZW[2];
}
else
{
pose[0] = tr.getOrigin()[0];
pose[1] = tr.getOrigin()[1];
pose[2] = tr.getOrigin()[2];
pose[3] = tr.getRotation()[3];
pose[4] = tr.getRotation()[0];
pose[5] = tr.getRotation()[1];
pose[6] = tr.getRotation()[2];
}
if (baseDofQdot == 6)
{
vel[0] = jointVelocitiesQdot[velsrcdof++];
vel[1] = jointVelocitiesQdot[velsrcdof++];
vel[2] = jointVelocitiesQdot[velsrcdof++];
vel[3] = jointVelocitiesQdot[velsrcdof++];
vel[4] = jointVelocitiesQdot[velsrcdof++];
vel[5] = jointVelocitiesQdot[velsrcdof++];
vel[6] = jointVelocitiesQdot[velsrcdof++];
vel[6] = 0;
}
else
{
vel[0] = multiBody->getBaseVel()[0];
vel[1] = multiBody->getBaseVel()[1];
vel[2] = multiBody->getBaseVel()[2];
vel[3] = multiBody->getBaseOmega()[0];
vel[4] = multiBody->getBaseOmega()[1];
vel[5] = multiBody->getBaseOmega()[2];
vel[6] = 0;
}
int dof = 7;
int veldof = 7;
for (int l = 0; l < multiBody->getNumLinks(); l++)
{
switch (multiBody->getLink(l).m_jointType)
{
case btMultibodyLink::eRevolute:
case btMultibodyLink::ePrismatic:
{
pose[dof++] = jointPositionsQ[dofsrc++];
vel[veldof++] = jointVelocitiesQdot[velsrcdof++];
break;
}
case btMultibodyLink::eSpherical:
{
double quatXYZW[4];
quatXYZW[0] = jointPositionsQ[dofsrc++];
quatXYZW[1] = jointPositionsQ[dofsrc++];
quatXYZW[2] = jointPositionsQ[dofsrc++];
quatXYZW[3] = jointPositionsQ[dofsrc++];
pose[dof++] = quatXYZW[3];
pose[dof++] = quatXYZW[0];
pose[dof++] = quatXYZW[1];
pose[dof++] = quatXYZW[2];
vel[veldof++] = jointVelocitiesQdot[velsrcdof++];
vel[veldof++] = jointVelocitiesQdot[velsrcdof++];
vel[veldof++] = jointVelocitiesQdot[velsrcdof++];
vel[veldof++] = jointVelocitiesQdot[velsrcdof++];
break;
}
case btMultibodyLink::eFixed:
{
break;
}
default:
{
assert(0);
}
}
}
}
cRBDModel* findOrCreateRBDModel(btMultiBody* multiBody, const double* jointPositionsQ, const double* jointVelocitiesQdot)
{
cRBDModel* rbdModel = 0;
cRBDModel** rbdModelPtr = m_rbdModels.find(multiBody);
if (rbdModelPtr)
{
rbdModel = *rbdModelPtr;
}
else
{
rbdModel = new cRBDModel();
Eigen::MatrixXd bodyDefs;
Eigen::MatrixXd jointMat;
btExtractJointBodyFromBullet(multiBody, bodyDefs, jointMat);
btVector3 grav = m_dynamicsWorld->getGravity();
tVector3 gravity(grav[0], grav[1], grav[2], 0);
rbdModel->Init(jointMat, bodyDefs, gravity);
m_rbdModels.insert(multiBody, rbdModel);
}
//sync pose and vel
Eigen::VectorXd pose, vel;
PhysicsServerCommandProcessorInternalData::convertPose(multiBody, jointPositionsQ, jointVelocitiesQdot, pose, vel);
btVector3 gravOrg = m_dynamicsWorld->getGravity();
tVector grav(gravOrg[0], gravOrg[1], gravOrg[2], 0);
rbdModel->SetGravity(grav);
{
BT_PROFILE("rbdModel::Update");
rbdModel->Update(pose, vel);
}
return rbdModel;
}
#endif
btInverseDynamics::MultiBodyTree* findOrCreateTree(btMultiBody* multiBody)
{
btInverseDynamics::MultiBodyTree* tree = 0;
btInverseDynamics::MultiBodyTree** treePtrPtr =
m_inverseDynamicsBodies.find(multiBody);
if (treePtrPtr)
{
tree = *treePtrPtr;
}
else
{
btInverseDynamics::btMultiBodyTreeCreator id_creator;
if (-1 == id_creator.createFromBtMultiBody(multiBody, false))
{
}
else
{
tree = btInverseDynamics::CreateMultiBodyTree(id_creator);
m_inverseDynamicsBodies.insert(multiBody, tree);
}
}
return tree;
}
};
void PhysicsServerCommandProcessor::setGuiHelper(struct GUIHelperInterface* guiHelper)
{
if (guiHelper)
{
guiHelper->createPhysicsDebugDrawer(m_data->m_dynamicsWorld);
}
else
{
//state loggers use guiHelper, so remove them before the guiHelper is deleted
deleteStateLoggers();
if (m_data->m_guiHelper && m_data->m_dynamicsWorld && m_data->m_dynamicsWorld->getDebugDrawer())
{
m_data->m_dynamicsWorld->setDebugDrawer(0);
}
}
m_data->m_guiHelper = guiHelper;
}
PhysicsServerCommandProcessor::PhysicsServerCommandProcessor()
: m_data(0)
{
m_data = new PhysicsServerCommandProcessorInternalData(this);
createEmptyDynamicsWorld();
}
PhysicsServerCommandProcessor::~PhysicsServerCommandProcessor()
{
deleteDynamicsWorld();
if (m_data->m_commandLogger)
{
delete m_data->m_commandLogger;
m_data->m_commandLogger = 0;
}
for (int i = 0; i < m_data->m_profileEvents.size(); i++)
{
char* event = *m_data->m_profileEvents.getAtIndex(i);
delete[] event;
}
if (m_data->m_threadPool)
delete m_data->m_threadPool;
for (int i = 0; i < m_data->m_savedStates.size(); i++)
{
delete m_data->m_savedStates[i].m_bulletFile;
delete m_data->m_savedStates[i].m_serializer;
}
delete m_data;
}
void preTickCallback(btDynamicsWorld* world, btScalar timeStep)
{
PhysicsServerCommandProcessor* proc = (PhysicsServerCommandProcessor*)world->getWorldUserInfo();
proc->tickPlugins(timeStep, true);
}
void logCallback(btDynamicsWorld* world, btScalar timeStep)
{
//handle the logging and playing sounds
PhysicsServerCommandProcessor* proc = (PhysicsServerCommandProcessor*)world->getWorldUserInfo();
proc->processCollisionForces(timeStep);
proc->logObjectStates(timeStep);
proc->tickPlugins(timeStep, false);
}
bool MyContactAddedCallback(btManifoldPoint& cp, const btCollisionObjectWrapper* colObj0Wrap, int partId0, int index0, const btCollisionObjectWrapper* colObj1Wrap, int partId1, int index1)
{
btAdjustInternalEdgeContacts(cp, colObj1Wrap, colObj0Wrap, partId1, index1);
return true;
}
bool MyContactDestroyedCallback(void* userPersistentData)
{
//printf("destroyed\n");
return false;
}
bool MyContactProcessedCallback(btManifoldPoint& cp, void* body0, void* body1)
{
//printf("processed\n");
return false;
}
void MyContactStartedCallback(btPersistentManifold* const& manifold)
{
//printf("started\n");
}
void MyContactEndedCallback(btPersistentManifold* const& manifold)
{
// printf("ended\n");
}
void PhysicsServerCommandProcessor::processCollisionForces(btScalar timeStep)
{
#ifdef B3_ENABLE_TINY_AUDIO
//this is experimental at the moment: impulse thresholds, sound parameters will be exposed in C-API/pybullet.
//audio will go into a wav file, as well as real-time output to speakers/headphones using RtAudio/DAC.
int numContactManifolds = m_data->m_dynamicsWorld->getDispatcher()->getNumManifolds();
for (int i = 0; i < numContactManifolds; i++)
{
const btPersistentManifold* manifold = m_data->m_dynamicsWorld->getDispatcher()->getInternalManifoldPointer()[i];
bool objHasSound[2];
objHasSound[0] = (0 != (manifold->getBody0()->getCollisionFlags() & btCollisionObject::CF_HAS_COLLISION_SOUND_TRIGGER));
objHasSound[1] = (0 != (manifold->getBody1()->getCollisionFlags() & btCollisionObject::CF_HAS_COLLISION_SOUND_TRIGGER));
const btCollisionObject* colObjs[2] = {manifold->getBody0(), manifold->getBody1()};
for (int ob = 0; ob < 2; ob++)
{
if (objHasSound[ob])
{
int uid0 = -1;
int linkIndex = -2;
const btMultiBodyLinkCollider* mblB = btMultiBodyLinkCollider::upcast(colObjs[ob]);
if (mblB && mblB->m_multiBody)
{
linkIndex = mblB->m_link;
uid0 = mblB->m_multiBody->getUserIndex2();
}
const btRigidBody* bodyB = btRigidBody::upcast(colObjs[ob]);
if (bodyB)
{
uid0 = bodyB->getUserIndex2();
linkIndex = -1;
}
if ((uid0 < 0) || (linkIndex < -1))
continue;
InternalBodyHandle* bodyHandle0 = m_data->m_bodyHandles.getHandle(uid0);
SDFAudioSource* audioSrc = bodyHandle0->m_audioSources[linkIndex];
if (audioSrc == 0)
continue;
for (int p = 0; p < manifold->getNumContacts(); p++)
{
double imp = manifold->getContactPoint(p).getAppliedImpulse();
//printf ("manifold %d, contact %d, lifeTime:%d, appliedImpulse:%f\n",i,p, manifold->getContactPoint(p).getLifeTime(),imp);
if (imp > audioSrc->m_collisionForceThreshold && manifold->getContactPoint(p).getLifeTime() == 1)
{
int soundSourceIndex = m_data->m_soundEngine.getAvailableSoundSource();
if (soundSourceIndex >= 0)
{
b3SoundMessage msg;
msg.m_attackRate = audioSrc->m_attackRate;
msg.m_decayRate = audioSrc->m_decayRate;
msg.m_sustainLevel = audioSrc->m_sustainLevel;
msg.m_releaseRate = audioSrc->m_releaseRate;
msg.m_amplitude = audioSrc->m_gain;
msg.m_frequency = audioSrc->m_pitch;
msg.m_type = B3_SOUND_SOURCE_WAV_FILE;
msg.m_wavId = audioSrc->m_userIndex;
msg.m_autoKeyOff = true;
m_data->m_soundEngine.startSound(soundSourceIndex, msg);
}
}
}
}
}
}
#endif //B3_ENABLE_TINY_AUDIO
}
void PhysicsServerCommandProcessor::processClientCommands()
{
m_data->m_pluginManager.tickPlugins(0, B3_PROCESS_CLIENT_COMMANDS_TICK);
}
void PhysicsServerCommandProcessor::reportNotifications()
{
m_data->m_pluginManager.reportNotifications();
}
void PhysicsServerCommandProcessor::tickPlugins(btScalar timeStep, bool isPreTick)
{
b3PluginManagerTickMode tickMode = isPreTick ? B3_PRE_TICK_MODE : B3_POST_TICK_MODE;
m_data->m_pluginManager.tickPlugins(timeStep, tickMode);
if (!isPreTick)
{
//clear events after each postTick, so we don't receive events multiple ticks
m_data->m_pluginManager.clearEvents();
}
}
void PhysicsServerCommandProcessor::logObjectStates(btScalar timeStep)
{
for (int i = 0; i < m_data->m_stateLoggers.size(); i++)
{
m_data->m_stateLoggers[i]->logState(timeStep);
}
}
struct ProgrammaticUrdfInterface : public URDFImporterInterface
{
int m_bodyUniqueId;
const b3CreateMultiBodyArgs& m_createBodyArgs;
mutable b3AlignedObjectArray<btCollisionShape*> m_allocatedCollisionShapes;
PhysicsServerCommandProcessorInternalData* m_data;
int m_flags;
ProgrammaticUrdfInterface(const b3CreateMultiBodyArgs& bodyArgs, PhysicsServerCommandProcessorInternalData* data, int flags)
: m_bodyUniqueId(-1),
m_createBodyArgs(bodyArgs),
m_data(data),
m_flags(flags)
{
}
virtual ~ProgrammaticUrdfInterface()
{
}
virtual bool loadURDF(const char* fileName, bool forceFixedBase = false)
{
b3Assert(0);
return false;
}
virtual const char* getPathPrefix()
{
return "";
}
///return >=0 for the root link index, -1 if there is no root link
virtual int getRootLinkIndex() const
{
return m_createBodyArgs.m_baseLinkIndex;
}
///pure virtual interfaces, precondition is a valid linkIndex (you can assert/terminate if the linkIndex is out of range)
virtual std::string getLinkName(int linkIndex) const
{
std::string linkName = "link";
char numstr[21]; // enough to hold all numbers up to 64-bits
sprintf(numstr, "%d", linkIndex);
linkName = linkName + numstr;
return linkName;
}
//various derived class in internal source code break with new pure virtual methods, so provide some default implementation
virtual std::string getBodyName() const
{
return m_createBodyArgs.m_bodyName;
}
/// optional method to provide the link color. return true if the color is available and copied into colorRGBA, return false otherwise
virtual bool getLinkColor(int linkIndex, btVector4& colorRGBA) const
{
b3Assert(0);
return false;
}
mutable btHashMap<btHashInt, UrdfMaterialColor> m_linkColors;
virtual bool getLinkColor2(int linkIndex, struct UrdfMaterialColor& matCol) const
{
if (m_flags & URDF_USE_MATERIAL_COLORS_FROM_MTL)
{
const UrdfMaterialColor* matColPtr = m_linkColors[linkIndex];
if (matColPtr)
{
matCol = *matColPtr;
if ((m_flags & CUF_USE_MATERIAL_TRANSPARANCY_FROM_MTL) == 0)
{
matCol.m_rgbaColor[3] = 1;
}
return true;
}
}
else
{
if (m_createBodyArgs.m_linkVisualShapeUniqueIds[linkIndex] >= 0)
{
const InternalVisualShapeHandle* visHandle = m_data->m_userVisualShapeHandles.getHandle(m_createBodyArgs.m_linkVisualShapeUniqueIds[linkIndex]);
if (visHandle)
{
for (int i = 0; i < visHandle->m_visualShapes.size(); i++)
{
if (visHandle->m_visualShapes[i].m_geometry.m_hasLocalMaterial)
{
matCol = visHandle->m_visualShapes[i].m_geometry.m_localMaterial.m_matColor;
return true;
}
}
}
}
}
return false;
}
virtual int getCollisionGroupAndMask(int linkIndex, int& colGroup, int& colMask) const
{
return 0;
}
///this API will likely change, don't override it!
virtual bool getLinkContactInfo(int linkIndex, URDFLinkContactInfo& contactInfo) const
{
return false;
}
virtual bool getLinkAudioSource(int linkIndex, SDFAudioSource& audioSource) const
{
b3Assert(0);
return false;
}
virtual std::string getJointName(int linkIndex) const
{
std::string jointName = "joint";
char numstr[21]; // enough to hold all numbers up to 64-bits
sprintf(numstr, "%d", linkIndex);
jointName = jointName + numstr;
return jointName;
}
//fill mass and inertial data. If inertial data is missing, please initialize mass, inertia to sensitive values, and inertialFrame to identity.
virtual void getMassAndInertia(int urdfLinkIndex, btScalar& mass, btVector3& localInertiaDiagonal, btTransform& inertialFrame) const
{
if (urdfLinkIndex >= 0 && urdfLinkIndex < m_createBodyArgs.m_numLinks)
{
mass = m_createBodyArgs.m_linkMasses[urdfLinkIndex];
localInertiaDiagonal.setValue(
m_createBodyArgs.m_linkInertias[urdfLinkIndex * 3 + 0],
m_createBodyArgs.m_linkInertias[urdfLinkIndex * 3 + 1],
m_createBodyArgs.m_linkInertias[urdfLinkIndex * 3 + 2]);
inertialFrame.setOrigin(btVector3(
m_createBodyArgs.m_linkInertialFramePositions[urdfLinkIndex * 3 + 0],
m_createBodyArgs.m_linkInertialFramePositions[urdfLinkIndex * 3 + 1],
m_createBodyArgs.m_linkInertialFramePositions[urdfLinkIndex * 3 + 2]));
inertialFrame.setRotation(btQuaternion(
m_createBodyArgs.m_linkInertialFrameOrientations[urdfLinkIndex * 4 + 0],
m_createBodyArgs.m_linkInertialFrameOrientations[urdfLinkIndex * 4 + 1],
m_createBodyArgs.m_linkInertialFrameOrientations[urdfLinkIndex * 4 + 2],
m_createBodyArgs.m_linkInertialFrameOrientations[urdfLinkIndex * 4 + 3]));
}
else
{
mass = 0;
localInertiaDiagonal.setValue(0, 0, 0);
inertialFrame.setIdentity();
}
}
///fill an array of child link indices for this link, btAlignedObjectArray behaves like a std::vector so just use push_back and resize(0) if needed
virtual void getLinkChildIndices(int urdfLinkIndex, btAlignedObjectArray<int>& childLinkIndices) const
{
for (int i = 0; i < m_createBodyArgs.m_numLinks; i++)
{
if (m_createBodyArgs.m_linkParentIndices[i] == urdfLinkIndex)
{
childLinkIndices.push_back(i);
}
}
}
virtual bool getJointInfo(int urdfLinkIndex, btTransform& parent2joint, btTransform& linkTransformInWorld, btVector3& jointAxisInJointSpace, int& jointType, btScalar& jointLowerLimit, btScalar& jointUpperLimit, btScalar& jointDamping, btScalar& jointFriction) const
{
return false;
};
virtual bool getJointInfo2(int urdfLinkIndex, btTransform& parent2joint, btTransform& linkTransformInWorld, btVector3& jointAxisInJointSpace, int& jointType, btScalar& jointLowerLimit, btScalar& jointUpperLimit, btScalar& jointDamping, btScalar& jointFriction, btScalar& jointMaxForce, btScalar& jointMaxVelocity) const
{
bool isValid = false;
int jointTypeOrg = m_createBodyArgs.m_linkJointTypes[urdfLinkIndex];
switch (jointTypeOrg)
{
case eRevoluteType:
{
isValid = true;
jointType = URDFRevoluteJoint;
break;
}
case ePrismaticType:
{
isValid = true;
jointType = URDFPrismaticJoint;
break;
}
case eFixedType:
{
isValid = true;
jointType = URDFFixedJoint;
break;
}
case eSphericalType:
{
isValid = true;
jointType = URDFSphericalJoint;
break;
}
//case ePlanarType:
//case eFixedType:
//case ePoint2PointType:
//case eGearType:
default:
{
}
};
if (isValid)
{
//backwards compatibility for custom file importers
jointMaxForce = 0;
jointMaxVelocity = 0;
jointFriction = 0;
jointDamping = 0;
jointLowerLimit = 1;
jointUpperLimit = -1;
parent2joint.setOrigin(btVector3(
m_createBodyArgs.m_linkPositions[urdfLinkIndex * 3 + 0],
m_createBodyArgs.m_linkPositions[urdfLinkIndex * 3 + 1],
m_createBodyArgs.m_linkPositions[urdfLinkIndex * 3 + 2]));
parent2joint.setRotation(btQuaternion(
m_createBodyArgs.m_linkOrientations[urdfLinkIndex * 4 + 0],
m_createBodyArgs.m_linkOrientations[urdfLinkIndex * 4 + 1],
m_createBodyArgs.m_linkOrientations[urdfLinkIndex * 4 + 2],
m_createBodyArgs.m_linkOrientations[urdfLinkIndex * 4 + 3]));
linkTransformInWorld.setIdentity();
jointAxisInJointSpace.setValue(
m_createBodyArgs.m_linkJointAxis[3 * urdfLinkIndex + 0],
m_createBodyArgs.m_linkJointAxis[3 * urdfLinkIndex + 1],
m_createBodyArgs.m_linkJointAxis[3 * urdfLinkIndex + 2]);
}
return isValid;
};
virtual bool getRootTransformInWorld(btTransform& rootTransformInWorld) const
{
int baseLinkIndex = m_createBodyArgs.m_baseLinkIndex;
rootTransformInWorld.setOrigin(btVector3(
m_createBodyArgs.m_linkPositions[baseLinkIndex * 3 + 0],
m_createBodyArgs.m_linkPositions[baseLinkIndex * 3 + 1],
m_createBodyArgs.m_linkPositions[baseLinkIndex * 3 + 2]));
rootTransformInWorld.setRotation(btQuaternion(
m_createBodyArgs.m_linkOrientations[baseLinkIndex * 4 + 0],
m_createBodyArgs.m_linkOrientations[baseLinkIndex * 4 + 1],
m_createBodyArgs.m_linkOrientations[baseLinkIndex * 4 + 2],
m_createBodyArgs.m_linkOrientations[baseLinkIndex * 4 + 3]));
return true;
}
virtual void setRootTransformInWorld(const btTransform& rootTransformInWorld)
{
b3Assert(0);
}
virtual int convertLinkVisualShapes(int linkIndex, const char* pathPrefix, const btTransform& localInertiaFrame) const
{
int graphicsIndex = -1;
double globalScaling = 1.f; //todo!
int flags = 0;
CommonFileIOInterface* fileIO = m_data->m_pluginManager.getFileIOInterface();
BulletURDFImporter u2b(m_data->m_guiHelper, m_data->m_pluginManager.getRenderInterface(), fileIO, globalScaling, flags);
u2b.setEnableTinyRenderer(m_data->m_enableTinyRenderer);
btAlignedObjectArray<GLInstanceVertex> vertices;
btAlignedObjectArray<int> indices;
btTransform startTrans;
startTrans.setIdentity();
btAlignedObjectArray<BulletURDFTexture> textures;
if (m_createBodyArgs.m_linkVisualShapeUniqueIds[linkIndex] >= 0)
{
InternalVisualShapeHandle* visHandle = m_data->m_userVisualShapeHandles.getHandle(m_createBodyArgs.m_linkVisualShapeUniqueIds[linkIndex]);
if (visHandle)
{
if (visHandle->m_OpenGLGraphicsIndex >= 0)
{
//instancing. assume the inertial frame is identical
graphicsIndex = visHandle->m_OpenGLGraphicsIndex;
}
else
{
for (int v = 0; v < visHandle->m_visualShapes.size(); v++)
{
b3ImportMeshData meshData;
u2b.convertURDFToVisualShapeInternal(&visHandle->m_visualShapes[v], pathPrefix, localInertiaFrame.inverse() * visHandle->m_visualShapes[v].m_linkLocalFrame, vertices, indices, textures, meshData);
if ((meshData.m_flags & B3_IMPORT_MESH_HAS_RGBA_COLOR) &&
(meshData.m_flags & B3_IMPORT_MESH_HAS_SPECULAR_COLOR))
{
UrdfMaterialColor matCol;
matCol.m_rgbaColor.setValue(meshData.m_rgbaColor[0],
meshData.m_rgbaColor[1],
meshData.m_rgbaColor[2],
meshData.m_rgbaColor[3]);
matCol.m_specularColor.setValue(meshData.m_specularColor[0],
meshData.m_specularColor[1],
meshData.m_specularColor[2]);
m_linkColors.insert(linkIndex, matCol);
}
}
if (vertices.size() && indices.size())
{
if (1)
{
int textureIndex = -1;
if (textures.size())
{
textureIndex = m_data->m_guiHelper->registerTexture(textures[0].textureData1, textures[0].m_width, textures[0].m_height);
}
{
B3_PROFILE("registerGraphicsShape");
graphicsIndex = m_data->m_guiHelper->registerGraphicsShape(&vertices[0].xyzw[0], vertices.size(), &indices[0], indices.size(), B3_GL_TRIANGLES, textureIndex);
visHandle->m_OpenGLGraphicsIndex = graphicsIndex;
}
}
}
}
}
}
//delete textures
for (int i = 0; i < textures.size(); i++)
{
B3_PROFILE("free textureData");
if (!textures[i].m_isCached)
{
m_data->m_allocatedTexturesRequireFree.push_back(textures[i].textureData1);
}
}
return graphicsIndex;
}
virtual void convertLinkVisualShapes2(int linkIndex, int urdfIndex, const char* pathPrefix, const btTransform& localInertiaFrame, class btCollisionObject* colObj, int bodyUniqueId) const
{
//if there is a visual, use it, otherwise convert collision shape back into UrdfCollision...
UrdfModel model; // = m_data->m_urdfParser.getModel();
UrdfLink link;
if (m_createBodyArgs.m_linkVisualShapeUniqueIds[urdfIndex] >= 0)
{
const InternalVisualShapeHandle* visHandle = m_data->m_userVisualShapeHandles.getHandle(m_createBodyArgs.m_linkVisualShapeUniqueIds[urdfIndex]);
if (visHandle)
{
for (int i = 0; i < visHandle->m_visualShapes.size(); i++)
{
link.m_visualArray.push_back(visHandle->m_visualShapes[i]);
}
}
}
if (link.m_visualArray.size() == 0)
{
int colShapeUniqueId = m_createBodyArgs.m_linkCollisionShapeUniqueIds[urdfIndex];
if (colShapeUniqueId >= 0)
{
InternalCollisionShapeHandle* handle = m_data->m_userCollisionShapeHandles.getHandle(colShapeUniqueId);
if (handle)
{
for (int i = 0; i < handle->m_urdfCollisionObjects.size(); i++)
{
link.m_collisionArray.push_back(handle->m_urdfCollisionObjects[i]);
}
}
}
}
//UrdfVisual vis;
//link.m_visualArray.push_back(vis);
//UrdfLink*const* linkPtr = model.m_links.getAtIndex(urdfIndex);
if (m_data->m_pluginManager.getRenderInterface())
{
CommonFileIOInterface* fileIO = m_data->m_pluginManager.getFileIOInterface();
int visualShapeUniqueid = m_data->m_pluginManager.getRenderInterface()->convertVisualShapes(
linkIndex,
pathPrefix,
localInertiaFrame,
&link,
&model,
colObj->getBroadphaseHandle()->getUid(),
bodyUniqueId,
fileIO);
colObj->getCollisionShape()->setUserIndex2(visualShapeUniqueid);
colObj->setUserIndex3(visualShapeUniqueid);
}
}
virtual void setBodyUniqueId(int bodyId)
{
m_bodyUniqueId = bodyId;
}
virtual int getBodyUniqueId() const
{
return m_bodyUniqueId;
}
//default implementation for backward compatibility
virtual class btCompoundShape* convertLinkCollisionShapes(int linkIndex, const char* pathPrefix, const btTransform& localInertiaFrame) const
{
btCompoundShape* compound = new btCompoundShape();
int colShapeUniqueId = m_createBodyArgs.m_linkCollisionShapeUniqueIds[linkIndex];
if (colShapeUniqueId >= 0)
{
InternalCollisionShapeHandle* handle = m_data->m_userCollisionShapeHandles.getHandle(colShapeUniqueId);
if (handle && handle->m_collisionShape)
{
handle->m_used++;
if (handle->m_collisionShape->getShapeType() == COMPOUND_SHAPE_PROXYTYPE)
{
btCompoundShape* childCompound = (btCompoundShape*)handle->m_collisionShape;
for (int c = 0; c < childCompound->getNumChildShapes(); c++)
{
btTransform childTrans = childCompound->getChildTransform(c);
btCollisionShape* childShape = childCompound->getChildShape(c);
btTransform tr = localInertiaFrame.inverse() * childTrans;
compound->addChildShape(tr, childShape);
}
}
else
{
btTransform childTrans;
childTrans.setIdentity();
compound->addChildShape(localInertiaFrame.inverse() * childTrans, handle->m_collisionShape);
}
}
}
m_allocatedCollisionShapes.push_back(compound);
return compound;
}
virtual int getNumAllocatedCollisionShapes() const
{
return m_allocatedCollisionShapes.size();
}
virtual class btCollisionShape* getAllocatedCollisionShape(int index)
{
return m_allocatedCollisionShapes[index];
}
virtual int getNumModels() const
{
return 1;
}
virtual void activateModel(int /*modelIndex*/)
{
}
};
btDeformableMultiBodyDynamicsWorld* PhysicsServerCommandProcessor::getDeformableWorld()
{
btDeformableMultiBodyDynamicsWorld* world = 0;
if (m_data->m_dynamicsWorld && m_data->m_dynamicsWorld->getWorldType() == BT_DEFORMABLE_MULTIBODY_DYNAMICS_WORLD)
{
world = (btDeformableMultiBodyDynamicsWorld*)m_data->m_dynamicsWorld;
}
return world;
}
btSoftMultiBodyDynamicsWorld* PhysicsServerCommandProcessor::getSoftWorld()
{
btSoftMultiBodyDynamicsWorld* world = 0;
if (m_data->m_dynamicsWorld && m_data->m_dynamicsWorld->getWorldType() == BT_SOFT_MULTIBODY_DYNAMICS_WORLD)
{
world = (btSoftMultiBodyDynamicsWorld*)m_data->m_dynamicsWorld;
}
return world;
}
void PhysicsServerCommandProcessor::createEmptyDynamicsWorld(int flags)
{
m_data->m_constraintSolverType = eConstraintSolverLCP_SI;
///collision configuration contains default setup for memory, collision setup
//m_collisionConfiguration->setConvexConvexMultipointIterations();
#ifndef SKIP_SOFT_BODY_MULTI_BODY_DYNAMICS_WORLD
m_data->m_collisionConfiguration = new btSoftBodyRigidBodyCollisionConfiguration();
#else
m_data->m_collisionConfiguration = new btDefaultCollisionConfiguration();
#endif
///use the default collision dispatcher. For parallel processing you can use a diffent dispatcher (see Extras/BulletMultiThreaded)
m_data->m_dispatcher = new btCollisionDispatcher(m_data->m_collisionConfiguration);
m_data->m_broadphaseCollisionFilterCallback = new MyOverlapFilterCallback(&m_data->m_pluginManager);
m_data->m_broadphaseCollisionFilterCallback->m_filterMode = B3_FILTER_GROUPAMASKB_OR_GROUPBMASKA;
m_data->m_pairCache = new btHashedOverlappingPairCache();
m_data->m_pairCache->setOverlapFilterCallback(m_data->m_broadphaseCollisionFilterCallback);
//int maxProxies = 32768;
if (flags & RESET_USE_SIMPLE_BROADPHASE)
{
m_data->m_broadphase = new btSimpleBroadphase(65536, m_data->m_pairCache);
}
else
{
btDbvtBroadphase* bv = new btDbvtBroadphase(m_data->m_pairCache);
bv->setVelocityPrediction(0);
m_data->m_broadphase = bv;
}
if (flags & RESET_USE_DEFORMABLE_WORLD)
{
#ifndef SKIP_DEFORMABLE_BODY
m_data->m_deformablebodySolver = new btDeformableBodySolver();
btDeformableMultiBodyConstraintSolver* solver = new btDeformableMultiBodyConstraintSolver;
m_data->m_solver = solver;
solver->setDeformableSolver(m_data->m_deformablebodySolver);
m_data->m_dynamicsWorld = new btDeformableMultiBodyDynamicsWorld(m_data->m_dispatcher, m_data->m_broadphase, solver, m_data->m_collisionConfiguration, m_data->m_deformablebodySolver);
#endif
}
if ((0 == m_data->m_dynamicsWorld) && (0 == (flags & RESET_USE_DISCRETE_DYNAMICS_WORLD)))
{
#ifndef SKIP_SOFT_BODY_MULTI_BODY_DYNAMICS_WORLD
m_data->m_solver = new btMultiBodyConstraintSolver;
m_data->m_dynamicsWorld = new btSoftMultiBodyDynamicsWorld(m_data->m_dispatcher, m_data->m_broadphase, m_data->m_solver, m_data->m_collisionConfiguration);
#else
#ifdef USE_DISCRETE_DYNAMICS_WORLD
m_data->m_solver = new btSequentialImpulseConstraintSolver;
m_data->m_dynamicsWorld = new btDiscreteDynamicsWorld(m_data->m_dispatcher, m_data->m_broadphase, m_data->m_solver, m_data->m_collisionConfiguration);
#else
m_data->m_solver = new btMultiBodyConstraintSolver;
m_data->m_dynamicsWorld = new btMultiBodyDynamicsWorld(m_data->m_dispatcher, m_data->m_broadphase, m_data->m_solver, m_data->m_collisionConfiguration);
#endif
#endif
}
if (0 == m_data->m_dynamicsWorld)
{
#ifdef USE_DISCRETE_DYNAMICS_WORLD
m_data->m_solver = new btSequentialImpulseConstraintSolver;
m_data->m_dynamicsWorld = new btDiscreteDynamicsWorld(m_data->m_dispatcher, m_data->m_broadphase, m_data->m_solver, m_data->m_collisionConfiguration);
#else
m_data->m_solver = new btMultiBodyConstraintSolver;
m_data->m_dynamicsWorld = new btMultiBodyDynamicsWorld(m_data->m_dispatcher, m_data->m_broadphase, m_data->m_solver, m_data->m_collisionConfiguration);
#endif
}
//may help improve run-time performance for many sleeping objects
m_data->m_dynamicsWorld->setForceUpdateAllAabbs(false);
//Workaround: in a VR application, where we avoid synchronizing between GFX/Physics threads, we don't want to resize this array, so pre-allocate it
m_data->m_dynamicsWorld->getCollisionObjectArray().reserve(128 * 1024);
m_data->m_remoteDebugDrawer = new SharedMemoryDebugDrawer();
m_data->m_dynamicsWorld->setGravity(btVector3(0, 0, 0));
m_data->m_dynamicsWorld->getSolverInfo().m_erp2 = 0.08;
m_data->m_dynamicsWorld->getSolverInfo().m_frictionERP = 0.2; //need to check if there are artifacts with frictionERP
m_data->m_dynamicsWorld->getSolverInfo().m_linearSlop = 0.00001;
m_data->m_dynamicsWorld->getSolverInfo().m_numIterations = 50;
m_data->m_dynamicsWorld->getSolverInfo().m_minimumSolverBatchSize = 0;
m_data->m_dynamicsWorld->getSolverInfo().m_warmstartingFactor = 0.1;
gDbvtMargin = btScalar(0);
m_data->m_dynamicsWorld->getSolverInfo().m_leastSquaresResidualThreshold = 1e-7;
if (m_data->m_guiHelper)
{
m_data->m_guiHelper->createPhysicsDebugDrawer(m_data->m_dynamicsWorld);
}
bool isPreTick = false;
m_data->m_dynamicsWorld->setInternalTickCallback(logCallback, this, isPreTick);
isPreTick = true;
m_data->m_dynamicsWorld->setInternalTickCallback(preTickCallback, this, isPreTick);
gContactAddedCallback = MyContactAddedCallback;
#ifdef B3_ENABLE_TINY_AUDIO
m_data->m_soundEngine.init(16, true);
//we don't use those callbacks (yet), experimental
// gContactDestroyedCallback = MyContactDestroyedCallback;
// gContactProcessedCallback = MyContactProcessedCallback;
// gContactStartedCallback = MyContactStartedCallback;
// gContactEndedCallback = MyContactEndedCallback;
#endif
}
void PhysicsServerCommandProcessor::deleteStateLoggers()
{
for (int i = 0; i < m_data->m_stateLoggers.size(); i++)
{
m_data->m_stateLoggers[i]->stop();
delete m_data->m_stateLoggers[i];
}
m_data->m_stateLoggers.clear();
}
void PhysicsServerCommandProcessor::deleteCachedInverseKinematicsBodies()
{
for (int i = 0; i < m_data->m_inverseKinematicsHelpers.size(); i++)
{
IKTrajectoryHelper** ikHelperPtr = m_data->m_inverseKinematicsHelpers.getAtIndex(i);
if (ikHelperPtr)
{
IKTrajectoryHelper* ikHelper = *ikHelperPtr;
delete ikHelper;
}
}
m_data->m_inverseKinematicsHelpers.clear();
}
void PhysicsServerCommandProcessor::deleteCachedInverseDynamicsBodies()
{
for (int i = 0; i < m_data->m_inverseDynamicsBodies.size(); i++)
{
btInverseDynamics::MultiBodyTree** treePtrPtr = m_data->m_inverseDynamicsBodies.getAtIndex(i);
if (treePtrPtr)
{
btInverseDynamics::MultiBodyTree* tree = *treePtrPtr;
delete tree;
}
}
m_data->m_inverseDynamicsBodies.clear();
}
void PhysicsServerCommandProcessor::deleteDynamicsWorld()
{
#ifdef B3_ENABLE_TINY_AUDIO
m_data->m_soundEngine.exit();
//gContactDestroyedCallback = 0;
//gContactProcessedCallback = 0;
//gContactStartedCallback = 0;
//gContactEndedCallback = 0;
#endif
deleteCachedInverseDynamicsBodies();
deleteCachedInverseKinematicsBodies();
deleteStateLoggers();
m_data->m_userConstraints.clear();
m_data->m_saveWorldBodyData.clear();
for (int i = 0; i < m_data->m_multiBodyJointFeedbacks.size(); i++)
{
delete m_data->m_multiBodyJointFeedbacks[i];
}
m_data->m_multiBodyJointFeedbacks.clear();
for (int i = 0; i < m_data->m_worldImporters.size(); i++)
{
m_data->m_worldImporters[i]->deleteAllData();
delete m_data->m_worldImporters[i];
}
m_data->m_worldImporters.clear();
#ifdef ENABLE_LINK_MAPPER
for (int i = 0; i < m_data->m_urdfLinkNameMapper.size(); i++)
{
delete m_data->m_urdfLinkNameMapper[i];
}
m_data->m_urdfLinkNameMapper.clear();
#endif //ENABLE_LINK_MAPPER
for (int i = 0; i < m_data->m_strings.size(); i++)
{
delete m_data->m_strings[i];
}
m_data->m_strings.clear();
btAlignedObjectArray<btTypedConstraint*> constraints;
btAlignedObjectArray<btMultiBodyConstraint*> mbconstraints;
if (m_data->m_dynamicsWorld)
{
int i;
for (i = m_data->m_dynamicsWorld->getNumConstraints() - 1; i >= 0; i--)
{
btTypedConstraint* constraint = m_data->m_dynamicsWorld->getConstraint(i);
constraints.push_back(constraint);
m_data->m_dynamicsWorld->removeConstraint(constraint);
}
#ifndef USE_DISCRETE_DYNAMICS_WORLD
for (i = m_data->m_dynamicsWorld->getNumMultiBodyConstraints() - 1; i >= 0; i--)
{
btMultiBodyConstraint* mbconstraint = m_data->m_dynamicsWorld->getMultiBodyConstraint(i);
mbconstraints.push_back(mbconstraint);
m_data->m_dynamicsWorld->removeMultiBodyConstraint(mbconstraint);
}
#endif
for (i = m_data->m_dynamicsWorld->getNumCollisionObjects() - 1; i >= 0; i--)
{
btCollisionObject* obj = m_data->m_dynamicsWorld->getCollisionObjectArray()[i];
btRigidBody* body = btRigidBody::upcast(obj);
if (body && body->getMotionState())
{
delete body->getMotionState();
}
m_data->m_dynamicsWorld->removeCollisionObject(obj);
delete obj;
}
#ifndef USE_DISCRETE_DYNAMICS_WORLD
for (i = m_data->m_dynamicsWorld->getNumMultibodies() - 1; i >= 0; i--)
{
btMultiBody* mb = m_data->m_dynamicsWorld->getMultiBody(i);
m_data->m_dynamicsWorld->removeMultiBody(mb);
delete mb;
}
#endif
#ifndef SKIP_DEFORMABLE_BODY
for (int j = 0; j < m_data->m_lf.size(); j++)
{
btDeformableLagrangianForce* force = m_data->m_lf[j];
delete force;
}
m_data->m_lf.clear();
#endif
#ifndef SKIP_SOFT_BODY_MULTI_BODY_DYNAMICS_WORLD
{
btSoftMultiBodyDynamicsWorld* softWorld = getSoftWorld();
if (softWorld)
{
for (i = softWorld->getSoftBodyArray().size() - 1; i >= 0; i--)
{
btSoftBody* sb = softWorld->getSoftBodyArray()[i];
softWorld->removeSoftBody(sb);
delete sb;
}
}
}
#endif //SKIP_SOFT_BODY_MULTI_BODY_DYNAMICS_WORLD
#ifndef SKIP_DEFORMABLE_BODY
{
btDeformableMultiBodyDynamicsWorld* deformWorld = getDeformableWorld();
if (deformWorld)
{
for (i = deformWorld->getSoftBodyArray().size() - 1; i >= 0; i--)
{
btSoftBody* sb = deformWorld->getSoftBodyArray()[i];
deformWorld->removeSoftBody(sb);
delete sb;
}
}
}
#endif
}
for (int i = 0; i < constraints.size(); i++)
{
delete constraints[i];
}
constraints.clear();
for (int i = 0; i < mbconstraints.size(); i++)
{
delete mbconstraints[i];
}
mbconstraints.clear();
//delete collision shapes
for (int j = 0; j < m_data->m_collisionShapes.size(); j++)
{
btCollisionShape* shape = m_data->m_collisionShapes[j];
//check for internal edge utility, delete memory
if (shape->getShapeType() == TRIANGLE_MESH_SHAPE_PROXYTYPE)
{
btBvhTriangleMeshShape* trimesh = (btBvhTriangleMeshShape*)shape;
if (trimesh->getTriangleInfoMap())
{
delete trimesh->getTriangleInfoMap();
}
}
if (shape->getShapeType() == TERRAIN_SHAPE_PROXYTYPE)
{
btHeightfieldTerrainShape* terrain = (btHeightfieldTerrainShape*)shape;
if (terrain->getTriangleInfoMap())
{
delete terrain->getTriangleInfoMap();
}
}
delete shape;
}
for (int j = 0; j < m_data->m_heightfieldDatas.size(); j++)
{
delete[] m_data->m_heightfieldDatas[j];
}
for (int j = 0; j < m_data->m_meshInterfaces.size(); j++)
{
delete m_data->m_meshInterfaces[j];
}
if (m_data->m_guiHelper)
{
for (int j = 0; j < m_data->m_allocatedTextures.size(); j++)
{
int texId = m_data->m_allocatedTextures[j];
m_data->m_guiHelper->removeTexture(texId);
}
}
for (int i = 0; i < m_data->m_allocatedTexturesRequireFree.size(); i++)
{
//we can't free them right away, due to caching based on memory pointer in PhysicsServerExample
free(m_data->m_allocatedTexturesRequireFree[i]);
}
m_data->m_heightfieldDatas.clear();
m_data->m_allocatedTextures.clear();
m_data->m_allocatedTexturesRequireFree.clear();
m_data->m_meshInterfaces.clear();
m_data->m_collisionShapes.clear();
m_data->m_bulletCollisionShape2UrdfCollision.clear();
m_data->m_graphicsIndexToSegmentationMask.clear();
delete m_data->m_dynamicsWorld;
m_data->m_dynamicsWorld = 0;
delete m_data->m_remoteDebugDrawer;
m_data->m_remoteDebugDrawer = 0;
#if !defined(SKIP_DEFORMABLE_BODY) && !defined(SKIP_SOFT_BODY_MULTI_BODY_DYNAMICS_WORLD)
delete m_data->m_deformablebodySolver;
m_data->m_deformablebodySolver = 0;
#endif
delete m_data->m_solver;
m_data->m_solver = 0;
delete m_data->m_broadphase;
m_data->m_broadphase = 0;
delete m_data->m_pairCache;
m_data->m_pairCache = 0;
delete m_data->m_broadphaseCollisionFilterCallback;
m_data->m_broadphaseCollisionFilterCallback = 0;
delete m_data->m_dispatcher;
m_data->m_dispatcher = 0;
delete m_data->m_collisionConfiguration;
m_data->m_collisionConfiguration = 0;
m_data->m_userConstraintUIDGenerator = 1;
#ifdef STATIC_LINK_SPD_PLUGIN
for (int i = 0; i < m_data->m_rbdModels.size(); i++)
{
delete *(m_data->m_rbdModels.getAtIndex(i));
}
m_data->m_rbdModels.clear();
#endif //STATIC_LINK_SPD_PLUGIN
}
bool PhysicsServerCommandProcessor::supportsJointMotor(btMultiBody* mb, int mbLinkIndex)
{
bool canHaveMotor = (mb->getLink(mbLinkIndex).m_jointType == btMultibodyLink::eRevolute || mb->getLink(mbLinkIndex).m_jointType == btMultibodyLink::ePrismatic);
return canHaveMotor;
}
//for testing, create joint motors for revolute and prismatic joints
void PhysicsServerCommandProcessor::createJointMotors(btMultiBody* mb)
{
int numLinks = mb->getNumLinks();
for (int i = 0; i < numLinks; i++)
{
int mbLinkIndex = i;
float maxMotorImpulse = 1.f;
if (supportsJointMotor(mb, mbLinkIndex))
{
int dof = 0;
btScalar desiredVelocity = 0.f;
btMultiBodyJointMotor* motor = new btMultiBodyJointMotor(mb, mbLinkIndex, dof, desiredVelocity, maxMotorImpulse);
motor->setPositionTarget(0, 0);
motor->setVelocityTarget(0, 1);
//motor->setRhsClamp(gRhsClamp);
//motor->setMaxAppliedImpulse(0);
mb->getLink(mbLinkIndex).m_userPtr = motor;
#ifndef USE_DISCRETE_DYNAMICS_WORLD
m_data->m_dynamicsWorld->addMultiBodyConstraint(motor);
#endif
motor->finalizeMultiDof();
}
if (mb->getLink(mbLinkIndex).m_jointType == btMultibodyLink::eSpherical)
{
btMultiBodySphericalJointMotor* motor = new btMultiBodySphericalJointMotor(mb, mbLinkIndex, 1000 * maxMotorImpulse);
mb->getLink(mbLinkIndex).m_userPtr = motor;
#ifndef USE_DISCRETE_DYNAMICS_WORLD
m_data->m_dynamicsWorld->addMultiBodyConstraint(motor);
#endif
motor->finalizeMultiDof();
}
}
}
int PhysicsServerCommandProcessor::addUserData(int bodyUniqueId, int linkIndex, int visualShapeIndex, const char* key, const char* valueBytes, int valueLength, int valueType)
{
InternalBodyData* body = m_data->m_bodyHandles.getHandle(bodyUniqueId);
if (!body)
{
return -1;
}
SharedMemoryUserDataHashKey userDataIdentifier(key, bodyUniqueId, linkIndex, visualShapeIndex);
int* userDataHandlePtr = m_data->m_userDataHandleLookup.find(userDataIdentifier);
int userDataHandle = userDataHandlePtr ? *userDataHandlePtr : m_data->m_userDataHandles.allocHandle();
SharedMemoryUserData* userData = m_data->m_userDataHandles.getHandle(userDataHandle);
if (!userData)
{
return -1;
}
if (!userDataHandlePtr)
{
userData->m_key = key;
userData->m_bodyUniqueId = bodyUniqueId;
userData->m_linkIndex = linkIndex;
userData->m_visualShapeIndex = visualShapeIndex;
m_data->m_userDataHandleLookup.insert(userDataIdentifier, userDataHandle);
body->m_userDataHandles.push_back(userDataHandle);
}
userData->replaceValue(valueBytes, valueLength, valueType);
return userDataHandle;
}
void PhysicsServerCommandProcessor::addUserData(const btHashMap<btHashString, std::string>& user_data_entries, int bodyUniqueId, int linkIndex, int visualShapeIndex)
{
for (int i = 0; i < user_data_entries.size(); ++i)
{
const std::string key = user_data_entries.getKeyAtIndex(i).m_string1;
const std::string* value = user_data_entries.getAtIndex(i);
if (value)
{
addUserData(bodyUniqueId, linkIndex, visualShapeIndex, key.c_str(), value->c_str(),
value->size() + 1, USER_DATA_VALUE_TYPE_STRING);
}
}
}
bool PhysicsServerCommandProcessor::processImportedObjects(const char* fileName, char* bufferServerToClient, int bufferSizeInBytes, bool useMultiBody, int flags, URDFImporterInterface& u2b)
{
bool loadOk = true;
btTransform rootTrans;
rootTrans.setIdentity();
if (m_data->m_verboseOutput)
{
b3Printf("loaded %s OK!", fileName);
}
SaveWorldObjectData sd;
sd.m_fileName = fileName;
for (int m = 0; m < u2b.getNumModels(); m++)
{
u2b.activateModel(m);
btMultiBody* mb = 0;
btRigidBody* rb = 0;
//get a body index
int bodyUniqueId = m_data->m_bodyHandles.allocHandle();
InternalBodyHandle* bodyHandle = m_data->m_bodyHandles.getHandle(bodyUniqueId);
sd.m_bodyUniqueIds.push_back(bodyUniqueId);
u2b.setBodyUniqueId(bodyUniqueId);
{
btScalar mass = 0;
bodyHandle->m_rootLocalInertialFrame.setIdentity();
bodyHandle->m_bodyName = u2b.getBodyName();
btVector3 localInertiaDiagonal(0, 0, 0);
int urdfLinkIndex = u2b.getRootLinkIndex();
u2b.getMassAndInertia2(urdfLinkIndex, mass, localInertiaDiagonal, bodyHandle->m_rootLocalInertialFrame, flags);
}
//todo: move these internal API called inside the 'ConvertURDF2Bullet' call, hidden from the user
//int rootLinkIndex = u2b.getRootLinkIndex();
//b3Printf("urdf root link index = %d\n",rootLinkIndex);
MyMultiBodyCreator creation(m_data->m_guiHelper);
u2b.getRootTransformInWorld(rootTrans);
//CUF_RESERVED is a temporary flag, for backward compatibility purposes
flags |= CUF_RESERVED;
if (flags & CUF_ENABLE_CACHED_GRAPHICS_SHAPES)
{
{
UrdfVisualShapeCache* tmpPtr = m_data->m_cachedVUrdfisualShapes[fileName];
if (tmpPtr == 0)
{
m_data->m_cachedVUrdfisualShapes.insert(fileName, UrdfVisualShapeCache());
}
}
UrdfVisualShapeCache* cachedVisualShapesPtr = m_data->m_cachedVUrdfisualShapes[fileName];
ConvertURDF2Bullet(u2b, creation, rootTrans, m_data->m_dynamicsWorld, useMultiBody, u2b.getPathPrefix(), flags, cachedVisualShapesPtr);
}
else
{
ConvertURDF2Bullet(u2b, creation, rootTrans, m_data->m_dynamicsWorld, useMultiBody, u2b.getPathPrefix(), flags);
}
mb = creation.getBulletMultiBody();
rb = creation.getRigidBody();
if (rb)
rb->setUserIndex2(bodyUniqueId);
if (mb)
mb->setUserIndex2(bodyUniqueId);
if (mb)
{
bodyHandle->m_multiBody = mb;
m_data->m_sdfRecentLoadedBodies.push_back(bodyUniqueId);
int segmentationMask = bodyUniqueId;
{
int graphicsIndex = -1;
if (mb->getBaseCollider())
{
graphicsIndex = mb->getBaseCollider()->getUserIndex();
}
if (graphicsIndex >= 0)
{
if (m_data->m_graphicsIndexToSegmentationMask.size() < (graphicsIndex + 1))
{
m_data->m_graphicsIndexToSegmentationMask.resize(graphicsIndex + 1);
}
m_data->m_graphicsIndexToSegmentationMask[graphicsIndex] = segmentationMask;
}
}
createJointMotors(mb);
#ifdef B3_ENABLE_TINY_AUDIO
{
SDFAudioSource audioSource;
int urdfRootLink = u2b.getRootLinkIndex(); //LinkIndex = creation.m_mb2urdfLink[-1];
if (u2b.getLinkAudioSource(urdfRootLink, audioSource))
{
int flags = mb->getBaseCollider()->getCollisionFlags();
mb->getBaseCollider()->setCollisionFlags(flags | btCollisionObject::CF_HAS_COLLISION_SOUND_TRIGGER);
audioSource.m_userIndex = m_data->m_soundEngine.loadWavFile(audioSource.m_uri.c_str());
if (audioSource.m_userIndex >= 0)
{
bodyHandle->m_audioSources.insert(-1, audioSource);
}
}
}
#endif
//disable serialization of the collision objects (they are too big, and the client likely doesn't need them);
bodyHandle->m_linkLocalInertialFrames.reserve(mb->getNumLinks());
for (int i = 0; i < mb->getNumLinks(); i++)
{
//disable serialization of the collision objects
int urdfLinkIndex = creation.m_mb2urdfLink[i];
btScalar mass;
btVector3 localInertiaDiagonal(0, 0, 0);
btTransform localInertialFrame;
u2b.getMassAndInertia2(urdfLinkIndex, mass, localInertiaDiagonal, localInertialFrame, flags);
bodyHandle->m_linkLocalInertialFrames.push_back(localInertialFrame);
std::string* linkName = new std::string(u2b.getLinkName(urdfLinkIndex).c_str());
m_data->m_strings.push_back(linkName);
mb->getLink(i).m_linkName = linkName->c_str();
{
int graphicsIndex = -1;
if (mb->getLinkCollider(i))
{
graphicsIndex = mb->getLinkCollider(i)->getUserIndex();
}
if (graphicsIndex >= 0)
{
int linkIndex = i;
if (m_data->m_graphicsIndexToSegmentationMask.size() < (graphicsIndex + 1))
{
m_data->m_graphicsIndexToSegmentationMask.resize(graphicsIndex + 1);
}
int segmentationMask = bodyUniqueId + ((linkIndex + 1) << 24);
m_data->m_graphicsIndexToSegmentationMask[graphicsIndex] = segmentationMask;
}
}
std::string* jointName = new std::string(u2b.getJointName(urdfLinkIndex).c_str());
m_data->m_strings.push_back(jointName);
mb->getLink(i).m_jointName = jointName->c_str();
#ifdef B3_ENABLE_TINY_AUDIO
{
SDFAudioSource audioSource;
int urdfLinkIndex = creation.m_mb2urdfLink[i];
if (u2b.getLinkAudioSource(urdfLinkIndex, audioSource))
{
int flags = mb->getLink(i).m_collider->getCollisionFlags();
mb->getLink(i).m_collider->setCollisionFlags(flags | btCollisionObject::CF_HAS_COLLISION_SOUND_TRIGGER);
audioSource.m_userIndex = m_data->m_soundEngine.loadWavFile(audioSource.m_uri.c_str());
if (audioSource.m_userIndex >= 0)
{
bodyHandle->m_audioSources.insert(i, audioSource);
}
}
}
#endif
}
std::string* baseName = new std::string(u2b.getLinkName(u2b.getRootLinkIndex()));
m_data->m_strings.push_back(baseName);
mb->setBaseName(baseName->c_str());
#if 0
btAlignedObjectArray<char> urdf;
mb->dumpUrdf(urdf);
FILE* f = fopen("e:/pybullet.urdf", "w");
if (f)
{
fwrite(&urdf[0], urdf.size(), 1, f);
fclose(f);
}
#endif
}
else
{
int segmentationMask = bodyUniqueId;
if (rb)
{
int graphicsIndex = -1;
{
graphicsIndex = rb->getUserIndex();
}
if (graphicsIndex >= 0)
{
if (m_data->m_graphicsIndexToSegmentationMask.size() < (graphicsIndex + 1))
{
m_data->m_graphicsIndexToSegmentationMask.resize(graphicsIndex + 1);
}
m_data->m_graphicsIndexToSegmentationMask[graphicsIndex] = segmentationMask;
}
}
//b3Warning("No multibody loaded from URDF. Could add btRigidBody+btTypedConstraint solution later.");
bodyHandle->m_rigidBody = rb;
rb->setUserIndex2(bodyUniqueId);
m_data->m_sdfRecentLoadedBodies.push_back(bodyUniqueId);
std::string* baseName = new std::string(u2b.getLinkName(u2b.getRootLinkIndex()));
m_data->m_strings.push_back(baseName);
bodyHandle->m_bodyName = *baseName;
int numJoints = creation.getNum6DofConstraints();
bodyHandle->m_rigidBodyJoints.reserve(numJoints);
bodyHandle->m_rigidBodyJointNames.reserve(numJoints);
bodyHandle->m_rigidBodyLinkNames.reserve(numJoints);
for (int i = 0; i < numJoints; i++)
{
int urdfLinkIndex = creation.m_mb2urdfLink[i];
btGeneric6DofSpring2Constraint* con = creation.get6DofConstraint(i);
std::string* linkName = new std::string(u2b.getLinkName(urdfLinkIndex).c_str());
m_data->m_strings.push_back(linkName);
std::string* jointName = new std::string(u2b.getJointName(urdfLinkIndex).c_str());
m_data->m_strings.push_back(jointName);
bodyHandle->m_rigidBodyJointNames.push_back(*jointName);
bodyHandle->m_rigidBodyLinkNames.push_back(*linkName);
bodyHandle->m_rigidBodyJoints.push_back(con);
}
}
{
if (m_data->m_pluginManager.getRenderInterface())
{
int currentOpenGLTextureIndex = 0;
int totalNumVisualShapes = m_data->m_pluginManager.getRenderInterface()->getNumVisualShapes(bodyUniqueId);
for (int shapeIndex = 0; shapeIndex < totalNumVisualShapes; shapeIndex++)
{
b3VisualShapeData tmpShape;
int success = m_data->m_pluginManager.getRenderInterface()->getVisualShapesData(bodyUniqueId, shapeIndex, &tmpShape);
if (success)
{
if (tmpShape.m_tinyRendererTextureId >= 0)
{
int openglTextureUniqueId = -1;
//find companion opengl texture unique id and create a 'textureUid'
if (currentOpenGLTextureIndex < u2b.getNumAllocatedTextures())
{
openglTextureUniqueId = u2b.getAllocatedTexture(currentOpenGLTextureIndex++);
}
//if (openglTextureUniqueId>=0)
{
int texHandle = m_data->m_textureHandles.allocHandle();
InternalTextureHandle* texH = m_data->m_textureHandles.getHandle(texHandle);
if (texH)
{
texH->m_tinyRendererTextureId = tmpShape.m_tinyRendererTextureId;
texH->m_openglTextureId = openglTextureUniqueId;
}
}
}
}
}
}
}
// Because the link order between UrdfModel and MultiBody may be different,
// create a mapping from link name to link index in order to apply the user
// data to the correct link in the MultiBody.
btHashMap<btHashString, int> linkNameToIndexMap;
if (bodyHandle->m_multiBody)
{
btMultiBody* mb = bodyHandle->m_multiBody;
linkNameToIndexMap.insert(mb->getBaseName(), -1);
for (int linkIndex = 0; linkIndex < mb->getNumLinks(); ++linkIndex)
{
linkNameToIndexMap.insert(mb->getLink(linkIndex).m_linkName, linkIndex);
}
}
const UrdfModel* urdfModel = u2b.getUrdfModel();
if (urdfModel)
{
addUserData(urdfModel->m_userData, bodyUniqueId);
for (int i = 0; i < urdfModel->m_links.size(); ++i)
{
const UrdfLink* link = *urdfModel->m_links.getAtIndex(i);
int* linkIndex = linkNameToIndexMap.find(link->m_name.c_str());
if (linkIndex)
{
addUserData(link->m_userData, bodyUniqueId, *linkIndex);
for (int visualShapeIndex = 0; visualShapeIndex < link->m_visualArray.size(); ++visualShapeIndex)
{
addUserData(link->m_visualArray.at(visualShapeIndex).m_userData, bodyUniqueId, *linkIndex, visualShapeIndex);
}
}
}
}
b3Notification notification;
notification.m_notificationType = BODY_ADDED;
notification.m_bodyArgs.m_bodyUniqueId = bodyUniqueId;
m_data->m_pluginManager.addNotification(notification);
}
for (int i = 0; i < u2b.getNumAllocatedTextures(); i++)
{
int texId = u2b.getAllocatedTexture(i);
m_data->m_allocatedTextures.push_back(texId);
}
/*
int texHandle = m_data->m_textureHandles.allocHandle();
InternalTextureHandle* texH = m_data->m_textureHandles.getHandle(texHandle);
if(texH)
{
texH->m_tinyRendererTextureId = -1;
texH->m_openglTextureId = -1;
*/
for (int i = 0; i < u2b.getNumAllocatedMeshInterfaces(); i++)
{
m_data->m_meshInterfaces.push_back(u2b.getAllocatedMeshInterface(i));
}
for (int i = 0; i < u2b.getNumAllocatedCollisionShapes(); i++)
{
btCollisionShape* shape = u2b.getAllocatedCollisionShape(i);
m_data->m_collisionShapes.push_back(shape);
UrdfCollision urdfCollision;
if (u2b.getUrdfFromCollisionShape(shape, urdfCollision))
{
m_data->m_bulletCollisionShape2UrdfCollision.insert(shape, urdfCollision);
}
if (shape->getShapeType() == COMPOUND_SHAPE_PROXYTYPE)
{
btCompoundShape* compound = (btCompoundShape*)shape;
for (int c = 0; c < compound->getNumChildShapes(); c++)
{
btCollisionShape* childShape = compound->getChildShape(c);
if (u2b.getUrdfFromCollisionShape(childShape, urdfCollision))
{
m_data->m_bulletCollisionShape2UrdfCollision.insert(childShape, urdfCollision);
}
}
}
}
m_data->m_saveWorldBodyData.push_back(sd);
syncPhysicsToGraphics2();
return loadOk;
}
struct MyMJCFLogger2 : public MJCFErrorLogger
{
virtual void reportError(const char* error)
{
b3Error(error);
}
virtual void reportWarning(const char* warning)
{
b3Warning(warning);
}
virtual void printMessage(const char* msg)
{
b3Printf(msg);
}
};
bool PhysicsServerCommandProcessor::loadMjcf(const char* fileName, char* bufferServerToClient, int bufferSizeInBytes, bool useMultiBody, int flags)
{
btAssert(m_data->m_dynamicsWorld);
if (!m_data->m_dynamicsWorld)
{
b3Error("loadSdf: No valid m_dynamicsWorld");
return false;
}
m_data->m_sdfRecentLoadedBodies.clear();
CommonFileIOInterface* fileIO = m_data->m_pluginManager.getFileIOInterface();
BulletMJCFImporter u2b(m_data->m_guiHelper, m_data->m_pluginManager.getRenderInterface(), fileIO, flags);
bool useFixedBase = false;
MyMJCFLogger2 logger;
bool loadOk = u2b.loadMJCF(fileName, &logger, useFixedBase);
if (loadOk)
{
processImportedObjects(fileName, bufferServerToClient, bufferSizeInBytes, useMultiBody, flags, u2b);
}
return loadOk;
}
bool PhysicsServerCommandProcessor::loadSdf(const char* fileName, char* bufferServerToClient, int bufferSizeInBytes, bool useMultiBody, int flags, btScalar globalScaling)
{
btAssert(m_data->m_dynamicsWorld);
if (!m_data->m_dynamicsWorld)
{
b3Error("loadSdf: No valid m_dynamicsWorld");
return false;
}
m_data->m_sdfRecentLoadedBodies.clear();
CommonFileIOInterface* fileIO = m_data->m_pluginManager.getFileIOInterface();
BulletURDFImporter u2b(m_data->m_guiHelper, m_data->m_pluginManager.getRenderInterface(), fileIO, globalScaling, flags);
u2b.setEnableTinyRenderer(m_data->m_enableTinyRenderer);
bool forceFixedBase = false;
bool loadOk = u2b.loadSDF(fileName, forceFixedBase);
if (loadOk)
{
processImportedObjects(fileName, bufferServerToClient, bufferSizeInBytes, useMultiBody, flags, u2b);
}
return loadOk;
}
bool PhysicsServerCommandProcessor::loadUrdf(const char* fileName, const btVector3& pos, const btQuaternion& orn,
bool useMultiBody, bool useFixedBase, int* bodyUniqueIdPtr, char* bufferServerToClient, int bufferSizeInBytes, int orgFlags, btScalar globalScaling)
{
//clear the LOAD_SDF_FILE=1 bit, which is reserved for internal use of loadSDF command.
int flags = orgFlags & ~1;
m_data->m_sdfRecentLoadedBodies.clear();
*bodyUniqueIdPtr = -1;
BT_PROFILE("loadURDF");
btAssert(m_data->m_dynamicsWorld);
if (!m_data->m_dynamicsWorld)
{
b3Error("loadUrdf: No valid m_dynamicsWorld");
return false;
}
CommonFileIOInterface* fileIO = m_data->m_pluginManager.getFileIOInterface();
BulletURDFImporter u2b(m_data->m_guiHelper, m_data->m_pluginManager.getRenderInterface(), fileIO, globalScaling, flags);
u2b.setEnableTinyRenderer(m_data->m_enableTinyRenderer);
bool loadOk = u2b.loadURDF(fileName, useFixedBase);
if (loadOk)
{
btTransform rootTrans;
rootTrans.setOrigin(pos);
rootTrans.setRotation(orn);
u2b.setRootTransformInWorld(rootTrans);
if (!(u2b.getDeformableModel().m_visualFileName.empty()))
{
bool use_self_collision = false;
use_self_collision = (flags & CUF_USE_SELF_COLLISION);
bool ok = processDeformable(u2b.getDeformableModel(), pos, orn, bodyUniqueIdPtr, bufferServerToClient, bufferSizeInBytes, globalScaling, use_self_collision);
if (ok)
{
const UrdfModel* urdfModel = u2b.getUrdfModel();
if (urdfModel)
{
addUserData(urdfModel->m_userData, *bodyUniqueIdPtr);
}
return true;
}
else
{
return false;
}
}
bool ok = processImportedObjects(fileName, bufferServerToClient, bufferSizeInBytes, useMultiBody, flags, u2b);
if (ok)
{
if (m_data->m_sdfRecentLoadedBodies.size() == 1)
{
*bodyUniqueIdPtr = m_data->m_sdfRecentLoadedBodies[0];
}
m_data->m_sdfRecentLoadedBodies.clear();
}
return ok;
}
return false;
}
void PhysicsServerCommandProcessor::replayLogCommand(char* bufferServerToClient, int bufferSizeInBytes)
{
if (m_data->m_logPlayback)
{
SharedMemoryCommand clientCmd;
SharedMemoryStatus serverStatus;
bool hasCommand = m_data->m_logPlayback->processNextCommand(&clientCmd);
if (hasCommand)
{
processCommand(clientCmd, serverStatus, bufferServerToClient, bufferSizeInBytes);
}
}
}
int PhysicsServerCommandProcessor::createBodyInfoStream(int bodyUniqueId, char* bufferServerToClient, int bufferSizeInBytes)
{
int streamSizeInBytes = 0;
//serialize the btMultiBody and send the data to the client. This is one way to get the link/joint names across the (shared memory) wire
InternalBodyHandle* bodyHandle = m_data->m_bodyHandles.getHandle(bodyUniqueId);
if (!bodyHandle) return 0;
if (bodyHandle->m_multiBody)
{
btMultiBody* mb = bodyHandle->m_multiBody;
btDefaultSerializer ser(bufferSizeInBytes, (unsigned char*)bufferServerToClient);
ser.startSerialization();
//disable serialization of the collision objects (they are too big, and the client likely doesn't need them);
ser.m_skipPointers.insert(mb->getBaseCollider(), 0);
if (mb->getBaseName())
{
ser.registerNameForPointer(mb->getBaseName(), mb->getBaseName());
}
bodyHandle->m_linkLocalInertialFrames.reserve(mb->getNumLinks());
for (int i = 0; i < mb->getNumLinks(); i++)
{
//disable serialization of the collision objects
ser.m_skipPointers.insert(mb->getLink(i).m_collider, 0);
ser.registerNameForPointer(mb->getLink(i).m_linkName, mb->getLink(i).m_linkName);
ser.registerNameForPointer(mb->getLink(i).m_jointName, mb->getLink(i).m_jointName);
}
ser.registerNameForPointer(mb->getBaseName(), mb->getBaseName());
int len = mb->calculateSerializeBufferSize();
btChunk* chunk = ser.allocate(len, 1);
const char* structType = mb->serialize(chunk->m_oldPtr, &ser);
ser.finalizeChunk(chunk, structType, BT_MULTIBODY_CODE, mb);
streamSizeInBytes = ser.getCurrentBufferSize();
}
else if (bodyHandle->m_rigidBody)
{
btRigidBody* rb = bodyHandle->m_rigidBody;
btDefaultSerializer ser(bufferSizeInBytes, (unsigned char*)bufferServerToClient);
ser.startSerialization();
ser.registerNameForPointer(bodyHandle->m_rigidBody, bodyHandle->m_bodyName.c_str());
//disable serialization of the collision objects (they are too big, and the client likely doesn't need them);
for (int i = 0; i < bodyHandle->m_rigidBodyJoints.size(); i++)
{
const btGeneric6DofSpring2Constraint* con = bodyHandle->m_rigidBodyJoints.at(i);
ser.registerNameForPointer(con, bodyHandle->m_rigidBodyJointNames[i].c_str());
ser.registerNameForPointer(&con->getRigidBodyB(), bodyHandle->m_rigidBodyLinkNames[i].c_str());
const btRigidBody& bodyA = con->getRigidBodyA();
int len = con->calculateSerializeBufferSize();
btChunk* chunk = ser.allocate(len, 1);
const char* structType = con->serialize(chunk->m_oldPtr, &ser);
ser.finalizeChunk(chunk, structType, BT_CONSTRAINT_CODE, (void*)con);
}
streamSizeInBytes = ser.getCurrentBufferSize();
}
#ifndef SKIP_SOFT_BODY_MULTI_BODY_DYNAMICS_WORLD
else if (bodyHandle->m_softBody)
{
//minimum serialization, registerNameForPointer
btSoftBody* sb = bodyHandle->m_softBody;
btDefaultSerializer ser(bufferSizeInBytes, (unsigned char*)bufferServerToClient);
ser.startSerialization();
int len = sb->calculateSerializeBufferSize();
btChunk* chunk = ser.allocate(len, 1);
const char* structType = sb->serialize(chunk->m_oldPtr, &ser);
ser.finalizeChunk(chunk, structType, BT_SOFTBODY_CODE, sb);
streamSizeInBytes = ser.getCurrentBufferSize();
}
#endif
return streamSizeInBytes;
}
bool PhysicsServerCommandProcessor::processStateLoggingCommand(const struct SharedMemoryCommand& clientCmd, struct SharedMemoryStatus& serverStatusOut, char* bufferServerToClient, int bufferSizeInBytes)
{
BT_PROFILE("CMD_STATE_LOGGING");
serverStatusOut.m_type = CMD_STATE_LOGGING_FAILED;
bool hasStatus = true;
if (clientCmd.m_updateFlags & STATE_LOGGING_START_LOG)
{
if (clientCmd.m_stateLoggingArguments.m_logType == STATE_LOGGING_ALL_COMMANDS)
{
if (m_data->m_commandLogger == 0)
{
enableCommandLogging(true, clientCmd.m_stateLoggingArguments.m_fileName);
serverStatusOut.m_type = CMD_STATE_LOGGING_START_COMPLETED;
int loggerUid = m_data->m_stateLoggersUniqueId++;
m_data->m_commandLoggingUid = loggerUid;
serverStatusOut.m_stateLoggingResultArgs.m_loggingUniqueId = loggerUid;
}
}
if (clientCmd.m_stateLoggingArguments.m_logType == STATE_REPLAY_ALL_COMMANDS)
{
if (m_data->m_logPlayback == 0)
{
replayFromLogFile(clientCmd.m_stateLoggingArguments.m_fileName);
serverStatusOut.m_type = CMD_STATE_LOGGING_START_COMPLETED;
int loggerUid = m_data->m_stateLoggersUniqueId++;
m_data->m_logPlaybackUid = loggerUid;
serverStatusOut.m_stateLoggingResultArgs.m_loggingUniqueId = loggerUid;
}
}
if (clientCmd.m_stateLoggingArguments.m_logType == STATE_LOGGING_PROFILE_TIMINGS)
{
if (m_data->m_profileTimingLoggingUid < 0)
{
b3ChromeUtilsStartTimings();
m_data->m_profileTimingFileName = clientCmd.m_stateLoggingArguments.m_fileName;
int loggerUid = m_data->m_stateLoggersUniqueId++;
serverStatusOut.m_type = CMD_STATE_LOGGING_START_COMPLETED;
serverStatusOut.m_stateLoggingResultArgs.m_loggingUniqueId = loggerUid;
m_data->m_profileTimingLoggingUid = loggerUid;
}
}
if (clientCmd.m_stateLoggingArguments.m_logType == STATE_LOGGING_VIDEO_MP4)
{
//if (clientCmd.m_stateLoggingArguments.m_fileName)
{
int loggerUid = m_data->m_stateLoggersUniqueId++;
VideoMP4Loggger* logger = new VideoMP4Loggger(loggerUid, clientCmd.m_stateLoggingArguments.m_fileName, this->m_data->m_guiHelper);
m_data->m_stateLoggers.push_back(logger);
serverStatusOut.m_type = CMD_STATE_LOGGING_START_COMPLETED;
serverStatusOut.m_stateLoggingResultArgs.m_loggingUniqueId = loggerUid;
}
}
if (clientCmd.m_stateLoggingArguments.m_logType == STATE_LOGGING_MINITAUR)
{
std::string fileName = clientCmd.m_stateLoggingArguments.m_fileName;
//either provide the minitaur by object unique Id, or search for first multibody with 8 motors...
if ((clientCmd.m_updateFlags & STATE_LOGGING_FILTER_OBJECT_UNIQUE_ID) && (clientCmd.m_stateLoggingArguments.m_numBodyUniqueIds > 0))
{
int bodyUniqueId = clientCmd.m_stateLoggingArguments.m_bodyUniqueIds[0];
InternalBodyData* body = m_data->m_bodyHandles.getHandle(bodyUniqueId);
if (body)
{
if (body->m_multiBody)
{
btAlignedObjectArray<std::string> motorNames;
motorNames.push_back("motor_front_leftR_joint");
motorNames.push_back("motor_front_leftL_joint");
motorNames.push_back("motor_back_leftR_joint");
motorNames.push_back("motor_back_leftL_joint");
motorNames.push_back("motor_front_rightL_joint");
motorNames.push_back("motor_front_rightR_joint");
motorNames.push_back("motor_back_rightL_joint");
motorNames.push_back("motor_back_rightR_joint");
btAlignedObjectArray<int> motorIdList;
for (int m = 0; m < motorNames.size(); m++)
{
for (int i = 0; i < body->m_multiBody->getNumLinks(); i++)
{
std::string jointName;
if (body->m_multiBody->getLink(i).m_jointName)
{
jointName = body->m_multiBody->getLink(i).m_jointName;
}
if (motorNames[m] == jointName)
{
motorIdList.push_back(i);
}
}
}
if (motorIdList.size() == 8)
{
int loggerUid = m_data->m_stateLoggersUniqueId++;
MinitaurStateLogger* logger = new MinitaurStateLogger(loggerUid, fileName, body->m_multiBody, motorIdList);
m_data->m_stateLoggers.push_back(logger);
serverStatusOut.m_type = CMD_STATE_LOGGING_START_COMPLETED;
serverStatusOut.m_stateLoggingResultArgs.m_loggingUniqueId = loggerUid;
}
}
}
}
}
#ifndef USE_DISCRETE_DYNAMICS_WORLD
if (clientCmd.m_stateLoggingArguments.m_logType == STATE_LOGGING_GENERIC_ROBOT)
{
std::string fileName = clientCmd.m_stateLoggingArguments.m_fileName;
int loggerUid = m_data->m_stateLoggersUniqueId++;
int maxLogDof = 12;
if ((clientCmd.m_updateFlags & STATE_LOGGING_MAX_LOG_DOF))
{
maxLogDof = clientCmd.m_stateLoggingArguments.m_maxLogDof;
}
int logFlags = 0;
if (clientCmd.m_updateFlags & STATE_LOGGING_LOG_FLAGS)
{
logFlags = clientCmd.m_stateLoggingArguments.m_logFlags;
}
GenericRobotStateLogger* logger = new GenericRobotStateLogger(loggerUid, fileName, m_data->m_dynamicsWorld, maxLogDof, logFlags);
if ((clientCmd.m_updateFlags & STATE_LOGGING_FILTER_OBJECT_UNIQUE_ID) && (clientCmd.m_stateLoggingArguments.m_numBodyUniqueIds > 0))
{
logger->m_filterObjectUniqueId = true;
for (int i = 0; i < clientCmd.m_stateLoggingArguments.m_numBodyUniqueIds; ++i)
{
int objectUniqueId = clientCmd.m_stateLoggingArguments.m_bodyUniqueIds[i];
logger->m_bodyIdList.push_back(objectUniqueId);
}
}
m_data->m_stateLoggers.push_back(logger);
serverStatusOut.m_type = CMD_STATE_LOGGING_START_COMPLETED;
serverStatusOut.m_stateLoggingResultArgs.m_loggingUniqueId = loggerUid;
}
if (clientCmd.m_stateLoggingArguments.m_logType == STATE_LOGGING_CONTACT_POINTS)
{
std::string fileName = clientCmd.m_stateLoggingArguments.m_fileName;
int loggerUid = m_data->m_stateLoggersUniqueId++;
ContactPointsStateLogger* logger = new ContactPointsStateLogger(loggerUid, fileName, m_data->m_dynamicsWorld);
if ((clientCmd.m_updateFlags & STATE_LOGGING_FILTER_LINK_INDEX_A) && clientCmd.m_stateLoggingArguments.m_linkIndexA >= -1)
{
logger->m_filterLinkA = true;
logger->m_linkIndexA = clientCmd.m_stateLoggingArguments.m_linkIndexA;
}
if ((clientCmd.m_updateFlags & STATE_LOGGING_FILTER_LINK_INDEX_B) && clientCmd.m_stateLoggingArguments.m_linkIndexB >= -1)
{
logger->m_filterLinkB = true;
logger->m_linkIndexB = clientCmd.m_stateLoggingArguments.m_linkIndexB;
}
if ((clientCmd.m_updateFlags & STATE_LOGGING_FILTER_BODY_UNIQUE_ID_A) && clientCmd.m_stateLoggingArguments.m_bodyUniqueIdA > -1)
{
logger->m_bodyUniqueIdA = clientCmd.m_stateLoggingArguments.m_bodyUniqueIdA;
}
if ((clientCmd.m_updateFlags & STATE_LOGGING_FILTER_BODY_UNIQUE_ID_B) && clientCmd.m_stateLoggingArguments.m_bodyUniqueIdB > -1)
{
logger->m_bodyUniqueIdB = clientCmd.m_stateLoggingArguments.m_bodyUniqueIdB;
}
m_data->m_stateLoggers.push_back(logger);
serverStatusOut.m_type = CMD_STATE_LOGGING_START_COMPLETED;
serverStatusOut.m_stateLoggingResultArgs.m_loggingUniqueId = loggerUid;
}
#endif
if (clientCmd.m_stateLoggingArguments.m_logType == STATE_LOGGING_VR_CONTROLLERS)
{
std::string fileName = clientCmd.m_stateLoggingArguments.m_fileName;
int loggerUid = m_data->m_stateLoggersUniqueId++;
int deviceFilterType = VR_DEVICE_CONTROLLER;
if (clientCmd.m_updateFlags & STATE_LOGGING_FILTER_DEVICE_TYPE)
{
deviceFilterType = clientCmd.m_stateLoggingArguments.m_deviceFilterType;
}
VRControllerStateLogger* logger = new VRControllerStateLogger(loggerUid, deviceFilterType, fileName);
m_data->m_stateLoggers.push_back(logger);
serverStatusOut.m_type = CMD_STATE_LOGGING_START_COMPLETED;
serverStatusOut.m_stateLoggingResultArgs.m_loggingUniqueId = loggerUid;
}
}
if ((clientCmd.m_updateFlags & STATE_LOGGING_STOP_LOG) && clientCmd.m_stateLoggingArguments.m_loggingUniqueId >= 0)
{
if (clientCmd.m_stateLoggingArguments.m_loggingUniqueId == m_data->m_logPlaybackUid)
{
if (m_data->m_logPlayback)
{
delete m_data->m_logPlayback;
m_data->m_logPlayback = 0;
m_data->m_logPlaybackUid = -1;
}
}
if (clientCmd.m_stateLoggingArguments.m_loggingUniqueId == m_data->m_commandLoggingUid)
{
if (m_data->m_commandLogger)
{
enableCommandLogging(false, 0);
serverStatusOut.m_type = CMD_STATE_LOGGING_COMPLETED;
m_data->m_commandLoggingUid = -1;
}
}
if (clientCmd.m_stateLoggingArguments.m_loggingUniqueId == m_data->m_profileTimingLoggingUid)
{
serverStatusOut.m_type = CMD_STATE_LOGGING_COMPLETED;
b3ChromeUtilsStopTimingsAndWriteJsonFile(m_data->m_profileTimingFileName.c_str());
m_data->m_profileTimingLoggingUid = -1;
}
else
{
serverStatusOut.m_type = CMD_STATE_LOGGING_COMPLETED;
for (int i = 0; i < m_data->m_stateLoggers.size(); i++)
{
if (m_data->m_stateLoggers[i]->m_loggingUniqueId == clientCmd.m_stateLoggingArguments.m_loggingUniqueId)
{
m_data->m_stateLoggers[i]->stop();
delete m_data->m_stateLoggers[i];
m_data->m_stateLoggers.removeAtIndex(i);
}
}
}
}
return hasStatus;
}
bool PhysicsServerCommandProcessor::processRequestCameraImageCommand(const struct SharedMemoryCommand& clientCmd, struct SharedMemoryStatus& serverStatusOut, char* bufferServerToClient, int bufferSizeInBytes)
{
bool hasStatus = true;
BT_PROFILE("CMD_REQUEST_CAMERA_IMAGE_DATA");
int startPixelIndex = clientCmd.m_requestPixelDataArguments.m_startPixelIndex;
int width = clientCmd.m_requestPixelDataArguments.m_pixelWidth;
int height = clientCmd.m_requestPixelDataArguments.m_pixelHeight;
int numPixelsCopied = 0;
if ((clientCmd.m_requestPixelDataArguments.m_startPixelIndex == 0) &&
(clientCmd.m_updateFlags & REQUEST_PIXEL_ARGS_SET_PIXEL_WIDTH_HEIGHT) != 0)
{
if (m_data->m_pluginManager.getRenderInterface())
{
m_data->m_pluginManager.getRenderInterface()->setWidthAndHeight(clientCmd.m_requestPixelDataArguments.m_pixelWidth,
clientCmd.m_requestPixelDataArguments.m_pixelHeight);
}
}
int flags = 0;
if (clientCmd.m_updateFlags & REQUEST_PIXEL_ARGS_HAS_FLAGS)
{
flags = clientCmd.m_requestPixelDataArguments.m_flags;
}
if (m_data->m_pluginManager.getRenderInterface())
{
m_data->m_pluginManager.getRenderInterface()->setFlags(flags);
}
int numTotalPixels = width * height;
int numRemainingPixels = numTotalPixels - startPixelIndex;
if (numRemainingPixels > 0)
{
int totalBytesPerPixel = 4 + 4 + 4; //4 for rgb, 4 for depth, 4 for segmentation mask
int maxNumPixels = bufferSizeInBytes / totalBytesPerPixel - 1;
unsigned char* pixelRGBA = (unsigned char*)bufferServerToClient;
int numRequestedPixels = btMin(maxNumPixels, numRemainingPixels);
float* depthBuffer = (float*)(bufferServerToClient + numRequestedPixels * 4);
int* segmentationMaskBuffer = (int*)(bufferServerToClient + numRequestedPixels * 8);
serverStatusOut.m_numDataStreamBytes = numRequestedPixels * totalBytesPerPixel;
float viewMat[16];
float projMat[16];
float projTextureViewMat[16];
float projTextureProjMat[16];
for (int i = 0; i < 16; i++)
{
viewMat[i] = clientCmd.m_requestPixelDataArguments.m_viewMatrix[i];
projMat[i] = clientCmd.m_requestPixelDataArguments.m_projectionMatrix[i];
}
if ((clientCmd.m_updateFlags & REQUEST_PIXEL_ARGS_HAS_CAMERA_MATRICES) == 0)
{
b3OpenGLVisualizerCameraInfo tmpCamResult;
bool result = this->m_data->m_guiHelper->getCameraInfo(
&tmpCamResult.m_width,
&tmpCamResult.m_height,
tmpCamResult.m_viewMatrix,
tmpCamResult.m_projectionMatrix,
tmpCamResult.m_camUp,
tmpCamResult.m_camForward,
tmpCamResult.m_horizontal,
tmpCamResult.m_vertical,
&tmpCamResult.m_yaw,
&tmpCamResult.m_pitch,
&tmpCamResult.m_dist,
tmpCamResult.m_target);
if (result)
{
for (int i = 0; i < 16; i++)
{
viewMat[i] = tmpCamResult.m_viewMatrix[i];
projMat[i] = tmpCamResult.m_projectionMatrix[i];
}
}
}
bool handled = false;
if ((clientCmd.m_updateFlags & ER_BULLET_HARDWARE_OPENGL) != 0)
{
if ((flags & ER_USE_PROJECTIVE_TEXTURE) != 0)
{
this->m_data->m_guiHelper->setProjectiveTexture(true);
if ((clientCmd.m_updateFlags & REQUEST_PIXEL_ARGS_HAS_PROJECTIVE_TEXTURE_MATRICES) != 0)
{
for (int i = 0; i < 16; i++)
{
projTextureViewMat[i] = clientCmd.m_requestPixelDataArguments.m_projectiveTextureViewMatrix[i];
projTextureProjMat[i] = clientCmd.m_requestPixelDataArguments.m_projectiveTextureProjectionMatrix[i];
}
}
else // If no specified matrices for projective texture, then use the camera matrices.
{
for (int i = 0; i < 16; i++)
{
projTextureViewMat[i] = viewMat[i];
projTextureProjMat[i] = projMat[i];
}
}
this->m_data->m_guiHelper->setProjectiveTextureMatrices(projTextureViewMat, projTextureProjMat);
}
else
{
this->m_data->m_guiHelper->setProjectiveTexture(false);
}
if ((flags & ER_NO_SEGMENTATION_MASK) != 0)
{
segmentationMaskBuffer = 0;
}
m_data->m_guiHelper->copyCameraImageData(viewMat,
projMat, pixelRGBA, numRequestedPixels,
depthBuffer, numRequestedPixels,
segmentationMaskBuffer, numRequestedPixels,
startPixelIndex, width, height, &numPixelsCopied);
if (numPixelsCopied > 0)
{
//convert segmentation mask
if (segmentationMaskBuffer)
{
for (int i = 0; i < numPixelsCopied; i++)
{
int graphicsSegMask = segmentationMaskBuffer[i];
int segMask = -1;
if ((graphicsSegMask >= 0) && (graphicsSegMask < m_data->m_graphicsIndexToSegmentationMask.size()))
{
segMask = m_data->m_graphicsIndexToSegmentationMask[graphicsSegMask];
}
if ((flags & ER_SEGMENTATION_MASK_OBJECT_AND_LINKINDEX) == 0)
{
if (segMask >= 0)
{
segMask &= ((1 << 24) - 1);
}
}
segmentationMaskBuffer[i] = segMask;
}
}
handled = true;
m_data->m_guiHelper->debugDisplayCameraImageData(viewMat,
projMat, pixelRGBA, numRequestedPixels,
depthBuffer, numRequestedPixels,
segmentationMaskBuffer, numRequestedPixels,
startPixelIndex, width, height, &numPixelsCopied);
}
}
if (!handled)
{
if (m_data->m_pluginManager.getRenderInterface())
{
if (clientCmd.m_requestPixelDataArguments.m_startPixelIndex == 0)
{
// printf("-------------------------------\nRendering\n");
if ((clientCmd.m_updateFlags & REQUEST_PIXEL_ARGS_SET_LIGHT_DIRECTION) != 0)
{
m_data->m_pluginManager.getRenderInterface()->setLightDirection(clientCmd.m_requestPixelDataArguments.m_lightDirection[0], clientCmd.m_requestPixelDataArguments.m_lightDirection[1], clientCmd.m_requestPixelDataArguments.m_lightDirection[2]);
}
if ((clientCmd.m_updateFlags & REQUEST_PIXEL_ARGS_SET_LIGHT_COLOR) != 0)
{
m_data->m_pluginManager.getRenderInterface()->setLightColor(clientCmd.m_requestPixelDataArguments.m_lightColor[0], clientCmd.m_requestPixelDataArguments.m_lightColor[1], clientCmd.m_requestPixelDataArguments.m_lightColor[2]);
}
if ((clientCmd.m_updateFlags & REQUEST_PIXEL_ARGS_SET_LIGHT_DISTANCE) != 0)
{
m_data->m_pluginManager.getRenderInterface()->setLightDistance(clientCmd.m_requestPixelDataArguments.m_lightDistance);
}
if ((clientCmd.m_updateFlags & REQUEST_PIXEL_ARGS_SET_SHADOW) != 0)
{
m_data->m_pluginManager.getRenderInterface()->setShadow((clientCmd.m_requestPixelDataArguments.m_hasShadow != 0));
}
if ((clientCmd.m_updateFlags & REQUEST_PIXEL_ARGS_SET_AMBIENT_COEFF) != 0)
{
m_data->m_pluginManager.getRenderInterface()->setLightAmbientCoeff(clientCmd.m_requestPixelDataArguments.m_lightAmbientCoeff);
}
if ((clientCmd.m_updateFlags & REQUEST_PIXEL_ARGS_SET_DIFFUSE_COEFF) != 0)
{
m_data->m_pluginManager.getRenderInterface()->setLightDiffuseCoeff(clientCmd.m_requestPixelDataArguments.m_lightDiffuseCoeff);
}
if ((clientCmd.m_updateFlags & REQUEST_PIXEL_ARGS_SET_SPECULAR_COEFF) != 0)
{
m_data->m_pluginManager.getRenderInterface()->setLightSpecularCoeff(clientCmd.m_requestPixelDataArguments.m_lightSpecularCoeff);
}
for (int i = 0; i < m_data->m_dynamicsWorld->getNumCollisionObjects(); i++)
{
const btCollisionObject* colObj = m_data->m_dynamicsWorld->getCollisionObjectArray()[i];
btVector3 localScaling(1, 1, 1);
m_data->m_pluginManager.getRenderInterface()->syncTransform(colObj->getUserIndex3(), colObj->getWorldTransform(), localScaling);
const btCollisionShape* collisionShape = colObj->getCollisionShape();
if (collisionShape->getShapeType() == SOFTBODY_SHAPE_PROXYTYPE)
{
#ifndef SKIP_SOFT_BODY_MULTI_BODY_DYNAMICS_WORLD
const btSoftBody* psb = (const btSoftBody*)colObj;
if (psb->getUserIndex3() >= 0)
{
btAlignedObjectArray<btVector3> vertices;
btAlignedObjectArray<btVector3> normals;
if (psb->m_renderNodes.size() == 0)
{
vertices.resize(psb->m_faces.size() * 3);
normals.resize(psb->m_faces.size() * 3);
for (int i = 0; i < psb->m_faces.size(); i++) // Foreach face
{
for (int k = 0; k < 3; k++) // Foreach vertex on a face
{
int currentIndex = i * 3 + k;
vertices[currentIndex] = psb->m_faces[i].m_n[k]->m_x;
normals[currentIndex] = psb->m_faces[i].m_n[k]->m_n;
}
}
}
else
{
vertices.resize(psb->m_renderNodes.size());
for (int i = 0; i < psb->m_renderNodes.size(); i++) // Foreach face
{
vertices[i] = psb->m_renderNodes[i].m_x;
}
}
m_data->m_pluginManager.getRenderInterface()->updateShape(psb->getUserIndex3(), &vertices[0], vertices.size(), &normals[0],normals.size());
}
#endif //SKIP_SOFT_BODY_MULTI_BODY_DYNAMICS_WORLD
}
}
if ((clientCmd.m_updateFlags & REQUEST_PIXEL_ARGS_HAS_CAMERA_MATRICES) != 0)
{
m_data->m_pluginManager.getRenderInterface()->render(
clientCmd.m_requestPixelDataArguments.m_viewMatrix,
clientCmd.m_requestPixelDataArguments.m_projectionMatrix);
}
else
{
b3OpenGLVisualizerCameraInfo tmpCamResult;
bool result = this->m_data->m_guiHelper->getCameraInfo(
&tmpCamResult.m_width,
&tmpCamResult.m_height,
tmpCamResult.m_viewMatrix,
tmpCamResult.m_projectionMatrix,
tmpCamResult.m_camUp,
tmpCamResult.m_camForward,
tmpCamResult.m_horizontal,
tmpCamResult.m_vertical,
&tmpCamResult.m_yaw,
&tmpCamResult.m_pitch,
&tmpCamResult.m_dist,
tmpCamResult.m_target);
if (result)
{
m_data->m_pluginManager.getRenderInterface()->render(tmpCamResult.m_viewMatrix, tmpCamResult.m_projectionMatrix);
}
else
{
m_data->m_pluginManager.getRenderInterface()->render();
}
}
}
}
if (m_data->m_pluginManager.getRenderInterface())
{
if ((flags & ER_USE_PROJECTIVE_TEXTURE) != 0)
{
m_data->m_pluginManager.getRenderInterface()->setProjectiveTexture(true);
if ((clientCmd.m_updateFlags & REQUEST_PIXEL_ARGS_HAS_PROJECTIVE_TEXTURE_MATRICES) != 0)
{
for (int i = 0; i < 16; i++)
{
projTextureViewMat[i] = clientCmd.m_requestPixelDataArguments.m_projectiveTextureViewMatrix[i];
projTextureProjMat[i] = clientCmd.m_requestPixelDataArguments.m_projectiveTextureProjectionMatrix[i];
}
}
else // If no specified matrices for projective texture, then use the camera matrices.
{
for (int i = 0; i < 16; i++)
{
projTextureViewMat[i] = viewMat[i];
projTextureProjMat[i] = projMat[i];
}
}
m_data->m_pluginManager.getRenderInterface()->setProjectiveTextureMatrices(projTextureViewMat, projTextureProjMat);
}
else
{
m_data->m_pluginManager.getRenderInterface()->setProjectiveTexture(false);
}
if ((flags & ER_NO_SEGMENTATION_MASK) != 0)
{
segmentationMaskBuffer = 0;
}
m_data->m_pluginManager.getRenderInterface()->copyCameraImageData(pixelRGBA, numRequestedPixels,
depthBuffer, numRequestedPixels,
segmentationMaskBuffer, numRequestedPixels,
startPixelIndex, &width, &height, &numPixelsCopied);
m_data->m_pluginManager.getRenderInterface()->setProjectiveTexture(false);
}
m_data->m_guiHelper->debugDisplayCameraImageData(clientCmd.m_requestPixelDataArguments.m_viewMatrix,
clientCmd.m_requestPixelDataArguments.m_projectionMatrix, pixelRGBA, numRequestedPixels,
depthBuffer, numRequestedPixels,
segmentationMaskBuffer, numRequestedPixels,
startPixelIndex, width, height, &numPixelsCopied);
}
//each pixel takes 4 RGBA values and 1 float = 8 bytes
}
else
{
}
serverStatusOut.m_type = CMD_CAMERA_IMAGE_COMPLETED;
serverStatusOut.m_sendPixelDataArguments.m_numPixelsCopied = numPixelsCopied;
serverStatusOut.m_sendPixelDataArguments.m_numRemainingPixels = numRemainingPixels - numPixelsCopied;
serverStatusOut.m_sendPixelDataArguments.m_startingPixelIndex = startPixelIndex;
serverStatusOut.m_sendPixelDataArguments.m_imageWidth = width;
serverStatusOut.m_sendPixelDataArguments.m_imageHeight = height;
return hasStatus;
}
bool PhysicsServerCommandProcessor::processSaveWorldCommand(const struct SharedMemoryCommand& clientCmd, struct SharedMemoryStatus& serverStatusOut, char* bufferServerToClient, int bufferSizeInBytes)
{
bool hasStatus = false;
BT_PROFILE("CMD_SAVE_WORLD");
serverStatusOut.m_type = CMD_SAVE_WORLD_FAILED;
///this is a very rudimentary way to save the state of the world, for scene authoring
///many todo's, for example save the state of motor controllers etc.
{
//saveWorld(clientCmd.m_sdfArguments.m_sdfFileName);
int constraintCount = 0;
FILE* f = fopen(clientCmd.m_sdfArguments.m_sdfFileName, "w");
if (f)
{
char line[2048];
{
sprintf(line, "import pybullet as p\n");
int len = strlen(line);
fwrite(line, len, 1, f);
}
{
sprintf(line, "cin = p.connect(p.SHARED_MEMORY)\n");
int len = strlen(line);
fwrite(line, len, 1, f);
}
{
sprintf(line, "if (cin < 0):\n");
int len = strlen(line);
fwrite(line, len, 1, f);
}
{
sprintf(line, " cin = p.connect(p.GUI)\n");
int len = strlen(line);
fwrite(line, len, 1, f);
}
//for each objects ...
for (int i = 0; i < m_data->m_saveWorldBodyData.size(); i++)
{
SaveWorldObjectData& sd = m_data->m_saveWorldBodyData[i];
for (int i = 0; i < sd.m_bodyUniqueIds.size(); i++)
{
{
int bodyUniqueId = sd.m_bodyUniqueIds[i];
InternalBodyData* body = m_data->m_bodyHandles.getHandle(bodyUniqueId);
if (body)
{
if (body->m_multiBody)
{
btMultiBody* mb = body->m_multiBody;
btTransform comTr = mb->getBaseWorldTransform();
btTransform tr = comTr * body->m_rootLocalInertialFrame.inverse();
if (strstr(sd.m_fileName.c_str(), ".urdf"))
{
sprintf(line, "objects = [p.loadURDF(\"%s\", %f,%f,%f,%f,%f,%f,%f)]\n", sd.m_fileName.c_str(),
tr.getOrigin()[0], tr.getOrigin()[1], tr.getOrigin()[2],
tr.getRotation()[0], tr.getRotation()[1], tr.getRotation()[2], tr.getRotation()[3]);
int len = strlen(line);
fwrite(line, len, 1, f);
}
if (strstr(sd.m_fileName.c_str(), ".sdf") && i == 0)
{
sprintf(line, "objects = p.loadSDF(\"%s\")\n", sd.m_fileName.c_str());
int len = strlen(line);
fwrite(line, len, 1, f);
}
if (strstr(sd.m_fileName.c_str(), ".xml") && i == 0)
{
sprintf(line, "objects = p.loadMJCF(\"%s\")\n", sd.m_fileName.c_str());
int len = strlen(line);
fwrite(line, len, 1, f);
}
if (strstr(sd.m_fileName.c_str(), ".sdf") || strstr(sd.m_fileName.c_str(), ".xml") || ((strstr(sd.m_fileName.c_str(), ".urdf")) && mb->getNumLinks()))
{
sprintf(line, "ob = objects[%d]\n", i);
int len = strlen(line);
fwrite(line, len, 1, f);
}
if (strstr(sd.m_fileName.c_str(), ".sdf") || strstr(sd.m_fileName.c_str(), ".xml"))
{
sprintf(line, "p.resetBasePositionAndOrientation(ob,[%f,%f,%f],[%f,%f,%f,%f])\n",
comTr.getOrigin()[0], comTr.getOrigin()[1], comTr.getOrigin()[2],
comTr.getRotation()[0], comTr.getRotation()[1], comTr.getRotation()[2], comTr.getRotation()[3]);
int len = strlen(line);
fwrite(line, len, 1, f);
}
if (mb->getNumLinks())
{
{
sprintf(line, "jointPositions=[");
int len = strlen(line);
fwrite(line, len, 1, f);
}
for (int i = 0; i < mb->getNumLinks(); i++)
{
btScalar jointPos = mb->getJointPosMultiDof(i)[0];
if (i < mb->getNumLinks() - 1)
{
sprintf(line, " %f,", jointPos);
int len = strlen(line);
fwrite(line, len, 1, f);
}
else
{
sprintf(line, " %f ", jointPos);
int len = strlen(line);
fwrite(line, len, 1, f);
}
}
{
sprintf(line, "]\nfor jointIndex in range (p.getNumJoints(ob)):\n\tp.resetJointState(ob,jointIndex,jointPositions[jointIndex])\n\n");
int len = strlen(line);
fwrite(line, len, 1, f);
}
}
}
else
{
//todo: btRigidBody/btSoftBody etc case
}
}
}
}
//for URDF, load at origin, then reposition...
struct SaveWorldObjectData
{
b3AlignedObjectArray<int> m_bodyUniqueIds;
std::string m_fileName;
};
}
//user constraints
{
for (int i = 0; i < m_data->m_userConstraints.size(); i++)
{
InteralUserConstraintData* ucptr = m_data->m_userConstraints.getAtIndex(i);
b3UserConstraint& uc = ucptr->m_userConstraintData;
int parentBodyIndex = uc.m_parentBodyIndex;
int parentJointIndex = uc.m_parentJointIndex;
int childBodyIndex = uc.m_childBodyIndex;
int childJointIndex = uc.m_childJointIndex;
btVector3 jointAxis(uc.m_jointAxis[0], uc.m_jointAxis[1], uc.m_jointAxis[2]);
btVector3 pivotParent(uc.m_parentFrame[0], uc.m_parentFrame[1], uc.m_parentFrame[2]);
btVector3 pivotChild(uc.m_childFrame[0], uc.m_childFrame[1], uc.m_childFrame[2]);
btQuaternion ornFrameParent(uc.m_parentFrame[3], uc.m_parentFrame[4], uc.m_parentFrame[5], uc.m_parentFrame[6]);
btQuaternion ornFrameChild(uc.m_childFrame[3], uc.m_childFrame[4], uc.m_childFrame[5], uc.m_childFrame[6]);
{
char jointTypeStr[1024] = "FIXED";
bool hasKnownJointType = true;
switch (uc.m_jointType)
{
case eRevoluteType:
{
sprintf(jointTypeStr, "p.JOINT_REVOLUTE");
break;
}
case ePrismaticType:
{
sprintf(jointTypeStr, "p.JOINT_PRISMATIC");
break;
}
case eSphericalType:
{
sprintf(jointTypeStr, "p.JOINT_SPHERICAL");
break;
}
case ePlanarType:
{
sprintf(jointTypeStr, "p.JOINT_PLANAR");
break;
}
case eFixedType:
{
sprintf(jointTypeStr, "p.JOINT_FIXED");
break;
}
case ePoint2PointType:
{
sprintf(jointTypeStr, "p.JOINT_POINT2POINT");
break;
}
case eGearType:
{
sprintf(jointTypeStr, "p.JOINT_GEAR");
break;
}
default:
{
hasKnownJointType = false;
b3Warning("unknown constraint type in SAVE_WORLD");
}
};
if (hasKnownJointType)
{
{
sprintf(line, "cid%d = p.createConstraint(%d,%d,%d,%d,%s,[%f,%f,%f],[%f,%f,%f],[%f,%f,%f],[%f,%f,%f,%f],[%f,%f,%f,%f])\n",
constraintCount,
parentBodyIndex,
parentJointIndex,
childBodyIndex,
childJointIndex,
jointTypeStr,
jointAxis[0], jointAxis[1], jointAxis[2],
pivotParent[0], pivotParent[1], pivotParent[2],
pivotChild[0], pivotChild[1], pivotChild[2],
ornFrameParent[0], ornFrameParent[1], ornFrameParent[2], ornFrameParent[3],
ornFrameChild[0], ornFrameChild[1], ornFrameChild[2], ornFrameChild[3]);
int len = strlen(line);
fwrite(line, len, 1, f);
}
{
sprintf(line, "p.changeConstraint(cid%d,maxForce=%f)\n", constraintCount, uc.m_maxAppliedForce);
int len = strlen(line);
fwrite(line, len, 1, f);
constraintCount++;
}
}
}
}
}
{
btVector3 grav = this->m_data->m_dynamicsWorld->getGravity();
sprintf(line, "p.setGravity(%f,%f,%f)\n", grav[0], grav[1], grav[2]);
int len = strlen(line);
fwrite(line, len, 1, f);
}
{
sprintf(line, "p.stepSimulation()\np.disconnect()\n");
int len = strlen(line);
fwrite(line, len, 1, f);
}
fclose(f);
}
serverStatusOut.m_type = CMD_SAVE_WORLD_COMPLETED;
hasStatus = true;
}
return hasStatus;
}
#define MYLINELENGTH 16 * 32768
static unsigned char* MyGetRawHeightfieldData(CommonFileIOInterface& fileIO, PHY_ScalarType type, const char* fileName, int& width, int& height,
btScalar& minHeight,
btScalar& maxHeight)
{
std::string ext;
std::string fn(fileName);
std::string ext_ = fn.substr(fn.size() - 4);
for (std::string::iterator i = ext_.begin(); i != ext_.end(); ++i)
{
ext += char(tolower(*i));
}
if (ext != ".txt")
{
char relativeFileName[1024];
int found = fileIO.findResourcePath(fileName, relativeFileName, 1024);
b3AlignedObjectArray<char> buffer;
buffer.reserve(1024);
int fileId = fileIO.fileOpen(relativeFileName, "rb");
if (fileId >= 0)
{
int size = fileIO.getFileSize(fileId);
if (size > 0)
{
buffer.resize(size);
int actual = fileIO.fileRead(fileId, &buffer[0], size);
if (actual != size)
{
b3Warning("STL filesize mismatch!\n");
buffer.resize(0);
}
}
fileIO.fileClose(fileId);
}
if (buffer.size())
{
int n;
unsigned char* image = stbi_load_from_memory((const unsigned char*)&buffer[0], buffer.size(), &width, &height, &n, 3);
if (image)
{
fileIO.fileClose(fileId);
int nElements = width * height;
int bytesPerElement = sizeof(btScalar);
btAssert(bytesPerElement > 0 && "bad bytes per element");
int nBytes = nElements * bytesPerElement;
unsigned char* raw = new unsigned char[nBytes];
btAssert(raw && "out of memory");
unsigned char* p = raw;
for (int j = 0; j < height; ++j)
{
for (int i = 0; i < width; ++i)
{
float z = double(image[(width - 1 - i) * 3 + width * j * 3]) * (1. / 255.);
btScalar* pf = (btScalar*)p;
*pf = z;
p += bytesPerElement;
// update min/max
if (!i && !j)
{
minHeight = z;
maxHeight = z;
}
else
{
if (z < minHeight)
{
minHeight = z;
}
if (z > maxHeight)
{
maxHeight = z;
}
}
}
}
free(image);
return raw;
}
}
}
if (ext == ".txt")
{
//read a csv file as used in DeepLoco
{
char relativePath[1024];
int found = fileIO.findResourcePath(fileName, relativePath, 1024);
btAlignedObjectArray<char> lineBuffer;
lineBuffer.resize(MYLINELENGTH);
int slot = fileIO.fileOpen(relativePath, "r");
int rows = 0;
int cols = 0;
btAlignedObjectArray<double> allValues;
if (slot >= 0)
{
char* lineChar;
while (lineChar = fileIO.readLine(slot, &lineBuffer[0], MYLINELENGTH))
{
rows = 0;
std::string line(lineChar);
int pos = 0;
while (pos < line.length())
{
int nextPos = pos + 1;
while (nextPos < line.length())
{
if (line[nextPos - 1] == ',')
{
break;
}
nextPos++;
}
std::string substr = line.substr(pos, nextPos - pos - 1);
double v;
if (sscanf(substr.c_str(), "%lf", &v) == 1)
{
allValues.push_back(v);
rows++;
}
pos = nextPos;
}
cols++;
}
width = rows;
height = cols;
fileIO.fileClose(slot);
int nElements = width * height;
// std::cerr << " nElements = " << nElements << "\n";
int bytesPerElement = sizeof(btScalar);
// std::cerr << " bytesPerElement = " << bytesPerElement << "\n";
btAssert(bytesPerElement > 0 && "bad bytes per element");
long nBytes = nElements * bytesPerElement;
// std::cerr << " nBytes = " << nBytes << "\n";
unsigned char* raw = new unsigned char[nBytes];
btAssert(raw && "out of memory");
unsigned char* p = raw;
for (int i = 0; i < width; ++i)
{
for (int j = 0; j < height; ++j)
{
double z = allValues[i + width * j];
//convertFromFloat(p, z, type);
btScalar* pf = (btScalar*)p;
*pf = z;
p += bytesPerElement;
// update min/max
if (!i && !j)
{
minHeight = z;
maxHeight = z;
}
else
{
if (z < minHeight)
{
minHeight = z;
}
if (z > maxHeight)
{
maxHeight = z;
}
}
}
}
return raw;
}
}
}
return 0;
}
class MyTriangleCollector4 : public btTriangleCallback
{
public:
btAlignedObjectArray<GLInstanceVertex>* m_pVerticesOut;
btAlignedObjectArray<int>* m_pIndicesOut;
btVector3 m_aabbMin, m_aabbMax;
btScalar m_textureScaling;
MyTriangleCollector4(const btVector3& aabbMin, const btVector3& aabbMax)
:m_aabbMin(aabbMin), m_aabbMax(aabbMax), m_textureScaling(1)
{
m_pVerticesOut = 0;
m_pIndicesOut = 0;
}
virtual void processTriangle(btVector3* tris, int partId, int triangleIndex)
{
for (int k = 0; k < 3; k++)
{
GLInstanceVertex v;
v.xyzw[3] = 0;
btVector3 normal = (tris[0] - tris[1]).cross(tris[0] - tris[2]);
normal.safeNormalize();
for (int l = 0; l < 3; l++)
{
v.xyzw[l] = tris[k][l];
v.normal[l] = normal[l];
}
btVector3 extents = m_aabbMax - m_aabbMin;
v.uv[0] = (1. - ((v.xyzw[0] - m_aabbMin[0]) / (m_aabbMax[0] - m_aabbMin[0]))) * m_textureScaling;
v.uv[1] = (1. - (v.xyzw[1] - m_aabbMin[1]) / (m_aabbMax[1] - m_aabbMin[1])) * m_textureScaling;
m_pIndicesOut->push_back(m_pVerticesOut->size());
m_pVerticesOut->push_back(v);
}
}
};
bool PhysicsServerCommandProcessor::processCreateCollisionShapeCommand(const struct SharedMemoryCommand& clientCmd, struct SharedMemoryStatus& serverStatusOut, char* bufferServerToClient, int bufferSizeInBytes)
{
bool hasStatus = true;
serverStatusOut.m_type = CMD_CREATE_COLLISION_SHAPE_FAILED;
#ifdef USE_DISCRETE_DYNAMICS_WORLD
btWorldImporter* worldImporter = new btWorldImporter(m_data->m_dynamicsWorld);
#else
btMultiBodyWorldImporter* worldImporter = new btMultiBodyWorldImporter(m_data->m_dynamicsWorld);
#endif
btCollisionShape* shape = 0;
b3AlignedObjectArray<UrdfCollision> urdfCollisionObjects;
btCompoundShape* compound = 0;
if (clientCmd.m_createUserShapeArgs.m_numUserShapes > 1)
{
compound = worldImporter->createCompoundShape();
compound->setMargin(m_data->m_defaultCollisionMargin);
}
for (int i = 0; i < clientCmd.m_createUserShapeArgs.m_numUserShapes; i++)
{
GLInstanceGraphicsShape* glmesh = 0;
char pathPrefix[1024] = "";
char relativeFileName[1024] = "";
UrdfCollision urdfColObj;
btTransform childTransform;
childTransform.setIdentity();
if (clientCmd.m_createUserShapeArgs.m_shapes[i].m_hasChildTransform)
{
childTransform.setOrigin(btVector3(clientCmd.m_createUserShapeArgs.m_shapes[i].m_childPosition[0],
clientCmd.m_createUserShapeArgs.m_shapes[i].m_childPosition[1],
clientCmd.m_createUserShapeArgs.m_shapes[i].m_childPosition[2]));
childTransform.setRotation(btQuaternion(
clientCmd.m_createUserShapeArgs.m_shapes[i].m_childOrientation[0],
clientCmd.m_createUserShapeArgs.m_shapes[i].m_childOrientation[1],
clientCmd.m_createUserShapeArgs.m_shapes[i].m_childOrientation[2],
clientCmd.m_createUserShapeArgs.m_shapes[i].m_childOrientation[3]));
if (compound == 0)
{
compound = worldImporter->createCompoundShape();
}
}
urdfColObj.m_linkLocalFrame = childTransform;
urdfColObj.m_sourceFileLocation = "memory";
urdfColObj.m_name = "memory";
urdfColObj.m_geometry.m_type = URDF_GEOM_UNKNOWN;
switch (clientCmd.m_createUserShapeArgs.m_shapes[i].m_type)
{
case GEOM_SPHERE:
{
double radius = clientCmd.m_createUserShapeArgs.m_shapes[i].m_sphereRadius;
shape = worldImporter->createSphereShape(radius);
shape->setMargin(m_data->m_defaultCollisionMargin);
if (compound)
{
compound->addChildShape(childTransform, shape);
}
urdfColObj.m_geometry.m_type = URDF_GEOM_SPHERE;
urdfColObj.m_geometry.m_sphereRadius = radius;
break;
}
case GEOM_BOX:
{
//double halfExtents[3] = clientCmd.m_createUserShapeArgs.m_shapes[i].m_sphereRadius;
btVector3 halfExtents(
clientCmd.m_createUserShapeArgs.m_shapes[i].m_boxHalfExtents[0],
clientCmd.m_createUserShapeArgs.m_shapes[i].m_boxHalfExtents[1],
clientCmd.m_createUserShapeArgs.m_shapes[i].m_boxHalfExtents[2]);
shape = worldImporter->createBoxShape(halfExtents);
shape->setMargin(m_data->m_defaultCollisionMargin);
if (compound)
{
compound->addChildShape(childTransform, shape);
}
urdfColObj.m_geometry.m_type = URDF_GEOM_BOX;
urdfColObj.m_geometry.m_boxSize = 2. * halfExtents;
break;
}
case GEOM_CAPSULE:
{
shape = worldImporter->createCapsuleShapeZ(clientCmd.m_createUserShapeArgs.m_shapes[i].m_capsuleRadius,
clientCmd.m_createUserShapeArgs.m_shapes[i].m_capsuleHeight);
shape->setMargin(m_data->m_defaultCollisionMargin);
if (compound)
{
compound->addChildShape(childTransform, shape);
}
urdfColObj.m_geometry.m_type = URDF_GEOM_CAPSULE;
urdfColObj.m_geometry.m_capsuleRadius = clientCmd.m_createUserShapeArgs.m_shapes[i].m_capsuleRadius;
urdfColObj.m_geometry.m_capsuleHeight = clientCmd.m_createUserShapeArgs.m_shapes[i].m_capsuleHeight;
break;
}
case GEOM_CYLINDER:
{
shape = worldImporter->createCylinderShapeZ(clientCmd.m_createUserShapeArgs.m_shapes[i].m_capsuleRadius,
0.5 * clientCmd.m_createUserShapeArgs.m_shapes[i].m_capsuleHeight);
shape->setMargin(m_data->m_defaultCollisionMargin);
if (compound)
{
compound->addChildShape(childTransform, shape);
}
urdfColObj.m_geometry.m_type = URDF_GEOM_CYLINDER;
urdfColObj.m_geometry.m_capsuleRadius = clientCmd.m_createUserShapeArgs.m_shapes[i].m_capsuleRadius;
urdfColObj.m_geometry.m_capsuleHeight = clientCmd.m_createUserShapeArgs.m_shapes[i].m_capsuleHeight;
break;
}
case GEOM_HEIGHTFIELD:
{
int width;
int height;
btScalar minHeight, maxHeight;
PHY_ScalarType scalarType = PHY_FLOAT;
CommonFileIOInterface* fileIO = m_data->m_pluginManager.getFileIOInterface();
const unsigned char* heightfieldData = 0;
if (clientCmd.m_createUserShapeArgs.m_shapes[i].m_numHeightfieldColumns > 0 &&
clientCmd.m_createUserShapeArgs.m_shapes[i].m_numHeightfieldRows > 0)
{
width = clientCmd.m_createUserShapeArgs.m_shapes[i].m_numHeightfieldRows;
height = clientCmd.m_createUserShapeArgs.m_shapes[i].m_numHeightfieldColumns;
float* heightfieldDataSrc = (float*)bufferServerToClient;
heightfieldData = new unsigned char[width * height * sizeof(btScalar)];
btScalar* datafl = (btScalar*)heightfieldData;
minHeight = heightfieldDataSrc[0];
maxHeight = heightfieldDataSrc[0];
for (int i = 0; i < width * height; i++)
{
datafl[i] = heightfieldDataSrc[i];
minHeight = btMin(minHeight, (btScalar)datafl[i]);
maxHeight = btMax(maxHeight, (btScalar)datafl[i]);
}
}
else
{
heightfieldData = MyGetRawHeightfieldData(*fileIO, scalarType, clientCmd.m_createUserShapeArgs.m_shapes[i].m_meshFileName, width, height, minHeight, maxHeight);
}
if (heightfieldData)
{
//replace heightfield data or create new heightfield
if (clientCmd.m_createUserShapeArgs.m_shapes[i].m_replaceHeightfieldIndex >= 0)
{
int collisionShapeUid = clientCmd.m_createUserShapeArgs.m_shapes[i].m_replaceHeightfieldIndex;
InternalCollisionShapeHandle* handle = m_data->m_userCollisionShapeHandles.getHandle(collisionShapeUid);
if (handle && handle->m_collisionShape && handle->m_collisionShape->getShapeType() == TERRAIN_SHAPE_PROXYTYPE)
{
btHeightfieldTerrainShape* terrainShape = (btHeightfieldTerrainShape*)handle->m_collisionShape;
btScalar* heightfieldDest = (btScalar*)terrainShape->getHeightfieldRawData();
//replace the data
btScalar* datafl = (btScalar*)heightfieldData;
for (int i = 0; i < width * height; i++)
{
heightfieldDest[i] = datafl[i];
}
//update graphics
btAlignedObjectArray<GLInstanceVertex> gfxVertices;
btAlignedObjectArray<int> indices;
int strideInBytes = 9 * sizeof(float);
btVector3 aabbMin, aabbMax;
btTransform tr;
tr.setIdentity();
terrainShape->getAabb(tr, aabbMin, aabbMax);
MyTriangleCollector4 col(aabbMin, aabbMax);
col.m_pVerticesOut = &gfxVertices;
col.m_pIndicesOut = &indices;
terrainShape->processAllTriangles(&col, aabbMin, aabbMax);
if (gfxVertices.size() && indices.size())
{
m_data->m_guiHelper->updateShape(terrainShape->getUserIndex(), &gfxVertices[0].xyzw[0], gfxVertices.size());
}
btAlignedObjectArray<btVector3> vts;
btAlignedObjectArray<btVector3> normals;
vts.resize(gfxVertices.size());
normals.resize(gfxVertices.size());
for (int v = 0; v < gfxVertices.size(); v++)
{
vts[v].setValue(gfxVertices[v].xyzw[0], gfxVertices[v].xyzw[1], gfxVertices[v].xyzw[2]);
normals[v].setValue(gfxVertices[v].normal[0], gfxVertices[v].normal[1], gfxVertices[v].normal[2]);
}
m_data->m_pluginManager.getRenderInterface()->updateShape(terrainShape->getUserIndex2(), &vts[0], vts.size(), &normals[0], normals.size());
terrainShape->clearAccelerator();
terrainShape->buildAccelerator();
btTriangleInfoMap* oldTriangleInfoMap = terrainShape->getTriangleInfoMap();
delete (oldTriangleInfoMap);
terrainShape->setTriangleInfoMap(0);
if (clientCmd.m_createUserShapeArgs.m_shapes[i].m_collisionFlags & GEOM_CONCAVE_INTERNAL_EDGE)
{
btTriangleInfoMap* triangleInfoMap = new btTriangleInfoMap();
btGenerateInternalEdgeInfo(terrainShape, triangleInfoMap);
}
serverStatusOut.m_createUserShapeResultArgs.m_userShapeUniqueId = collisionShapeUid;
delete worldImporter;
serverStatusOut.m_type = CMD_CREATE_COLLISION_SHAPE_COMPLETED;
}
delete heightfieldData;
return hasStatus;
}
else
{
btScalar gridSpacing = 0.5;
btScalar gridHeightScale = 1. / 256.;
bool flipQuadEdges = false;
int upAxis = 2;
/*btHeightfieldTerrainShape* heightfieldShape = worldImporter->createHeightfieldShape( width, height,
heightfieldData,
gridHeightScale,
minHeight, maxHeight,
upAxis, int(scalarType), flipQuadEdges);
*/
btHeightfieldTerrainShape* heightfieldShape = new btHeightfieldTerrainShape(width, height,
heightfieldData,
gridHeightScale,
minHeight, maxHeight,
upAxis, scalarType, flipQuadEdges);
m_data->m_collisionShapes.push_back(heightfieldShape);
double textureScaling = clientCmd.m_createUserShapeArgs.m_shapes[i].m_heightfieldTextureScaling;
heightfieldShape->setUserValue3(textureScaling);
shape = heightfieldShape;
if (upAxis == 2)
heightfieldShape->setFlipTriangleWinding(true);
// scale the shape
btVector3 localScaling(clientCmd.m_createUserShapeArgs.m_shapes[i].m_meshScale[0],
clientCmd.m_createUserShapeArgs.m_shapes[i].m_meshScale[1],
clientCmd.m_createUserShapeArgs.m_shapes[i].m_meshScale[2]);
heightfieldShape->setLocalScaling(localScaling);
//buildAccelerator is optional, it may not support all features.
heightfieldShape->buildAccelerator();
if (clientCmd.m_createUserShapeArgs.m_shapes[i].m_collisionFlags & GEOM_CONCAVE_INTERNAL_EDGE)
{
btTriangleInfoMap* triangleInfoMap = new btTriangleInfoMap();
btGenerateInternalEdgeInfo(heightfieldShape, triangleInfoMap);
}
this->m_data->m_heightfieldDatas.push_back(heightfieldData);
btAlignedObjectArray<GLInstanceVertex> gfxVertices;
btAlignedObjectArray<int> indices;
int strideInBytes = 9 * sizeof(float);
btTransform tr;
tr.setIdentity();
btVector3 aabbMin, aabbMax;
heightfieldShape->getAabb(tr, aabbMin, aabbMax);
MyTriangleCollector4 col(aabbMin, aabbMax);
col.m_pVerticesOut = &gfxVertices;
col.m_pIndicesOut = &indices;
heightfieldShape->processAllTriangles(&col, aabbMin, aabbMax);
if (gfxVertices.size() && indices.size())
{
urdfColObj.m_geometry.m_type = URDF_GEOM_HEIGHTFIELD;
urdfColObj.m_geometry.m_meshFileType = UrdfGeometry::MEMORY_VERTICES;
urdfColObj.m_geometry.m_normals.resize(gfxVertices.size());
urdfColObj.m_geometry.m_vertices.resize(gfxVertices.size());
urdfColObj.m_geometry.m_uvs.resize(gfxVertices.size());
for (int v = 0; v < gfxVertices.size(); v++)
{
urdfColObj.m_geometry.m_vertices[v].setValue(gfxVertices[v].xyzw[0], gfxVertices[v].xyzw[1], gfxVertices[v].xyzw[2]);
urdfColObj.m_geometry.m_uvs[v].setValue(gfxVertices[v].uv[0], gfxVertices[v].uv[1], 0);
urdfColObj.m_geometry.m_normals[v].setValue(gfxVertices[v].normal[0], gfxVertices[v].normal[1], gfxVertices[v].normal[2]);
}
urdfColObj.m_geometry.m_indices.resize(indices.size());
for (int ii = 0; ii < indices.size(); ii++)
{
urdfColObj.m_geometry.m_indices[ii] = indices[ii];
}
}
}
}
break;
}
case GEOM_PLANE:
{
btVector3 planeNormal(clientCmd.m_createUserShapeArgs.m_shapes[i].m_planeNormal[0],
clientCmd.m_createUserShapeArgs.m_shapes[i].m_planeNormal[1],
clientCmd.m_createUserShapeArgs.m_shapes[i].m_planeNormal[2]);
shape = worldImporter->createPlaneShape(planeNormal, clientCmd.m_createUserShapeArgs.m_shapes[i].m_planeConstant);
shape->setMargin(m_data->m_defaultCollisionMargin);
if (compound)
{
compound->addChildShape(childTransform, shape);
}
urdfColObj.m_geometry.m_type = URDF_GEOM_PLANE;
urdfColObj.m_geometry.m_planeNormal.setValue(
clientCmd.m_createUserShapeArgs.m_shapes[i].m_planeNormal[0],
clientCmd.m_createUserShapeArgs.m_shapes[i].m_planeNormal[1],
clientCmd.m_createUserShapeArgs.m_shapes[i].m_planeNormal[2]);
break;
}
case GEOM_MESH:
{
btVector3 meshScale(clientCmd.m_createUserShapeArgs.m_shapes[i].m_meshScale[0],
clientCmd.m_createUserShapeArgs.m_shapes[i].m_meshScale[1],
clientCmd.m_createUserShapeArgs.m_shapes[i].m_meshScale[2]);
const std::string& urdf_path = "";
std::string fileName = clientCmd.m_createUserShapeArgs.m_shapes[i].m_meshFileName;
urdfColObj.m_geometry.m_type = URDF_GEOM_MESH;
urdfColObj.m_geometry.m_meshFileName = fileName;
urdfColObj.m_geometry.m_meshScale = meshScale;
CommonFileIOInterface* fileIO = m_data->m_pluginManager.getFileIOInterface();
pathPrefix[0] = 0;
if (fileIO->findResourcePath(fileName.c_str(), relativeFileName, 1024))
{
b3FileUtils::extractPath(relativeFileName, pathPrefix, 1024);
}
const std::string& error_message_prefix = "";
std::string out_found_filename;
int out_type;
if (clientCmd.m_createUserShapeArgs.m_shapes[i].m_numVertices)
{
int numVertices = clientCmd.m_createUserShapeArgs.m_shapes[i].m_numVertices;
int numIndices = clientCmd.m_createUserShapeArgs.m_shapes[i].m_numIndices;
//int totalUploadSizeInBytes = numVertices * sizeof(double) * 3 + numIndices * sizeof(int);
char* data = bufferServerToClient;
double* vertexUpload = (double*)data;
int* indexUpload = (int*)(data + numVertices * sizeof(double) * 3);
if (compound == 0)
{
compound = worldImporter->createCompoundShape();
}
compound->setMargin(m_data->m_defaultCollisionMargin);
if (clientCmd.m_createUserShapeArgs.m_shapes[i].m_numIndices)
{
BT_PROFILE("convert trimesh2");
btTriangleMesh* meshInterface = new btTriangleMesh();
this->m_data->m_meshInterfaces.push_back(meshInterface);
{
BT_PROFILE("convert vertices2");
for (int j = 0; j < clientCmd.m_createUserShapeArgs.m_shapes[i].m_numIndices / 3; j++)
{
int i0 = indexUpload[j * 3 + 0];
int i1 = indexUpload[j * 3 + 1];
int i2 = indexUpload[j * 3 + 2];
btVector3 v0(vertexUpload[i0 * 3 + 0],
vertexUpload[i0 * 3 + 1],
vertexUpload[i0 * 3 + 2]);
btVector3 v1(vertexUpload[i1 * 3 + 0],
vertexUpload[i1 * 3 + 1],
vertexUpload[i1 * 3 + 2]);
btVector3 v2(vertexUpload[i2 * 3 + 0],
vertexUpload[i2 * 3 + 1],
vertexUpload[i2 * 3 + 2]);
meshInterface->addTriangle(v0 * meshScale, v1 * meshScale, v2 * meshScale);
}
}
{
BT_PROFILE("create btBvhTriangleMeshShape");
btBvhTriangleMeshShape* trimesh = new btBvhTriangleMeshShape(meshInterface, true, true);
m_data->m_collisionShapes.push_back(trimesh);
if (clientCmd.m_createUserShapeArgs.m_shapes[i].m_collisionFlags & GEOM_CONCAVE_INTERNAL_EDGE)
{
btTriangleInfoMap* triangleInfoMap = new btTriangleInfoMap();
btGenerateInternalEdgeInfo(trimesh, triangleInfoMap);
}
shape = trimesh;
if (compound)
{
compound->addChildShape(childTransform, shape);
shape->setMargin(m_data->m_defaultCollisionMargin);
}
}
}
else
{
btConvexHullShape* convexHull = worldImporter->createConvexHullShape();
convexHull->setMargin(m_data->m_defaultCollisionMargin);
for (int v = 0; v < clientCmd.m_createUserShapeArgs.m_shapes[i].m_numVertices; v++)
{
btVector3 pt(vertexUpload[v * 3 + 0],
vertexUpload[v * 3 + 1],
vertexUpload[v * 3 + 2]);
convexHull->addPoint(pt * meshScale, false);
}
convexHull->recalcLocalAabb();
convexHull->optimizeConvexHull();
compound->addChildShape(childTransform, convexHull);
}
urdfColObj.m_geometry.m_meshFileType = UrdfGeometry::MEMORY_VERTICES;
break;
}
bool foundFile = UrdfFindMeshFile(fileIO, pathPrefix, relativeFileName, error_message_prefix, &out_found_filename, &out_type);
if (foundFile)
{
urdfColObj.m_geometry.m_meshFileType = out_type;
if (clientCmd.m_createUserShapeArgs.m_shapes[i].m_collisionFlags & GEOM_FORCE_CONCAVE_TRIMESH)
{
CommonFileIOInterface* fileIO = m_data->m_pluginManager.getFileIOInterface();
if (out_type == UrdfGeometry::FILE_STL)
{
CommonFileIOInterface* fileIO(m_data->m_pluginManager.getFileIOInterface());
glmesh = LoadMeshFromSTL(relativeFileName, fileIO);
}
if (out_type == UrdfGeometry::FILE_OBJ)
{
CommonFileIOInterface* fileIO = m_data->m_pluginManager.getFileIOInterface();
glmesh = LoadMeshFromObj(relativeFileName, pathPrefix, fileIO);
}
//btBvhTriangleMeshShape is created below
}
else
{
if (out_type == UrdfGeometry::FILE_STL)
{
CommonFileIOInterface* fileIO(m_data->m_pluginManager.getFileIOInterface());
glmesh = LoadMeshFromSTL(relativeFileName, fileIO);
B3_PROFILE("createConvexHullFromShapes");
if (compound == 0)
{
compound = worldImporter->createCompoundShape();
}
btConvexHullShape* convexHull = worldImporter->createConvexHullShape();
convexHull->setMargin(m_data->m_defaultCollisionMargin);
for (int vv = 0; vv < glmesh->m_numvertices; vv++)
{
btVector3 pt(
glmesh->m_vertices->at(vv).xyzw[0],
glmesh->m_vertices->at(vv).xyzw[1],
glmesh->m_vertices->at(vv).xyzw[2]);
convexHull->addPoint(pt * meshScale, false);
}
if (clientCmd.m_createUserShapeArgs.m_shapes[i].m_collisionFlags & GEOM_INITIALIZE_SAT_FEATURES)
{
convexHull->initializePolyhedralFeatures();
}
convexHull->recalcLocalAabb();
convexHull->optimizeConvexHull();
compound->addChildShape(childTransform, convexHull);
delete glmesh;
glmesh = 0;
}
if (out_type == UrdfGeometry::FILE_OBJ)
{
//create a convex hull for each shape, and store it in a btCompoundShape
std::vector<tinyobj::shape_t> shapes;
tinyobj::attrib_t attribute;
std::string err = tinyobj::LoadObj(attribute, shapes, out_found_filename.c_str(), "", fileIO);
//shape = createConvexHullFromShapes(shapes, collision->m_geometry.m_meshScale);
//static btCollisionShape* createConvexHullFromShapes(std::vector<tinyobj::shape_t>& shapes, const btVector3& geomScale)
B3_PROFILE("createConvexHullFromShapes");
if (compound == 0)
{
compound = worldImporter->createCompoundShape();
}
compound->setMargin(m_data->m_defaultCollisionMargin);
for (int s = 0; s < (int)shapes.size(); s++)
{
btConvexHullShape* convexHull = worldImporter->createConvexHullShape();
convexHull->setMargin(m_data->m_defaultCollisionMargin);
tinyobj::shape_t& shape = shapes[s];
int faceCount = shape.mesh.indices.size();
for (int f = 0; f < faceCount; f += 3)
{
btVector3 pt;
pt.setValue(attribute.vertices[3 * shape.mesh.indices[f + 0].vertex_index + 0],
attribute.vertices[3 * shape.mesh.indices[f + 0].vertex_index + 1],
attribute.vertices[3 * shape.mesh.indices[f + 0].vertex_index + 2]);
convexHull->addPoint(pt * meshScale, false);
pt.setValue(attribute.vertices[3 * shape.mesh.indices[f + 1].vertex_index + 0],
attribute.vertices[3 * shape.mesh.indices[f + 1].vertex_index + 1],
attribute.vertices[3 * shape.mesh.indices[f + 1].vertex_index + 2]);
convexHull->addPoint(pt * meshScale, false);
pt.setValue(attribute.vertices[3 * shape.mesh.indices[f + 2].vertex_index + 0],
attribute.vertices[3 * shape.mesh.indices[f + 2].vertex_index + 1],
attribute.vertices[3 * shape.mesh.indices[f + 2].vertex_index + 2]);
convexHull->addPoint(pt * meshScale, false);
}
if (clientCmd.m_createUserShapeArgs.m_shapes[i].m_collisionFlags & GEOM_INITIALIZE_SAT_FEATURES)
{
convexHull->initializePolyhedralFeatures();
}
convexHull->recalcLocalAabb();
convexHull->optimizeConvexHull();
compound->addChildShape(childTransform, convexHull);
}
}
}
}
break;
}
default:
{
}
}
if (urdfColObj.m_geometry.m_type != URDF_GEOM_UNKNOWN)
{
urdfCollisionObjects.push_back(urdfColObj);
}
if (glmesh)
{
btVector3 meshScale(clientCmd.m_createUserShapeArgs.m_shapes[i].m_meshScale[0],
clientCmd.m_createUserShapeArgs.m_shapes[i].m_meshScale[1],
clientCmd.m_createUserShapeArgs.m_shapes[i].m_meshScale[2]);
if (!glmesh || glmesh->m_numvertices <= 0)
{
b3Warning("%s: cannot extract mesh from '%s'\n", pathPrefix, relativeFileName);
delete glmesh;
}
else
{
btAlignedObjectArray<btVector3> convertedVerts;
convertedVerts.reserve(glmesh->m_numvertices);
for (int v = 0; v < glmesh->m_numvertices; v++)
{
convertedVerts.push_back(btVector3(
glmesh->m_vertices->at(v).xyzw[0] * meshScale[0],
glmesh->m_vertices->at(v).xyzw[1] * meshScale[1],
glmesh->m_vertices->at(v).xyzw[2] * meshScale[2]));
}
if (clientCmd.m_createUserShapeArgs.m_shapes[i].m_collisionFlags & GEOM_FORCE_CONCAVE_TRIMESH)
{
BT_PROFILE("convert trimesh");
btTriangleMesh* meshInterface = new btTriangleMesh();
this->m_data->m_meshInterfaces.push_back(meshInterface);
{
BT_PROFILE("convert vertices");
for (int i = 0; i < glmesh->m_numIndices / 3; i++)
{
const btVector3& v0 = convertedVerts[glmesh->m_indices->at(i * 3)];
const btVector3& v1 = convertedVerts[glmesh->m_indices->at(i * 3 + 1)];
const btVector3& v2 = convertedVerts[glmesh->m_indices->at(i * 3 + 2)];
meshInterface->addTriangle(v0, v1, v2);
}
}
{
BT_PROFILE("create btBvhTriangleMeshShape");
btBvhTriangleMeshShape* trimesh = new btBvhTriangleMeshShape(meshInterface, true, true);
m_data->m_collisionShapes.push_back(trimesh);
if (clientCmd.m_createUserShapeArgs.m_shapes[i].m_collisionFlags & GEOM_CONCAVE_INTERNAL_EDGE)
{
btTriangleInfoMap* triangleInfoMap = new btTriangleInfoMap();
btGenerateInternalEdgeInfo(trimesh, triangleInfoMap);
}
//trimesh->setLocalScaling(collision->m_geometry.m_meshScale);
shape = trimesh;
if (compound)
{
compound->addChildShape(childTransform, shape);
shape->setMargin(m_data->m_defaultCollisionMargin);
}
}
delete glmesh;
}
else
{
//convex mesh
if (compound == 0)
{
compound = worldImporter->createCompoundShape();
}
compound->setMargin(m_data->m_defaultCollisionMargin);
{
btConvexHullShape* convexHull = worldImporter->createConvexHullShape();
convexHull->setMargin(m_data->m_defaultCollisionMargin);
for (int v = 0; v < convertedVerts.size(); v++)
{
btVector3 pt = convertedVerts[v];
convexHull->addPoint(pt, false);
}
convexHull->recalcLocalAabb();
convexHull->optimizeConvexHull();
compound->addChildShape(childTransform, convexHull);
}
}
}
}
}
if (compound && compound->getNumChildShapes())
{
shape = compound;
}
if (shape)
{
int collisionShapeUid = m_data->m_userCollisionShapeHandles.allocHandle();
InternalCollisionShapeHandle* handle = m_data->m_userCollisionShapeHandles.getHandle(collisionShapeUid);
handle->m_collisionShape = shape;
for (int i = 0; i < urdfCollisionObjects.size(); i++)
{
handle->m_urdfCollisionObjects.push_back(urdfCollisionObjects[i]);
}
serverStatusOut.m_createUserShapeResultArgs.m_userShapeUniqueId = collisionShapeUid;
m_data->m_worldImporters.push_back(worldImporter);
serverStatusOut.m_type = CMD_CREATE_COLLISION_SHAPE_COMPLETED;
}
else
{
delete worldImporter;
}
return hasStatus;
}
static void gatherVertices(const btTransform& trans, const btCollisionShape* colShape, btAlignedObjectArray<btVector3>& verticesOut, int collisionShapeIndex)
{
switch (colShape->getShapeType())
{
case COMPOUND_SHAPE_PROXYTYPE:
{
const btCompoundShape* compound = (const btCompoundShape*)colShape;
for (int i = 0; i < compound->getNumChildShapes(); i++)
{
btTransform childTr = trans * compound->getChildTransform(i);
if ((collisionShapeIndex < 0) || (collisionShapeIndex == i))
{
gatherVertices(childTr, compound->getChildShape(i), verticesOut, collisionShapeIndex);
}
}
break;
}
case CONVEX_HULL_SHAPE_PROXYTYPE:
{
const btConvexHullShape* convex = (const btConvexHullShape*)colShape;
btVector3 vtx;
for (int i = 0; i < convex->getNumVertices(); i++)
{
convex->getVertex(i, vtx);
btVector3 trVertex = trans * vtx;
verticesOut.push_back(trVertex);
}
break;
}
default:
{
printf("?\n");
}
}
}
bool PhysicsServerCommandProcessor::processResetMeshDataCommand(const struct SharedMemoryCommand& clientCmd, struct SharedMemoryStatus& serverStatusOut, char* bufferServerToClient, int bufferSizeInBytes)
{
bool hasStatus = true;
BT_PROFILE("CMD_REQUEST_MESH_DATA");
serverStatusOut.m_type = CMD_RESET_MESH_DATA_FAILED;
int sizeInBytes = 0;
InternalBodyHandle* bodyHandle = m_data->m_bodyHandles.getHandle(clientCmd.m_requestMeshDataArgs.m_bodyUniqueId);
if (bodyHandle)
{
int totalBytesPerVertex = sizeof(btVector3);
double* vertexUpload = (double*)bufferServerToClient;
#ifndef SKIP_SOFT_BODY_MULTI_BODY_DYNAMICS_WORLD
if (bodyHandle->m_softBody)
{
btSoftBody* psb = bodyHandle->m_softBody;
int numVertices = psb->m_nodes.size();
if (clientCmd.m_resetMeshDataArgs.m_numVertices == numVertices)
{
for (int i = 0; i < numVertices; ++i)
{
btSoftBody::Node& n = psb->m_nodes[i];
n.m_x.setValue(vertexUpload[i*3+0], vertexUpload[i*3+1],vertexUpload[i*3+2]);
}
serverStatusOut.m_type = CMD_RESET_MESH_DATA_COMPLETED;
}
}
#endif //SKIP_SOFT_BODY_MULTI_BODY_DYNAMICS_WORLD
}
serverStatusOut.m_numDataStreamBytes = 0;
return hasStatus;
}
bool PhysicsServerCommandProcessor::processRequestMeshDataCommand(const struct SharedMemoryCommand& clientCmd, struct SharedMemoryStatus& serverStatusOut, char* bufferServerToClient, int bufferSizeInBytes)
{
bool hasStatus = true;
BT_PROFILE("CMD_REQUEST_MESH_DATA");
serverStatusOut.m_type = CMD_REQUEST_MESH_DATA_FAILED;
serverStatusOut.m_numDataStreamBytes = 0;
int sizeInBytes = 0;
InternalBodyHandle* bodyHandle = m_data->m_bodyHandles.getHandle(clientCmd.m_requestMeshDataArgs.m_bodyUniqueId);
if (bodyHandle)
{
int totalBytesPerVertex = sizeof(btVector3);
btVector3* verticesOut = (btVector3*)bufferServerToClient;
const btCollisionShape* colShape = 0;
if (bodyHandle->m_multiBody)
{
//collision shape
if (clientCmd.m_requestMeshDataArgs.m_linkIndex == -1)
{
colShape = bodyHandle->m_multiBody->getBaseCollider()->getCollisionShape();
}
else
{
colShape = bodyHandle->m_multiBody->getLinkCollider(clientCmd.m_requestMeshDataArgs.m_linkIndex)->getCollisionShape();
}
}
if (bodyHandle->m_rigidBody)
{
colShape = bodyHandle->m_rigidBody->getCollisionShape();
}
if (colShape)
{
btAlignedObjectArray<btVector3> vertices;
btTransform tr;
tr.setIdentity();
int collisionShapeIndex = -1;
if (clientCmd.m_updateFlags & B3_MESH_DATA_COLLISIONSHAPEINDEX)
{
collisionShapeIndex = clientCmd.m_requestMeshDataArgs.m_collisionShapeIndex;
}
gatherVertices(tr, colShape, vertices, collisionShapeIndex);
int numVertices = vertices.size();
int maxNumVertices = bufferSizeInBytes / totalBytesPerVertex - 1;
int numVerticesRemaining = numVertices - clientCmd.m_requestMeshDataArgs.m_startingVertex;
int verticesCopied = btMin(maxNumVertices, numVerticesRemaining);
if (verticesCopied > 0)
{
memcpy(verticesOut, &vertices[0], sizeof(btVector3) * verticesCopied);
}
sizeInBytes = verticesCopied * sizeof(btVector3);
serverStatusOut.m_type = CMD_REQUEST_MESH_DATA_COMPLETED;
serverStatusOut.m_sendMeshDataArgs.m_numVerticesCopied = verticesCopied;
serverStatusOut.m_sendMeshDataArgs.m_startingVertex = clientCmd.m_requestMeshDataArgs.m_startingVertex;
serverStatusOut.m_sendMeshDataArgs.m_numVerticesRemaining = numVerticesRemaining - verticesCopied;
}
#ifndef SKIP_SOFT_BODY_MULTI_BODY_DYNAMICS_WORLD
if (bodyHandle->m_softBody)
{
btSoftBody* psb = bodyHandle->m_softBody;
int flags = 0;
if (clientCmd.m_updateFlags & B3_MESH_DATA_FLAGS)
{
flags = clientCmd.m_requestMeshDataArgs.m_flags;
}
bool separateRenderMesh = false;
if ((flags & B3_MESH_DATA_SIMULATION_MESH) == 0)
{
separateRenderMesh = (psb->m_renderNodes.size() != 0);
}
int numVertices = separateRenderMesh ? psb->m_renderNodes.size() : psb->m_nodes.size();
int maxNumVertices = bufferSizeInBytes / totalBytesPerVertex - 1;
int numVerticesRemaining = numVertices - clientCmd.m_requestMeshDataArgs.m_startingVertex;
int verticesCopied = btMin(maxNumVertices, numVerticesRemaining);
for (int i = 0; i < verticesCopied; ++i)
{
if (separateRenderMesh)
{
const btSoftBody::RenderNode& n = psb->m_renderNodes[i + clientCmd.m_requestMeshDataArgs.m_startingVertex];
verticesOut[i].setValue(n.m_x.x(), n.m_x.y(), n.m_x.z());
}
else
{
const btSoftBody::Node& n = psb->m_nodes[i + clientCmd.m_requestMeshDataArgs.m_startingVertex];
verticesOut[i].setValue(n.m_x.x(), n.m_x.y(), n.m_x.z());
}
}
sizeInBytes = verticesCopied * sizeof(btVector3);
serverStatusOut.m_type = CMD_REQUEST_MESH_DATA_COMPLETED;
serverStatusOut.m_sendMeshDataArgs.m_numVerticesCopied = verticesCopied;
serverStatusOut.m_sendMeshDataArgs.m_startingVertex = clientCmd.m_requestMeshDataArgs.m_startingVertex;
serverStatusOut.m_sendMeshDataArgs.m_numVerticesRemaining = numVerticesRemaining - verticesCopied;
}
#endif //SKIP_SOFT_BODY_MULTI_BODY_DYNAMICS_WORLD
}
serverStatusOut.m_numDataStreamBytes = sizeInBytes;
return hasStatus;
}
bool PhysicsServerCommandProcessor::processCreateVisualShapeCommand(const struct SharedMemoryCommand& clientCmd, struct SharedMemoryStatus& serverStatusOut, char* bufferServerToClient, int bufferSizeInBytes)
{
bool hasStatus = true;
serverStatusOut.m_type = CMD_CREATE_VISUAL_SHAPE_FAILED;
double globalScaling = 1.f;
int flags = 0;
CommonFileIOInterface* fileIO = m_data->m_pluginManager.getFileIOInterface();
BulletURDFImporter u2b(m_data->m_guiHelper, m_data->m_pluginManager.getRenderInterface(), fileIO, globalScaling, flags);
u2b.setEnableTinyRenderer(m_data->m_enableTinyRenderer);
btTransform localInertiaFrame;
localInertiaFrame.setIdentity();
const char* pathPrefix = "";
int visualShapeUniqueId = -1;
UrdfVisual visualShape;
for (int userShapeIndex = 0; userShapeIndex < clientCmd.m_createUserShapeArgs.m_numUserShapes; userShapeIndex++)
{
btTransform childTrans;
childTrans.setIdentity();
visualShape.m_geometry.m_type = (UrdfGeomTypes)clientCmd.m_createUserShapeArgs.m_shapes[userShapeIndex].m_type;
char relativeFileName[1024];
char pathPrefix[1024];
pathPrefix[0] = 0;
const b3CreateUserShapeData& visShape = clientCmd.m_createUserShapeArgs.m_shapes[userShapeIndex];
switch (visualShape.m_geometry.m_type)
{
case URDF_GEOM_CYLINDER:
{
visualShape.m_geometry.m_capsuleHeight = visShape.m_capsuleHeight;
visualShape.m_geometry.m_capsuleRadius = visShape.m_capsuleRadius;
break;
}
case URDF_GEOM_BOX:
{
visualShape.m_geometry.m_boxSize.setValue(2. * visShape.m_boxHalfExtents[0],
2. * visShape.m_boxHalfExtents[1],
2. * visShape.m_boxHalfExtents[2]);
break;
}
case URDF_GEOM_SPHERE:
{
visualShape.m_geometry.m_sphereRadius = visShape.m_sphereRadius;
break;
}
case URDF_GEOM_CAPSULE:
{
visualShape.m_geometry.m_hasFromTo = visShape.m_hasFromTo;
if (visualShape.m_geometry.m_hasFromTo)
{
visualShape.m_geometry.m_capsuleFrom.setValue(visShape.m_capsuleFrom[0],
visShape.m_capsuleFrom[1],
visShape.m_capsuleFrom[2]);
visualShape.m_geometry.m_capsuleTo.setValue(visShape.m_capsuleTo[0],
visShape.m_capsuleTo[1],
visShape.m_capsuleTo[2]);
}
else
{
visualShape.m_geometry.m_capsuleHeight = visShape.m_capsuleHeight;
visualShape.m_geometry.m_capsuleRadius = visShape.m_capsuleRadius;
}
break;
}
case URDF_GEOM_MESH:
{
std::string fileName = clientCmd.m_createUserShapeArgs.m_shapes[userShapeIndex].m_meshFileName;
if (fileName.length())
{
const std::string& error_message_prefix = "";
std::string out_found_filename;
int out_type;
if (fileIO->findResourcePath(fileName.c_str(), relativeFileName, 1024))
{
b3FileUtils::extractPath(relativeFileName, pathPrefix, 1024);
}
bool foundFile = UrdfFindMeshFile(fileIO, pathPrefix, relativeFileName, error_message_prefix, &out_found_filename, &out_type);
if (foundFile)
{
visualShape.m_geometry.m_meshFileType = out_type;
visualShape.m_geometry.m_meshFileName = fileName;
}
else
{
}
}
else
{
visualShape.m_geometry.m_meshFileType = UrdfGeometry::MEMORY_VERTICES;
int numVertices = clientCmd.m_createUserShapeArgs.m_shapes[userShapeIndex].m_numVertices;
int numIndices = clientCmd.m_createUserShapeArgs.m_shapes[userShapeIndex].m_numIndices;
int numUVs = clientCmd.m_createUserShapeArgs.m_shapes[userShapeIndex].m_numUVs;
int numNormals = clientCmd.m_createUserShapeArgs.m_shapes[userShapeIndex].m_numNormals;
if (numVertices > 0 && numIndices > 0)
{
char* data = bufferServerToClient;
double* vertexUpload = (double*)data;
int* indexUpload = (int*)(data + numVertices * sizeof(double) * 3);
double* normalUpload = (double*)(data + numVertices * sizeof(double) * 3 + numIndices * sizeof(int));
double* uvUpload = (double*)(data + numVertices * sizeof(double) * 3 + numIndices * sizeof(int) + numNormals * sizeof(double) * 3);
for (int i = 0; i < numIndices; i++)
{
visualShape.m_geometry.m_indices.push_back(indexUpload[i]);
}
for (int i = 0; i < numVertices; i++)
{
btVector3 v0(vertexUpload[i * 3 + 0],
vertexUpload[i * 3 + 1],
vertexUpload[i * 3 + 2]);
visualShape.m_geometry.m_vertices.push_back(v0);
}
for (int i = 0; i < numNormals; i++)
{
btVector3 normal(normalUpload[i * 3 + 0],
normalUpload[i * 3 + 1],
normalUpload[i * 3 + 2]);
visualShape.m_geometry.m_normals.push_back(normal);
}
for (int i = 0; i < numUVs; i++)
{
btVector3 uv(uvUpload[i * 2 + 0], uvUpload[i * 2 + 1], 0);
visualShape.m_geometry.m_uvs.push_back(uv);
}
}
}
visualShape.m_geometry.m_meshScale.setValue(clientCmd.m_createUserShapeArgs.m_shapes[userShapeIndex].m_meshScale[0],
clientCmd.m_createUserShapeArgs.m_shapes[userShapeIndex].m_meshScale[1],
clientCmd.m_createUserShapeArgs.m_shapes[userShapeIndex].m_meshScale[2]);
break;
}
default:
{
}
};
visualShape.m_name = "in_memory";
visualShape.m_materialName = "";
visualShape.m_sourceFileLocation = "in_memory_unknown_line";
visualShape.m_linkLocalFrame.setIdentity();
visualShape.m_geometry.m_hasLocalMaterial = false;
bool hasRGBA = (clientCmd.m_createUserShapeArgs.m_shapes[userShapeIndex].m_visualFlags & GEOM_VISUAL_HAS_RGBA_COLOR) != 0;
;
bool hasSpecular = (clientCmd.m_createUserShapeArgs.m_shapes[userShapeIndex].m_visualFlags & GEOM_VISUAL_HAS_SPECULAR_COLOR) != 0;
;
visualShape.m_geometry.m_hasLocalMaterial = hasRGBA | hasSpecular;
if (visualShape.m_geometry.m_hasLocalMaterial)
{
if (hasRGBA)
{
visualShape.m_geometry.m_localMaterial.m_matColor.m_rgbaColor.setValue(
clientCmd.m_createUserShapeArgs.m_shapes[userShapeIndex].m_rgbaColor[0],
clientCmd.m_createUserShapeArgs.m_shapes[userShapeIndex].m_rgbaColor[1],
clientCmd.m_createUserShapeArgs.m_shapes[userShapeIndex].m_rgbaColor[2],
clientCmd.m_createUserShapeArgs.m_shapes[userShapeIndex].m_rgbaColor[3]);
}
else
{
visualShape.m_geometry.m_localMaterial.m_matColor.m_rgbaColor.setValue(1, 1, 1, 1);
}
if (hasSpecular)
{
visualShape.m_geometry.m_localMaterial.m_matColor.m_specularColor.setValue(
clientCmd.m_createUserShapeArgs.m_shapes[userShapeIndex].m_specularColor[0],
clientCmd.m_createUserShapeArgs.m_shapes[userShapeIndex].m_specularColor[1],
clientCmd.m_createUserShapeArgs.m_shapes[userShapeIndex].m_specularColor[2]);
}
else
{
visualShape.m_geometry.m_localMaterial.m_matColor.m_specularColor.setValue(0.4, 0.4, 0.4);
}
}
if (clientCmd.m_createUserShapeArgs.m_shapes[userShapeIndex].m_hasChildTransform != 0)
{
childTrans.setOrigin(btVector3(clientCmd.m_createUserShapeArgs.m_shapes[userShapeIndex].m_childPosition[0],
clientCmd.m_createUserShapeArgs.m_shapes[userShapeIndex].m_childPosition[1],
clientCmd.m_createUserShapeArgs.m_shapes[userShapeIndex].m_childPosition[2]));
childTrans.setRotation(btQuaternion(
clientCmd.m_createUserShapeArgs.m_shapes[userShapeIndex].m_childOrientation[0],
clientCmd.m_createUserShapeArgs.m_shapes[userShapeIndex].m_childOrientation[1],
clientCmd.m_createUserShapeArgs.m_shapes[userShapeIndex].m_childOrientation[2],
clientCmd.m_createUserShapeArgs.m_shapes[userShapeIndex].m_childOrientation[3]));
}
if (visualShapeUniqueId < 0)
{
visualShapeUniqueId = m_data->m_userVisualShapeHandles.allocHandle();
}
InternalVisualShapeHandle* visualHandle = m_data->m_userVisualShapeHandles.getHandle(visualShapeUniqueId);
visualHandle->m_OpenGLGraphicsIndex = -1;
visualHandle->m_tinyRendererVisualShapeIndex = -1;
//tinyrenderer doesn't separate shape versus instance, so create it when creating the multibody instance
//store needed info for tinyrenderer
visualShape.m_linkLocalFrame = childTrans;
visualHandle->m_visualShapes.push_back(visualShape);
visualHandle->m_pathPrefixes.push_back(pathPrefix[0] ? pathPrefix : "");
serverStatusOut.m_createUserShapeResultArgs.m_userShapeUniqueId = visualShapeUniqueId;
serverStatusOut.m_type = CMD_CREATE_VISUAL_SHAPE_COMPLETED;
}
return hasStatus;
}
bool PhysicsServerCommandProcessor::processCustomCommand(const struct SharedMemoryCommand& clientCmd, struct SharedMemoryStatus& serverStatusOut, char* bufferServerToClient, int bufferSizeInBytes)
{
bool hasStatus = true;
SharedMemoryStatus& serverCmd = serverStatusOut;
serverCmd.m_type = CMD_CUSTOM_COMMAND_FAILED;
serverCmd.m_customCommandResultArgs.m_returnDataSizeInBytes = 0;
serverCmd.m_customCommandResultArgs.m_returnDataType = -1;
serverCmd.m_customCommandResultArgs.m_returnDataStart = 0;
serverCmd.m_customCommandResultArgs.m_pluginUniqueId = -1;
if (clientCmd.m_updateFlags & CMD_CUSTOM_COMMAND_LOAD_PLUGIN)
{
//pluginPath could be registered or load from disk
const char* postFix = "";
if (clientCmd.m_updateFlags & CMD_CUSTOM_COMMAND_LOAD_PLUGIN_POSTFIX)
{
postFix = clientCmd.m_customCommandArgs.m_postFix;
}
int pluginUniqueId = m_data->m_pluginManager.loadPlugin(clientCmd.m_customCommandArgs.m_pluginPath, postFix);
if (pluginUniqueId >= 0)
{
serverCmd.m_customCommandResultArgs.m_pluginUniqueId = pluginUniqueId;
serverCmd.m_type = CMD_CUSTOM_COMMAND_COMPLETED;
}
}
if (clientCmd.m_updateFlags & CMD_CUSTOM_COMMAND_UNLOAD_PLUGIN)
{
m_data->m_pluginManager.unloadPlugin(clientCmd.m_customCommandArgs.m_pluginUniqueId);
serverCmd.m_type = CMD_CUSTOM_COMMAND_COMPLETED;
}
if (clientCmd.m_updateFlags & CMD_CUSTOM_COMMAND_EXECUTE_PLUGIN_COMMAND)
{
int startBytes = clientCmd.m_customCommandArgs.m_startingReturnBytes;
if (startBytes == 0)
{
int result = m_data->m_pluginManager.executePluginCommand(clientCmd.m_customCommandArgs.m_pluginUniqueId, &clientCmd.m_customCommandArgs.m_arguments);
serverCmd.m_customCommandResultArgs.m_executeCommandResult = result;
}
const b3UserDataValue* returnData = m_data->m_pluginManager.getReturnData(clientCmd.m_customCommandArgs.m_pluginUniqueId);
if (returnData)
{
int totalRemain = returnData->m_length - startBytes;
int numBytes = totalRemain <= bufferSizeInBytes ? totalRemain : bufferSizeInBytes;
serverStatusOut.m_numDataStreamBytes = numBytes;
for (int i = 0; i < numBytes; i++)
{
bufferServerToClient[i] = returnData->m_data1[i+ startBytes];
}
serverCmd.m_customCommandResultArgs.m_returnDataSizeInBytes = returnData->m_length;
serverCmd.m_customCommandResultArgs.m_returnDataType = returnData->m_type;
serverCmd.m_customCommandResultArgs.m_returnDataStart = startBytes;
}
else
{
serverStatusOut.m_numDataStreamBytes = 0;
}
serverCmd.m_type = CMD_CUSTOM_COMMAND_COMPLETED;
}
return hasStatus;
}
bool PhysicsServerCommandProcessor::processUserDebugDrawCommand(const struct SharedMemoryCommand& clientCmd, struct SharedMemoryStatus& serverStatusOut, char* bufferServerToClient, int bufferSizeInBytes)
{
bool hasStatus = true;
BT_PROFILE("CMD_USER_DEBUG_DRAW");
SharedMemoryStatus& serverCmd = serverStatusOut;
serverCmd.m_type = CMD_USER_DEBUG_DRAW_FAILED;
int trackingVisualShapeIndex = -1;
if (clientCmd.m_userDebugDrawArgs.m_parentObjectUniqueId >= 0)
{
InternalBodyHandle* bodyHandle = m_data->m_bodyHandles.getHandle(clientCmd.m_userDebugDrawArgs.m_parentObjectUniqueId);
if (bodyHandle)
{
int linkIndex = -1;
if (bodyHandle->m_multiBody)
{
int linkIndex = clientCmd.m_userDebugDrawArgs.m_parentLinkIndex;
if (linkIndex == -1)
{
if (bodyHandle->m_multiBody->getBaseCollider())
{
trackingVisualShapeIndex = bodyHandle->m_multiBody->getBaseCollider()->getUserIndex();
}
}
else
{
if (linkIndex >= 0 && linkIndex < bodyHandle->m_multiBody->getNumLinks())
{
if (bodyHandle->m_multiBody->getLink(linkIndex).m_collider)
{
trackingVisualShapeIndex = bodyHandle->m_multiBody->getLink(linkIndex).m_collider->getUserIndex();
}
}
}
}
if (bodyHandle->m_rigidBody)
{
trackingVisualShapeIndex = bodyHandle->m_rigidBody->getUserIndex();
}
}
}
if (clientCmd.m_updateFlags & USER_DEBUG_ADD_PARAMETER)
{
int uid = m_data->m_guiHelper->addUserDebugParameter(
clientCmd.m_userDebugDrawArgs.m_text,
clientCmd.m_userDebugDrawArgs.m_rangeMin,
clientCmd.m_userDebugDrawArgs.m_rangeMax,
clientCmd.m_userDebugDrawArgs.m_startValue);
serverCmd.m_userDebugDrawArgs.m_debugItemUniqueId = uid;
serverCmd.m_type = CMD_USER_DEBUG_DRAW_COMPLETED;
}
if (clientCmd.m_updateFlags & USER_DEBUG_READ_PARAMETER)
{
int ok = m_data->m_guiHelper->readUserDebugParameter(
clientCmd.m_userDebugDrawArgs.m_itemUniqueId,
&serverCmd.m_userDebugDrawArgs.m_parameterValue);
if (ok)
{
serverCmd.m_type = CMD_USER_DEBUG_DRAW_PARAMETER_COMPLETED;
}
}
if ((clientCmd.m_updateFlags & USER_DEBUG_SET_CUSTOM_OBJECT_COLOR) || (clientCmd.m_updateFlags & USER_DEBUG_REMOVE_CUSTOM_OBJECT_COLOR))
{
int bodyUniqueId = clientCmd.m_userDebugDrawArgs.m_objectUniqueId;
InternalBodyData* body = m_data->m_bodyHandles.getHandle(bodyUniqueId);
if (body)
{
btCollisionObject* destColObj = 0;
if (body->m_multiBody)
{
if (clientCmd.m_userDebugDrawArgs.m_linkIndex == -1)
{
destColObj = body->m_multiBody->getBaseCollider();
}
else
{
if (clientCmd.m_userDebugDrawArgs.m_linkIndex >= 0 && clientCmd.m_userDebugDrawArgs.m_linkIndex < body->m_multiBody->getNumLinks())
{
destColObj = body->m_multiBody->getLink(clientCmd.m_userDebugDrawArgs.m_linkIndex).m_collider;
}
}
}
if (body->m_rigidBody)
{
destColObj = body->m_rigidBody;
}
if (destColObj)
{
if (clientCmd.m_updateFlags & USER_DEBUG_REMOVE_CUSTOM_OBJECT_COLOR)
{
destColObj->removeCustomDebugColor();
serverCmd.m_type = CMD_USER_DEBUG_DRAW_COMPLETED;
}
if (clientCmd.m_updateFlags & USER_DEBUG_SET_CUSTOM_OBJECT_COLOR)
{
btVector3 objectColorRGB;
objectColorRGB.setValue(clientCmd.m_userDebugDrawArgs.m_objectDebugColorRGB[0],
clientCmd.m_userDebugDrawArgs.m_objectDebugColorRGB[1],
clientCmd.m_userDebugDrawArgs.m_objectDebugColorRGB[2]);
destColObj->setCustomDebugColor(objectColorRGB);
serverCmd.m_type = CMD_USER_DEBUG_DRAW_COMPLETED;
}
}
}
}
if (clientCmd.m_updateFlags & USER_DEBUG_HAS_TEXT)
{
//addUserDebugText3D( const double orientation[4], const double textColorRGB[3], double size, double lifeTime, int trackingObjectUniqueId, int optionFlags){return -1;}
int optionFlags = clientCmd.m_userDebugDrawArgs.m_optionFlags;
if ((clientCmd.m_updateFlags & USER_DEBUG_HAS_TEXT_ORIENTATION) == 0)
{
optionFlags |= DEB_DEBUG_TEXT_ALWAYS_FACE_CAMERA;
}
int replaceItemUniqueId = -1;
if ((clientCmd.m_updateFlags & USER_DEBUG_HAS_REPLACE_ITEM_UNIQUE_ID) != 0)
{
replaceItemUniqueId = clientCmd.m_userDebugDrawArgs.m_replaceItemUniqueId;
}
int uid = m_data->m_guiHelper->addUserDebugText3D(clientCmd.m_userDebugDrawArgs.m_text,
clientCmd.m_userDebugDrawArgs.m_textPositionXYZ,
clientCmd.m_userDebugDrawArgs.m_textOrientation,
clientCmd.m_userDebugDrawArgs.m_textColorRGB,
clientCmd.m_userDebugDrawArgs.m_textSize,
clientCmd.m_userDebugDrawArgs.m_lifeTime,
trackingVisualShapeIndex,
optionFlags,
replaceItemUniqueId);
if (uid >= 0)
{
serverCmd.m_userDebugDrawArgs.m_debugItemUniqueId = uid;
serverCmd.m_type = CMD_USER_DEBUG_DRAW_COMPLETED;
}
}
if (clientCmd.m_updateFlags & USER_DEBUG_HAS_LINE)
{
int replaceItemUid = -1;
if (clientCmd.m_updateFlags & USER_DEBUG_HAS_REPLACE_ITEM_UNIQUE_ID)
{
replaceItemUid = clientCmd.m_userDebugDrawArgs.m_replaceItemUniqueId;
}
int uid = m_data->m_guiHelper->addUserDebugLine(
clientCmd.m_userDebugDrawArgs.m_debugLineFromXYZ,
clientCmd.m_userDebugDrawArgs.m_debugLineToXYZ,
clientCmd.m_userDebugDrawArgs.m_debugLineColorRGB,
clientCmd.m_userDebugDrawArgs.m_lineWidth,
clientCmd.m_userDebugDrawArgs.m_lifeTime,
trackingVisualShapeIndex,
replaceItemUid);
if (uid >= 0)
{
serverCmd.m_userDebugDrawArgs.m_debugItemUniqueId = uid;
serverCmd.m_type = CMD_USER_DEBUG_DRAW_COMPLETED;
}
}
if (clientCmd.m_updateFlags & USER_DEBUG_REMOVE_ALL)
{
m_data->m_guiHelper->removeAllUserDebugItems();
serverCmd.m_type = CMD_USER_DEBUG_DRAW_COMPLETED;
}
if (clientCmd.m_updateFlags & USER_DEBUG_REMOVE_ALL_PARAMETERS)
{
m_data->m_guiHelper->removeAllUserParameters();
serverCmd.m_type = CMD_USER_DEBUG_DRAW_COMPLETED;
}
if (clientCmd.m_updateFlags & USER_DEBUG_REMOVE_ONE_ITEM)
{
m_data->m_guiHelper->removeUserDebugItem(clientCmd.m_userDebugDrawArgs.m_itemUniqueId);
serverCmd.m_type = CMD_USER_DEBUG_DRAW_COMPLETED;
}
return hasStatus;
}
bool PhysicsServerCommandProcessor::processSetVRCameraStateCommand(const struct SharedMemoryCommand& clientCmd, struct SharedMemoryStatus& serverStatusOut, char* bufferServerToClient, int bufferSizeInBytes)
{
bool hasStatus = true;
BT_PROFILE("CMD_SET_VR_CAMERA_STATE");
if (clientCmd.m_updateFlags & VR_CAMERA_ROOT_POSITION)
{
gVRTeleportPos1[0] = clientCmd.m_vrCameraStateArguments.m_rootPosition[0];
gVRTeleportPos1[1] = clientCmd.m_vrCameraStateArguments.m_rootPosition[1];
gVRTeleportPos1[2] = clientCmd.m_vrCameraStateArguments.m_rootPosition[2];
}
if (clientCmd.m_updateFlags & VR_CAMERA_ROOT_ORIENTATION)
{
gVRTeleportOrn[0] = clientCmd.m_vrCameraStateArguments.m_rootOrientation[0];
gVRTeleportOrn[1] = clientCmd.m_vrCameraStateArguments.m_rootOrientation[1];
gVRTeleportOrn[2] = clientCmd.m_vrCameraStateArguments.m_rootOrientation[2];
gVRTeleportOrn[3] = clientCmd.m_vrCameraStateArguments.m_rootOrientation[3];
}
if (clientCmd.m_updateFlags & VR_CAMERA_ROOT_TRACKING_OBJECT)
{
gVRTrackingObjectUniqueId = clientCmd.m_vrCameraStateArguments.m_trackingObjectUniqueId;
}
if (clientCmd.m_updateFlags & VR_CAMERA_FLAG)
{
gVRTrackingObjectFlag = clientCmd.m_vrCameraStateArguments.m_trackingObjectFlag;
}
serverStatusOut.m_type = CMD_CLIENT_COMMAND_COMPLETED;
return hasStatus;
}
bool PhysicsServerCommandProcessor::processRequestVREventsCommand(const struct SharedMemoryCommand& clientCmd, struct SharedMemoryStatus& serverStatusOut, char* bufferServerToClient, int bufferSizeInBytes)
{
bool hasStatus = true;
//BT_PROFILE("CMD_REQUEST_VR_EVENTS_DATA");
serverStatusOut.m_sendVREvents.m_numVRControllerEvents = 0;
for (int i = 0; i < MAX_VR_CONTROLLERS; i++)
{
b3VRControllerEvent& event = m_data->m_vrControllerEvents.m_vrEvents[i];
if (clientCmd.m_updateFlags & event.m_deviceType)
{
if (event.m_numButtonEvents + event.m_numMoveEvents)
{
serverStatusOut.m_sendVREvents.m_controllerEvents[serverStatusOut.m_sendVREvents.m_numVRControllerEvents++] = event;
event.m_numButtonEvents = 0;
event.m_numMoveEvents = 0;
for (int b = 0; b < MAX_VR_BUTTONS; b++)
{
event.m_buttons[b] = 0;
}
}
}
}
serverStatusOut.m_type = CMD_REQUEST_VR_EVENTS_DATA_COMPLETED;
return hasStatus;
}
bool PhysicsServerCommandProcessor::processRequestMouseEventsCommand(const struct SharedMemoryCommand& clientCmd, struct SharedMemoryStatus& serverStatusOut, char* bufferServerToClient, int bufferSizeInBytes)
{
bool hasStatus = true;
serverStatusOut.m_sendMouseEvents.m_numMouseEvents = m_data->m_mouseEvents.size();
if (serverStatusOut.m_sendMouseEvents.m_numMouseEvents > MAX_MOUSE_EVENTS)
{
serverStatusOut.m_sendMouseEvents.m_numMouseEvents = MAX_MOUSE_EVENTS;
}
for (int i = 0; i < serverStatusOut.m_sendMouseEvents.m_numMouseEvents; i++)
{
serverStatusOut.m_sendMouseEvents.m_mouseEvents[i] = m_data->m_mouseEvents[i];
}
m_data->m_mouseEvents.resize(0);
serverStatusOut.m_type = CMD_REQUEST_MOUSE_EVENTS_DATA_COMPLETED;
return hasStatus;
}
bool PhysicsServerCommandProcessor::processRequestKeyboardEventsCommand(const struct SharedMemoryCommand& clientCmd, struct SharedMemoryStatus& serverStatusOut, char* bufferServerToClient, int bufferSizeInBytes)
{
//BT_PROFILE("CMD_REQUEST_KEYBOARD_EVENTS_DATA");
bool hasStatus = true;
serverStatusOut.m_sendKeyboardEvents.m_numKeyboardEvents = m_data->m_keyboardEvents.size();
if (serverStatusOut.m_sendKeyboardEvents.m_numKeyboardEvents > MAX_KEYBOARD_EVENTS)
{
serverStatusOut.m_sendKeyboardEvents.m_numKeyboardEvents = MAX_KEYBOARD_EVENTS;
}
for (int i = 0; i < serverStatusOut.m_sendKeyboardEvents.m_numKeyboardEvents; i++)
{
serverStatusOut.m_sendKeyboardEvents.m_keyboardEvents[i] = m_data->m_keyboardEvents[i];
}
btAlignedObjectArray<b3KeyboardEvent> events;
//remove out-of-date events
for (int i = 0; i < m_data->m_keyboardEvents.size(); i++)
{
b3KeyboardEvent event = m_data->m_keyboardEvents[i];
if (event.m_keyState & eButtonIsDown)
{
event.m_keyState = eButtonIsDown;
events.push_back(event);
}
}
m_data->m_keyboardEvents.resize(events.size());
for (int i = 0; i < events.size(); i++)
{
m_data->m_keyboardEvents[i] = events[i];
}
serverStatusOut.m_type = CMD_REQUEST_KEYBOARD_EVENTS_DATA_COMPLETED;
return hasStatus;
}
#if __cplusplus >= 201103L
#include <atomic>
struct CastSyncInfo
{
std::atomic<int> m_nextTaskNumber;
CastSyncInfo() : m_nextTaskNumber(0) {}
inline int getNextTask()
{
return m_nextTaskNumber++;
}
};
#else // __cplusplus >= 201103L
struct CastSyncInfo
{
volatile int m_nextTaskNumber;
btSpinMutex m_taskLock;
CastSyncInfo() : m_nextTaskNumber(0) {}
inline int getNextTask()
{
m_taskLock.lock();
const int taskNr = m_nextTaskNumber++;
m_taskLock.unlock();
return taskNr;
}
};
#endif // __cplusplus >= 201103L
struct FilteredClosestRayResultCallback : public btCollisionWorld::ClosestRayResultCallback
{
FilteredClosestRayResultCallback(const btVector3& rayFromWorld, const btVector3& rayToWorld, int collisionFilterMask)
: btCollisionWorld::ClosestRayResultCallback(rayFromWorld, rayToWorld),
m_collisionFilterMask(collisionFilterMask)
{
}
int m_collisionFilterMask;
virtual btScalar addSingleResult(btCollisionWorld::LocalRayResult& rayResult, bool normalInWorldSpace)
{
bool collides = (rayResult.m_collisionObject->getBroadphaseHandle()->m_collisionFilterGroup & m_collisionFilterMask) != 0;
if (!collides)
return m_closestHitFraction;
return btCollisionWorld::ClosestRayResultCallback::addSingleResult(rayResult, normalInWorldSpace);
}
};
struct FilteredAllHitsRayResultCallback : public btCollisionWorld::AllHitsRayResultCallback
{
FilteredAllHitsRayResultCallback(const btVector3& rayFromWorld, const btVector3& rayToWorld, int collisionFilterMask, btScalar fractionEpsilon)
: btCollisionWorld::AllHitsRayResultCallback(rayFromWorld, rayToWorld),
m_collisionFilterMask(collisionFilterMask),
m_fractionEpsilon(fractionEpsilon)
{
}
int m_collisionFilterMask;
btScalar m_fractionEpsilon;
virtual btScalar addSingleResult(btCollisionWorld::LocalRayResult& rayResult, bool normalInWorldSpace)
{
bool collides = (rayResult.m_collisionObject->getBroadphaseHandle()->m_collisionFilterGroup & m_collisionFilterMask) != 0;
if (!collides)
return m_closestHitFraction;
//remove duplicate hits:
//same collision object, link index and hit fraction
bool isDuplicate = false;
for (int i = 0; i < m_collisionObjects.size(); i++)
{
if (m_collisionObjects[i] == rayResult.m_collisionObject)
{
btScalar diffFraction = m_hitFractions[i] - rayResult.m_hitFraction;
if (btEqual(diffFraction, m_fractionEpsilon))
{
isDuplicate = true;
break;
}
}
}
if (isDuplicate)
return m_closestHitFraction;
return btCollisionWorld::AllHitsRayResultCallback::addSingleResult(rayResult, normalInWorldSpace);
}
};
struct BatchRayCaster
{
b3ThreadPool* m_threadPool;
CastSyncInfo* m_syncInfo;
const btCollisionWorld* m_world;
const b3RayData* m_rayInputBuffer;
b3RayHitInfo* m_hitInfoOutputBuffer;
int m_numRays;
int m_reportHitNumber;
int m_collisionFilterMask;
btScalar m_fractionEpsilon;
BatchRayCaster(b3ThreadPool* threadPool, const btCollisionWorld* world, const b3RayData* rayInputBuffer, b3RayHitInfo* hitInfoOutputBuffer, int numRays, int reportHitNumber, int collisionFilterMask, btScalar fractionEpsilon)
: m_threadPool(threadPool), m_world(world), m_rayInputBuffer(rayInputBuffer), m_hitInfoOutputBuffer(hitInfoOutputBuffer), m_numRays(numRays), m_reportHitNumber(reportHitNumber), m_collisionFilterMask(collisionFilterMask), m_fractionEpsilon(fractionEpsilon)
{
m_syncInfo = new CastSyncInfo;
}
~BatchRayCaster()
{
delete m_syncInfo;
}
void castRays(int numWorkers)
{
#if BT_THREADSAFE
if (numWorkers <= 1)
{
castSequentially();
}
else
{
{
BT_PROFILE("BatchRayCaster_startingWorkerThreads");
int numTasks = btMin(m_threadPool->numWorkers(), numWorkers - 1);
for (int i = 0; i < numTasks; i++)
{
m_threadPool->runTask(i, BatchRayCaster::rayCastWorker, this);
}
}
rayCastWorker(this);
m_threadPool->waitForAllTasks();
}
#else // BT_THREADSAFE
castSequentially();
#endif // BT_THREADSAFE
}
static void rayCastWorker(void* arg)
{
BT_PROFILE("BatchRayCaster_raycastWorker");
BatchRayCaster* const obj = (BatchRayCaster*)arg;
const int numRays = obj->m_numRays;
int taskNr;
while (true)
{
{
BT_PROFILE("CastSyncInfo_getNextTask");
taskNr = obj->m_syncInfo->getNextTask();
}
if (taskNr >= numRays)
return;
obj->processRay(taskNr);
}
}
void castSequentially()
{
for (int i = 0; i < m_numRays; i++)
{
processRay(i);
}
}
void processRay(int ray)
{
BT_PROFILE("BatchRayCaster_processRay");
const double* from = m_rayInputBuffer[ray].m_rayFromPosition;
const double* to = m_rayInputBuffer[ray].m_rayToPosition;
btVector3 rayFromWorld(from[0], from[1], from[2]);
btVector3 rayToWorld(to[0], to[1], to[2]);
FilteredClosestRayResultCallback rayResultCallback(rayFromWorld, rayToWorld, m_collisionFilterMask);
rayResultCallback.m_flags |= btTriangleRaycastCallback::kF_UseGjkConvexCastRaytest;
if (m_reportHitNumber >= 0)
{
//compute all hits, and select the m_reportHitNumber, if available
FilteredAllHitsRayResultCallback allResultsCallback(rayFromWorld, rayToWorld, m_collisionFilterMask, m_fractionEpsilon);
allResultsCallback.m_flags |= btTriangleRaycastCallback::kF_UseGjkConvexCastRaytest;
m_world->rayTest(rayFromWorld, rayToWorld, allResultsCallback);
if (allResultsCallback.m_collisionObjects.size() > m_reportHitNumber)
{
rayResultCallback.m_collisionObject = allResultsCallback.m_collisionObjects[m_reportHitNumber];
rayResultCallback.m_closestHitFraction = allResultsCallback.m_hitFractions[m_reportHitNumber];
rayResultCallback.m_hitNormalWorld = allResultsCallback.m_hitNormalWorld[m_reportHitNumber];
rayResultCallback.m_hitPointWorld = allResultsCallback.m_hitPointWorld[m_reportHitNumber];
}
}
else
{
m_world->rayTest(rayFromWorld, rayToWorld, rayResultCallback);
}
b3RayHitInfo& hit = m_hitInfoOutputBuffer[ray];
if (rayResultCallback.hasHit())
{
hit.m_hitFraction = rayResultCallback.m_closestHitFraction;
int objectUniqueId = -1;
int linkIndex = -1;
const btRigidBody* body = btRigidBody::upcast(rayResultCallback.m_collisionObject);
#ifndef SKIP_SOFT_BODY_MULTI_BODY_DYNAMICS_WORLD
const btSoftBody* softBody = btSoftBody::upcast(rayResultCallback.m_collisionObject);
if (softBody)
{
objectUniqueId = rayResultCallback.m_collisionObject->getUserIndex2();
}
#endif //SKIP_SOFT_BODY_MULTI_BODY_DYNAMICS_WORLD
if (body)
{
objectUniqueId = rayResultCallback.m_collisionObject->getUserIndex2();
}
else
{
const btMultiBodyLinkCollider* mblB = btMultiBodyLinkCollider::upcast(rayResultCallback.m_collisionObject);
if (mblB && mblB->m_multiBody)
{
linkIndex = mblB->m_link;
objectUniqueId = mblB->m_multiBody->getUserIndex2();
}
}
hit.m_hitObjectUniqueId = objectUniqueId;
hit.m_hitObjectLinkIndex = linkIndex;
hit.m_hitPositionWorld[0] = rayResultCallback.m_hitPointWorld[0];
hit.m_hitPositionWorld[1] = rayResultCallback.m_hitPointWorld[1];
hit.m_hitPositionWorld[2] = rayResultCallback.m_hitPointWorld[2];
hit.m_hitNormalWorld[0] = rayResultCallback.m_hitNormalWorld[0];
hit.m_hitNormalWorld[1] = rayResultCallback.m_hitNormalWorld[1];
hit.m_hitNormalWorld[2] = rayResultCallback.m_hitNormalWorld[2];
}
else
{
hit.m_hitFraction = 1;
hit.m_hitObjectUniqueId = -1;
hit.m_hitObjectLinkIndex = -1;
hit.m_hitPositionWorld[0] = 0;
hit.m_hitPositionWorld[1] = 0;
hit.m_hitPositionWorld[2] = 0;
hit.m_hitNormalWorld[0] = 0;
hit.m_hitNormalWorld[1] = 0;
hit.m_hitNormalWorld[2] = 0;
}
}
};
void PhysicsServerCommandProcessor::createThreadPool()
{
#ifdef BT_THREADSAFE
if (m_data->m_threadPool == 0)
{
m_data->m_threadPool = new b3ThreadPool("PhysicsServerCommandProcessorThreadPool");
}
#endif //BT_THREADSAFE
}
bool PhysicsServerCommandProcessor::processRequestRaycastIntersectionsCommand(const struct SharedMemoryCommand& clientCmd, struct SharedMemoryStatus& serverStatusOut, char* bufferServerToClient, int bufferSizeInBytes)
{
bool hasStatus = true;
BT_PROFILE("CMD_REQUEST_RAY_CAST_INTERSECTIONS");
serverStatusOut.m_raycastHits.m_numRaycastHits = 0;
const int numCommandRays = clientCmd.m_requestRaycastIntersections.m_numCommandRays;
const int numStreamingRays = clientCmd.m_requestRaycastIntersections.m_numStreamingRays;
const int totalRays = numCommandRays + numStreamingRays;
int numThreads = clientCmd.m_requestRaycastIntersections.m_numThreads;
int reportHitNumber = clientCmd.m_requestRaycastIntersections.m_reportHitNumber;
int collisionFilterMask = clientCmd.m_requestRaycastIntersections.m_collisionFilterMask;
btScalar fractionEpsilon = clientCmd.m_requestRaycastIntersections.m_fractionEpsilon;
if (numThreads == 0)
{
// When 0 is specified, Bullet can decide how many threads to use.
// About 16 rays per thread seems to work reasonably well.
numThreads = btMax(1, totalRays / 16);
}
if (numThreads > 1)
{
createThreadPool();
}
btAlignedObjectArray<b3RayData> rays;
rays.resize(totalRays);
if (numCommandRays)
{
memcpy(&rays[0], &clientCmd.m_requestRaycastIntersections.m_fromToRays[0], numCommandRays * sizeof(b3RayData));
}
if (numStreamingRays)
{
memcpy(&rays[numCommandRays], bufferServerToClient, numStreamingRays * sizeof(b3RayData));
}
if (clientCmd.m_requestRaycastIntersections.m_parentObjectUniqueId >= 0)
{
btTransform tr;
tr.setIdentity();
InternalBodyHandle* bodyHandle = m_data->m_bodyHandles.getHandle(clientCmd.m_requestRaycastIntersections.m_parentObjectUniqueId);
if (bodyHandle)
{
int linkIndex = -1;
if (bodyHandle->m_multiBody)
{
int linkIndex = clientCmd.m_requestRaycastIntersections.m_parentLinkIndex;
if (linkIndex == -1)
{
tr = bodyHandle->m_multiBody->getBaseWorldTransform();
}
else
{
if (linkIndex >= 0 && linkIndex < bodyHandle->m_multiBody->getNumLinks())
{
tr = bodyHandle->m_multiBody->getLink(linkIndex).m_cachedWorldTransform;
}
}
}
if (bodyHandle->m_rigidBody)
{
tr = bodyHandle->m_rigidBody->getWorldTransform();
}
//convert all rays into world space
for (int i = 0; i < totalRays; i++)
{
btVector3 localPosTo(rays[i].m_rayToPosition[0], rays[i].m_rayToPosition[1], rays[i].m_rayToPosition[2]);
btVector3 worldPosTo = tr * localPosTo;
btVector3 localPosFrom(rays[i].m_rayFromPosition[0], rays[i].m_rayFromPosition[1], rays[i].m_rayFromPosition[2]);
btVector3 worldPosFrom = tr * localPosFrom;
rays[i].m_rayFromPosition[0] = worldPosFrom[0];
rays[i].m_rayFromPosition[1] = worldPosFrom[1];
rays[i].m_rayFromPosition[2] = worldPosFrom[2];
rays[i].m_rayToPosition[0] = worldPosTo[0];
rays[i].m_rayToPosition[1] = worldPosTo[1];
rays[i].m_rayToPosition[2] = worldPosTo[2];
}
}
}
BatchRayCaster batchRayCaster(m_data->m_threadPool, m_data->m_dynamicsWorld, &rays[0], (b3RayHitInfo*)bufferServerToClient, totalRays, reportHitNumber, collisionFilterMask, fractionEpsilon);
batchRayCaster.castRays(numThreads);
serverStatusOut.m_numDataStreamBytes = totalRays * sizeof(b3RayData);
serverStatusOut.m_raycastHits.m_numRaycastHits = totalRays;
serverStatusOut.m_type = CMD_REQUEST_RAY_CAST_INTERSECTIONS_COMPLETED;
return hasStatus;
}
bool PhysicsServerCommandProcessor::processRequestDebugLinesCommand(const struct SharedMemoryCommand& clientCmd, struct SharedMemoryStatus& serverStatusOut, char* bufferServerToClient, int bufferSizeInBytes)
{
bool hasStatus = true;
BT_PROFILE("CMD_REQUEST_DEBUG_LINES");
int curFlags = m_data->m_remoteDebugDrawer->getDebugMode();
int debugMode = clientCmd.m_requestDebugLinesArguments.m_debugMode; //clientCmd.btIDebugDraw::DBG_DrawWireframe|btIDebugDraw::DBG_DrawAabb;
int startingLineIndex = clientCmd.m_requestDebugLinesArguments.m_startingLineIndex;
if (startingLineIndex < 0)
{
b3Warning("startingLineIndex should be non-negative");
startingLineIndex = 0;
}
if (clientCmd.m_requestDebugLinesArguments.m_startingLineIndex == 0)
{
m_data->m_remoteDebugDrawer->m_lines2.resize(0);
//|btIDebugDraw::DBG_DrawAabb|
// btIDebugDraw::DBG_DrawConstraints |btIDebugDraw::DBG_DrawConstraintLimits ;
m_data->m_remoteDebugDrawer->setDebugMode(debugMode);
btIDebugDraw* oldDebugDrawer = m_data->m_dynamicsWorld->getDebugDrawer();
m_data->m_dynamicsWorld->setDebugDrawer(m_data->m_remoteDebugDrawer);
m_data->m_dynamicsWorld->debugDrawWorld();
m_data->m_dynamicsWorld->setDebugDrawer(oldDebugDrawer);
m_data->m_remoteDebugDrawer->setDebugMode(curFlags);
}
//9 floats per line: 3 floats for 'from', 3 floats for 'to' and 3 floats for 'color'
int bytesPerLine = (sizeof(float) * 9);
int maxNumLines = bufferSizeInBytes / bytesPerLine - 1;
if (startingLineIndex > m_data->m_remoteDebugDrawer->m_lines2.size())
{
b3Warning("m_startingLineIndex exceeds total number of debug lines");
startingLineIndex = m_data->m_remoteDebugDrawer->m_lines2.size();
}
int numLines = btMin(maxNumLines, m_data->m_remoteDebugDrawer->m_lines2.size() - startingLineIndex);
if (numLines)
{
float* linesFrom = (float*)bufferServerToClient;
float* linesTo = (float*)(bufferServerToClient + numLines * 3 * sizeof(float));
float* linesColor = (float*)(bufferServerToClient + 2 * numLines * 3 * sizeof(float));
for (int i = 0; i < numLines; i++)
{
linesFrom[i * 3] = m_data->m_remoteDebugDrawer->m_lines2[i + startingLineIndex].m_from.x();
linesTo[i * 3] = m_data->m_remoteDebugDrawer->m_lines2[i + startingLineIndex].m_to.x();
linesColor[i * 3] = m_data->m_remoteDebugDrawer->m_lines2[i + startingLineIndex].m_color.x();
linesFrom[i * 3 + 1] = m_data->m_remoteDebugDrawer->m_lines2[i + startingLineIndex].m_from.y();
linesTo[i * 3 + 1] = m_data->m_remoteDebugDrawer->m_lines2[i + startingLineIndex].m_to.y();
linesColor[i * 3 + 1] = m_data->m_remoteDebugDrawer->m_lines2[i + startingLineIndex].m_color.y();
linesFrom[i * 3 + 2] = m_data->m_remoteDebugDrawer->m_lines2[i + startingLineIndex].m_from.z();
linesTo[i * 3 + 2] = m_data->m_remoteDebugDrawer->m_lines2[i + startingLineIndex].m_to.z();
linesColor[i * 3 + 2] = m_data->m_remoteDebugDrawer->m_lines2[i + startingLineIndex].m_color.z();
}
}
serverStatusOut.m_type = CMD_DEBUG_LINES_COMPLETED;
serverStatusOut.m_numDataStreamBytes = numLines * bytesPerLine;
serverStatusOut.m_sendDebugLinesArgs.m_numDebugLines = numLines;
serverStatusOut.m_sendDebugLinesArgs.m_startingLineIndex = startingLineIndex;
serverStatusOut.m_sendDebugLinesArgs.m_numRemainingDebugLines = m_data->m_remoteDebugDrawer->m_lines2.size() - (startingLineIndex + numLines);
return hasStatus;
}
bool PhysicsServerCommandProcessor::processSyncBodyInfoCommand(const struct SharedMemoryCommand& clientCmd, struct SharedMemoryStatus& serverStatusOut, char* bufferServerToClient, int bufferSizeInBytes)
{
bool hasStatus = true;
BT_PROFILE("CMD_SYNC_BODY_INFO");
b3AlignedObjectArray<int> usedHandles;
m_data->m_bodyHandles.getUsedHandles(usedHandles);
int actualNumBodies = 0;
int* bodyUids = (int*)bufferServerToClient;
for (int i = 0; i < usedHandles.size(); i++)
{
int usedHandle = usedHandles[i];
InternalBodyData* body = m_data->m_bodyHandles.getHandle(usedHandle);
#ifndef SKIP_SOFT_BODY_MULTI_BODY_DYNAMICS_WORLD
if (body && (body->m_multiBody || body->m_rigidBody || body->m_softBody))
#else
if (body && (body->m_multiBody || body->m_rigidBody))
#endif
{
bodyUids[actualNumBodies++] = usedHandle;
}
}
serverStatusOut.m_sdfLoadedArgs.m_numBodies = actualNumBodies;
int usz = m_data->m_userConstraints.size();
int* constraintUid = bodyUids + actualNumBodies;
serverStatusOut.m_sdfLoadedArgs.m_numUserConstraints = usz;
for (int i = 0; i < usz; i++)
{
int key = m_data->m_userConstraints.getKeyAtIndex(i).getUid1();
constraintUid[i] = key;
}
serverStatusOut.m_numDataStreamBytes = sizeof(int) * (actualNumBodies + usz);
serverStatusOut.m_type = CMD_SYNC_BODY_INFO_COMPLETED;
return hasStatus;
}
bool PhysicsServerCommandProcessor::processSyncUserDataCommand(const struct SharedMemoryCommand& clientCmd, struct SharedMemoryStatus& serverStatusOut, char* bufferServerToClient, int bufferSizeInBytes)
{
bool hasStatus = true;
BT_PROFILE("CMD_SYNC_USER_DATA");
b3AlignedObjectArray<int> userDataHandles;
if (clientCmd.m_syncUserDataRequestArgs.m_numRequestedBodies == 0)
{
m_data->m_userDataHandles.getUsedHandles(userDataHandles);
}
else
{
for (int i = 0; i < clientCmd.m_syncUserDataRequestArgs.m_numRequestedBodies; ++i)
{
const int bodyUniqueId = clientCmd.m_syncUserDataRequestArgs.m_requestedBodyIds[i];
InternalBodyData* body = m_data->m_bodyHandles.getHandle(bodyUniqueId);
if (!body)
{
return hasStatus;
}
for (int j = 0; j < body->m_userDataHandles.size(); ++j)
{
userDataHandles.push_back(body->m_userDataHandles[j]);
}
}
}
int sizeInBytes = sizeof(int) * userDataHandles.size();
if (userDataHandles.size())
{
memcpy(bufferServerToClient, &userDataHandles[0], sizeInBytes);
}
// Only clear the client-side cache when a full sync is requested
serverStatusOut.m_syncUserDataArgs.m_clearCachedUserDataEntries = clientCmd.m_syncUserDataRequestArgs.m_numRequestedBodies == 0;
serverStatusOut.m_syncUserDataArgs.m_numUserDataIdentifiers = userDataHandles.size();
serverStatusOut.m_numDataStreamBytes = sizeInBytes;
serverStatusOut.m_type = CMD_SYNC_USER_DATA_COMPLETED;
return hasStatus;
}
bool PhysicsServerCommandProcessor::processRequestUserDataCommand(const struct SharedMemoryCommand& clientCmd, struct SharedMemoryStatus& serverStatusOut, char* bufferServerToClient, int bufferSizeInBytes)
{
bool hasStatus = true;
BT_PROFILE("CMD_REQUEST_USER_DATA");
serverStatusOut.m_type = CMD_REQUEST_USER_DATA_FAILED;
SharedMemoryUserData* userData = m_data->m_userDataHandles.getHandle(clientCmd.m_userDataRequestArgs.m_userDataId);
if (!userData)
{
return hasStatus;
}
btAssert(bufferSizeInBytes >= userData->m_bytes.size());
serverStatusOut.m_userDataResponseArgs.m_userDataId = clientCmd.m_userDataRequestArgs.m_userDataId;
serverStatusOut.m_userDataResponseArgs.m_bodyUniqueId = userData->m_bodyUniqueId;
serverStatusOut.m_userDataResponseArgs.m_linkIndex = userData->m_linkIndex;
serverStatusOut.m_userDataResponseArgs.m_visualShapeIndex = userData->m_visualShapeIndex;
serverStatusOut.m_userDataResponseArgs.m_valueType = userData->m_type;
serverStatusOut.m_userDataResponseArgs.m_valueLength = userData->m_bytes.size();
serverStatusOut.m_type = CMD_REQUEST_USER_DATA_COMPLETED;
strcpy(serverStatusOut.m_userDataResponseArgs.m_key, userData->m_key.c_str());
if (userData->m_bytes.size())
{
memcpy(bufferServerToClient, &userData->m_bytes[0], userData->m_bytes.size());
}
serverStatusOut.m_numDataStreamBytes = userData->m_bytes.size();
return hasStatus;
}
bool PhysicsServerCommandProcessor::processAddUserDataCommand(const struct SharedMemoryCommand& clientCmd, struct SharedMemoryStatus& serverStatusOut, char* bufferServerToClient, int bufferSizeInBytes)
{
bool hasStatus = true;
BT_PROFILE("CMD_ADD_USER_DATA");
serverStatusOut.m_type = CMD_ADD_USER_DATA_FAILED;
const AddUserDataRequestArgs& addUserDataArgs = clientCmd.m_addUserDataRequestArgs;
if (addUserDataArgs.m_bodyUniqueId < 0 || addUserDataArgs.m_bodyUniqueId >= m_data->m_bodyHandles.getNumHandles())
{
return hasStatus;
}
int userDataHandle = addUserData(
addUserDataArgs.m_bodyUniqueId, addUserDataArgs.m_linkIndex,
addUserDataArgs.m_visualShapeIndex, addUserDataArgs.m_key,
bufferServerToClient, addUserDataArgs.m_valueLength,
addUserDataArgs.m_valueType);
if (userDataHandle < 0)
{
return hasStatus;
}
serverStatusOut.m_type = CMD_ADD_USER_DATA_COMPLETED;
UserDataResponseArgs& userDataResponseArgs = serverStatusOut.m_userDataResponseArgs;
userDataResponseArgs.m_userDataId = userDataHandle;
userDataResponseArgs.m_bodyUniqueId = addUserDataArgs.m_bodyUniqueId;
userDataResponseArgs.m_linkIndex = addUserDataArgs.m_linkIndex;
userDataResponseArgs.m_visualShapeIndex = addUserDataArgs.m_visualShapeIndex;
userDataResponseArgs.m_valueLength = addUserDataArgs.m_valueLength;
userDataResponseArgs.m_valueType = addUserDataArgs.m_valueType;
strcpy(userDataResponseArgs.m_key, addUserDataArgs.m_key);
b3Notification notification;
notification.m_notificationType = USER_DATA_ADDED;
b3UserDataNotificationArgs& userDataArgs = notification.m_userDataArgs;
userDataArgs.m_userDataId = userDataHandle;
userDataArgs.m_bodyUniqueId = addUserDataArgs.m_bodyUniqueId;
userDataArgs.m_linkIndex = addUserDataArgs.m_linkIndex;
userDataArgs.m_visualShapeIndex = addUserDataArgs.m_visualShapeIndex;
strcpy(userDataArgs.m_key, addUserDataArgs.m_key);
m_data->m_pluginManager.addNotification(notification);
// Keep bufferServerToClient as-is.
return hasStatus;
}
bool PhysicsServerCommandProcessor::processCollisionFilterCommand(const struct SharedMemoryCommand& clientCmd, struct SharedMemoryStatus& serverStatusOut, char* bufferServerToClient, int bufferSizeInBytes)
{
serverStatusOut.m_type = CMD_CLIENT_COMMAND_COMPLETED;
b3PluginCollisionInterface* collisionInterface = m_data->m_pluginManager.getCollisionInterface();
if (collisionInterface)
{
if (clientCmd.m_updateFlags & B3_COLLISION_FILTER_PAIR)
{
collisionInterface->setBroadphaseCollisionFilter(clientCmd.m_collisionFilterArgs.m_bodyUniqueIdA,
clientCmd.m_collisionFilterArgs.m_bodyUniqueIdB,
clientCmd.m_collisionFilterArgs.m_linkIndexA,
clientCmd.m_collisionFilterArgs.m_linkIndexB,
clientCmd.m_collisionFilterArgs.m_enableCollision);
btAlignedObjectArray<InternalBodyData*> bodies;
//now also 'refresh' the broadphase collision pairs involved
if (clientCmd.m_collisionFilterArgs.m_bodyUniqueIdA >= 0)
{
bodies.push_back(m_data->m_bodyHandles.getHandle(clientCmd.m_collisionFilterArgs.m_bodyUniqueIdA));
}
if (clientCmd.m_collisionFilterArgs.m_bodyUniqueIdB >= 0)
{
bodies.push_back(m_data->m_bodyHandles.getHandle(clientCmd.m_collisionFilterArgs.m_bodyUniqueIdB));
}
for (int i = 0; i < bodies.size(); i++)
{
InternalBodyData* body = bodies[i];
if (body)
{
if (body->m_multiBody)
{
if (body->m_multiBody->getBaseCollider())
{
m_data->m_dynamicsWorld->refreshBroadphaseProxy(body->m_multiBody->getBaseCollider());
}
for (int i = 0; i < body->m_multiBody->getNumLinks(); i++)
{
if (body->m_multiBody->getLinkCollider(i))
{
m_data->m_dynamicsWorld->refreshBroadphaseProxy(body->m_multiBody->getLinkCollider(i));
}
}
}
else
{
//btRigidBody case
if (body->m_rigidBody)
{
m_data->m_dynamicsWorld->refreshBroadphaseProxy(body->m_rigidBody);
}
}
}
}
}
if (clientCmd.m_updateFlags & B3_COLLISION_FILTER_GROUP_MASK)
{
InternalBodyData* body = m_data->m_bodyHandles.getHandle(clientCmd.m_collisionFilterArgs.m_bodyUniqueIdA);
if (body)
{
btCollisionObject* colObj = 0;
if (body->m_multiBody)
{
if (clientCmd.m_collisionFilterArgs.m_linkIndexA == -1)
{
colObj = body->m_multiBody->getBaseCollider();
}
else
{
if (clientCmd.m_collisionFilterArgs.m_linkIndexA >= 0 && clientCmd.m_collisionFilterArgs.m_linkIndexA < body->m_multiBody->getNumLinks())
{
colObj = body->m_multiBody->getLinkCollider(clientCmd.m_collisionFilterArgs.m_linkIndexA);
}
}
}
else
{
if (body->m_rigidBody)
{
colObj = body->m_rigidBody;
}
}
if (colObj)
{
colObj->getBroadphaseHandle()->m_collisionFilterGroup = clientCmd.m_collisionFilterArgs.m_collisionFilterGroup;
colObj->getBroadphaseHandle()->m_collisionFilterMask = clientCmd.m_collisionFilterArgs.m_collisionFilterMask;
m_data->m_dynamicsWorld->refreshBroadphaseProxy(colObj);
}
}
}
}
return true;
}
bool PhysicsServerCommandProcessor::processRemoveUserDataCommand(const struct SharedMemoryCommand& clientCmd, struct SharedMemoryStatus& serverStatusOut, char* bufferServerToClient, int bufferSizeInBytes)
{
bool hasStatus = true;
BT_PROFILE("CMD_REMOVE_USER_DATA");
serverStatusOut.m_type = CMD_REMOVE_USER_DATA_FAILED;
SharedMemoryUserData* userData = m_data->m_userDataHandles.getHandle(clientCmd.m_removeUserDataRequestArgs.m_userDataId);
if (!userData)
{
return hasStatus;
}
InternalBodyData* body = m_data->m_bodyHandles.getHandle(userData->m_bodyUniqueId);
if (!body)
{
return hasStatus;
}
body->m_userDataHandles.remove(clientCmd.m_removeUserDataRequestArgs.m_userDataId);
b3Notification notification;
notification.m_notificationType = USER_DATA_REMOVED;
b3UserDataNotificationArgs& userDataArgs = notification.m_userDataArgs;
userDataArgs.m_userDataId = clientCmd.m_removeUserDataRequestArgs.m_userDataId;
userDataArgs.m_bodyUniqueId = userData->m_bodyUniqueId;
userDataArgs.m_linkIndex = userData->m_linkIndex;
userDataArgs.m_visualShapeIndex = userData->m_visualShapeIndex;
strcpy(userDataArgs.m_key, userData->m_key.c_str());
m_data->m_userDataHandleLookup.remove(SharedMemoryUserDataHashKey(userData));
m_data->m_userDataHandles.freeHandle(clientCmd.m_removeUserDataRequestArgs.m_userDataId);
serverStatusOut.m_removeUserDataResponseArgs = clientCmd.m_removeUserDataRequestArgs;
serverStatusOut.m_type = CMD_REMOVE_USER_DATA_COMPLETED;
m_data->m_pluginManager.addNotification(notification);
return hasStatus;
}
bool PhysicsServerCommandProcessor::processSendDesiredStateCommand(const struct SharedMemoryCommand& clientCmd, struct SharedMemoryStatus& serverStatusOut, char* bufferServerToClient, int bufferSizeInBytes)
{
bool hasStatus = true;
BT_PROFILE("CMD_SEND_DESIRED_STATE");
if (m_data->m_verboseOutput)
{
b3Printf("Processed CMD_SEND_DESIRED_STATE");
}
int bodyUniqueId = clientCmd.m_sendDesiredStateCommandArgument.m_bodyUniqueId;
InternalBodyData* body = m_data->m_bodyHandles.getHandle(bodyUniqueId);
if (body && body->m_multiBody)
{
btMultiBody* mb = body->m_multiBody;
btAssert(mb);
switch (clientCmd.m_sendDesiredStateCommandArgument.m_controlMode)
{
case CONTROL_MODE_PD:
{
if (m_data->m_verboseOutput)
{
b3Printf("Using CONTROL_MODE_PD");
}
b3PluginArguments args;
args.m_ints[1] = bodyUniqueId;
//find the joint motors and apply the desired velocity and maximum force/torque
{
args.m_numInts = 0;
args.m_numFloats = 0;
//syncBodies is expensive/slow, use it only once
m_data->m_pluginManager.executePluginCommand(m_data->m_pdControlPlugin, &args);
int velIndex = 6; //skip the 3 linear + 3 angular degree of freedom velocity entries of the base
int posIndex = 7; //skip 3 positional and 4 orientation (quaternion) positional degrees of freedom of the base
for (int link = 0; link < mb->getNumLinks(); link++)
{
if (supportsJointMotor(mb, link))
{
bool hasDesiredPosOrVel = false;
btScalar desiredVelocity = 0.f;
if ((clientCmd.m_sendDesiredStateCommandArgument.m_hasDesiredStateFlags[velIndex] & SIM_DESIRED_STATE_HAS_QDOT) != 0)
{
hasDesiredPosOrVel = true;
desiredVelocity = clientCmd.m_sendDesiredStateCommandArgument.m_desiredStateQdot[velIndex];
args.m_floats[2] = 0.1; // kd
}
btScalar desiredPosition = 0.f;
if ((clientCmd.m_sendDesiredStateCommandArgument.m_hasDesiredStateFlags[posIndex] & SIM_DESIRED_STATE_HAS_Q) != 0)
{
hasDesiredPosOrVel = true;
desiredPosition = clientCmd.m_sendDesiredStateCommandArgument.m_desiredStateQ[posIndex];
args.m_floats[3] = 0.1; // kp
}
if (hasDesiredPosOrVel)
{
if ((clientCmd.m_sendDesiredStateCommandArgument.m_hasDesiredStateFlags[velIndex] & SIM_DESIRED_STATE_HAS_KP) != 0)
{
args.m_floats[3] = clientCmd.m_sendDesiredStateCommandArgument.m_Kp[velIndex];
}
if ((clientCmd.m_sendDesiredStateCommandArgument.m_hasDesiredStateFlags[velIndex] & SIM_DESIRED_STATE_HAS_KD) != 0)
{
args.m_floats[2] = clientCmd.m_sendDesiredStateCommandArgument.m_Kd[velIndex];
}
args.m_floats[1] = desiredVelocity;
//clamp position
if (mb->getLink(link).m_jointLowerLimit <= mb->getLink(link).m_jointUpperLimit)
{
btClamp(desiredPosition, mb->getLink(link).m_jointLowerLimit, mb->getLink(link).m_jointUpperLimit);
}
args.m_floats[0] = desiredPosition;
btScalar maxImp = 1000000.f;
if ((clientCmd.m_updateFlags & SIM_DESIRED_STATE_HAS_MAX_FORCE) != 0)
maxImp = clientCmd.m_sendDesiredStateCommandArgument.m_desiredStateForceTorque[velIndex];
args.m_floats[4] = maxImp;
args.m_ints[2] = link;
args.m_numInts = 3;
args.m_numFloats = 5;
args.m_ints[0] = eSetPDControl;
if (args.m_floats[4] < B3_EPSILON)
{
args.m_ints[0] = eRemovePDControl;
}
m_data->m_pluginManager.executePluginCommand(m_data->m_pdControlPlugin, &args);
}
}
velIndex += mb->getLink(link).m_dofCount;
posIndex += mb->getLink(link).m_posVarCount;
}
}
break;
}
case CONTROL_MODE_TORQUE:
{
if (m_data->m_verboseOutput)
{
b3Printf("Using CONTROL_MODE_TORQUE");
}
// mb->clearForcesAndTorques();
int torqueIndex = 6;
if ((clientCmd.m_updateFlags & SIM_DESIRED_STATE_HAS_MAX_FORCE) != 0)
{
for (int link = 0; link < mb->getNumLinks(); link++)
{
for (int dof = 0; dof < mb->getLink(link).m_dofCount; dof++)
{
double torque = 0.f;
if ((clientCmd.m_sendDesiredStateCommandArgument.m_hasDesiredStateFlags[torqueIndex] & SIM_DESIRED_STATE_HAS_MAX_FORCE) != 0)
{
torque = clientCmd.m_sendDesiredStateCommandArgument.m_desiredStateForceTorque[torqueIndex];
mb->addJointTorqueMultiDof(link, dof, torque);
}
torqueIndex++;
}
}
}
break;
}
case CONTROL_MODE_VELOCITY:
{
if (m_data->m_verboseOutput)
{
b3Printf("Using CONTROL_MODE_VELOCITY");
}
int numMotors = 0;
//find the joint motors and apply the desired velocity and maximum force/torque
{
int dofIndex = 6; //skip the 3 linear + 3 angular degree of freedom entries of the base
for (int link = 0; link < mb->getNumLinks(); link++)
{
if (supportsJointMotor(mb, link))
{
btMultiBodyJointMotor* motor = (btMultiBodyJointMotor*)mb->getLink(link).m_userPtr;
if (motor)
{
btScalar desiredVelocity = 0.f;
bool hasDesiredVelocity = false;
if ((clientCmd.m_sendDesiredStateCommandArgument.m_hasDesiredStateFlags[dofIndex] & SIM_DESIRED_STATE_HAS_QDOT) != 0)
{
desiredVelocity = clientCmd.m_sendDesiredStateCommandArgument.m_desiredStateQdot[dofIndex];
btScalar kd = 0.1f;
if ((clientCmd.m_sendDesiredStateCommandArgument.m_hasDesiredStateFlags[dofIndex] & SIM_DESIRED_STATE_HAS_KD) != 0)
{
kd = clientCmd.m_sendDesiredStateCommandArgument.m_Kd[dofIndex];
}
motor->setVelocityTarget(desiredVelocity, kd);
btScalar kp = 0.f;
motor->setPositionTarget(0, kp);
hasDesiredVelocity = true;
}
if (hasDesiredVelocity)
{
//disable velocity clamp in velocity mode
motor->setRhsClamp(SIMD_INFINITY);
btScalar maxImp = 1000000.f * m_data->m_physicsDeltaTime;
if ((clientCmd.m_sendDesiredStateCommandArgument.m_hasDesiredStateFlags[dofIndex] & SIM_DESIRED_STATE_HAS_MAX_FORCE) != 0)
{
maxImp = clientCmd.m_sendDesiredStateCommandArgument.m_desiredStateForceTorque[dofIndex] * m_data->m_physicsDeltaTime;
}
motor->setMaxAppliedImpulse(maxImp);
}
numMotors++;
}
}
dofIndex += mb->getLink(link).m_dofCount;
}
}
break;
}
case CONTROL_MODE_POSITION_VELOCITY_PD:
{
if (m_data->m_verboseOutput)
{
b3Printf("Using CONTROL_MODE_POSITION_VELOCITY_PD");
}
//compute the force base on PD control
int numMotors = 0;
//find the joint motors and apply the desired velocity and maximum force/torque
{
int velIndex = 6; //skip the 3 linear + 3 angular degree of freedom velocity entries of the base
int posIndex = 7; //skip 3 positional and 4 orientation (quaternion) positional degrees of freedom of the base
for (int link = 0; link < mb->getNumLinks(); link++)
{
if (supportsJointMotor(mb, link))
{
btMultiBodyJointMotor* motor = (btMultiBodyJointMotor*)mb->getLink(link).m_userPtr;
if (motor)
{
if ((clientCmd.m_sendDesiredStateCommandArgument.m_hasDesiredStateFlags[velIndex] & SIM_DESIRED_STATE_HAS_RHS_CLAMP) != 0)
{
motor->setRhsClamp(clientCmd.m_sendDesiredStateCommandArgument.m_rhsClamp[velIndex]);
}
bool hasDesiredPosOrVel = false;
btScalar kp = 0.f;
btScalar kd = 0.f;
btScalar desiredVelocity = 0.f;
if ((clientCmd.m_sendDesiredStateCommandArgument.m_hasDesiredStateFlags[velIndex] & SIM_DESIRED_STATE_HAS_QDOT) != 0)
{
hasDesiredPosOrVel = true;
desiredVelocity = clientCmd.m_sendDesiredStateCommandArgument.m_desiredStateQdot[velIndex];
kd = 0.1;
}
btScalar desiredPosition = 0.f;
if ((clientCmd.m_sendDesiredStateCommandArgument.m_hasDesiredStateFlags[posIndex] & SIM_DESIRED_STATE_HAS_Q) != 0)
{
hasDesiredPosOrVel = true;
desiredPosition = clientCmd.m_sendDesiredStateCommandArgument.m_desiredStateQ[posIndex];
kp = 0.1;
}
if (hasDesiredPosOrVel)
{
if ((clientCmd.m_sendDesiredStateCommandArgument.m_hasDesiredStateFlags[velIndex] & SIM_DESIRED_STATE_HAS_KP) != 0)
{
kp = clientCmd.m_sendDesiredStateCommandArgument.m_Kp[velIndex];
}
if ((clientCmd.m_sendDesiredStateCommandArgument.m_hasDesiredStateFlags[velIndex] & SIM_DESIRED_STATE_HAS_KD) != 0)
{
kd = clientCmd.m_sendDesiredStateCommandArgument.m_Kd[velIndex];
}
motor->setVelocityTarget(desiredVelocity, kd);
//todo: instead of clamping, combine the motor and limit
//and combine handling of limit force and motor force.
//clamp position
if (mb->getLink(link).m_jointLowerLimit <= mb->getLink(link).m_jointUpperLimit)
{
btClamp(desiredPosition, mb->getLink(link).m_jointLowerLimit, mb->getLink(link).m_jointUpperLimit);
}
motor->setPositionTarget(desiredPosition, kp);
btScalar maxImp = 1000000.f * m_data->m_physicsDeltaTime;
if ((clientCmd.m_updateFlags & SIM_DESIRED_STATE_HAS_MAX_FORCE) != 0)
maxImp = clientCmd.m_sendDesiredStateCommandArgument.m_desiredStateForceTorque[velIndex] * m_data->m_physicsDeltaTime;
motor->setMaxAppliedImpulse(maxImp);
}
numMotors++;
}
}
if (mb->getLink(link).m_jointType == btMultibodyLink::eSpherical)
{
btMultiBodySphericalJointMotor* motor = (btMultiBodySphericalJointMotor*)mb->getLink(link).m_userPtr;
if (motor)
{
if ((clientCmd.m_sendDesiredStateCommandArgument.m_hasDesiredStateFlags[velIndex] & SIM_DESIRED_STATE_HAS_RHS_CLAMP) != 0)
{
motor->setRhsClamp(clientCmd.m_sendDesiredStateCommandArgument.m_rhsClamp[velIndex]);
}
bool hasDesiredPosOrVel = false;
btVector3 kp(0, 0, 0);
btVector3 kd(0, 0, 0);
btVector3 desiredVelocity(0, 0, 0);
if ((clientCmd.m_sendDesiredStateCommandArgument.m_hasDesiredStateFlags[velIndex] & SIM_DESIRED_STATE_HAS_QDOT) != 0)
{
hasDesiredPosOrVel = true;
desiredVelocity.setValue(
clientCmd.m_sendDesiredStateCommandArgument.m_desiredStateQdot[velIndex + 0],
clientCmd.m_sendDesiredStateCommandArgument.m_desiredStateQdot[velIndex + 1],
clientCmd.m_sendDesiredStateCommandArgument.m_desiredStateQdot[velIndex + 2]);
kd.setValue(0.1, 0.1, 0.1);
}
btQuaternion desiredPosition(0, 0, 0, 1);
if ((clientCmd.m_sendDesiredStateCommandArgument.m_hasDesiredStateFlags[posIndex] & SIM_DESIRED_STATE_HAS_Q) != 0)
{
hasDesiredPosOrVel = true;
desiredPosition.setValue(
clientCmd.m_sendDesiredStateCommandArgument.m_desiredStateQ[posIndex + 0],
clientCmd.m_sendDesiredStateCommandArgument.m_desiredStateQ[posIndex + 1],
clientCmd.m_sendDesiredStateCommandArgument.m_desiredStateQ[posIndex + 2],
clientCmd.m_sendDesiredStateCommandArgument.m_desiredStateQ[posIndex + 3]);
kp.setValue(0.1, 0.1, 0.1);
}
if (hasDesiredPosOrVel)
{
bool useMultiDof = true;
if ((clientCmd.m_sendDesiredStateCommandArgument.m_hasDesiredStateFlags[velIndex] & SIM_DESIRED_STATE_HAS_KP) != 0)
{
kp.setValue(
clientCmd.m_sendDesiredStateCommandArgument.m_Kp[velIndex + 0],
clientCmd.m_sendDesiredStateCommandArgument.m_Kp[velIndex + 0],
clientCmd.m_sendDesiredStateCommandArgument.m_Kp[velIndex + 0]);
}
if (((clientCmd.m_sendDesiredStateCommandArgument.m_hasDesiredStateFlags[velIndex+0] & SIM_DESIRED_STATE_HAS_KP) != 0) &&
((clientCmd.m_sendDesiredStateCommandArgument.m_hasDesiredStateFlags[velIndex+1] & SIM_DESIRED_STATE_HAS_KP) != 0) &&
((clientCmd.m_sendDesiredStateCommandArgument.m_hasDesiredStateFlags[velIndex+2] & SIM_DESIRED_STATE_HAS_KP) != 0)
)
{
kp.setValue(
clientCmd.m_sendDesiredStateCommandArgument.m_Kp[velIndex + 0],
clientCmd.m_sendDesiredStateCommandArgument.m_Kp[velIndex + 1],
clientCmd.m_sendDesiredStateCommandArgument.m_Kp[velIndex + 2]);
} else
{
useMultiDof = false;
}
if ((clientCmd.m_sendDesiredStateCommandArgument.m_hasDesiredStateFlags[velIndex] & SIM_DESIRED_STATE_HAS_KD) != 0)
{
kd.setValue(
clientCmd.m_sendDesiredStateCommandArgument.m_Kd[velIndex + 0],
clientCmd.m_sendDesiredStateCommandArgument.m_Kd[velIndex + 0],
clientCmd.m_sendDesiredStateCommandArgument.m_Kd[velIndex + 0]);
}
if (((clientCmd.m_sendDesiredStateCommandArgument.m_hasDesiredStateFlags[velIndex+0] & SIM_DESIRED_STATE_HAS_KD) != 0) &&
((clientCmd.m_sendDesiredStateCommandArgument.m_hasDesiredStateFlags[velIndex+1] & SIM_DESIRED_STATE_HAS_KD) != 0) &&
((clientCmd.m_sendDesiredStateCommandArgument.m_hasDesiredStateFlags[velIndex+2] & SIM_DESIRED_STATE_HAS_KD) != 0))
{
kd.setValue(
clientCmd.m_sendDesiredStateCommandArgument.m_Kd[velIndex + 0],
clientCmd.m_sendDesiredStateCommandArgument.m_Kd[velIndex + 1],
clientCmd.m_sendDesiredStateCommandArgument.m_Kd[velIndex + 2]);
} else
{
useMultiDof = false;
}
btVector3 maxImp(
1000000.f * m_data->m_physicsDeltaTime,
1000000.f * m_data->m_physicsDeltaTime,
1000000.f * m_data->m_physicsDeltaTime);
if ((clientCmd.m_sendDesiredStateCommandArgument.m_hasDesiredStateFlags[velIndex] & SIM_DESIRED_STATE_HAS_MAX_FORCE)!=0)
{
maxImp.setValue(
clientCmd.m_sendDesiredStateCommandArgument.m_desiredStateForceTorque[velIndex + 0] * m_data->m_physicsDeltaTime,
clientCmd.m_sendDesiredStateCommandArgument.m_desiredStateForceTorque[velIndex + 0] * m_data->m_physicsDeltaTime,
clientCmd.m_sendDesiredStateCommandArgument.m_desiredStateForceTorque[velIndex + 0] * m_data->m_physicsDeltaTime);
}
if (((clientCmd.m_sendDesiredStateCommandArgument.m_hasDesiredStateFlags[velIndex+0] & SIM_DESIRED_STATE_HAS_MAX_FORCE)!=0) &&
((clientCmd.m_sendDesiredStateCommandArgument.m_hasDesiredStateFlags[velIndex+1] & SIM_DESIRED_STATE_HAS_MAX_FORCE)!=0) &&
((clientCmd.m_sendDesiredStateCommandArgument.m_hasDesiredStateFlags[velIndex+2] & SIM_DESIRED_STATE_HAS_MAX_FORCE)!=0))
{
maxImp.setValue(
clientCmd.m_sendDesiredStateCommandArgument.m_desiredStateForceTorque[velIndex + 0] * m_data->m_physicsDeltaTime,
clientCmd.m_sendDesiredStateCommandArgument.m_desiredStateForceTorque[velIndex + 1] * m_data->m_physicsDeltaTime,
clientCmd.m_sendDesiredStateCommandArgument.m_desiredStateForceTorque[velIndex + 2] * m_data->m_physicsDeltaTime);
} else
{
useMultiDof = false;
}
if (useMultiDof)
{
motor->setVelocityTargetMultiDof(desiredVelocity, kd);
motor->setPositionTargetMultiDof(desiredPosition, kp);
motor->setMaxAppliedImpulseMultiDof(maxImp);
} else
{
motor->setVelocityTarget(desiredVelocity, kd[0]);
//todo: instead of clamping, combine the motor and limit
//and combine handling of limit force and motor force.
//clamp position
//if (mb->getLink(link).m_jointLowerLimit <= mb->getLink(link).m_jointUpperLimit)
//{
// btClamp(desiredPosition, mb->getLink(link).m_jointLowerLimit, mb->getLink(link).m_jointUpperLimit);
//}
motor->setPositionTarget(desiredPosition, kp[0]);
motor->setMaxAppliedImpulse(maxImp[0]);
}
btVector3 damping(1.f, 1.f, 1.f);
if ((clientCmd.m_updateFlags & SIM_DESIRED_STATE_HAS_DAMPING) != 0) {
if (
(clientCmd.m_sendDesiredStateCommandArgument.m_hasDesiredStateFlags[velIndex+0] & SIM_DESIRED_STATE_HAS_DAMPING)&&
(clientCmd.m_sendDesiredStateCommandArgument.m_hasDesiredStateFlags[velIndex+1] & SIM_DESIRED_STATE_HAS_DAMPING)&&
(clientCmd.m_sendDesiredStateCommandArgument.m_hasDesiredStateFlags[velIndex+2] & SIM_DESIRED_STATE_HAS_DAMPING)
)
{
damping.setValue(
clientCmd.m_sendDesiredStateCommandArgument.m_damping[velIndex + 0],
clientCmd.m_sendDesiredStateCommandArgument.m_damping[velIndex + 1],
clientCmd.m_sendDesiredStateCommandArgument.m_damping[velIndex + 2]);
} else
{
damping.setValue(
clientCmd.m_sendDesiredStateCommandArgument.m_damping[velIndex + 0],
clientCmd.m_sendDesiredStateCommandArgument.m_damping[velIndex + 0],
clientCmd.m_sendDesiredStateCommandArgument.m_damping[velIndex + 0]);
}
}
motor->setDamping(damping);
}
numMotors++;
}
}
velIndex += mb->getLink(link).m_dofCount;
posIndex += mb->getLink(link).m_posVarCount;
}
}
break;
}
#ifdef STATIC_LINK_SPD_PLUGIN
case CONTROL_MODE_STABLE_PD:
{
int posVal = body->m_multiBody->getNumPosVars();
btAlignedObjectArray<double> zeroVel;
int dof = 7 + posVal;
zeroVel.resize(dof);
//clientCmd.m_sendDesiredStateCommandArgument.
//current positions and velocities
btAlignedObjectArray<double> jointPositionsQ;
btAlignedObjectArray<double> jointVelocitiesQdot;
btTransform baseTr = body->m_multiBody->getBaseWorldTransform();
#if 1
jointPositionsQ.push_back(baseTr.getOrigin()[0]);
jointPositionsQ.push_back(baseTr.getOrigin()[1]);
jointPositionsQ.push_back(baseTr.getOrigin()[2]);
jointPositionsQ.push_back(baseTr.getRotation()[0]);
jointPositionsQ.push_back(baseTr.getRotation()[1]);
jointPositionsQ.push_back(baseTr.getRotation()[2]);
jointPositionsQ.push_back(baseTr.getRotation()[3]);
jointVelocitiesQdot.push_back(body->m_multiBody->getBaseVel()[0]);
jointVelocitiesQdot.push_back(body->m_multiBody->getBaseVel()[1]);
jointVelocitiesQdot.push_back(body->m_multiBody->getBaseVel()[2]);
jointVelocitiesQdot.push_back(body->m_multiBody->getBaseOmega()[0]);
jointVelocitiesQdot.push_back(body->m_multiBody->getBaseOmega()[1]);
jointVelocitiesQdot.push_back(body->m_multiBody->getBaseOmega()[2]);
jointVelocitiesQdot.push_back(0);
#else
for (int i = 0; i < 7; i++)
{
jointPositionsQ.push_back(0);
jointVelocitiesQdot.push_back(0);
}
jointPositionsQ[6] = 1;
#endif
for (int i = 0; i < body->m_multiBody->getNumLinks(); i++)
{
switch (body->m_multiBody->getLink(i).m_jointType)
{
case btMultibodyLink::eSpherical:
{
btScalar* jointPos = body->m_multiBody->getJointPosMultiDof(i);
jointPositionsQ.push_back(jointPos[0]);
jointPositionsQ.push_back(jointPos[1]);
jointPositionsQ.push_back(jointPos[2]);
jointPositionsQ.push_back(jointPos[3]);
btScalar* jointVel = body->m_multiBody->getJointVelMultiDof(i);
jointVelocitiesQdot.push_back(jointVel[0]);
jointVelocitiesQdot.push_back(jointVel[1]);
jointVelocitiesQdot.push_back(jointVel[2]);
jointVelocitiesQdot.push_back(0);
break;
}
case btMultibodyLink::ePrismatic:
case btMultibodyLink::eRevolute:
{
btScalar* jointPos = body->m_multiBody->getJointPosMultiDof(i);
jointPositionsQ.push_back(jointPos[0]);
btScalar* jointVel = body->m_multiBody->getJointVelMultiDof(i);
jointVelocitiesQdot.push_back(jointVel[0]);
break;
}
case btMultibodyLink::eFixed:
{
//skip
break;
}
default:
{
b3Error("Unsupported joint type");
btAssert(0);
}
}
}
cRBDModel* rbdModel = 0;
{
BT_PROFILE("findOrCreateRBDModel");
rbdModel = m_data->findOrCreateRBDModel(body->m_multiBody, &jointPositionsQ[0], &jointVelocitiesQdot[0]);
}
if (rbdModel)
{
int num_dof = jointPositionsQ.size();
const Eigen::VectorXd& pose = rbdModel->GetPose();
const Eigen::VectorXd& vel = rbdModel->GetVel();
Eigen::Map<Eigen::VectorXd> mKp((double*)clientCmd.m_sendDesiredStateCommandArgument.m_Kp, num_dof);
Eigen::Map<Eigen::VectorXd> mKd((double*)clientCmd.m_sendDesiredStateCommandArgument.m_Kd, num_dof);
Eigen::Map<Eigen::VectorXd> maxForce((double*)clientCmd.m_sendDesiredStateCommandArgument.m_desiredStateForceTorque, num_dof);
Eigen::DiagonalMatrix<double, Eigen::Dynamic> Kp_mat = mKp.asDiagonal();
Eigen::DiagonalMatrix<double, Eigen::Dynamic> Kd_mat = mKd.asDiagonal();
Eigen::MatrixXd M = rbdModel->GetMassMat();
//rbdModel->UpdateBiasForce();
const Eigen::VectorXd& C = rbdModel->GetBiasForce();
M.diagonal() += m_data->m_physicsDeltaTime * mKd;
Eigen::VectorXd pose_inc;
const Eigen::MatrixXd& joint_mat = rbdModel->GetJointMat();
{
BT_PROFILE("cKinTree::VelToPoseDiff");
cKinTree::VelToPoseDiff(joint_mat, rbdModel->GetPose(), rbdModel->GetVel(), pose_inc);
}
//tar_pose needs to be reshuffled?
Eigen::VectorXd tar_pose, tar_vel;
{
BT_PROFILE("convertPose");
PhysicsServerCommandProcessorInternalData::convertPose(body->m_multiBody,
(double*)clientCmd.m_sendDesiredStateCommandArgument.m_desiredStateQ,
(double*)clientCmd.m_sendDesiredStateCommandArgument.m_desiredStateQdot,
tar_pose, tar_vel);
}
pose_inc = pose + m_data->m_physicsDeltaTime * pose_inc;
{
BT_PROFILE("cKinTree::PostProcessPose");
cKinTree::PostProcessPose(joint_mat, pose_inc);
}
Eigen::VectorXd pose_err;
{
BT_PROFILE("cKinTree::CalcVel");
cKinTree::CalcVel(joint_mat, pose_inc, tar_pose, 1, pose_err);
}
for (int i = 0; i < 7; i++)
{
pose_err[i] = 0;
}
Eigen::VectorXd vel_err = tar_vel - vel;
Eigen::VectorXd acc;
{
BT_PROFILE("acc");
acc = Kp_mat * pose_err + Kd_mat * vel_err - C;
}
{
BT_PROFILE("M.ldlt().solve");
acc = M.ldlt().solve(acc);
}
Eigen::VectorXd out_tau = Eigen::VectorXd::Zero(num_dof);
out_tau += Kp_mat * pose_err + Kd_mat * (vel_err - m_data->m_physicsDeltaTime * acc);
//clamp the forces
out_tau = out_tau.cwiseMax(-maxForce);
out_tau = out_tau.cwiseMin(maxForce);
//apply the forces
int torqueIndex = 7;
for (int link = 0; link < mb->getNumLinks(); link++)
{
int dofCount = mb->getLink(link).m_dofCount;
int dofOffset = mb->getLink(link).m_dofOffset;
if (dofCount == 3)
{
for (int dof = 0; dof < 3; dof++)
{
double torque = out_tau[torqueIndex + dof];
mb->addJointTorqueMultiDof(link, dof, torque);
}
torqueIndex += 4;
}
if (dofCount == 1)
{
double torque = out_tau[torqueIndex];
mb->addJointTorqueMultiDof(link, 0, torque);
torqueIndex++;
}
}
}
break;
}
#endif
default:
{
b3Warning("m_controlMode not implemented yet");
break;
}
}
}
else
{
//support for non-btMultiBody, such as btRigidBody
if (body && body->m_rigidBody)
{
btRigidBody* rb = body->m_rigidBody;
btAssert(rb);
//switch (clientCmd.m_sendDesiredStateCommandArgument.m_controlMode)
{
//case CONTROL_MODE_TORQUE:
{
if (m_data->m_verboseOutput)
{
b3Printf("Using CONTROL_MODE_TORQUE");
}
// mb->clearForcesAndTorques();
///see addJointInfoFromConstraint
int velIndex = 6;
int posIndex = 7;
//if ((clientCmd.m_updateFlags&SIM_DESIRED_STATE_HAS_MAX_FORCE)!=0)
{
for (int link = 0; link < body->m_rigidBodyJoints.size(); link++)
{
btGeneric6DofSpring2Constraint* con = body->m_rigidBodyJoints[link];
btVector3 linearLowerLimit;
btVector3 linearUpperLimit;
btVector3 angularLowerLimit;
btVector3 angularUpperLimit;
//for (int dof=0;dof<mb->getLink(link).m_dofCount;dof++)
{
{
int torqueIndex = velIndex;
double torque = 100;
bool hasDesiredTorque = false;
if ((clientCmd.m_sendDesiredStateCommandArgument.m_hasDesiredStateFlags[velIndex] & SIM_DESIRED_STATE_HAS_MAX_FORCE) != 0)
{
torque = clientCmd.m_sendDesiredStateCommandArgument.m_desiredStateForceTorque[velIndex];
hasDesiredTorque = true;
}
bool hasDesiredPosOrVel = false;
btScalar qdotTarget = 0.f;
if ((clientCmd.m_sendDesiredStateCommandArgument.m_hasDesiredStateFlags[velIndex] & SIM_DESIRED_STATE_HAS_QDOT) != 0)
{
hasDesiredPosOrVel = true;
qdotTarget = clientCmd.m_sendDesiredStateCommandArgument.m_desiredStateQdot[velIndex];
}
btScalar qTarget = 0.f;
if ((clientCmd.m_sendDesiredStateCommandArgument.m_hasDesiredStateFlags[posIndex] & SIM_DESIRED_STATE_HAS_Q) != 0)
{
hasDesiredPosOrVel = true;
qTarget = clientCmd.m_sendDesiredStateCommandArgument.m_desiredStateQ[posIndex];
}
con->getLinearLowerLimit(linearLowerLimit);
con->getLinearUpperLimit(linearUpperLimit);
con->getAngularLowerLimit(angularLowerLimit);
con->getAngularUpperLimit(angularUpperLimit);
if (linearLowerLimit.isZero() && linearUpperLimit.isZero() && angularLowerLimit.isZero() && angularUpperLimit.isZero())
{
//fixed, don't do anything
}
else
{
con->calculateTransforms();
if (linearLowerLimit.isZero() && linearUpperLimit.isZero())
{
//eRevoluteType;
btVector3 limitRange = angularLowerLimit.absolute() + angularUpperLimit.absolute();
int limitAxis = limitRange.maxAxis();
const btTransform& transA = con->getCalculatedTransformA();
const btTransform& transB = con->getCalculatedTransformB();
btVector3 axisA = transA.getBasis().getColumn(limitAxis);
btVector3 axisB = transB.getBasis().getColumn(limitAxis);
switch (clientCmd.m_sendDesiredStateCommandArgument.m_controlMode)
{
case CONTROL_MODE_TORQUE:
{
if (hasDesiredTorque)
{
con->getRigidBodyA().applyTorque(torque * axisA);
con->getRigidBodyB().applyTorque(-torque * axisB);
}
break;
}
case CONTROL_MODE_VELOCITY:
{
if (hasDesiredPosOrVel)
{
con->enableMotor(3 + limitAxis, true);
con->setTargetVelocity(3 + limitAxis, qdotTarget);
con->setMaxMotorForce(3 + limitAxis, torque);
}
break;
}
case CONTROL_MODE_POSITION_VELOCITY_PD:
{
if (hasDesiredPosOrVel)
{
con->setServo(3 + limitAxis, true);
con->setServoTarget(3 + limitAxis, -qTarget);
//next one is the maximum velocity to reach target position.
//the maximum velocity is limited by maxMotorForce
con->setTargetVelocity(3 + limitAxis, 100);
con->setMaxMotorForce(3 + limitAxis, torque);
con->enableMotor(3 + limitAxis, true);
}
break;
}
default:
{
}
};
}
else
{
//ePrismaticType; @todo
btVector3 limitRange = linearLowerLimit.absolute() + linearUpperLimit.absolute();
int limitAxis = limitRange.maxAxis();
const btTransform& transA = con->getCalculatedTransformA();
const btTransform& transB = con->getCalculatedTransformB();
btVector3 axisA = transA.getBasis().getColumn(limitAxis);
btVector3 axisB = transB.getBasis().getColumn(limitAxis);
switch (clientCmd.m_sendDesiredStateCommandArgument.m_controlMode)
{
case CONTROL_MODE_TORQUE:
{
con->getRigidBodyA().applyForce(-torque * axisA, btVector3(0, 0, 0));
con->getRigidBodyB().applyForce(torque * axisB, btVector3(0, 0, 0));
break;
}
case CONTROL_MODE_VELOCITY:
{
con->enableMotor(limitAxis, true);
con->setTargetVelocity(limitAxis, -qdotTarget);
con->setMaxMotorForce(limitAxis, torque);
break;
}
case CONTROL_MODE_POSITION_VELOCITY_PD:
{
con->setServo(limitAxis, true);
con->setServoTarget(limitAxis, qTarget);
//next one is the maximum velocity to reach target position.
//the maximum velocity is limited by maxMotorForce
con->setTargetVelocity(limitAxis, 100);
con->setMaxMotorForce(limitAxis, torque);
con->enableMotor(limitAxis, true);
break;
}
default:
{
}
};
}
}
} //fi
///see addJointInfoFromConstraint
velIndex++; //info.m_uIndex
posIndex++; //info.m_qIndex
}
}
} //fi
//break;
}
}
} //if (body && body->m_rigidBody)
}
serverStatusOut.m_type = CMD_DESIRED_STATE_RECEIVED_COMPLETED;
return hasStatus;
}
bool PhysicsServerCommandProcessor::processRequestActualStateCommand(const struct SharedMemoryCommand& clientCmd, struct SharedMemoryStatus& serverStatusOut, char* bufferServerToClient, int bufferSizeInBytes)
{
bool hasStatus = true;
serverStatusOut.m_type = CMD_ACTUAL_STATE_UPDATE_FAILED;
BT_PROFILE("CMD_REQUEST_ACTUAL_STATE");
if (m_data->m_verboseOutput)
{
b3Printf("Sending the actual state (Q,U)");
}
int bodyUniqueId = clientCmd.m_requestActualStateInformationCommandArgument.m_bodyUniqueId;
InternalBodyData* body = m_data->m_bodyHandles.getHandle(bodyUniqueId);
//we store the state details in the shared memory block, to reduce status size
SendActualStateSharedMemoryStorage* stateDetails = (SendActualStateSharedMemoryStorage*)bufferServerToClient;
//make sure the storage fits, otherwise
btAssert(sizeof(SendActualStateSharedMemoryStorage) < bufferSizeInBytes);
if (sizeof(SendActualStateSharedMemoryStorage) > bufferSizeInBytes)
{
//this forces an error report
body = 0;
}
if (body && body->m_multiBody)
{
btMultiBody* mb = body->m_multiBody;
SharedMemoryStatus& serverCmd = serverStatusOut;
serverStatusOut.m_type = CMD_ACTUAL_STATE_UPDATE_COMPLETED;
serverCmd.m_sendActualStateArgs.m_bodyUniqueId = bodyUniqueId;
serverCmd.m_sendActualStateArgs.m_numLinks = body->m_multiBody->getNumLinks();
serverCmd.m_numDataStreamBytes = sizeof(SendActualStateSharedMemoryStorage);
serverCmd.m_sendActualStateArgs.m_stateDetails = 0;
int totalDegreeOfFreedomQ = 0;
int totalDegreeOfFreedomU = 0;
if (mb->getNumLinks() >= MAX_DEGREE_OF_FREEDOM)
{
serverStatusOut.m_type = CMD_ACTUAL_STATE_UPDATE_FAILED;
hasStatus = true;
return hasStatus;
}
//always add the base, even for static (non-moving objects)
//so that we can easily move the 'fixed' base when needed
//do we don't use this conditional "if (!mb->hasFixedBase())"
{
btTransform tr;
tr.setOrigin(mb->getBasePos());
tr.setRotation(mb->getWorldToBaseRot().inverse());
serverCmd.m_sendActualStateArgs.m_rootLocalInertialFrame[0] =
body->m_rootLocalInertialFrame.getOrigin()[0];
serverCmd.m_sendActualStateArgs.m_rootLocalInertialFrame[1] =
body->m_rootLocalInertialFrame.getOrigin()[1];
serverCmd.m_sendActualStateArgs.m_rootLocalInertialFrame[2] =
body->m_rootLocalInertialFrame.getOrigin()[2];
serverCmd.m_sendActualStateArgs.m_rootLocalInertialFrame[3] =
body->m_rootLocalInertialFrame.getRotation()[0];
serverCmd.m_sendActualStateArgs.m_rootLocalInertialFrame[4] =
body->m_rootLocalInertialFrame.getRotation()[1];
serverCmd.m_sendActualStateArgs.m_rootLocalInertialFrame[5] =
body->m_rootLocalInertialFrame.getRotation()[2];
serverCmd.m_sendActualStateArgs.m_rootLocalInertialFrame[6] =
body->m_rootLocalInertialFrame.getRotation()[3];
//base position in world space, cartesian
stateDetails->m_actualStateQ[0] = tr.getOrigin()[0];
stateDetails->m_actualStateQ[1] = tr.getOrigin()[1];
stateDetails->m_actualStateQ[2] = tr.getOrigin()[2];
//base orientation, quaternion x,y,z,w, in world space, cartesian
stateDetails->m_actualStateQ[3] = tr.getRotation()[0];
stateDetails->m_actualStateQ[4] = tr.getRotation()[1];
stateDetails->m_actualStateQ[5] = tr.getRotation()[2];
stateDetails->m_actualStateQ[6] = tr.getRotation()[3];
totalDegreeOfFreedomQ += 7; //pos + quaternion
//base linear velocity (in world space, cartesian)
stateDetails->m_actualStateQdot[0] = mb->getBaseVel()[0];
stateDetails->m_actualStateQdot[1] = mb->getBaseVel()[1];
stateDetails->m_actualStateQdot[2] = mb->getBaseVel()[2];
//base angular velocity (in world space, cartesian)
stateDetails->m_actualStateQdot[3] = mb->getBaseOmega()[0];
stateDetails->m_actualStateQdot[4] = mb->getBaseOmega()[1];
stateDetails->m_actualStateQdot[5] = mb->getBaseOmega()[2];
totalDegreeOfFreedomU += 6; //3 linear and 3 angular DOF
}
btAlignedObjectArray<btVector3> omega;
btAlignedObjectArray<btVector3> linVel;
bool computeForwardKinematics = ((clientCmd.m_updateFlags & ACTUAL_STATE_COMPUTE_FORWARD_KINEMATICS) != 0);
if (computeForwardKinematics)
{
B3_PROFILE("compForwardKinematics");
btAlignedObjectArray<btQuaternion> world_to_local;
btAlignedObjectArray<btVector3> local_origin;
world_to_local.resize(mb->getNumLinks() + 1);
local_origin.resize(mb->getNumLinks() + 1);
mb->forwardKinematics(world_to_local, local_origin);
}
bool computeLinkVelocities = ((clientCmd.m_updateFlags & ACTUAL_STATE_COMPUTE_LINKVELOCITY) != 0);
if (computeLinkVelocities)
{
omega.resize(mb->getNumLinks() + 1);
linVel.resize(mb->getNumLinks() + 1);
{
B3_PROFILE("compTreeLinkVelocities");
mb->compTreeLinkVelocities(&omega[0], &linVel[0]);
}
}
for (int l = 0; l < mb->getNumLinks(); l++)
{
for (int d = 0; d < mb->getLink(l).m_posVarCount; d++)
{
stateDetails->m_actualStateQ[totalDegreeOfFreedomQ++] = mb->getJointPosMultiDof(l)[d];
}
for (int d = 0; d < mb->getLink(l).m_dofCount; d++)
{
stateDetails->m_jointMotorForceMultiDof[totalDegreeOfFreedomU] = 0;
if (mb->getLink(l).m_jointType == btMultibodyLink::eSpherical)
{
btMultiBodySphericalJointMotor* motor = (btMultiBodySphericalJointMotor*)mb->getLink(l).m_userPtr;
if (motor)
{
btScalar impulse = motor->getAppliedImpulse(d);
btScalar force = impulse / m_data->m_physicsDeltaTime;
stateDetails->m_jointMotorForceMultiDof[totalDegreeOfFreedomU] = force;
}
}
else
{
if (supportsJointMotor(mb, l))
{
btMultiBodyJointMotor* motor = (btMultiBodyJointMotor*)body->m_multiBody->getLink(l).m_userPtr;
if (motor && m_data->m_physicsDeltaTime > btScalar(0))
{
btScalar force = motor->getAppliedImpulse(0) / m_data->m_physicsDeltaTime;
stateDetails->m_jointMotorForceMultiDof[totalDegreeOfFreedomU] = force;
}
}
}
stateDetails->m_actualStateQdot[totalDegreeOfFreedomU++] = mb->getJointVelMultiDof(l)[d];
}
if (0 == mb->getLink(l).m_jointFeedback)
{
for (int d = 0; d < 6; d++)
{
stateDetails->m_jointReactionForces[l * 6 + d] = 0;
}
}
else
{
btVector3 sensedForce = mb->getLink(l).m_jointFeedback->m_reactionForces.getLinear();
btVector3 sensedTorque = mb->getLink(l).m_jointFeedback->m_reactionForces.getAngular();
stateDetails->m_jointReactionForces[l * 6 + 0] = sensedForce[0];
stateDetails->m_jointReactionForces[l * 6 + 1] = sensedForce[1];
stateDetails->m_jointReactionForces[l * 6 + 2] = sensedForce[2];
stateDetails->m_jointReactionForces[l * 6 + 3] = sensedTorque[0];
stateDetails->m_jointReactionForces[l * 6 + 4] = sensedTorque[1];
stateDetails->m_jointReactionForces[l * 6 + 5] = sensedTorque[2];
}
stateDetails->m_jointMotorForce[l] = 0;
if (supportsJointMotor(mb, l))
{
btMultiBodyJointMotor* motor = (btMultiBodyJointMotor*)body->m_multiBody->getLink(l).m_userPtr;
if (motor && m_data->m_physicsDeltaTime > btScalar(0))
{
btScalar force = motor->getAppliedImpulse(0) / m_data->m_physicsDeltaTime;
stateDetails->m_jointMotorForce[l] =
force;
//if (force>0)
//{
// b3Printf("force = %f\n", force);
//}
}
}
btVector3 linkLocalInertialOrigin = body->m_linkLocalInertialFrames[l].getOrigin();
btQuaternion linkLocalInertialRotation = body->m_linkLocalInertialFrames[l].getRotation();
btVector3 linkCOMOrigin = mb->getLink(l).m_cachedWorldTransform.getOrigin();
btQuaternion linkCOMRotation = mb->getLink(l).m_cachedWorldTransform.getRotation();
stateDetails->m_linkState[l * 7 + 0] = linkCOMOrigin.getX();
stateDetails->m_linkState[l * 7 + 1] = linkCOMOrigin.getY();
stateDetails->m_linkState[l * 7 + 2] = linkCOMOrigin.getZ();
stateDetails->m_linkState[l * 7 + 3] = linkCOMRotation.x();
stateDetails->m_linkState[l * 7 + 4] = linkCOMRotation.y();
stateDetails->m_linkState[l * 7 + 5] = linkCOMRotation.z();
stateDetails->m_linkState[l * 7 + 6] = linkCOMRotation.w();
btVector3 worldLinVel(0, 0, 0);
btVector3 worldAngVel(0, 0, 0);
if (computeLinkVelocities)
{
const btMatrix3x3& linkRotMat = mb->getLink(l).m_cachedWorldTransform.getBasis();
worldLinVel = linkRotMat * linVel[l + 1];
worldAngVel = linkRotMat * omega[l + 1];
}
stateDetails->m_linkWorldVelocities[l * 6 + 0] = worldLinVel[0];
stateDetails->m_linkWorldVelocities[l * 6 + 1] = worldLinVel[1];
stateDetails->m_linkWorldVelocities[l * 6 + 2] = worldLinVel[2];
stateDetails->m_linkWorldVelocities[l * 6 + 3] = worldAngVel[0];
stateDetails->m_linkWorldVelocities[l * 6 + 4] = worldAngVel[1];
stateDetails->m_linkWorldVelocities[l * 6 + 5] = worldAngVel[2];
stateDetails->m_linkLocalInertialFrames[l * 7 + 0] = linkLocalInertialOrigin.getX();
stateDetails->m_linkLocalInertialFrames[l * 7 + 1] = linkLocalInertialOrigin.getY();
stateDetails->m_linkLocalInertialFrames[l * 7 + 2] = linkLocalInertialOrigin.getZ();
stateDetails->m_linkLocalInertialFrames[l * 7 + 3] = linkLocalInertialRotation.x();
stateDetails->m_linkLocalInertialFrames[l * 7 + 4] = linkLocalInertialRotation.y();
stateDetails->m_linkLocalInertialFrames[l * 7 + 5] = linkLocalInertialRotation.z();
stateDetails->m_linkLocalInertialFrames[l * 7 + 6] = linkLocalInertialRotation.w();
}
serverCmd.m_sendActualStateArgs.m_numDegreeOfFreedomQ = totalDegreeOfFreedomQ;
serverCmd.m_sendActualStateArgs.m_numDegreeOfFreedomU = totalDegreeOfFreedomU;
hasStatus = true;
}
else if (body && body->m_rigidBody)
{
btRigidBody* rb = body->m_rigidBody;
SharedMemoryStatus& serverCmd = serverStatusOut;
serverCmd.m_type = CMD_ACTUAL_STATE_UPDATE_COMPLETED;
serverCmd.m_sendActualStateArgs.m_bodyUniqueId = bodyUniqueId;
serverCmd.m_sendActualStateArgs.m_numLinks = 0;
serverCmd.m_numDataStreamBytes = sizeof(SendActualStateSharedMemoryStorage);
serverCmd.m_sendActualStateArgs.m_stateDetails = 0;
serverCmd.m_sendActualStateArgs.m_rootLocalInertialFrame[0] =
body->m_rootLocalInertialFrame.getOrigin()[0];
serverCmd.m_sendActualStateArgs.m_rootLocalInertialFrame[1] =
body->m_rootLocalInertialFrame.getOrigin()[1];
serverCmd.m_sendActualStateArgs.m_rootLocalInertialFrame[2] =
body->m_rootLocalInertialFrame.getOrigin()[2];
serverCmd.m_sendActualStateArgs.m_rootLocalInertialFrame[3] =
body->m_rootLocalInertialFrame.getRotation()[0];
serverCmd.m_sendActualStateArgs.m_rootLocalInertialFrame[4] =
body->m_rootLocalInertialFrame.getRotation()[1];
serverCmd.m_sendActualStateArgs.m_rootLocalInertialFrame[5] =
body->m_rootLocalInertialFrame.getRotation()[2];
serverCmd.m_sendActualStateArgs.m_rootLocalInertialFrame[6] =
body->m_rootLocalInertialFrame.getRotation()[3];
btTransform tr = rb->getWorldTransform();
//base position in world space, cartesian
stateDetails->m_actualStateQ[0] = tr.getOrigin()[0];
stateDetails->m_actualStateQ[1] = tr.getOrigin()[1];
stateDetails->m_actualStateQ[2] = tr.getOrigin()[2];
//base orientation, quaternion x,y,z,w, in world space, cartesian
stateDetails->m_actualStateQ[3] = tr.getRotation()[0];
stateDetails->m_actualStateQ[4] = tr.getRotation()[1];
stateDetails->m_actualStateQ[5] = tr.getRotation()[2];
stateDetails->m_actualStateQ[6] = tr.getRotation()[3];
int totalDegreeOfFreedomQ = 7; //pos + quaternion
//base linear velocity (in world space, cartesian)
stateDetails->m_actualStateQdot[0] = rb->getLinearVelocity()[0];
stateDetails->m_actualStateQdot[1] = rb->getLinearVelocity()[1];
stateDetails->m_actualStateQdot[2] = rb->getLinearVelocity()[2];
//base angular velocity (in world space, cartesian)
stateDetails->m_actualStateQdot[3] = rb->getAngularVelocity()[0];
stateDetails->m_actualStateQdot[4] = rb->getAngularVelocity()[1];
stateDetails->m_actualStateQdot[5] = rb->getAngularVelocity()[2];
int totalDegreeOfFreedomU = 6; //3 linear and 3 angular DOF
serverCmd.m_sendActualStateArgs.m_numDegreeOfFreedomQ = totalDegreeOfFreedomQ;
serverCmd.m_sendActualStateArgs.m_numDegreeOfFreedomU = totalDegreeOfFreedomU;
hasStatus = true;
}
#ifndef SKIP_SOFT_BODY_MULTI_BODY_DYNAMICS_WORLD
else if (body && body->m_softBody)
{
btSoftBody* sb = body->m_softBody;
SharedMemoryStatus& serverCmd = serverStatusOut;
serverCmd.m_type = CMD_ACTUAL_STATE_UPDATE_COMPLETED;
serverCmd.m_sendActualStateArgs.m_bodyUniqueId = bodyUniqueId;
serverCmd.m_sendActualStateArgs.m_numLinks = 0;
serverCmd.m_numDataStreamBytes = sizeof(SendActualStateSharedMemoryStorage);
serverCmd.m_sendActualStateArgs.m_stateDetails = 0;
serverCmd.m_sendActualStateArgs.m_rootLocalInertialFrame[0] =
body->m_rootLocalInertialFrame.getOrigin()[0];
serverCmd.m_sendActualStateArgs.m_rootLocalInertialFrame[1] =
body->m_rootLocalInertialFrame.getOrigin()[1];
serverCmd.m_sendActualStateArgs.m_rootLocalInertialFrame[2] =
body->m_rootLocalInertialFrame.getOrigin()[2];
serverCmd.m_sendActualStateArgs.m_rootLocalInertialFrame[3] =
body->m_rootLocalInertialFrame.getRotation()[0];
serverCmd.m_sendActualStateArgs.m_rootLocalInertialFrame[4] =
body->m_rootLocalInertialFrame.getRotation()[1];
serverCmd.m_sendActualStateArgs.m_rootLocalInertialFrame[5] =
body->m_rootLocalInertialFrame.getRotation()[2];
serverCmd.m_sendActualStateArgs.m_rootLocalInertialFrame[6] =
body->m_rootLocalInertialFrame.getRotation()[3];
btVector3 center_of_mass(sb->getCenterOfMass());
btTransform tr = sb->getRigidTransform();
//base position in world space, cartesian
stateDetails->m_actualStateQ[0] = center_of_mass[0];
stateDetails->m_actualStateQ[1] = center_of_mass[1];
stateDetails->m_actualStateQ[2] = center_of_mass[2];
//base orientation, quaternion x,y,z,w, in world space, cartesian
stateDetails->m_actualStateQ[3] = tr.getRotation()[0];
stateDetails->m_actualStateQ[4] = tr.getRotation()[1];
stateDetails->m_actualStateQ[5] = tr.getRotation()[2];
stateDetails->m_actualStateQ[6] = tr.getRotation()[3];
int totalDegreeOfFreedomQ = 7; //pos + quaternion
int totalDegreeOfFreedomU = 6; //3 linear and 3 angular DOF
serverCmd.m_sendActualStateArgs.m_numDegreeOfFreedomQ = totalDegreeOfFreedomQ;
serverCmd.m_sendActualStateArgs.m_numDegreeOfFreedomU = totalDegreeOfFreedomU;
hasStatus = true;
}
#endif
else
{
//b3Warning("Request state but no multibody or rigid body available");
SharedMemoryStatus& serverCmd = serverStatusOut;
serverCmd.m_type = CMD_ACTUAL_STATE_UPDATE_FAILED;
hasStatus = true;
}
return hasStatus;
}
bool PhysicsServerCommandProcessor::processRequestDeformableContactpointHelper(const struct SharedMemoryCommand& clientCmd)
{
#ifndef SKIP_DEFORMABLE_BODY
btDeformableMultiBodyDynamicsWorld* deformWorld = getDeformableWorld();
if (!deformWorld)
{
return false;
}
int numSoftbodyContact = 0;
for (int i = deformWorld->getSoftBodyArray().size() - 1; i >= 0; i--)
{
numSoftbodyContact += deformWorld->getSoftBodyArray()[i]->m_faceRigidContacts.size();
}
int num_contact_points = m_data->m_cachedContactPoints.size();
m_data->m_cachedContactPoints.reserve(num_contact_points + numSoftbodyContact);
for (int i = deformWorld->getSoftBodyArray().size() - 1; i >= 0; i--)
{
btSoftBody* psb = deformWorld->getSoftBodyArray()[i];
for (int c = 0; c < psb->m_faceRigidContacts.size(); c++)
{
const btSoftBody::DeformableFaceRigidContact* contact = &psb->m_faceRigidContacts[i];
//convert rigidbody contact
int linkIndexA = -1;
int linkIndexB = -1;
int objectIndexA = psb->getUserIndex2();
int objectIndexB = -1;
const btRigidBody* bodyB = btRigidBody::upcast(contact->m_cti.m_colObj);
if (bodyB)
{
objectIndexB = bodyB->getUserIndex2();
}
const btMultiBodyLinkCollider* mblB = btMultiBodyLinkCollider::upcast(contact->m_cti.m_colObj);
if (mblB && mblB->m_multiBody)
{
linkIndexB = mblB->m_link;
objectIndexB = mblB->m_multiBody->getUserIndex2();
}
//apply the filter, if the user provides it
bool swap = false;
if (clientCmd.m_requestContactPointArguments.m_objectAIndexFilter >= 0)
{
if (clientCmd.m_requestContactPointArguments.m_objectAIndexFilter == objectIndexA)
{
swap = false;
}
else if (clientCmd.m_requestContactPointArguments.m_objectAIndexFilter == objectIndexB)
{
swap = true;
}
else
{
continue;
}
}
if (swap)
{
std::swap(objectIndexA, objectIndexB);
std::swap(linkIndexA, linkIndexB);
}
//apply the second object filter, if the user provides it
if (clientCmd.m_requestContactPointArguments.m_objectBIndexFilter >= 0)
{
if (clientCmd.m_requestContactPointArguments.m_objectBIndexFilter != objectIndexB)
{
continue;
}
}
if (
(clientCmd.m_updateFlags & CMD_REQUEST_CONTACT_POINT_HAS_LINK_INDEX_A_FILTER) &&
clientCmd.m_requestContactPointArguments.m_linkIndexAIndexFilter != linkIndexA)
{
continue;
}
if (
(clientCmd.m_updateFlags & CMD_REQUEST_CONTACT_POINT_HAS_LINK_INDEX_B_FILTER) &&
clientCmd.m_requestContactPointArguments.m_linkIndexBIndexFilter != linkIndexB)
{
continue;
}
b3ContactPointData pt;
pt.m_bodyUniqueIdA = objectIndexA;
pt.m_bodyUniqueIdB = objectIndexB;
pt.m_contactDistance = contact->m_cti.m_offset;
pt.m_contactFlags = 0;
pt.m_linkIndexA = linkIndexA;
pt.m_linkIndexB = linkIndexB;
for (int j = 0; j < 3; j++)
{
if (swap)
{
pt.m_contactNormalOnBInWS[j] = -contact->m_cti.m_normal[j];
pt.m_positionOnAInWS[j] = contact->m_cti.m_normal[j];
pt.m_positionOnBInWS[j] = -contact->m_cti.m_normal[j];
}
else
{
pt.m_contactNormalOnBInWS[j] = contact->m_cti.m_normal[j];
pt.m_positionOnAInWS[j] = -contact->m_cti.m_normal[j];
pt.m_positionOnBInWS[j] = contact->m_cti.m_normal[j];
}
}
pt.m_normalForce = 1;
pt.m_linearFrictionForce1 = 0;
pt.m_linearFrictionForce2 = 0;
for (int j = 0; j < 3; j++)
{
pt.m_linearFrictionDirection1[j] = 0;
pt.m_linearFrictionDirection2[j] = 0;
}
m_data->m_cachedContactPoints.push_back(pt);
}
}
#endif
return true;
}
bool PhysicsServerCommandProcessor::processRequestContactpointInformationCommand(const struct SharedMemoryCommand& clientCmd, struct SharedMemoryStatus& serverStatusOut, char* bufferServerToClient, int bufferSizeInBytes)
{
bool hasStatus = true;
BT_PROFILE("CMD_REQUEST_CONTACT_POINT_INFORMATION");
SharedMemoryStatus& serverCmd = serverStatusOut;
serverCmd.m_sendContactPointArgs.m_numContactPointsCopied = 0;
//make a snapshot of the contact manifolds into individual contact points
if (clientCmd.m_requestContactPointArguments.m_startingContactPointIndex == 0)
{
m_data->m_cachedContactPoints.resize(0);
int mode = CONTACT_QUERY_MODE_REPORT_EXISTING_CONTACT_POINTS;
if (clientCmd.m_updateFlags & CMD_REQUEST_CONTACT_POINT_HAS_QUERY_MODE)
{
mode = clientCmd.m_requestContactPointArguments.m_mode;
}
switch (mode)
{
case CONTACT_QUERY_MODE_REPORT_EXISTING_CONTACT_POINTS:
{
int numContactManifolds = m_data->m_dynamicsWorld->getDispatcher()->getNumManifolds();
m_data->m_cachedContactPoints.reserve(numContactManifolds * 4);
for (int i = 0; i < numContactManifolds; i++)
{
const btPersistentManifold* manifold = m_data->m_dynamicsWorld->getDispatcher()->getInternalManifoldPointer()[i];
int linkIndexA = -1;
int linkIndexB = -1;
int objectIndexB = -1;
const btRigidBody* bodyB = btRigidBody::upcast(manifold->getBody1());
if (bodyB)
{
objectIndexB = bodyB->getUserIndex2();
}
const btMultiBodyLinkCollider* mblB = btMultiBodyLinkCollider::upcast(manifold->getBody1());
if (mblB && mblB->m_multiBody)
{
linkIndexB = mblB->m_link;
objectIndexB = mblB->m_multiBody->getUserIndex2();
}
int objectIndexA = -1;
const btRigidBody* bodyA = btRigidBody::upcast(manifold->getBody0());
if (bodyA)
{
objectIndexA = bodyA->getUserIndex2();
}
const btMultiBodyLinkCollider* mblA = btMultiBodyLinkCollider::upcast(manifold->getBody0());
if (mblA && mblA->m_multiBody)
{
linkIndexA = mblA->m_link;
objectIndexA = mblA->m_multiBody->getUserIndex2();
}
btAssert(bodyA || mblA);
//apply the filter, if the user provides it
bool swap = false;
if (clientCmd.m_requestContactPointArguments.m_objectAIndexFilter >= 0)
{
if (clientCmd.m_requestContactPointArguments.m_objectAIndexFilter == objectIndexA)
{
swap = false;
}
else if (clientCmd.m_requestContactPointArguments.m_objectAIndexFilter == objectIndexB)
{
swap = true;
}
else
{
continue;
}
}
if (swap)
{
std::swap(objectIndexA, objectIndexB);
std::swap(linkIndexA, linkIndexB);
std::swap(bodyA, bodyB);
}
//apply the second object filter, if the user provides it
if (clientCmd.m_requestContactPointArguments.m_objectBIndexFilter >= 0)
{
if (clientCmd.m_requestContactPointArguments.m_objectBIndexFilter != objectIndexB)
{
continue;
}
}
if (
(clientCmd.m_updateFlags & CMD_REQUEST_CONTACT_POINT_HAS_LINK_INDEX_A_FILTER) &&
clientCmd.m_requestContactPointArguments.m_linkIndexAIndexFilter != linkIndexA)
{
continue;
}
if (
(clientCmd.m_updateFlags & CMD_REQUEST_CONTACT_POINT_HAS_LINK_INDEX_B_FILTER) &&
clientCmd.m_requestContactPointArguments.m_linkIndexBIndexFilter != linkIndexB)
{
continue;
}
for (int p = 0; p < manifold->getNumContacts(); p++)
{
b3ContactPointData pt;
pt.m_bodyUniqueIdA = objectIndexA;
pt.m_bodyUniqueIdB = objectIndexB;
const btManifoldPoint& srcPt = manifold->getContactPoint(p);
pt.m_contactDistance = srcPt.getDistance();
pt.m_contactFlags = 0;
pt.m_linkIndexA = linkIndexA;
pt.m_linkIndexB = linkIndexB;
for (int j = 0; j < 3; j++)
{
if (swap)
{
pt.m_contactNormalOnBInWS[j] = -srcPt.m_normalWorldOnB[j];
pt.m_positionOnAInWS[j] = srcPt.getPositionWorldOnB()[j];
pt.m_positionOnBInWS[j] = srcPt.getPositionWorldOnA()[j];
}
else
{
pt.m_contactNormalOnBInWS[j] = srcPt.m_normalWorldOnB[j];
pt.m_positionOnAInWS[j] = srcPt.getPositionWorldOnA()[j];
pt.m_positionOnBInWS[j] = srcPt.getPositionWorldOnB()[j];
}
}
pt.m_normalForce = srcPt.getAppliedImpulse() / m_data->m_physicsDeltaTime;
pt.m_linearFrictionForce1 = srcPt.m_appliedImpulseLateral1 / m_data->m_physicsDeltaTime;
pt.m_linearFrictionForce2 = srcPt.m_appliedImpulseLateral2 / m_data->m_physicsDeltaTime;
for (int j = 0; j < 3; j++)
{
pt.m_linearFrictionDirection1[j] = srcPt.m_lateralFrictionDir1[j];
pt.m_linearFrictionDirection2[j] = srcPt.m_lateralFrictionDir2[j];
}
m_data->m_cachedContactPoints.push_back(pt);
}
}
#ifndef SKIP_DEFORMABLE_BODY
processRequestDeformableContactpointHelper(clientCmd);
#endif
break;
}
case CONTACT_QUERY_MODE_COMPUTE_CLOSEST_POINTS:
{
//todo(erwincoumans) compute closest points between all, and vs all, pair
btScalar closestDistanceThreshold = 0.f;
if (clientCmd.m_updateFlags & CMD_REQUEST_CONTACT_POINT_HAS_CLOSEST_DISTANCE_THRESHOLD)
{
closestDistanceThreshold = clientCmd.m_requestContactPointArguments.m_closestDistanceThreshold;
}
int bodyUniqueIdA = clientCmd.m_requestContactPointArguments.m_objectAIndexFilter;
int bodyUniqueIdB = clientCmd.m_requestContactPointArguments.m_objectBIndexFilter;
bool hasLinkIndexAFilter = (0 != (clientCmd.m_updateFlags & CMD_REQUEST_CONTACT_POINT_HAS_LINK_INDEX_A_FILTER));
bool hasLinkIndexBFilter = (0 != (clientCmd.m_updateFlags & CMD_REQUEST_CONTACT_POINT_HAS_LINK_INDEX_B_FILTER));
int linkIndexA = clientCmd.m_requestContactPointArguments.m_linkIndexAIndexFilter;
int linkIndexB = clientCmd.m_requestContactPointArguments.m_linkIndexBIndexFilter;
btAlignedObjectArray<btCollisionObject*> setA;
btAlignedObjectArray<btCollisionObject*> setB;
btAlignedObjectArray<int> setALinkIndex;
btAlignedObjectArray<int> setBLinkIndex;
btCollisionObject colObA;
btCollisionObject colObB;
int collisionShapeA = (clientCmd.m_updateFlags & CMD_REQUEST_CONTACT_POINT_HAS_COLLISION_SHAPE_A) ? clientCmd.m_requestContactPointArguments.m_collisionShapeA : -1;
int collisionShapeB = (clientCmd.m_updateFlags & CMD_REQUEST_CONTACT_POINT_HAS_COLLISION_SHAPE_B) ? clientCmd.m_requestContactPointArguments.m_collisionShapeB : -1;
if (collisionShapeA >= 0)
{
btVector3 posA(0, 0, 0);
if (clientCmd.m_updateFlags & CMD_REQUEST_CONTACT_POINT_HAS_COLLISION_SHAPE_POSITION_A)
{
posA.setValue(clientCmd.m_requestContactPointArguments.m_collisionShapePositionA[0],
clientCmd.m_requestContactPointArguments.m_collisionShapePositionA[1],
clientCmd.m_requestContactPointArguments.m_collisionShapePositionA[2]);
}
btQuaternion ornA(0, 0, 0, 1);
if (clientCmd.m_updateFlags & CMD_REQUEST_CONTACT_POINT_HAS_COLLISION_SHAPE_ORIENTATION_A)
{
ornA.setValue(clientCmd.m_requestContactPointArguments.m_collisionShapeOrientationA[0],
clientCmd.m_requestContactPointArguments.m_collisionShapeOrientationA[1],
clientCmd.m_requestContactPointArguments.m_collisionShapeOrientationA[2],
clientCmd.m_requestContactPointArguments.m_collisionShapeOrientationA[3]);
}
InternalCollisionShapeHandle* handle = m_data->m_userCollisionShapeHandles.getHandle(collisionShapeA);
if (handle && handle->m_collisionShape)
{
colObA.setCollisionShape(handle->m_collisionShape);
btTransform tr;
tr.setIdentity();
tr.setOrigin(posA);
tr.setRotation(ornA);
colObA.setWorldTransform(tr);
setA.push_back(&colObA);
setALinkIndex.push_back(-2);
}
else
{
b3Warning("collisionShapeA provided is not valid.");
}
}
if (collisionShapeB >= 0)
{
btVector3 posB(0, 0, 0);
if (clientCmd.m_updateFlags & CMD_REQUEST_CONTACT_POINT_HAS_COLLISION_SHAPE_POSITION_B)
{
posB.setValue(clientCmd.m_requestContactPointArguments.m_collisionShapePositionB[0],
clientCmd.m_requestContactPointArguments.m_collisionShapePositionB[1],
clientCmd.m_requestContactPointArguments.m_collisionShapePositionB[2]);
}
btQuaternion ornB(0, 0, 0, 1);
if (clientCmd.m_updateFlags & CMD_REQUEST_CONTACT_POINT_HAS_COLLISION_SHAPE_ORIENTATION_B)
{
ornB.setValue(clientCmd.m_requestContactPointArguments.m_collisionShapeOrientationB[0],
clientCmd.m_requestContactPointArguments.m_collisionShapeOrientationB[1],
clientCmd.m_requestContactPointArguments.m_collisionShapeOrientationB[2],
clientCmd.m_requestContactPointArguments.m_collisionShapeOrientationB[3]);
}
InternalCollisionShapeHandle* handle = m_data->m_userCollisionShapeHandles.getHandle(collisionShapeB);
if (handle && handle->m_collisionShape)
{
colObB.setCollisionShape(handle->m_collisionShape);
btTransform tr;
tr.setIdentity();
tr.setOrigin(posB);
tr.setRotation(ornB);
colObB.setWorldTransform(tr);
setB.push_back(&colObB);
setBLinkIndex.push_back(-2);
}
else
{
b3Warning("collisionShapeB provided is not valid.");
}
}
if (bodyUniqueIdA >= 0)
{
InternalBodyData* bodyA = m_data->m_bodyHandles.getHandle(bodyUniqueIdA);
if (bodyA)
{
if (bodyA->m_multiBody)
{
if (bodyA->m_multiBody->getBaseCollider())
{
if (!hasLinkIndexAFilter || (linkIndexA == -1))
{
setA.push_back(bodyA->m_multiBody->getBaseCollider());
setALinkIndex.push_back(-1);
}
}
for (int i = 0; i < bodyA->m_multiBody->getNumLinks(); i++)
{
if (bodyA->m_multiBody->getLink(i).m_collider)
{
if (!hasLinkIndexAFilter || (linkIndexA == i))
{
setA.push_back(bodyA->m_multiBody->getLink(i).m_collider);
setALinkIndex.push_back(i);
}
}
}
}
if (bodyA->m_rigidBody)
{
setA.push_back(bodyA->m_rigidBody);
setALinkIndex.push_back(-1);
}
}
}
if (bodyUniqueIdB >= 0)
{
InternalBodyData* bodyB = m_data->m_bodyHandles.getHandle(bodyUniqueIdB);
if (bodyB)
{
if (bodyB->m_multiBody)
{
if (bodyB->m_multiBody->getBaseCollider())
{
if (!hasLinkIndexBFilter || (linkIndexB == -1))
{
setB.push_back(bodyB->m_multiBody->getBaseCollider());
setBLinkIndex.push_back(-1);
}
}
for (int i = 0; i < bodyB->m_multiBody->getNumLinks(); i++)
{
if (bodyB->m_multiBody->getLink(i).m_collider)
{
if (!hasLinkIndexBFilter || (linkIndexB == i))
{
setB.push_back(bodyB->m_multiBody->getLink(i).m_collider);
setBLinkIndex.push_back(i);
}
}
}
}
if (bodyB->m_rigidBody)
{
setB.push_back(bodyB->m_rigidBody);
setBLinkIndex.push_back(-1);
}
}
}
{
///ContactResultCallback is used to report contact points
struct MyContactResultCallback : public btCollisionWorld::ContactResultCallback
{
int m_bodyUniqueIdA;
int m_bodyUniqueIdB;
int m_linkIndexA;
int m_linkIndexB;
btScalar m_deltaTime;
btAlignedObjectArray<b3ContactPointData>& m_cachedContactPoints;
MyContactResultCallback(btAlignedObjectArray<b3ContactPointData>& pointCache)
: m_cachedContactPoints(pointCache)
{
}
virtual ~MyContactResultCallback()
{
}
virtual bool needsCollision(btBroadphaseProxy* proxy0) const
{
//bool collides = (proxy0->m_collisionFilterGroup & m_collisionFilterMask) != 0;
//collides = collides && (m_collisionFilterGroup & proxy0->m_collisionFilterMask);
//return collides;
return true;
}
virtual btScalar addSingleResult(btManifoldPoint& cp, const btCollisionObjectWrapper* colObj0Wrap, int partId0, int index0, const btCollisionObjectWrapper* colObj1Wrap, int partId1, int index1)
{
const btCollisionObject* colObj = (btCollisionObject*)colObj0Wrap->getCollisionObject();
const btMultiBodyLinkCollider* mbl = btMultiBodyLinkCollider::upcast(colObj);
int bodyUniqueId = -1;
if (mbl)
{
bodyUniqueId = mbl->m_multiBody->getUserIndex2();
}
else
{
bodyUniqueId = colObj->getUserIndex2();
}
bool isSwapped = m_bodyUniqueIdA != bodyUniqueId;
if (cp.m_distance1 <= m_closestDistanceThreshold)
{
b3ContactPointData pt;
pt.m_bodyUniqueIdA = m_bodyUniqueIdA;
pt.m_bodyUniqueIdB = m_bodyUniqueIdB;
const btManifoldPoint& srcPt = cp;
pt.m_contactDistance = srcPt.getDistance();
pt.m_contactFlags = 0;
pt.m_linkIndexA = m_linkIndexA;
pt.m_linkIndexB = m_linkIndexB;
for (int j = 0; j < 3; j++)
{
if (isSwapped)
{
pt.m_contactNormalOnBInWS[j] = -srcPt.m_normalWorldOnB[j];
pt.m_positionOnAInWS[j] = srcPt.getPositionWorldOnB()[j];
pt.m_positionOnBInWS[j] = srcPt.getPositionWorldOnA()[j];
}
else
{
pt.m_contactNormalOnBInWS[j] = srcPt.m_normalWorldOnB[j];
pt.m_positionOnAInWS[j] = srcPt.getPositionWorldOnA()[j];
pt.m_positionOnBInWS[j] = srcPt.getPositionWorldOnB()[j];
}
}
pt.m_normalForce = srcPt.getAppliedImpulse() / m_deltaTime;
pt.m_linearFrictionForce1 = srcPt.m_appliedImpulseLateral1 / m_deltaTime;
pt.m_linearFrictionForce2 = srcPt.m_appliedImpulseLateral2 / m_deltaTime;
for (int j = 0; j < 3; j++)
{
pt.m_linearFrictionDirection1[j] = srcPt.m_lateralFrictionDir1[j];
pt.m_linearFrictionDirection2[j] = srcPt.m_lateralFrictionDir2[j];
}
m_cachedContactPoints.push_back(pt);
}
return 1;
}
};
MyContactResultCallback cb(m_data->m_cachedContactPoints);
cb.m_bodyUniqueIdA = bodyUniqueIdA;
cb.m_bodyUniqueIdB = bodyUniqueIdB;
cb.m_deltaTime = m_data->m_numSimulationSubSteps > 0 ? m_data->m_physicsDeltaTime / m_data->m_numSimulationSubSteps : m_data->m_physicsDeltaTime;
for (int i = 0; i < setA.size(); i++)
{
cb.m_linkIndexA = setALinkIndex[i];
for (int j = 0; j < setB.size(); j++)
{
cb.m_linkIndexB = setBLinkIndex[j];
cb.m_closestDistanceThreshold = closestDistanceThreshold;
this->m_data->m_dynamicsWorld->contactPairTest(setA[i], setB[j], cb);
}
}
}
break;
}
default:
{
b3Warning("Unknown contact query mode: %d", mode);
}
}
}
int numContactPoints = m_data->m_cachedContactPoints.size();
//b3ContactPoint
//struct b3ContactPointDynamics
int totalBytesPerContact = sizeof(b3ContactPointData);
int contactPointStorage = bufferSizeInBytes / totalBytesPerContact - 1;
b3ContactPointData* contactData = (b3ContactPointData*)bufferServerToClient;
int startContactPointIndex = clientCmd.m_requestContactPointArguments.m_startingContactPointIndex;
int numContactPointBatch = btMin(numContactPoints, contactPointStorage);
int endContactPointIndex = startContactPointIndex + numContactPointBatch;
for (int i = startContactPointIndex; i < endContactPointIndex; i++)
{
const b3ContactPointData& srcPt = m_data->m_cachedContactPoints[i];
b3ContactPointData& destPt = contactData[serverCmd.m_sendContactPointArgs.m_numContactPointsCopied];
destPt = srcPt;
serverCmd.m_sendContactPointArgs.m_numContactPointsCopied++;
}
serverCmd.m_sendContactPointArgs.m_startingContactPointIndex = clientCmd.m_requestContactPointArguments.m_startingContactPointIndex;
serverCmd.m_sendContactPointArgs.m_numRemainingContactPoints = numContactPoints - clientCmd.m_requestContactPointArguments.m_startingContactPointIndex - serverCmd.m_sendContactPointArgs.m_numContactPointsCopied;
serverCmd.m_numDataStreamBytes = totalBytesPerContact * serverCmd.m_sendContactPointArgs.m_numContactPointsCopied;
serverCmd.m_type = CMD_CONTACT_POINT_INFORMATION_COMPLETED; //CMD_CONTACT_POINT_INFORMATION_FAILED,
return hasStatus;
}
bool PhysicsServerCommandProcessor::processRequestBodyInfoCommand(const struct SharedMemoryCommand& clientCmd, struct SharedMemoryStatus& serverStatusOut, char* bufferServerToClient, int bufferSizeInBytes)
{
bool hasStatus = true;
BT_PROFILE("CMD_REQUEST_BODY_INFO");
const SdfRequestInfoArgs& sdfInfoArgs = clientCmd.m_sdfRequestInfoArgs;
//stream info into memory
int streamSizeInBytes = createBodyInfoStream(sdfInfoArgs.m_bodyUniqueId, bufferServerToClient, bufferSizeInBytes);
serverStatusOut.m_type = CMD_BODY_INFO_COMPLETED;
serverStatusOut.m_dataStreamArguments.m_bodyUniqueId = sdfInfoArgs.m_bodyUniqueId;
serverStatusOut.m_dataStreamArguments.m_bodyName[0] = 0;
InternalBodyHandle* bodyHandle = m_data->m_bodyHandles.getHandle(sdfInfoArgs.m_bodyUniqueId);
if (bodyHandle)
{
strcpy(serverStatusOut.m_dataStreamArguments.m_bodyName, bodyHandle->m_bodyName.c_str());
}
serverStatusOut.m_numDataStreamBytes = streamSizeInBytes;
return hasStatus;
}
bool PhysicsServerCommandProcessor::processLoadSDFCommand(const struct SharedMemoryCommand& clientCmd, struct SharedMemoryStatus& serverStatusOut, char* bufferServerToClient, int bufferSizeInBytes)
{
bool hasStatus = true;
BT_PROFILE("CMD_LOAD_SDF");
const SdfArgs& sdfArgs = clientCmd.m_sdfArguments;
if (m_data->m_verboseOutput)
{
b3Printf("Processed CMD_LOAD_SDF:%s", sdfArgs.m_sdfFileName);
}
bool useMultiBody = (clientCmd.m_updateFlags & URDF_ARGS_USE_MULTIBODY) ? (sdfArgs.m_useMultiBody != 0) : true;
int flags = CUF_USE_SDF; //CUF_USE_URDF_INERTIA
btScalar globalScaling = 1.f;
if (clientCmd.m_updateFlags & URDF_ARGS_USE_GLOBAL_SCALING)
{
globalScaling = sdfArgs.m_globalScaling;
}
bool completedOk = loadSdf(sdfArgs.m_sdfFileName, bufferServerToClient, bufferSizeInBytes, useMultiBody, flags, globalScaling);
if (completedOk)
{
m_data->m_guiHelper->autogenerateGraphicsObjects(this->m_data->m_dynamicsWorld);
//serverStatusOut.m_type = CMD_SDF_LOADING_FAILED;
serverStatusOut.m_sdfLoadedArgs.m_numBodies = m_data->m_sdfRecentLoadedBodies.size();
serverStatusOut.m_sdfLoadedArgs.m_numUserConstraints = 0;
int maxBodies = btMin(MAX_SDF_BODIES, serverStatusOut.m_sdfLoadedArgs.m_numBodies);
for (int i = 0; i < maxBodies; i++)
{
serverStatusOut.m_sdfLoadedArgs.m_bodyUniqueIds[i] = m_data->m_sdfRecentLoadedBodies[i];
}
serverStatusOut.m_type = CMD_SDF_LOADING_COMPLETED;
}
else
{
serverStatusOut.m_type = CMD_SDF_LOADING_FAILED;
}
return hasStatus;
}
bool PhysicsServerCommandProcessor::processCreateMultiBodyCommand(const struct SharedMemoryCommand& clientCmd, struct SharedMemoryStatus& serverStatusOut, char* bufferServerToClient, int bufferSizeInBytes)
{
if (clientCmd.m_createMultiBodyArgs.m_numBatchObjects > 0)
{
//batch of objects, to speed up creation time
bool result = false;
SharedMemoryCommand clientCmd2 = clientCmd;
int baseLinkIndex = clientCmd.m_createMultiBodyArgs.m_baseLinkIndex;
double* basePositionAndOrientations = (double*)bufferServerToClient;
for (int i = 0; i < clientCmd2.m_createMultiBodyArgs.m_numBatchObjects; i++)
{
clientCmd2.m_createMultiBodyArgs.m_linkPositions[baseLinkIndex * 3 + 0] = basePositionAndOrientations[0 + i * 3];
clientCmd2.m_createMultiBodyArgs.m_linkPositions[baseLinkIndex * 3 + 1] = basePositionAndOrientations[1 + i * 3];
clientCmd2.m_createMultiBodyArgs.m_linkPositions[baseLinkIndex * 3 + 2] = basePositionAndOrientations[2 + i * 3];
if (i == (clientCmd2.m_createMultiBodyArgs.m_numBatchObjects - 1))
{
result = processCreateMultiBodyCommandSingle(clientCmd2, serverStatusOut, bufferServerToClient, bufferSizeInBytes);
}
else
{
result = processCreateMultiBodyCommandSingle(clientCmd2, serverStatusOut, 0, 0);
}
}
m_data->m_guiHelper->autogenerateGraphicsObjects(this->m_data->m_dynamicsWorld);
return result;
}
return processCreateMultiBodyCommandSingle(clientCmd, serverStatusOut, bufferServerToClient, bufferSizeInBytes);
}
bool PhysicsServerCommandProcessor::processCreateMultiBodyCommandSingle(const struct SharedMemoryCommand& clientCmd, struct SharedMemoryStatus& serverStatusOut, char* bufferServerToClient, int bufferSizeInBytes)
{
BT_PROFILE("processCreateMultiBodyCommand2");
bool hasStatus = true;
serverStatusOut.m_type = CMD_CREATE_MULTI_BODY_FAILED;
if (clientCmd.m_createMultiBodyArgs.m_baseLinkIndex >= 0)
{
m_data->m_sdfRecentLoadedBodies.clear();
int flags = 0;
if (clientCmd.m_updateFlags & MULT_BODY_HAS_FLAGS)
{
flags = clientCmd.m_createMultiBodyArgs.m_flags;
}
ProgrammaticUrdfInterface u2b(clientCmd.m_createMultiBodyArgs, m_data, flags);
bool useMultiBody = true;
if (clientCmd.m_updateFlags & MULT_BODY_USE_MAXIMAL_COORDINATES)
{
useMultiBody = false;
}
bool ok = 0;
{
BT_PROFILE("processImportedObjects");
ok = processImportedObjects("memory", bufferServerToClient, bufferSizeInBytes, useMultiBody, flags, u2b);
}
if (ok)
{
BT_PROFILE("post process");
int bodyUniqueId = -1;
if (m_data->m_sdfRecentLoadedBodies.size() == 1)
{
bodyUniqueId = m_data->m_sdfRecentLoadedBodies[0];
}
m_data->m_sdfRecentLoadedBodies.clear();
if (bodyUniqueId >= 0)
{
serverStatusOut.m_type = CMD_CREATE_MULTI_BODY_COMPLETED;
if (bufferSizeInBytes > 0 && serverStatusOut.m_numDataStreamBytes == 0)
{
{
BT_PROFILE("autogenerateGraphicsObjects");
m_data->m_guiHelper->autogenerateGraphicsObjects(this->m_data->m_dynamicsWorld);
}
BT_PROFILE("createBodyInfoStream");
int streamSizeInBytes = createBodyInfoStream(bodyUniqueId, bufferServerToClient, bufferSizeInBytes);
serverStatusOut.m_numDataStreamBytes = streamSizeInBytes;
serverStatusOut.m_dataStreamArguments.m_bodyUniqueId = bodyUniqueId;
InternalBodyData* body = m_data->m_bodyHandles.getHandle(bodyUniqueId);
strcpy(serverStatusOut.m_dataStreamArguments.m_bodyName, body->m_bodyName.c_str());
}
}
}
//ConvertURDF2Bullet(u2b,creation, rootTrans,m_data->m_dynamicsWorld,useMultiBody,u2b.getPathPrefix(),flags);
}
return hasStatus;
}
bool PhysicsServerCommandProcessor::processLoadURDFCommand(const struct SharedMemoryCommand& clientCmd, struct SharedMemoryStatus& serverStatusOut, char* bufferServerToClient, int bufferSizeInBytes)
{
bool hasStatus = true;
serverStatusOut.m_type = CMD_URDF_LOADING_FAILED;
BT_PROFILE("CMD_LOAD_URDF");
const UrdfArgs& urdfArgs = clientCmd.m_urdfArguments;
if (m_data->m_verboseOutput)
{
b3Printf("Processed CMD_LOAD_URDF:%s", urdfArgs.m_urdfFileName);
}
btAssert((clientCmd.m_updateFlags & URDF_ARGS_FILE_NAME) != 0);
btAssert(urdfArgs.m_urdfFileName);
btVector3 initialPos(0, 0, 0);
btQuaternion initialOrn(0, 0, 0, 1);
if (clientCmd.m_updateFlags & URDF_ARGS_INITIAL_POSITION)
{
initialPos[0] = urdfArgs.m_initialPosition[0];
initialPos[1] = urdfArgs.m_initialPosition[1];
initialPos[2] = urdfArgs.m_initialPosition[2];
}
int urdfFlags = 0;
if (clientCmd.m_updateFlags & URDF_ARGS_HAS_CUSTOM_URDF_FLAGS)
{
urdfFlags = urdfArgs.m_urdfFlags;
}
if (clientCmd.m_updateFlags & URDF_ARGS_INITIAL_ORIENTATION)
{
initialOrn[0] = urdfArgs.m_initialOrientation[0];
initialOrn[1] = urdfArgs.m_initialOrientation[1];
initialOrn[2] = urdfArgs.m_initialOrientation[2];
initialOrn[3] = urdfArgs.m_initialOrientation[3];
}
bool useMultiBody = (clientCmd.m_updateFlags & URDF_ARGS_USE_MULTIBODY) ? (urdfArgs.m_useMultiBody != 0) : true;
bool useFixedBase = (clientCmd.m_updateFlags & URDF_ARGS_USE_FIXED_BASE) ? (urdfArgs.m_useFixedBase != 0) : false;
int bodyUniqueId;
btScalar globalScaling = 1.f;
if (clientCmd.m_updateFlags & URDF_ARGS_USE_GLOBAL_SCALING)
{
globalScaling = urdfArgs.m_globalScaling;
}
//load the actual URDF and send a report: completed or failed
bool completedOk = loadUrdf(urdfArgs.m_urdfFileName,
initialPos, initialOrn,
useMultiBody, useFixedBase, &bodyUniqueId, bufferServerToClient, bufferSizeInBytes, urdfFlags, globalScaling);
if (completedOk && bodyUniqueId >= 0)
{
m_data->m_guiHelper->autogenerateGraphicsObjects(this->m_data->m_dynamicsWorld);
serverStatusOut.m_type = CMD_URDF_LOADING_COMPLETED;
int streamSizeInBytes = createBodyInfoStream(bodyUniqueId, bufferServerToClient, bufferSizeInBytes);
serverStatusOut.m_numDataStreamBytes = streamSizeInBytes;
#ifdef ENABLE_LINK_MAPPER
if (m_data->m_urdfLinkNameMapper.size())
{
serverStatusOut.m_numDataStreamBytes = m_data->m_urdfLinkNameMapper.at(m_data->m_urdfLinkNameMapper.size() - 1)->m_memSerializer->getCurrentBufferSize();
}
#endif
serverStatusOut.m_dataStreamArguments.m_bodyUniqueId = bodyUniqueId;
InternalBodyData* body = m_data->m_bodyHandles.getHandle(bodyUniqueId);
strcpy(serverStatusOut.m_dataStreamArguments.m_bodyName, body->m_bodyName.c_str());
}
return hasStatus;
}
void constructUrdfDeformable(const struct SharedMemoryCommand& clientCmd, UrdfDeformable& deformable, bool verbose)
{
const LoadSoftBodyArgs& loadSoftBodyArgs = clientCmd.m_loadSoftBodyArguments;
if (verbose)
{
b3Printf("Processed CMD_LOAD_SOFT_BODY:%s", loadSoftBodyArgs.m_fileName);
}
btAssert((clientCmd.m_updateFlags & LOAD_SOFT_BODY_FILE_NAME) != 0);
btAssert(loadSoftBodyArgs.m_fileName);
if (clientCmd.m_updateFlags & LOAD_SOFT_BODY_UPDATE_MASS)
{
deformable.m_mass = loadSoftBodyArgs.m_mass;
}
if (clientCmd.m_updateFlags & LOAD_SOFT_BODY_UPDATE_COLLISION_MARGIN)
{
deformable.m_collisionMargin = loadSoftBodyArgs.m_collisionMargin;
}
deformable.m_visualFileName = loadSoftBodyArgs.m_fileName;
if (clientCmd.m_updateFlags & LOAD_SOFT_BODY_SIM_MESH)
{
deformable.m_simFileName = loadSoftBodyArgs.m_simFileName;
}
else
{
deformable.m_simFileName = "";
}
#ifndef SKIP_DEFORMABLE_BODY
deformable.m_springCoefficients.elastic_stiffness = loadSoftBodyArgs.m_springElasticStiffness;
deformable.m_springCoefficients.damping_stiffness = loadSoftBodyArgs.m_springDampingStiffness;
if (clientCmd.m_updateFlags & LOAD_SOFT_BODY_ADD_BENDING_SPRINGS)
{
deformable.m_springCoefficients.bending_stiffness = loadSoftBodyArgs.m_springBendingStiffness;
}
if (clientCmd.m_updateFlags & LOAD_SOFT_BODY_SET_DAMPING_SPRING_MODE)
{
deformable.m_springCoefficients.damp_all_directions = loadSoftBodyArgs.m_dampAllDirections;
}
if (clientCmd.m_updateFlags & LOAD_SOFT_BODY_ADD_COROTATED_FORCE)
{
deformable.m_corotatedCoefficients.mu = loadSoftBodyArgs.m_corotatedMu;
deformable.m_corotatedCoefficients.lambda = loadSoftBodyArgs.m_corotatedLambda;
}
if (clientCmd.m_updateFlags & LOAD_SOFT_BODY_ADD_NEOHOOKEAN_FORCE)
{
deformable.m_neohookeanCoefficients.mu = loadSoftBodyArgs.m_NeoHookeanMu;
deformable.m_neohookeanCoefficients.lambda = loadSoftBodyArgs.m_NeoHookeanLambda;
deformable.m_neohookeanCoefficients.damping = loadSoftBodyArgs.m_NeoHookeanDamping;
}
if (clientCmd.m_updateFlags & LOAD_SOFT_BODY_SET_FRICTION_COEFFICIENT)
{
deformable.m_friction = loadSoftBodyArgs.m_frictionCoeff;
}
if (clientCmd.m_updateFlags & LOAD_SOFT_BODY_SET_REPULSION_STIFFNESS)
{
deformable.m_repulsionStiffness = loadSoftBodyArgs.m_repulsionStiffness;
}
if (clientCmd.m_updateFlags & LOAD_SOFT_BODY_SET_GRAVITY_FACTOR)
{
deformable.m_gravFactor = loadSoftBodyArgs.m_gravFactor;
}
#endif
}
bool PhysicsServerCommandProcessor::processDeformable(const UrdfDeformable& deformable, const btVector3& pos, const btQuaternion& orn, int* bodyUniqueId, char* bufferServerToClient, int bufferSizeInBytes, btScalar scale, bool useSelfCollision)
{
#ifndef SKIP_SOFT_BODY_MULTI_BODY_DYNAMICS_WORLD
btSoftBody* psb = NULL;
CommonFileIOInterface* fileIO(m_data->m_pluginManager.getFileIOInterface());
char relativeFileName[1024];
char pathPrefix[1024];
pathPrefix[0] = 0;
if (fileIO->findResourcePath(deformable.m_visualFileName.c_str(), relativeFileName, 1024))
{
b3FileUtils::extractPath(relativeFileName, pathPrefix, 1024);
}
const std::string& error_message_prefix = "";
std::string out_found_filename, out_found_sim_filename;
int out_type(0), out_sim_type(0);
bool foundFile = UrdfFindMeshFile(fileIO, pathPrefix, relativeFileName, error_message_prefix, &out_found_filename, &out_type);
if (!deformable.m_simFileName.empty())
{
bool foundSimMesh = UrdfFindMeshFile(fileIO, pathPrefix, deformable.m_simFileName, error_message_prefix, &out_found_sim_filename, &out_sim_type);
}
else
{
out_sim_type = out_type;
out_found_sim_filename = out_found_filename;
}
if (out_sim_type == UrdfGeometry::FILE_OBJ)
{
std::vector<tinyobj::shape_t> shapes;
tinyobj::attrib_t attribute;
std::string err = tinyobj::LoadObj(attribute, shapes, out_found_sim_filename.c_str(), "", fileIO);
if (!shapes.empty())
{
const tinyobj::shape_t& shape = shapes[0];
btAlignedObjectArray<btScalar> vertices;
btAlignedObjectArray<int> indices;
for (int i = 0; i < attribute.vertices.size(); i++)
{
vertices.push_back(attribute.vertices[i]);
}
for (int i = 0; i < shape.mesh.indices.size(); i++)
{
indices.push_back(shape.mesh.indices[i].vertex_index);
}
int numTris = shape.mesh.indices.size() / 3;
if (numTris > 0)
{
{
btSoftMultiBodyDynamicsWorld* softWorld = getSoftWorld();
if (softWorld)
{
psb = btSoftBodyHelpers::CreateFromTriMesh(softWorld->getWorldInfo(), &vertices[0], &indices[0], numTris);
if (!psb)
{
printf("Load deformable failed\n");
return false;
}
}
}
{
btDeformableMultiBodyDynamicsWorld* deformWorld = getDeformableWorld();
if (deformWorld)
{
psb = btSoftBodyHelpers::CreateFromTriMesh(deformWorld->getWorldInfo(), &vertices[0], &indices[0], numTris);
if (!psb)
{
printf("Load deformable failed\n");
return false;
}
}
}
}
}
#ifndef SKIP_DEFORMABLE_BODY
btDeformableMultiBodyDynamicsWorld* deformWorld = getDeformableWorld();
if (deformWorld && deformable.m_springCoefficients.elastic_stiffness > 0.)
{
btDeformableLagrangianForce* springForce =
new btDeformableMassSpringForce(deformable.m_springCoefficients.elastic_stiffness,
deformable.m_springCoefficients.damping_stiffness,
!deformable.m_springCoefficients.damp_all_directions,
deformable.m_springCoefficients.bending_stiffness);
deformWorld->addForce(psb, springForce);
m_data->m_lf.push_back(springForce);
}
#endif
}
else if (out_sim_type == UrdfGeometry::FILE_VTK)
{
#ifndef SKIP_DEFORMABLE_BODY
btDeformableMultiBodyDynamicsWorld* deformWorld = getDeformableWorld();
if (deformWorld)
{
psb = btSoftBodyHelpers::CreateFromVtkFile(deformWorld->getWorldInfo(), out_found_sim_filename.c_str());
if (!psb)
{
printf("Load deformable failed\n");
return false;
}
btScalar corotated_mu(0.), corotated_lambda(0.);
corotated_mu = deformable.m_corotatedCoefficients.mu;
corotated_lambda = deformable.m_corotatedCoefficients.lambda;
if (corotated_mu > 0 || corotated_lambda > 0)
{
btDeformableLagrangianForce* corotatedForce = new btDeformableCorotatedForce(corotated_mu, corotated_lambda);
deformWorld->addForce(psb, corotatedForce);
m_data->m_lf.push_back(corotatedForce);
}
btScalar neohookean_mu, neohookean_lambda, neohookean_damping;
neohookean_mu = deformable.m_neohookeanCoefficients.mu;
neohookean_lambda = deformable.m_neohookeanCoefficients.lambda;
neohookean_damping = deformable.m_neohookeanCoefficients.damping;
if (neohookean_mu > 0 || neohookean_lambda > 0)
{
btDeformableLagrangianForce* neohookeanForce = new btDeformableNeoHookeanForce(neohookean_mu, neohookean_lambda, neohookean_damping);
deformWorld->addForce(psb, neohookeanForce);
m_data->m_lf.push_back(neohookeanForce);
}
btScalar spring_elastic_stiffness, spring_damping_stiffness, spring_bending_stiffness;
spring_elastic_stiffness = deformable.m_springCoefficients.elastic_stiffness;
spring_damping_stiffness = deformable.m_springCoefficients.damping_stiffness;
spring_bending_stiffness = deformable.m_springCoefficients.bending_stiffness;
if (spring_elastic_stiffness > 0.)
{
btDeformableLagrangianForce* springForce = new btDeformableMassSpringForce(spring_elastic_stiffness, spring_damping_stiffness, true, spring_bending_stiffness);
deformWorld->addForce(psb, springForce);
m_data->m_lf.push_back(springForce);
}
}
#endif
}
b3ImportMeshData meshData;
if (psb != NULL)
{
#ifndef SKIP_SOFT_BODY_MULTI_BODY_DYNAMICS_WORLD
// load render mesh
if ((out_found_sim_filename != out_found_filename) || ((out_sim_type == UrdfGeometry::FILE_OBJ)))
{
// load render mesh
if (!m_data->m_useAlternativeDeformableIndexing)
{
float rgbaColor[4] = { 1,1,1,1 };
if (b3ImportMeshUtility::loadAndRegisterMeshFromFileInternal(
out_found_filename.c_str(), meshData, fileIO))
{
for (int v = 0; v < meshData.m_gfxShape->m_numvertices; v++)
{
btSoftBody::RenderNode n;
n.m_x.setValue(
meshData.m_gfxShape->m_vertices->at(v).xyzw[0],
meshData.m_gfxShape->m_vertices->at(v).xyzw[1],
meshData.m_gfxShape->m_vertices->at(v).xyzw[2]);
n.m_uv1.setValue(meshData.m_gfxShape->m_vertices->at(v).uv[0],
meshData.m_gfxShape->m_vertices->at(v).uv[1],
0.);
n.m_normal.setValue(meshData.m_gfxShape->m_vertices->at(v).normal[0],
meshData.m_gfxShape->m_vertices->at(v).normal[1],
meshData.m_gfxShape->m_vertices->at(v).normal[2]);
psb->m_renderNodes.push_back(n);
}
for (int f = 0; f < meshData.m_gfxShape->m_numIndices; f += 3)
{
btSoftBody::RenderFace ff;
ff.m_n[0] = &psb->m_renderNodes[meshData.m_gfxShape->m_indices->at(f + 0)];
ff.m_n[1] = &psb->m_renderNodes[meshData.m_gfxShape->m_indices->at(f + 1)];
ff.m_n[2] = &psb->m_renderNodes[meshData.m_gfxShape->m_indices->at(f + 2)];
psb->m_renderFaces.push_back(ff);
}
}
}
else
{
tinyobj::attrib_t attribute;
std::vector<tinyobj::shape_t> shapes;
std::string err = tinyobj::LoadObj(attribute, shapes, out_found_filename.c_str(), pathPrefix, m_data->m_pluginManager.getFileIOInterface());
for (int s = 0; s < (int)shapes.size(); s++)
{
tinyobj::shape_t& shape = shapes[s];
int faceCount = shape.mesh.indices.size();
int vertexCount = attribute.vertices.size() / 3;
for (int v = 0; v < vertexCount; v++)
{
btSoftBody::RenderNode n;
n.m_x = btVector3(attribute.vertices[3 * v], attribute.vertices[3 * v + 1], attribute.vertices[3 * v + 2]);
psb->m_renderNodes.push_back(n);
}
for (int f = 0; f < faceCount; f += 3)
{
if (f < 0 && f >= int(shape.mesh.indices.size()))
{
continue;
}
tinyobj::index_t v_0 = shape.mesh.indices[f];
tinyobj::index_t v_1 = shape.mesh.indices[f + 1];
tinyobj::index_t v_2 = shape.mesh.indices[f + 2];
btSoftBody::RenderFace ff;
ff.m_n[0] = &psb->m_renderNodes[v_0.vertex_index];
ff.m_n[1] = &psb->m_renderNodes[v_1.vertex_index];
ff.m_n[2] = &psb->m_renderNodes[v_2.vertex_index];
psb->m_renderFaces.push_back(ff);
}
}
}
if (out_sim_type == UrdfGeometry::FILE_VTK)
{
btSoftBodyHelpers::interpolateBarycentricWeights(psb);
}
else if (out_sim_type == UrdfGeometry::FILE_OBJ)
{
btSoftBodyHelpers::extrapolateBarycentricWeights(psb);
}
}
else
{
psb->m_renderNodes.resize(0);
}
#endif
#ifndef SKIP_DEFORMABLE_BODY
btDeformableMultiBodyDynamicsWorld* deformWorld = getDeformableWorld();
if (deformWorld)
{
btVector3 gravity = m_data->m_dynamicsWorld->getGravity();
btDeformableLagrangianForce* gravityForce = new btDeformableGravityForce(gravity);
deformWorld->addForce(psb, gravityForce);
m_data->m_lf.push_back(gravityForce);
btScalar collision_hardness = 1;
psb->m_cfg.kKHR = collision_hardness;
psb->m_cfg.kCHR = collision_hardness;
psb->m_cfg.kDF = deformable.m_friction;
if (deformable.m_springCoefficients.bending_stiffness)
{
psb->generateBendingConstraints(deformable.m_springCoefficients.bending_stride);
}
btSoftBody::Material* pm = psb->appendMaterial();
pm->m_flags -= btSoftBody::fMaterial::DebugDraw;
// turn on the collision flag for deformable
// collision between deformable and rigid
psb->m_cfg.collisions = btSoftBody::fCollision::SDF_RD;
// turn on face contact for multibodies
psb->m_cfg.collisions |= btSoftBody::fCollision::SDF_MDF;
/// turn on face contact for rigid body
psb->m_cfg.collisions |= btSoftBody::fCollision::SDF_RDF;
// collion between deformable and deformable and self-collision
psb->m_cfg.collisions |= btSoftBody::fCollision::VF_DD;
psb->setCollisionFlags(0);
psb->setTotalMass(deformable.m_mass);
psb->setSelfCollision(useSelfCollision);
psb->setSpringStiffness(deformable.m_repulsionStiffness);
psb->setGravityFactor(deformable.m_gravFactor);
psb->setCacheBarycenter(deformable.m_cache_barycenter);
psb->initializeFaceTree();
}
#endif //SKIP_DEFORMABLE_BODY
#ifndef SKIP_SOFT_BODY_MULTI_BODY_DYNAMICS_WORLD
btSoftMultiBodyDynamicsWorld* softWorld = getSoftWorld();
if (softWorld)
{
btSoftBody::Material* pm = psb->appendMaterial();
pm->m_kLST = 0.5;
pm->m_flags -= btSoftBody::fMaterial::DebugDraw;
psb->generateBendingConstraints(2, pm);
psb->m_cfg.piterations = 20;
psb->m_cfg.kDF = 0.5;
//turn on softbody vs softbody collision
psb->m_cfg.collisions |= btSoftBody::fCollision::VF_SS;
psb->randomizeConstraints();
psb->setTotalMass(deformable.m_mass, true);
}
#endif //SKIP_SOFT_BODY_MULTI_BODY_DYNAMICS_WORLD
psb->scale(btVector3(scale, scale, scale));
psb->rotate(orn);
psb->translate(pos);
psb->getCollisionShape()->setMargin(deformable.m_collisionMargin);
psb->getCollisionShape()->setUserPointer(psb);
#ifndef SKIP_DEFORMABLE_BODY
if (deformWorld)
{
deformWorld->addSoftBody(psb);
}
else
#endif //SKIP_DEFORMABLE_BODY
{
btSoftMultiBodyDynamicsWorld* softWorld = getSoftWorld();
if (softWorld)
{
softWorld->addSoftBody(psb);
}
}
*bodyUniqueId = m_data->m_bodyHandles.allocHandle();
InternalBodyHandle* bodyHandle = m_data->m_bodyHandles.getHandle(*bodyUniqueId);
bodyHandle->m_softBody = psb;
psb->setUserIndex2(*bodyUniqueId);
b3VisualShapeData visualShape;
visualShape.m_objectUniqueId = *bodyUniqueId;
visualShape.m_linkIndex = -1;
visualShape.m_visualGeometryType = URDF_GEOM_MESH;
//dimensions just contains the scale
visualShape.m_dimensions[0] = 1;
visualShape.m_dimensions[1] = 1;
visualShape.m_dimensions[2] = 1;
//filename
strncpy(visualShape.m_meshAssetFileName, relativeFileName, VISUAL_SHAPE_MAX_PATH_LEN);
visualShape.m_meshAssetFileName[VISUAL_SHAPE_MAX_PATH_LEN - 1] = 0;
//position and orientation
visualShape.m_localVisualFrame[0] = 0;
visualShape.m_localVisualFrame[1] = 0;
visualShape.m_localVisualFrame[2] = 0;
visualShape.m_localVisualFrame[3] = 0;
visualShape.m_localVisualFrame[4] = 0;
visualShape.m_localVisualFrame[5] = 0;
visualShape.m_localVisualFrame[6] = 1;
//color and ids to be set by the renderer
visualShape.m_rgbaColor[0] = 1;
visualShape.m_rgbaColor[1] = 1;
visualShape.m_rgbaColor[2] = 1;
visualShape.m_rgbaColor[3] = 1;
visualShape.m_tinyRendererTextureId = -1;
visualShape.m_textureUniqueId = -1;
visualShape.m_openglTextureId = -1;
if (meshData.m_gfxShape)
{
int texUid1 = -1;
if (meshData.m_textureHeight > 0 && meshData.m_textureWidth > 0 && meshData.m_textureImage1)
{
texUid1 = m_data->m_guiHelper->registerTexture(meshData.m_textureImage1, meshData.m_textureWidth, meshData.m_textureHeight);
}
visualShape.m_openglTextureId = texUid1;
int shapeUid1 = m_data->m_guiHelper->registerGraphicsShape(&meshData.m_gfxShape->m_vertices->at(0).xyzw[0], meshData.m_gfxShape->m_numvertices, &meshData.m_gfxShape->m_indices->at(0), meshData.m_gfxShape->m_numIndices, B3_GL_TRIANGLES, texUid1);
psb->getCollisionShape()->setUserIndex(shapeUid1);
float position[4] = { 0,0,0,1 };
float orientation[4] = { 0,0,0,1 };
float color[4] = { 1,1,1,1 };
float scaling[4] = { 1,1,1,1 };
int instanceUid = m_data->m_guiHelper->registerGraphicsInstance(shapeUid1, position, orientation, color, scaling);
psb->setUserIndex(instanceUid);
if (m_data->m_enableTinyRenderer)
{
int texUid2 = m_data->m_pluginManager.getRenderInterface()->registerTexture(meshData.m_textureImage1, meshData.m_textureWidth, meshData.m_textureHeight);
visualShape.m_tinyRendererTextureId = texUid2;
int linkIndex = -1;
int softBodyGraphicsShapeUid = m_data->m_pluginManager.getRenderInterface()->registerShapeAndInstance(
visualShape,
&meshData.m_gfxShape->m_vertices->at(0).xyzw[0],
meshData.m_gfxShape->m_numvertices,
&meshData.m_gfxShape->m_indices->at(0),
meshData.m_gfxShape->m_numIndices,
B3_GL_TRIANGLES,
texUid2,
psb->getBroadphaseHandle()->getUid(),
*bodyUniqueId,
linkIndex);
psb->setUserIndex3(softBodyGraphicsShapeUid);
}
delete meshData.m_gfxShape;
meshData.m_gfxShape = 0;
}
else
{
//m_data->m_guiHelper->createCollisionShapeGraphicsObject(psb->getCollisionShape());
btAlignedObjectArray<GLInstanceVertex> gfxVertices;
btAlignedObjectArray<int> indices;
int strideInBytes = 9 * sizeof(float);
gfxVertices.resize(psb->m_faces.size() * 3);
for (int i = 0; i < psb->m_faces.size(); i++) // Foreach face
{
for (int k = 0; k < 3; k++) // Foreach vertex on a face
{
int currentIndex = i * 3 + k;
for (int j = 0; j < 3; j++)
{
gfxVertices[currentIndex].xyzw[j] = psb->m_faces[i].m_n[k]->m_x[j];
}
for (int j = 0; j < 3; j++)
{
gfxVertices[currentIndex].normal[j] = psb->m_faces[i].m_n[k]->m_n[j];
}
for (int j = 0; j < 2; j++)
{
gfxVertices[currentIndex].uv[j] = btFabs(btFabs(10. * psb->m_faces[i].m_n[k]->m_x[j]));
}
indices.push_back(currentIndex);
}
}
if (gfxVertices.size() && indices.size())
{
int red = 173;
int green = 199;
int blue = 255;
int texWidth = 256;
int texHeight = 256;
btAlignedObjectArray<unsigned char> texels;
texels.resize(texWidth* texHeight * 3);
for (int i = 0; i < texWidth * texHeight * 3; i++)
texels[i] = 255;
for (int i = 0; i < texWidth; i++)
{
for (int j = 0; j < texHeight; j++)
{
int a = i < texWidth / 2 ? 1 : 0;
int b = j < texWidth / 2 ? 1 : 0;
if (a == b)
{
texels[(i + j * texWidth) * 3 + 0] = red;
texels[(i + j * texWidth) * 3 + 1] = green;
texels[(i + j * texWidth) * 3 + 2] = blue;
}
}
}
int texId = m_data->m_guiHelper->registerTexture(&texels[0], texWidth, texHeight);
visualShape.m_openglTextureId = texId;
int shapeId = m_data->m_guiHelper->registerGraphicsShape(&gfxVertices[0].xyzw[0], gfxVertices.size(), &indices[0], indices.size(), B3_GL_TRIANGLES, texId);
b3Assert(shapeId >= 0);
psb->getCollisionShape()->setUserIndex(shapeId);
if (m_data->m_enableTinyRenderer)
{
int texUid2 = m_data->m_pluginManager.getRenderInterface()->registerTexture(&texels[0], texWidth, texHeight);
visualShape.m_tinyRendererTextureId = texUid2;
int linkIndex = -1;
int softBodyGraphicsShapeUid = m_data->m_pluginManager.getRenderInterface()->registerShapeAndInstance(
visualShape,
&gfxVertices[0].xyzw[0], gfxVertices.size(), &indices[0], indices.size(), B3_GL_TRIANGLES, texUid2,
psb->getBroadphaseHandle()->getUid(),
*bodyUniqueId,
linkIndex);
psb->setUserIndex3(softBodyGraphicsShapeUid);
}
}
}
btAlignedObjectArray<btVector3> vertices;
btAlignedObjectArray<btVector3> normals;
if (psb->m_renderNodes.size() == 0)
{
psb->m_renderNodes.resize(psb->m_faces.size()*3);
vertices.resize(psb->m_faces.size() * 3);
normals.resize(psb->m_faces.size() * 3);
for (int i = 0; i < psb->m_faces.size(); i++) // Foreach face
{
for (int k = 0; k < 3; k++) // Foreach vertex on a face
{
int currentIndex = i * 3 + k;
for (int j = 0; j < 3; j++)
{
psb->m_renderNodes[currentIndex].m_x[j] = psb->m_faces[i].m_n[k]->m_x[j];
}
for (int j = 0; j < 3; j++)
{
psb->m_renderNodes[currentIndex].m_normal[j] = psb->m_faces[i].m_n[k]->m_n[j];
}
for (int j = 0; j < 2; j++)
{
psb->m_renderNodes[currentIndex].m_uv1[j] = btFabs(10*psb->m_faces[i].m_n[k]->m_x[j]);
}
psb->m_renderNodes[currentIndex].m_uv1[2] = 0;
vertices[currentIndex] = psb->m_faces[i].m_n[k]->m_x;
normals[currentIndex] = psb->m_faces[i].m_n[k]->m_n;
}
}
btSoftBodyHelpers::extrapolateBarycentricWeights(psb);
}
else
{
vertices.resize(psb->m_renderNodes.size());
normals.resize(psb->m_renderNodes.size());
for (int i = 0; i < psb->m_renderNodes.size(); i++) // Foreach face
{
vertices[i] = psb->m_renderNodes[i].m_x;
normals[i] = psb->m_renderNodes[i].m_normal;
}
}
m_data->m_pluginManager.getRenderInterface()->updateShape(psb->getUserIndex3(), &vertices[0], vertices.size(), &normals[0], normals.size());
if (!deformable.m_name.empty())
{
bodyHandle->m_bodyName = deformable.m_name;
}
else
{
int pos = strlen(relativeFileName) - 1;
while (pos >= 0 && relativeFileName[pos] != '/')
{
pos--;
}
btAssert(strlen(relativeFileName) - pos - 5 > 0);
std::string object_name(std::string(relativeFileName).substr(pos + 1, strlen(relativeFileName) - 5 - pos));
bodyHandle->m_bodyName = object_name;
}
b3Notification notification;
notification.m_notificationType = BODY_ADDED;
notification.m_bodyArgs.m_bodyUniqueId = *bodyUniqueId;
m_data->m_pluginManager.addNotification(notification);
}
#endif
return true;
}
bool PhysicsServerCommandProcessor::processLoadSoftBodyCommand(const struct SharedMemoryCommand& clientCmd, struct SharedMemoryStatus& serverStatusOut, char* bufferServerToClient, int bufferSizeInBytes)
{
serverStatusOut.m_type = CMD_LOAD_SOFT_BODY_FAILED;
bool hasStatus = true;
#ifndef SKIP_SOFT_BODY_MULTI_BODY_DYNAMICS_WORLD
UrdfDeformable deformable;
constructUrdfDeformable(clientCmd, deformable, m_data->m_verboseOutput);
// const LoadSoftBodyArgs& loadSoftBodyArgs = clientCmd.m_loadSoftBodyArguments;
btVector3 initialPos(0, 0, 0);
if (clientCmd.m_updateFlags & LOAD_SOFT_BODY_INITIAL_POSITION)
{
initialPos[0] = clientCmd.m_loadSoftBodyArguments.m_initialPosition[0];
initialPos[1] = clientCmd.m_loadSoftBodyArguments.m_initialPosition[1];
initialPos[2] = clientCmd.m_loadSoftBodyArguments.m_initialPosition[2];
}
btQuaternion initialOrn(0, 0, 0, 1);
if (clientCmd.m_updateFlags & LOAD_SOFT_BODY_INITIAL_ORIENTATION)
{
initialOrn[0] = clientCmd.m_loadSoftBodyArguments.m_initialOrientation[0];
initialOrn[1] = clientCmd.m_loadSoftBodyArguments.m_initialOrientation[1];
initialOrn[2] = clientCmd.m_loadSoftBodyArguments.m_initialOrientation[2];
initialOrn[3] = clientCmd.m_loadSoftBodyArguments.m_initialOrientation[3];
}
double scale = 1;
if (clientCmd.m_updateFlags & LOAD_SOFT_BODY_UPDATE_SCALE)
{
scale = clientCmd.m_loadSoftBodyArguments.m_scale;
}
bool use_self_collision = false;
if (clientCmd.m_updateFlags & LOAD_SOFT_BODY_USE_SELF_COLLISION)
{
use_self_collision = clientCmd.m_loadSoftBodyArguments.m_useSelfCollision;
}
int bodyUniqueId = -1;
bool completedOk = processDeformable(deformable, initialPos, initialOrn, &bodyUniqueId, bufferServerToClient, bufferSizeInBytes, scale, use_self_collision);
if (completedOk && bodyUniqueId >= 0)
{
m_data->m_guiHelper->autogenerateGraphicsObjects(m_data->m_dynamicsWorld);
serverStatusOut.m_type = CMD_LOAD_SOFT_BODY_COMPLETED;
int streamSizeInBytes = createBodyInfoStream(bodyUniqueId, bufferServerToClient, bufferSizeInBytes);
serverStatusOut.m_numDataStreamBytes = streamSizeInBytes;
#ifdef ENABLE_LINK_MAPPER
if (m_data->m_urdfLinkNameMapper.size())
{
serverStatusOut.m_numDataStreamBytes = m_data->m_urdfLinkNameMapper.at(m_data->m_urdfLinkNameMapper.size() - 1)->m_memSerializer->getCurrentBufferSize();
}
#endif
serverStatusOut.m_dataStreamArguments.m_bodyUniqueId = bodyUniqueId;
InternalBodyData* body = m_data->m_bodyHandles.getHandle(bodyUniqueId);
strcpy(serverStatusOut.m_dataStreamArguments.m_bodyName, body->m_bodyName.c_str());
serverStatusOut.m_loadSoftBodyResultArguments.m_objectUniqueId = bodyUniqueId;
}
#endif
return hasStatus;
}
bool PhysicsServerCommandProcessor::processCreateSensorCommand(const struct SharedMemoryCommand& clientCmd, struct SharedMemoryStatus& serverStatusOut, char* bufferServerToClient, int bufferSizeInBytes)
{
bool hasStatus = true;
BT_PROFILE("CMD_CREATE_SENSOR");
if (m_data->m_verboseOutput)
{
b3Printf("Processed CMD_CREATE_SENSOR");
}
int bodyUniqueId = clientCmd.m_createSensorArguments.m_bodyUniqueId;
InternalBodyData* body = m_data->m_bodyHandles.getHandle(bodyUniqueId);
if (body && body->m_multiBody)
{
btMultiBody* mb = body->m_multiBody;
btAssert(mb);
for (int i = 0; i < clientCmd.m_createSensorArguments.m_numJointSensorChanges; i++)
{
int jointIndex = clientCmd.m_createSensorArguments.m_jointIndex[i];
if (clientCmd.m_createSensorArguments.m_enableJointForceSensor[i])
{
if (mb->getLink(jointIndex).m_jointFeedback)
{
b3Warning("CMD_CREATE_SENSOR: sensor for joint [%d] already enabled", jointIndex);
}
else
{
btMultiBodyJointFeedback* fb = new btMultiBodyJointFeedback();
fb->m_reactionForces.setZero();
mb->getLink(jointIndex).m_jointFeedback = fb;
m_data->m_multiBodyJointFeedbacks.push_back(fb);
};
}
else
{
if (mb->getLink(jointIndex).m_jointFeedback)
{
m_data->m_multiBodyJointFeedbacks.remove(mb->getLink(jointIndex).m_jointFeedback);
delete mb->getLink(jointIndex).m_jointFeedback;
mb->getLink(jointIndex).m_jointFeedback = 0;
}
else
{
b3Warning("CMD_CREATE_SENSOR: cannot perform sensor removal request, no sensor on joint [%d]", jointIndex);
};
}
}
}
else
{
b3Warning("No btMultiBody in the world. btRigidBody/btTypedConstraint sensor not hooked up yet");
}
#if 0
//todo(erwincoumans) here is some sample code to hook up a force/torque sensor for btTypedConstraint/btRigidBody
/*
for (int i=0;i<m_data->m_dynamicsWorld->getNumConstraints();i++)
{
btTypedConstraint* c = m_data->m_dynamicsWorld->getConstraint(i);
btJointFeedback* fb = new btJointFeedback();
m_data->m_jointFeedbacks.push_back(fb);
c->setJointFeedback(fb);
}
*/
#endif
serverStatusOut.m_type = CMD_CLIENT_COMMAND_COMPLETED;
return hasStatus;
}
bool PhysicsServerCommandProcessor::processProfileTimingCommand(const struct SharedMemoryCommand& clientCmd, struct SharedMemoryStatus& serverStatusOut, char* bufferServerToClient, int bufferSizeInBytes)
{
bool hasStatus = true;
{
if (clientCmd.m_profile.m_type == 0)
{
char** eventNamePtr = m_data->m_profileEvents[clientCmd.m_profile.m_name];
char* eventName = 0;
if (eventNamePtr)
{
eventName = *eventNamePtr;
}
else
{
int len = strlen(clientCmd.m_profile.m_name);
eventName = new char[len + 1];
strcpy(eventName, clientCmd.m_profile.m_name);
eventName[len] = 0;
m_data->m_profileEvents.insert(eventName, eventName);
}
b3EnterProfileZone(eventName);
}
if (clientCmd.m_profile.m_type == 1)
{
b3LeaveProfileZone();
}
}
serverStatusOut.m_type = CMD_CLIENT_COMMAND_COMPLETED;
hasStatus = true;
return hasStatus;
}
void setDefaultRootWorldAABB(SharedMemoryStatus& serverCmd)
{
serverCmd.m_sendCollisionInfoArgs.m_rootWorldAABBMin[0] = 0;
serverCmd.m_sendCollisionInfoArgs.m_rootWorldAABBMin[1] = 0;
serverCmd.m_sendCollisionInfoArgs.m_rootWorldAABBMin[2] = 0;
serverCmd.m_sendCollisionInfoArgs.m_rootWorldAABBMax[0] = -1;
serverCmd.m_sendCollisionInfoArgs.m_rootWorldAABBMax[1] = -1;
serverCmd.m_sendCollisionInfoArgs.m_rootWorldAABBMax[2] = -1;
}
bool PhysicsServerCommandProcessor::processRequestCollisionInfoCommand(const struct SharedMemoryCommand& clientCmd, struct SharedMemoryStatus& serverStatusOut, char* bufferServerToClient, int bufferSizeInBytes)
{
bool hasStatus = true;
SharedMemoryStatus& serverCmd = serverStatusOut;
serverStatusOut.m_type = CMD_REQUEST_COLLISION_INFO_FAILED;
hasStatus = true;
int bodyUniqueId = clientCmd.m_requestCollisionInfoArgs.m_bodyUniqueId;
InternalBodyData* body = m_data->m_bodyHandles.getHandle(bodyUniqueId);
if (body && body->m_multiBody)
{
btMultiBody* mb = body->m_multiBody;
serverStatusOut.m_type = CMD_REQUEST_COLLISION_INFO_COMPLETED;
serverCmd.m_sendCollisionInfoArgs.m_numLinks = body->m_multiBody->getNumLinks();
setDefaultRootWorldAABB(serverCmd);
if (body->m_multiBody->getBaseCollider())
{
btTransform tr;
tr.setOrigin(mb->getBasePos());
tr.setRotation(mb->getWorldToBaseRot().inverse());
btVector3 aabbMin, aabbMax;
body->m_multiBody->getBaseCollider()->getCollisionShape()->getAabb(tr, aabbMin, aabbMax);
serverCmd.m_sendCollisionInfoArgs.m_rootWorldAABBMin[0] = aabbMin[0];
serverCmd.m_sendCollisionInfoArgs.m_rootWorldAABBMin[1] = aabbMin[1];
serverCmd.m_sendCollisionInfoArgs.m_rootWorldAABBMin[2] = aabbMin[2];
serverCmd.m_sendCollisionInfoArgs.m_rootWorldAABBMax[0] = aabbMax[0];
serverCmd.m_sendCollisionInfoArgs.m_rootWorldAABBMax[1] = aabbMax[1];
serverCmd.m_sendCollisionInfoArgs.m_rootWorldAABBMax[2] = aabbMax[2];
}
for (int l = 0; l < mb->getNumLinks(); l++)
{
serverCmd.m_sendCollisionInfoArgs.m_linkWorldAABBsMin[3 * l + 0] = 0;
serverCmd.m_sendCollisionInfoArgs.m_linkWorldAABBsMin[3 * l + 1] = 0;
serverCmd.m_sendCollisionInfoArgs.m_linkWorldAABBsMin[3 * l + 2] = 0;
serverCmd.m_sendCollisionInfoArgs.m_linkWorldAABBsMax[3 * l + 0] = -1;
serverCmd.m_sendCollisionInfoArgs.m_linkWorldAABBsMax[3 * l + 1] = -1;
serverCmd.m_sendCollisionInfoArgs.m_linkWorldAABBsMax[3 * l + 2] = -1;
if (body->m_multiBody->getLink(l).m_collider)
{
btVector3 aabbMin, aabbMax;
body->m_multiBody->getLinkCollider(l)->getCollisionShape()->getAabb(mb->getLink(l).m_cachedWorldTransform, aabbMin, aabbMax);
serverCmd.m_sendCollisionInfoArgs.m_linkWorldAABBsMin[3 * l + 0] = aabbMin[0];
serverCmd.m_sendCollisionInfoArgs.m_linkWorldAABBsMin[3 * l + 1] = aabbMin[1];
serverCmd.m_sendCollisionInfoArgs.m_linkWorldAABBsMin[3 * l + 2] = aabbMin[2];
serverCmd.m_sendCollisionInfoArgs.m_linkWorldAABBsMax[3 * l + 0] = aabbMax[0];
serverCmd.m_sendCollisionInfoArgs.m_linkWorldAABBsMax[3 * l + 1] = aabbMax[1];
serverCmd.m_sendCollisionInfoArgs.m_linkWorldAABBsMax[3 * l + 2] = aabbMax[2];
}
}
}
else if (body && body->m_rigidBody)
{
btRigidBody* rb = body->m_rigidBody;
SharedMemoryStatus& serverCmd = serverStatusOut;
serverStatusOut.m_type = CMD_REQUEST_COLLISION_INFO_COMPLETED;
serverCmd.m_sendCollisionInfoArgs.m_numLinks = 0;
setDefaultRootWorldAABB(serverCmd);
if (rb->getCollisionShape())
{
btTransform tr = rb->getWorldTransform();
btVector3 aabbMin, aabbMax;
rb->getCollisionShape()->getAabb(tr, aabbMin, aabbMax);
serverCmd.m_sendCollisionInfoArgs.m_rootWorldAABBMin[0] = aabbMin[0];
serverCmd.m_sendCollisionInfoArgs.m_rootWorldAABBMin[1] = aabbMin[1];
serverCmd.m_sendCollisionInfoArgs.m_rootWorldAABBMin[2] = aabbMin[2];
serverCmd.m_sendCollisionInfoArgs.m_rootWorldAABBMax[0] = aabbMax[0];
serverCmd.m_sendCollisionInfoArgs.m_rootWorldAABBMax[1] = aabbMax[1];
serverCmd.m_sendCollisionInfoArgs.m_rootWorldAABBMax[2] = aabbMax[2];
}
}
#ifndef SKIP_SOFT_BODY_MULTI_BODY_DYNAMICS_WORLD
else if (body && body->m_softBody)
{
btSoftBody* sb = body->m_softBody;
serverCmd.m_sendCollisionInfoArgs.m_numLinks = 0;
btVector3 aabbMin, aabbMax;
sb->getAabb(aabbMin, aabbMax);
serverCmd.m_sendCollisionInfoArgs.m_rootWorldAABBMin[0] = aabbMin[0];
serverCmd.m_sendCollisionInfoArgs.m_rootWorldAABBMin[1] = aabbMin[1];
serverCmd.m_sendCollisionInfoArgs.m_rootWorldAABBMin[2] = aabbMin[2];
serverCmd.m_sendCollisionInfoArgs.m_rootWorldAABBMax[0] = aabbMax[0];
serverCmd.m_sendCollisionInfoArgs.m_rootWorldAABBMax[1] = aabbMax[1];
serverCmd.m_sendCollisionInfoArgs.m_rootWorldAABBMax[2] = aabbMax[2];
SharedMemoryStatus& serverCmd = serverStatusOut;
serverStatusOut.m_type = CMD_REQUEST_COLLISION_INFO_COMPLETED;
}
#endif
return hasStatus;
}
bool PhysicsServerCommandProcessor::performCollisionDetectionCommand(const struct SharedMemoryCommand& clientCmd, struct SharedMemoryStatus& serverStatusOut, char* bufferServerToClient, int bufferSizeInBytes)
{
bool hasStatus = true;
BT_PROFILE("CMD_PERFORM_COLLISION_DETECTION");
if (m_data->m_verboseOutput)
{
b3Printf("Perform Collision Detection command");
b3Printf("CMD_PERFORM_COLLISION_DETECTION clientCmd = %d\n", clientCmd.m_sequenceNumber);
}
m_data->m_dynamicsWorld->performDiscreteCollisionDetection();
SharedMemoryStatus& serverCmd = serverStatusOut;
serverCmd.m_type = CMD_PERFORM_COLLISION_DETECTION_COMPLETED;
return true;
}
bool PhysicsServerCommandProcessor::processForwardDynamicsCommand(const struct SharedMemoryCommand& clientCmd, struct SharedMemoryStatus& serverStatusOut, char* bufferServerToClient, int bufferSizeInBytes)
{
bool hasStatus = true;
BT_PROFILE("CMD_STEP_FORWARD_SIMULATION");
if (m_data->m_verboseOutput)
{
b3Printf("Step simulation request");
b3Printf("CMD_STEP_FORWARD_SIMULATION clientCmd = %d\n", clientCmd.m_sequenceNumber);
}
#ifndef USE_DISCRETE_DYNAMICS_WORLD
///todo(erwincoumans) move this damping inside Bullet
for (int i = 0; i < m_data->m_dynamicsWorld->getNumMultibodies(); i++)
{
btMultiBody* mb = m_data->m_dynamicsWorld->getMultiBody(i);
for (int l = 0; l < mb->getNumLinks(); l++)
{
for (int d = 0; d < mb->getLink(l).m_dofCount; d++)
{
double damping_coefficient = mb->getLink(l).m_jointDamping;
double damping = -damping_coefficient * mb->getJointVelMultiDof(l)[d];
mb->addJointTorqueMultiDof(l, d, damping);
}
}
}
#endif
btScalar deltaTimeScaled = m_data->m_physicsDeltaTime * simTimeScalingFactor;
int numSteps = 0;
if (m_data->m_numSimulationSubSteps > 0)
{
numSteps = m_data->m_dynamicsWorld->stepSimulation(deltaTimeScaled, m_data->m_numSimulationSubSteps, m_data->m_physicsDeltaTime / m_data->m_numSimulationSubSteps);
m_data->m_simulationTimestamp += deltaTimeScaled;
}
else
{
numSteps = m_data->m_dynamicsWorld->stepSimulation(deltaTimeScaled, 0);
m_data->m_simulationTimestamp += deltaTimeScaled;
}
if (numSteps > 0)
{
addBodyChangedNotifications();
}
SharedMemoryStatus& serverCmd = serverStatusOut;
serverCmd.m_forwardDynamicsAnalyticsArgs.m_numSteps = numSteps;
btAlignedObjectArray<btSolverAnalyticsData> islandAnalyticsData;
#ifndef USE_DISCRETE_DYNAMICS_WORLD
m_data->m_dynamicsWorld->getAnalyticsData(islandAnalyticsData);
#endif
serverCmd.m_forwardDynamicsAnalyticsArgs.m_numIslands = islandAnalyticsData.size();
int numIslands = btMin(islandAnalyticsData.size(), MAX_ISLANDS_ANALYTICS);
for (int i = 0; i < numIslands; i++)
{
serverCmd.m_forwardDynamicsAnalyticsArgs.m_numSolverCalls = islandAnalyticsData[i].m_numSolverCalls;
serverCmd.m_forwardDynamicsAnalyticsArgs.m_islandData[i].m_islandId = islandAnalyticsData[i].m_islandId;
serverCmd.m_forwardDynamicsAnalyticsArgs.m_islandData[i].m_numBodies = islandAnalyticsData[i].m_numBodies;
serverCmd.m_forwardDynamicsAnalyticsArgs.m_islandData[i].m_numIterationsUsed = islandAnalyticsData[i].m_numIterationsUsed;
serverCmd.m_forwardDynamicsAnalyticsArgs.m_islandData[i].m_remainingLeastSquaresResidual = islandAnalyticsData[i].m_remainingLeastSquaresResidual;
serverCmd.m_forwardDynamicsAnalyticsArgs.m_islandData[i].m_numContactManifolds = islandAnalyticsData[i].m_numContactManifolds;
}
serverCmd.m_type = CMD_STEP_FORWARD_SIMULATION_COMPLETED;
m_data->m_remoteSyncTransformTime += deltaTimeScaled;
if (m_data->m_remoteSyncTransformTime >= m_data->m_remoteSyncTransformInterval)
{
m_data->m_remoteSyncTransformTime = 0;
syncPhysicsToGraphics2();
}
return hasStatus;
}
bool PhysicsServerCommandProcessor::processRequestInternalDataCommand(const struct SharedMemoryCommand& clientCmd, struct SharedMemoryStatus& serverStatusOut, char* bufferServerToClient, int bufferSizeInBytes)
{
bool hasStatus = true;
BT_PROFILE("CMD_REQUEST_INTERNAL_DATA");
//todo: also check version etc?
SharedMemoryStatus& serverCmd = serverStatusOut;
serverCmd.m_type = CMD_REQUEST_INTERNAL_DATA_FAILED;
int sz = btDefaultSerializer::getMemoryDnaSizeInBytes();
const char* memDna = btDefaultSerializer::getMemoryDna();
if (sz < bufferSizeInBytes)
{
for (int i = 0; i < sz; i++)
{
bufferServerToClient[i] = memDna[i];
}
serverCmd.m_type = CMD_REQUEST_INTERNAL_DATA_COMPLETED;
serverCmd.m_numDataStreamBytes = sz;
}
return hasStatus;
}
bool PhysicsServerCommandProcessor::processChangeDynamicsInfoCommand(const struct SharedMemoryCommand& clientCmd, struct SharedMemoryStatus& serverStatusOut, char* bufferServerToClient, int bufferSizeInBytes)
{
bool hasStatus = true;
BT_PROFILE("CMD_CHANGE_DYNAMICS_INFO");
int bodyUniqueId = clientCmd.m_changeDynamicsInfoArgs.m_bodyUniqueId;
int linkIndex = clientCmd.m_changeDynamicsInfoArgs.m_linkIndex;
double mass = clientCmd.m_changeDynamicsInfoArgs.m_mass;
double lateralFriction = clientCmd.m_changeDynamicsInfoArgs.m_lateralFriction;
double spinningFriction = clientCmd.m_changeDynamicsInfoArgs.m_spinningFriction;
double rollingFriction = clientCmd.m_changeDynamicsInfoArgs.m_rollingFriction;
double restitution = clientCmd.m_changeDynamicsInfoArgs.m_restitution;
btVector3 newLocalInertiaDiagonal(clientCmd.m_changeDynamicsInfoArgs.m_localInertiaDiagonal[0],
clientCmd.m_changeDynamicsInfoArgs.m_localInertiaDiagonal[1],
clientCmd.m_changeDynamicsInfoArgs.m_localInertiaDiagonal[2]);
btVector3 anisotropicFriction(clientCmd.m_changeDynamicsInfoArgs.m_anisotropicFriction[0],
clientCmd.m_changeDynamicsInfoArgs.m_anisotropicFriction[1],
clientCmd.m_changeDynamicsInfoArgs.m_anisotropicFriction[2]);
if (bodyUniqueId >= 0)
{
InternalBodyData* body = m_data->m_bodyHandles.getHandle(bodyUniqueId);
#ifndef USE_DISCRETE_DYNAMICS_WORLD
if (body && body->m_multiBody)
{
btMultiBody* mb = body->m_multiBody;
if (clientCmd.m_updateFlags & CHANGE_DYNAMICS_INFO_SET_ACTIVATION_STATE)
{
if (clientCmd.m_changeDynamicsInfoArgs.m_activationState & eActivationStateWakeUp)
{
mb->wakeUp();
}
if (clientCmd.m_changeDynamicsInfoArgs.m_activationState & eActivationStateSleep)
{
mb->goToSleep();
}
if (clientCmd.m_changeDynamicsInfoArgs.m_activationState & eActivationStateEnableSleeping)
{
mb->setCanSleep(true);
}
if (clientCmd.m_changeDynamicsInfoArgs.m_activationState & eActivationStateDisableSleeping)
{
mb->setCanSleep(false);
}
if (clientCmd.m_changeDynamicsInfoArgs.m_activationState & eActivationStateEnableWakeup)
{
mb->setCanWakeup(true);
}
if (clientCmd.m_changeDynamicsInfoArgs.m_activationState & eActivationStateDisableWakeup)
{
mb->setCanWakeup(false);
}
}
if (clientCmd.m_updateFlags & CHANGE_DYNAMICS_INFO_SET_LINEAR_DAMPING)
{
mb->setLinearDamping(clientCmd.m_changeDynamicsInfoArgs.m_linearDamping);
}
if (clientCmd.m_updateFlags & CHANGE_DYNAMICS_INFO_SET_ANGULAR_DAMPING)
{
mb->setAngularDamping(clientCmd.m_changeDynamicsInfoArgs.m_angularDamping);
}
if (clientCmd.m_updateFlags & CHANGE_DYNAMICS_INFO_SET_SLEEP_THRESHOLD)
{
mb->setSleepThreshold(clientCmd.m_changeDynamicsInfoArgs.m_sleepThreshold);
}
if (linkIndex == -1)
{
if (mb->getBaseCollider())
{
if (clientCmd.m_updateFlags & CHANGE_DYNAMICS_INFO_SET_RESTITUTION)
{
mb->getBaseCollider()->setRestitution(restitution);
}
if (clientCmd.m_updateFlags & CHANGE_DYNAMICS_INFO_SET_CONTACT_STIFFNESS_AND_DAMPING)
{
mb->getBaseCollider()->setContactStiffnessAndDamping(clientCmd.m_changeDynamicsInfoArgs.m_contactStiffness, clientCmd.m_changeDynamicsInfoArgs.m_contactDamping);
}
if (clientCmd.m_updateFlags & CHANGE_DYNAMICS_INFO_SET_LATERAL_FRICTION)
{
mb->getBaseCollider()->setFriction(lateralFriction);
}
if (clientCmd.m_updateFlags & CHANGE_DYNAMICS_INFO_SET_SPINNING_FRICTION)
{
mb->getBaseCollider()->setSpinningFriction(spinningFriction);
}
if (clientCmd.m_updateFlags & CHANGE_DYNAMICS_INFO_SET_ROLLING_FRICTION)
{
mb->getBaseCollider()->setRollingFriction(rollingFriction);
}
if (clientCmd.m_updateFlags & CHANGE_DYNAMICS_INFO_SET_FRICTION_ANCHOR)
{
if (clientCmd.m_changeDynamicsInfoArgs.m_frictionAnchor)
{
mb->getBaseCollider()->setCollisionFlags(mb->getBaseCollider()->getCollisionFlags() | btCollisionObject::CF_HAS_FRICTION_ANCHOR);
}
else
{
mb->getBaseCollider()->setCollisionFlags(mb->getBaseCollider()->getCollisionFlags() & ~btCollisionObject::CF_HAS_FRICTION_ANCHOR);
}
}
}
if (clientCmd.m_updateFlags & CHANGE_DYNAMICS_INFO_SET_MASS)
{
mb->setBaseMass(mass);
if (mb->getBaseCollider() && mb->getBaseCollider()->getCollisionShape())
{
btVector3 localInertia;
mb->getBaseCollider()->getCollisionShape()->calculateLocalInertia(mass, localInertia);
mb->setBaseInertia(localInertia);
}
//handle switch from static/fixedBase to dynamic and vise-versa
if (mass > 0)
{
bool isDynamic = true;
if (mb->hasFixedBase())
{
int collisionFilterGroup = isDynamic ? int(btBroadphaseProxy::DefaultFilter) : int(btBroadphaseProxy::StaticFilter);
int collisionFilterMask = isDynamic ? int(btBroadphaseProxy::AllFilter) : int(btBroadphaseProxy::AllFilter ^ btBroadphaseProxy::StaticFilter);
m_data->m_dynamicsWorld->removeCollisionObject(mb->getBaseCollider());
int oldFlags = mb->getBaseCollider()->getCollisionFlags();
mb->getBaseCollider()->setCollisionFlags(oldFlags & ~btCollisionObject::CF_STATIC_OBJECT);
mb->setFixedBase(false);
m_data->m_dynamicsWorld->addCollisionObject(mb->getBaseCollider(), collisionFilterGroup, collisionFilterMask);
}
}
else
{
if (!mb->hasFixedBase())
{
bool isDynamic = false;
int collisionFilterGroup = isDynamic ? int(btBroadphaseProxy::DefaultFilter) : int(btBroadphaseProxy::StaticFilter);
int collisionFilterMask = isDynamic ? int(btBroadphaseProxy::AllFilter) : int(btBroadphaseProxy::AllFilter ^ btBroadphaseProxy::StaticFilter);
int oldFlags = mb->getBaseCollider()->getCollisionFlags();
mb->getBaseCollider()->setCollisionFlags(oldFlags | btCollisionObject::CF_STATIC_OBJECT);
m_data->m_dynamicsWorld->removeCollisionObject(mb->getBaseCollider());
mb->setFixedBase(true);
m_data->m_dynamicsWorld->addCollisionObject(mb->getBaseCollider(), collisionFilterGroup, collisionFilterMask);
}
}
}
if (clientCmd.m_updateFlags & CHANGE_DYNAMICS_INFO_SET_LOCAL_INERTIA_DIAGONAL)
{
mb->setBaseInertia(newLocalInertiaDiagonal);
}
if (clientCmd.m_updateFlags & CHANGE_DYNAMICS_INFO_SET_ANISOTROPIC_FRICTION)
{
mb->getBaseCollider()->setAnisotropicFriction(anisotropicFriction);
}
if (clientCmd.m_updateFlags & CHANGE_DYNAMICS_INFO_SET_CONTACT_PROCESSING_THRESHOLD)
{
mb->getBaseCollider()->setContactProcessingThreshold(clientCmd.m_changeDynamicsInfoArgs.m_contactProcessingThreshold);
}
if (clientCmd.m_updateFlags & CHANGE_DYNAMICS_INFO_SET_MAX_JOINT_VELOCITY)
{
mb->setMaxCoordinateVelocity(clientCmd.m_changeDynamicsInfoArgs.m_maxJointVelocity);
}
if (clientCmd.m_updateFlags & CHANGE_DYNAMICS_INFO_SET_COLLISION_MARGIN)
{
mb->getBaseCollider()->getCollisionShape()->setMargin(clientCmd.m_changeDynamicsInfoArgs.m_collisionMargin);
if (mb->getBaseCollider()->getCollisionShape()->isCompound())
{
btCompoundShape* compound = (btCompoundShape*)mb->getBaseCollider()->getCollisionShape();
for (int s = 0; s < compound->getNumChildShapes(); s++)
{
compound->getChildShape(s)->setMargin(clientCmd.m_changeDynamicsInfoArgs.m_collisionMargin);
}
}
}
if (clientCmd.m_updateFlags & CHANGE_DYNAMICS_INFO_SET_DYNAMIC_TYPE)
{
int dynamic_type = clientCmd.m_changeDynamicsInfoArgs.m_dynamicType;
mb->setBaseDynamicType(dynamic_type);
bool isDynamic = dynamic_type == eDynamic;
int collisionFilterGroup = isDynamic ? int(btBroadphaseProxy::DefaultFilter) : int(btBroadphaseProxy::StaticFilter);
int collisionFilterMask = isDynamic ? int(btBroadphaseProxy::AllFilter) : int(btBroadphaseProxy::AllFilter ^ btBroadphaseProxy::StaticFilter);
m_data->m_dynamicsWorld->removeCollisionObject(mb->getBaseCollider());
m_data->m_dynamicsWorld->addCollisionObject(mb->getBaseCollider(), collisionFilterGroup, collisionFilterMask);
}
}
else
{
if (linkIndex >= 0 && linkIndex < mb->getNumLinks())
{
if ((clientCmd.m_updateFlags & CHANGE_DYNAMICS_INFO_SET_JOINT_LIMIT_MAX_FORCE) ||
(clientCmd.m_updateFlags & CHANGE_DYNAMICS_INFO_SET_JOINT_LIMITS))
{
btMultiBodyJointLimitConstraint* limC = 0;
int numConstraints = m_data->m_dynamicsWorld->getNumMultiBodyConstraints();
for (int c = 0; c < numConstraints; c++)
{
btMultiBodyConstraint* mbc = m_data->m_dynamicsWorld->getMultiBodyConstraint(c);
if (mbc->getConstraintType() == MULTIBODY_CONSTRAINT_LIMIT)
{
if ((mbc->getMultiBodyA() == mb) && (mbc->getLinkA() == linkIndex))
{
limC = (btMultiBodyJointLimitConstraint*)mbc;
}
}
}
if (clientCmd.m_updateFlags & CHANGE_DYNAMICS_INFO_SET_JOINT_LIMITS)
{
//find a joint limit
btScalar prevUpper = mb->getLink(linkIndex).m_jointUpperLimit;
btScalar prevLower = mb->getLink(linkIndex).m_jointLowerLimit;
btScalar lower = clientCmd.m_changeDynamicsInfoArgs.m_jointLowerLimit;
btScalar upper = clientCmd.m_changeDynamicsInfoArgs.m_jointUpperLimit;
bool enableLimit = lower <= upper;
if (enableLimit)
{
if (limC == 0)
{
limC = new btMultiBodyJointLimitConstraint(mb, linkIndex, lower, upper);
m_data->m_dynamicsWorld->addMultiBodyConstraint(limC);
}
else
{
limC->setLowerBound(lower);
limC->setUpperBound(upper);
}
mb->getLink(linkIndex).m_jointLowerLimit = lower;
mb->getLink(linkIndex).m_jointUpperLimit = upper;
}
else
{
if (limC)
{
m_data->m_dynamicsWorld->removeMultiBodyConstraint(limC);
delete limC;
limC = 0;
}
mb->getLink(linkIndex).m_jointLowerLimit = 1;
mb->getLink(linkIndex).m_jointUpperLimit = -1;
}
}
if (clientCmd.m_updateFlags & CHANGE_DYNAMICS_INFO_SET_JOINT_LIMIT_MAX_FORCE)
{
btScalar fixedTimeSubStep = m_data->m_numSimulationSubSteps > 0 ? m_data->m_physicsDeltaTime / m_data->m_numSimulationSubSteps : m_data->m_physicsDeltaTime;
btScalar maxImpulse = clientCmd.m_changeDynamicsInfoArgs.m_jointLimitForce * fixedTimeSubStep;
if (limC)
{
//convert from force to impulse
limC->setMaxAppliedImpulse(maxImpulse);
}
}
}
if (mb->getLinkCollider(linkIndex))
{
if (clientCmd.m_updateFlags & CHANGE_DYNAMICS_INFO_SET_RESTITUTION)
{
mb->getLinkCollider(linkIndex)->setRestitution(restitution);
}
if (clientCmd.m_updateFlags & CHANGE_DYNAMICS_INFO_SET_SPINNING_FRICTION)
{
mb->getLinkCollider(linkIndex)->setSpinningFriction(spinningFriction);
}
if (clientCmd.m_updateFlags & CHANGE_DYNAMICS_INFO_SET_ROLLING_FRICTION)
{
mb->getLinkCollider(linkIndex)->setRollingFriction(rollingFriction);
}
if (clientCmd.m_updateFlags & CHANGE_DYNAMICS_INFO_SET_FRICTION_ANCHOR)
{
if (clientCmd.m_changeDynamicsInfoArgs.m_frictionAnchor)
{
mb->getLinkCollider(linkIndex)->setCollisionFlags(mb->getLinkCollider(linkIndex)->getCollisionFlags() | btCollisionObject::CF_HAS_FRICTION_ANCHOR);
}
else
{
mb->getLinkCollider(linkIndex)->setCollisionFlags(mb->getLinkCollider(linkIndex)->getCollisionFlags() & ~btCollisionObject::CF_HAS_FRICTION_ANCHOR);
}
}
if (clientCmd.m_updateFlags & CHANGE_DYNAMICS_INFO_SET_LATERAL_FRICTION)
{
mb->getLinkCollider(linkIndex)->setFriction(lateralFriction);
}
if (clientCmd.m_updateFlags & CHANGE_DYNAMICS_INFO_SET_CONTACT_STIFFNESS_AND_DAMPING)
{
mb->getLinkCollider(linkIndex)->setContactStiffnessAndDamping(clientCmd.m_changeDynamicsInfoArgs.m_contactStiffness, clientCmd.m_changeDynamicsInfoArgs.m_contactDamping);
}
if (clientCmd.m_updateFlags & CHANGE_DYNAMICS_INFO_SET_COLLISION_MARGIN)
{
mb->getLinkCollider(linkIndex)->getCollisionShape()->setMargin(clientCmd.m_changeDynamicsInfoArgs.m_collisionMargin);
}
}
if (clientCmd.m_updateFlags & CHANGE_DYNAMICS_INFO_SET_JOINT_DAMPING)
{
mb->getLink(linkIndex).m_jointDamping = clientCmd.m_changeDynamicsInfoArgs.m_jointDamping;
}
if (clientCmd.m_updateFlags & CHANGE_DYNAMICS_INFO_SET_MASS)
{
mb->getLink(linkIndex).m_mass = mass;
if (mb->getLinkCollider(linkIndex) && mb->getLinkCollider(linkIndex)->getCollisionShape())
{
btVector3 localInertia;
mb->getLinkCollider(linkIndex)->getCollisionShape()->calculateLocalInertia(mass, localInertia);
mb->getLink(linkIndex).m_inertiaLocal = localInertia;
}
}
if (clientCmd.m_updateFlags & CHANGE_DYNAMICS_INFO_SET_LOCAL_INERTIA_DIAGONAL)
{
mb->getLink(linkIndex).m_inertiaLocal = newLocalInertiaDiagonal;
}
if (clientCmd.m_updateFlags & CHANGE_DYNAMICS_INFO_SET_ANISOTROPIC_FRICTION)
{
mb->getLinkCollider(linkIndex)->setAnisotropicFriction(anisotropicFriction);
}
if (clientCmd.m_updateFlags & CHANGE_DYNAMICS_INFO_SET_CONTACT_PROCESSING_THRESHOLD)
{
mb->getLinkCollider(linkIndex)->setContactProcessingThreshold(clientCmd.m_changeDynamicsInfoArgs.m_contactProcessingThreshold);
}
if (clientCmd.m_updateFlags & CHANGE_DYNAMICS_INFO_SET_DYNAMIC_TYPE)
{
int dynamic_type = clientCmd.m_changeDynamicsInfoArgs.m_dynamicType;
mb->setLinkDynamicType(linkIndex, dynamic_type);
bool isDynamic = dynamic_type == eDynamic;
int collisionFilterGroup = isDynamic ? int(btBroadphaseProxy::DefaultFilter) : int(btBroadphaseProxy::StaticFilter);
int collisionFilterMask = isDynamic ? int(btBroadphaseProxy::AllFilter) : int(btBroadphaseProxy::AllFilter ^ btBroadphaseProxy::StaticFilter);
m_data->m_dynamicsWorld->removeCollisionObject(mb->getLinkCollider(linkIndex));
m_data->m_dynamicsWorld->addCollisionObject(mb->getLinkCollider(linkIndex), collisionFilterGroup, collisionFilterMask);
}
}
}
}
else
#endif
{
btRigidBody* rb = 0;
if (body && body->m_rigidBody)
{
if (linkIndex == -1)
{
rb = body->m_rigidBody;
}
else
{
if (linkIndex >= 0 && linkIndex < body->m_rigidBodyJoints.size())
{
btRigidBody* parentRb = &body->m_rigidBodyJoints[linkIndex]->getRigidBodyA();
btRigidBody* childRb = &body->m_rigidBodyJoints[linkIndex]->getRigidBodyB();
rb = childRb;
}
}
}
if (rb)
{
if (clientCmd.m_updateFlags & CHANGE_DYNAMICS_INFO_SET_ACTIVATION_STATE)
{
if (clientCmd.m_changeDynamicsInfoArgs.m_activationState & eActivationStateEnableSleeping)
{
rb->forceActivationState(ACTIVE_TAG);
}
if (clientCmd.m_changeDynamicsInfoArgs.m_activationState & eActivationStateDisableSleeping)
{
rb->forceActivationState(DISABLE_DEACTIVATION);
}
if (clientCmd.m_changeDynamicsInfoArgs.m_activationState & eActivationStateWakeUp)
{
rb->forceActivationState(ACTIVE_TAG);
rb->setDeactivationTime(0.0);
}
if (clientCmd.m_changeDynamicsInfoArgs.m_activationState & eActivationStateSleep)
{
rb->forceActivationState(ISLAND_SLEEPING);
}
}
if (clientCmd.m_updateFlags & CHANGE_DYNAMICS_INFO_SET_LINEAR_DAMPING)
{
btScalar angDamping = rb->getAngularDamping();
rb->setDamping(clientCmd.m_changeDynamicsInfoArgs.m_linearDamping, angDamping);
}
if (clientCmd.m_updateFlags & CHANGE_DYNAMICS_INFO_SET_ANGULAR_DAMPING)
{
btScalar linDamping = rb->getLinearDamping();
rb->setDamping(linDamping, clientCmd.m_changeDynamicsInfoArgs.m_angularDamping);
}
if (clientCmd.m_updateFlags & CHANGE_DYNAMICS_INFO_SET_CONTACT_STIFFNESS_AND_DAMPING)
{
rb->setContactStiffnessAndDamping(clientCmd.m_changeDynamicsInfoArgs.m_contactStiffness, clientCmd.m_changeDynamicsInfoArgs.m_contactDamping);
}
if (clientCmd.m_updateFlags & CHANGE_DYNAMICS_INFO_SET_RESTITUTION)
{
rb->setRestitution(restitution);
}
if (clientCmd.m_updateFlags & CHANGE_DYNAMICS_INFO_SET_LATERAL_FRICTION)
{
rb->setFriction(lateralFriction);
}
if (clientCmd.m_updateFlags & CHANGE_DYNAMICS_INFO_SET_SPINNING_FRICTION)
{
rb->setSpinningFriction(spinningFriction);
}
if (clientCmd.m_updateFlags & CHANGE_DYNAMICS_INFO_SET_ROLLING_FRICTION)
{
rb->setRollingFriction(rollingFriction);
}
if (clientCmd.m_updateFlags & CHANGE_DYNAMICS_INFO_SET_FRICTION_ANCHOR)
{
if (clientCmd.m_changeDynamicsInfoArgs.m_frictionAnchor)
{
rb->setCollisionFlags(rb->getCollisionFlags() | btCollisionObject::CF_HAS_FRICTION_ANCHOR);
}
else
{
rb->setCollisionFlags(rb->getCollisionFlags() & ~btCollisionObject::CF_HAS_FRICTION_ANCHOR);
}
}
if (clientCmd.m_updateFlags & CHANGE_DYNAMICS_INFO_SET_MASS)
{
btVector3 localInertia;
if (rb->getCollisionShape())
{
rb->getCollisionShape()->calculateLocalInertia(mass, localInertia);
}
rb->setMassProps(mass, localInertia);
}
if (clientCmd.m_updateFlags & CHANGE_DYNAMICS_INFO_SET_LOCAL_INERTIA_DIAGONAL)
{
btScalar orgMass = rb->getInvMass();
if (orgMass > 0)
{
rb->setMassProps(mass, newLocalInertiaDiagonal);
}
}
if (clientCmd.m_updateFlags & CHANGE_DYNAMICS_INFO_SET_ANISOTROPIC_FRICTION)
{
rb->setAnisotropicFriction(anisotropicFriction);
}
if (clientCmd.m_updateFlags & CHANGE_DYNAMICS_INFO_SET_CONTACT_PROCESSING_THRESHOLD)
{
rb->setContactProcessingThreshold(clientCmd.m_changeDynamicsInfoArgs.m_contactProcessingThreshold);
}
if (clientCmd.m_updateFlags & CHANGE_DYNAMICS_INFO_SET_CCD_SWEPT_SPHERE_RADIUS)
{
rb->setCcdSweptSphereRadius(clientCmd.m_changeDynamicsInfoArgs.m_ccdSweptSphereRadius);
//for a given sphere radius, use a motion threshold of half the radius, before the ccd algorithm is enabled
rb->setCcdMotionThreshold(clientCmd.m_changeDynamicsInfoArgs.m_ccdSweptSphereRadius / 2.);
}
if (clientCmd.m_updateFlags & CHANGE_DYNAMICS_INFO_SET_COLLISION_MARGIN)
{
rb->getCollisionShape()->setMargin(clientCmd.m_changeDynamicsInfoArgs.m_collisionMargin);
}
if (clientCmd.m_updateFlags & CHANGE_DYNAMICS_INFO_SET_DYNAMIC_TYPE)
{
int dynamic_type = clientCmd.m_changeDynamicsInfoArgs.m_dynamicType;
// If mass is zero, the object cannot be set to be dynamic.
if (!(rb->getInvMass() != btScalar(0.) || dynamic_type != eDynamic)) {
int collision_flags = rb->getCollisionFlags();
collision_flags &= ~(btCollisionObject::CF_STATIC_OBJECT | btCollisionObject::CF_KINEMATIC_OBJECT);
collision_flags |= dynamic_type;
rb->setCollisionFlags(collision_flags);
bool isDynamic = dynamic_type == eDynamic;
int collisionFilterGroup = isDynamic ? int(btBroadphaseProxy::DefaultFilter) : int(btBroadphaseProxy::StaticFilter);
int collisionFilterMask = isDynamic ? int(btBroadphaseProxy::AllFilter) : int(btBroadphaseProxy::AllFilter ^ btBroadphaseProxy::StaticFilter);
m_data->m_dynamicsWorld->removeCollisionObject(rb);
m_data->m_dynamicsWorld->addCollisionObject(rb, collisionFilterGroup, collisionFilterMask);
}
}
if (clientCmd.m_updateFlags & CHANGE_DYNAMICS_INFO_SET_SLEEP_THRESHOLD)
{
btScalar threshold2 = btSqrt(clientCmd.m_changeDynamicsInfoArgs.m_sleepThreshold);
rb->setSleepingThresholds(threshold2,threshold2);
}
}
}
#ifndef SKIP_SOFT_BODY_MULTI_BODY_DYNAMICS_WORLD
if (body && body->m_softBody)
{
btSoftBody* psb = body->m_softBody;
if (psb)
{
if (clientCmd.m_updateFlags & CHANGE_DYNAMICS_INFO_SET_ACTIVATION_STATE)
{
if (clientCmd.m_changeDynamicsInfoArgs.m_activationState & eActivationStateEnableSleeping)
{
psb->forceActivationState(ACTIVE_TAG);
}
if (clientCmd.m_changeDynamicsInfoArgs.m_activationState & eActivationStateDisableSleeping)
{
psb->forceActivationState(DISABLE_DEACTIVATION);
}
if (clientCmd.m_changeDynamicsInfoArgs.m_activationState & eActivationStateWakeUp)
{
psb->forceActivationState(ACTIVE_TAG);
psb->setDeactivationTime(0.0);
}
if (clientCmd.m_changeDynamicsInfoArgs.m_activationState & eActivationStateSleep)
{
psb->forceActivationState(ISLAND_SLEEPING);
}
}
}
}
#endif
}
SharedMemoryStatus& serverCmd = serverStatusOut;
serverCmd.m_type = CMD_CLIENT_COMMAND_COMPLETED;
b3Notification notification;
notification.m_notificationType = LINK_DYNAMICS_CHANGED;
notification.m_linkArgs.m_bodyUniqueId = bodyUniqueId;
notification.m_linkArgs.m_linkIndex = linkIndex;
m_data->m_pluginManager.addNotification(notification);
return hasStatus;
}
bool PhysicsServerCommandProcessor::processSetAdditionalSearchPathCommand(const struct SharedMemoryCommand& clientCmd, struct SharedMemoryStatus& serverStatusOut, char* bufferServerToClient, int bufferSizeInBytes)
{
bool hasStatus = true;
BT_PROFILE("CMD_SET_ADDITIONAL_SEARCH_PATH");
b3ResourcePath::setAdditionalSearchPath(clientCmd.m_searchPathArgs.m_path);
serverStatusOut.m_type = CMD_CLIENT_COMMAND_COMPLETED;
return hasStatus;
}
bool PhysicsServerCommandProcessor::processGetDynamicsInfoCommand(const struct SharedMemoryCommand& clientCmd, struct SharedMemoryStatus& serverStatusOut, char* bufferServerToClient, int bufferSizeInBytes)
{
bool hasStatus = true;
SharedMemoryStatus& serverCmd = serverStatusOut;
serverCmd.m_type = CMD_GET_DYNAMICS_INFO_FAILED;
int bodyUniqueId = clientCmd.m_getDynamicsInfoArgs.m_bodyUniqueId;
int linkIndex = clientCmd.m_getDynamicsInfoArgs.m_linkIndex;
InternalBodyData* body = m_data->m_bodyHandles.getHandle(bodyUniqueId);
if (body && body->m_multiBody)
{
SharedMemoryStatus& serverCmd = serverStatusOut;
serverCmd.m_type = CMD_GET_DYNAMICS_INFO_COMPLETED;
serverCmd.m_dynamicsInfo.m_bodyType = BT_MULTI_BODY;
btMultiBody* mb = body->m_multiBody;
if (linkIndex == -1)
{
serverCmd.m_dynamicsInfo.m_mass = mb->getBaseMass();
if (mb->getBaseCollider())
{
serverCmd.m_dynamicsInfo.m_activationState = mb->getBaseCollider()->getActivationState();
serverCmd.m_dynamicsInfo.m_contactProcessingThreshold = mb->getBaseCollider()->getContactProcessingThreshold();
serverCmd.m_dynamicsInfo.m_ccdSweptSphereRadius = mb->getBaseCollider()->getCcdSweptSphereRadius();
serverCmd.m_dynamicsInfo.m_frictionAnchor = mb->getBaseCollider()->getCollisionFlags() & btCollisionObject::CF_HAS_FRICTION_ANCHOR;
serverCmd.m_dynamicsInfo.m_collisionMargin = mb->getBaseCollider()->getCollisionShape()->getMargin();
serverCmd.m_dynamicsInfo.m_dynamicType = mb->getBaseCollider()->getCollisionFlags() & (btCollisionObject::CF_STATIC_OBJECT | btCollisionObject::CF_KINEMATIC_OBJECT);
}
else
{
serverCmd.m_dynamicsInfo.m_activationState = 0;
serverCmd.m_dynamicsInfo.m_contactProcessingThreshold = 0;
serverCmd.m_dynamicsInfo.m_ccdSweptSphereRadius = 0;
serverCmd.m_dynamicsInfo.m_frictionAnchor = 0;
serverCmd.m_dynamicsInfo.m_collisionMargin = 0;
serverCmd.m_dynamicsInfo.m_dynamicType = 0;
}
serverCmd.m_dynamicsInfo.m_localInertialDiagonal[0] = mb->getBaseInertia()[0];
serverCmd.m_dynamicsInfo.m_localInertialDiagonal[1] = mb->getBaseInertia()[1];
serverCmd.m_dynamicsInfo.m_localInertialDiagonal[2] = mb->getBaseInertia()[2];
serverCmd.m_dynamicsInfo.m_lateralFrictionCoeff = mb->getBaseCollider()->getFriction();
serverCmd.m_dynamicsInfo.m_localInertialFrame[0] = body->m_rootLocalInertialFrame.getOrigin()[0];
serverCmd.m_dynamicsInfo.m_localInertialFrame[1] = body->m_rootLocalInertialFrame.getOrigin()[1];
serverCmd.m_dynamicsInfo.m_localInertialFrame[2] = body->m_rootLocalInertialFrame.getOrigin()[2];
serverCmd.m_dynamicsInfo.m_localInertialFrame[3] = body->m_rootLocalInertialFrame.getRotation()[0];
serverCmd.m_dynamicsInfo.m_localInertialFrame[4] = body->m_rootLocalInertialFrame.getRotation()[1];
serverCmd.m_dynamicsInfo.m_localInertialFrame[5] = body->m_rootLocalInertialFrame.getRotation()[2];
serverCmd.m_dynamicsInfo.m_localInertialFrame[6] = body->m_rootLocalInertialFrame.getRotation()[3];
serverCmd.m_dynamicsInfo.m_angularDamping = body->m_multiBody->getAngularDamping();
serverCmd.m_dynamicsInfo.m_linearDamping = body->m_multiBody->getLinearDamping();
serverCmd.m_dynamicsInfo.m_restitution = mb->getBaseCollider()->getRestitution();
serverCmd.m_dynamicsInfo.m_rollingFrictionCoeff = mb->getBaseCollider()->getRollingFriction();
serverCmd.m_dynamicsInfo.m_spinningFrictionCoeff = mb->getBaseCollider()->getSpinningFriction();
if (mb->getBaseCollider()->getCollisionFlags() & btCollisionObject::CF_HAS_CONTACT_STIFFNESS_DAMPING)
{
serverCmd.m_dynamicsInfo.m_contactStiffness = mb->getBaseCollider()->getContactStiffness();
serverCmd.m_dynamicsInfo.m_contactDamping = mb->getBaseCollider()->getContactDamping();
}
else
{
serverCmd.m_dynamicsInfo.m_contactStiffness = -1;
serverCmd.m_dynamicsInfo.m_contactDamping = -1;
}
}
else
{
serverCmd.m_dynamicsInfo.m_mass = mb->getLinkMass(linkIndex);
if (mb->getLinkCollider(linkIndex))
{
serverCmd.m_dynamicsInfo.m_activationState = mb->getLinkCollider(linkIndex)->getActivationState();
serverCmd.m_dynamicsInfo.m_contactProcessingThreshold = mb->getLinkCollider(linkIndex)->getContactProcessingThreshold();
serverCmd.m_dynamicsInfo.m_ccdSweptSphereRadius = mb->getLinkCollider(linkIndex)->getCcdSweptSphereRadius();
serverCmd.m_dynamicsInfo.m_frictionAnchor = mb->getLinkCollider(linkIndex)->getCollisionFlags() & btCollisionObject::CF_HAS_FRICTION_ANCHOR;
serverCmd.m_dynamicsInfo.m_collisionMargin = mb->getLinkCollider(linkIndex)->getCollisionShape()->getMargin();
serverCmd.m_dynamicsInfo.m_dynamicType = mb->getLinkCollider(linkIndex)->getCollisionFlags() & (btCollisionObject::CF_STATIC_OBJECT | btCollisionObject::CF_KINEMATIC_OBJECT);
}
else
{
serverCmd.m_dynamicsInfo.m_activationState = 0;
serverCmd.m_dynamicsInfo.m_contactProcessingThreshold = 0;
serverCmd.m_dynamicsInfo.m_ccdSweptSphereRadius = 0;
serverCmd.m_dynamicsInfo.m_frictionAnchor = 0;
serverCmd.m_dynamicsInfo.m_collisionMargin = 0;
serverCmd.m_dynamicsInfo.m_dynamicType = 0;
}
serverCmd.m_dynamicsInfo.m_localInertialDiagonal[0] = mb->getLinkInertia(linkIndex)[0];
serverCmd.m_dynamicsInfo.m_localInertialDiagonal[1] = mb->getLinkInertia(linkIndex)[1];
serverCmd.m_dynamicsInfo.m_localInertialDiagonal[2] = mb->getLinkInertia(linkIndex)[2];
serverCmd.m_dynamicsInfo.m_localInertialFrame[0] = body->m_linkLocalInertialFrames[linkIndex].getOrigin()[0];
serverCmd.m_dynamicsInfo.m_localInertialFrame[1] = body->m_linkLocalInertialFrames[linkIndex].getOrigin()[1];
serverCmd.m_dynamicsInfo.m_localInertialFrame[2] = body->m_linkLocalInertialFrames[linkIndex].getOrigin()[2];
serverCmd.m_dynamicsInfo.m_localInertialFrame[3] = body->m_linkLocalInertialFrames[linkIndex].getRotation()[0];
serverCmd.m_dynamicsInfo.m_localInertialFrame[4] = body->m_linkLocalInertialFrames[linkIndex].getRotation()[1];
serverCmd.m_dynamicsInfo.m_localInertialFrame[5] = body->m_linkLocalInertialFrames[linkIndex].getRotation()[2];
serverCmd.m_dynamicsInfo.m_localInertialFrame[6] = body->m_linkLocalInertialFrames[linkIndex].getRotation()[3];
serverCmd.m_dynamicsInfo.m_angularDamping = body->m_multiBody->getAngularDamping();
serverCmd.m_dynamicsInfo.m_linearDamping = body->m_multiBody->getLinearDamping();
if (mb->getLinkCollider(linkIndex))
{
serverCmd.m_dynamicsInfo.m_lateralFrictionCoeff = mb->getLinkCollider(linkIndex)->getFriction();
serverCmd.m_dynamicsInfo.m_restitution = mb->getLinkCollider(linkIndex)->getRestitution();
serverCmd.m_dynamicsInfo.m_rollingFrictionCoeff = mb->getLinkCollider(linkIndex)->getRollingFriction();
serverCmd.m_dynamicsInfo.m_spinningFrictionCoeff = mb->getLinkCollider(linkIndex)->getSpinningFriction();
if (mb->getLinkCollider(linkIndex)->getCollisionFlags() & btCollisionObject::CF_HAS_CONTACT_STIFFNESS_DAMPING)
{
serverCmd.m_dynamicsInfo.m_contactStiffness = mb->getLinkCollider(linkIndex)->getContactStiffness();
serverCmd.m_dynamicsInfo.m_contactDamping = mb->getLinkCollider(linkIndex)->getContactDamping();
}
else
{
serverCmd.m_dynamicsInfo.m_contactStiffness = -1;
serverCmd.m_dynamicsInfo.m_contactDamping = -1;
}
}
else
{
b3Warning("The dynamic info requested is not available");
serverCmd.m_type = CMD_GET_DYNAMICS_INFO_FAILED;
}
}
hasStatus = true;
}
else if (body && body->m_rigidBody)
{
SharedMemoryStatus& serverCmd = serverStatusOut;
serverCmd.m_type = CMD_GET_DYNAMICS_INFO_COMPLETED;
serverCmd.m_dynamicsInfo.m_bodyType = BT_RIGID_BODY;
btRigidBody* rb = body->m_rigidBody;
serverCmd.m_dynamicsInfo.m_localInertialDiagonal[0] = rb->getLocalInertia()[0];
serverCmd.m_dynamicsInfo.m_localInertialDiagonal[1] = rb->getLocalInertia()[1];
serverCmd.m_dynamicsInfo.m_localInertialDiagonal[2] = rb->getLocalInertia()[2];
serverCmd.m_dynamicsInfo.m_lateralFrictionCoeff = rb->getFriction();
serverCmd.m_dynamicsInfo.m_rollingFrictionCoeff = rb->getRollingFriction();
serverCmd.m_dynamicsInfo.m_spinningFrictionCoeff = rb->getSpinningFriction();
serverCmd.m_dynamicsInfo.m_angularDamping = rb->getAngularDamping();
serverCmd.m_dynamicsInfo.m_linearDamping = rb->getLinearDamping();
serverCmd.m_dynamicsInfo.m_mass = rb->getMass();
serverCmd.m_dynamicsInfo.m_collisionMargin = rb->getCollisionShape() ? rb->getCollisionShape()->getMargin() : 0;
serverCmd.m_dynamicsInfo.m_dynamicType = rb->getCollisionFlags() & (btCollisionObject::CF_STATIC_OBJECT | btCollisionObject::CF_KINEMATIC_OBJECT);
}
#ifndef SKIP_SOFT_BODY_MULTI_BODY_DYNAMICS_WORLD
else if (body && body->m_softBody)
{
SharedMemoryStatus& serverCmd = serverStatusOut;
serverCmd.m_type = CMD_GET_DYNAMICS_INFO_COMPLETED;
serverCmd.m_dynamicsInfo.m_bodyType = BT_SOFT_BODY;
serverCmd.m_dynamicsInfo.m_collisionMargin = 0;
}
#endif
return hasStatus;
}
bool PhysicsServerCommandProcessor::processRequestPhysicsSimulationParametersCommand(const struct SharedMemoryCommand& clientCmd, struct SharedMemoryStatus& serverStatusOut, char* bufferServerToClient, int bufferSizeInBytes)
{
bool hasStatus = true;
SharedMemoryStatus& serverCmd = serverStatusOut;
serverCmd.m_type = CMD_REQUEST_PHYSICS_SIMULATION_PARAMETERS_COMPLETED;
serverCmd.m_simulationParameterResultArgs.m_allowedCcdPenetration = m_data->m_dynamicsWorld->getDispatchInfo().m_allowedCcdPenetration;
serverCmd.m_simulationParameterResultArgs.m_collisionFilterMode = m_data->m_broadphaseCollisionFilterCallback->m_filterMode;
serverCmd.m_simulationParameterResultArgs.m_deltaTime = m_data->m_physicsDeltaTime;
serverCmd.m_simulationParameterResultArgs.m_simulationTimestamp = m_data->m_simulationTimestamp;
serverCmd.m_simulationParameterResultArgs.m_contactBreakingThreshold = gContactBreakingThreshold;
serverCmd.m_simulationParameterResultArgs.m_contactSlop = m_data->m_dynamicsWorld->getSolverInfo().m_linearSlop;
serverCmd.m_simulationParameterResultArgs.m_enableSAT = m_data->m_dynamicsWorld->getDispatchInfo().m_enableSatConvex;
serverCmd.m_simulationParameterResultArgs.m_defaultGlobalCFM = m_data->m_dynamicsWorld->getSolverInfo().m_globalCfm;
serverCmd.m_simulationParameterResultArgs.m_defaultContactERP = m_data->m_dynamicsWorld->getSolverInfo().m_erp2;
serverCmd.m_simulationParameterResultArgs.m_defaultNonContactERP = m_data->m_dynamicsWorld->getSolverInfo().m_erp;
serverCmd.m_simulationParameterResultArgs.m_deltaTime = m_data->m_physicsDeltaTime;
serverCmd.m_simulationParameterResultArgs.m_deterministicOverlappingPairs = m_data->m_dynamicsWorld->getDispatchInfo().m_deterministicOverlappingPairs;
serverCmd.m_simulationParameterResultArgs.m_enableConeFriction = (m_data->m_dynamicsWorld->getSolverInfo().m_solverMode & SOLVER_DISABLE_IMPLICIT_CONE_FRICTION) ? 0 : 1;
serverCmd.m_simulationParameterResultArgs.m_enableFileCaching = b3IsFileCachingEnabled();
serverCmd.m_simulationParameterResultArgs.m_frictionCFM = m_data->m_dynamicsWorld->getSolverInfo().m_frictionCFM;
serverCmd.m_simulationParameterResultArgs.m_frictionERP = m_data->m_dynamicsWorld->getSolverInfo().m_frictionERP;
btVector3 grav = m_data->m_dynamicsWorld->getGravity();
serverCmd.m_simulationParameterResultArgs.m_gravityAcceleration[0] = grav[0];
serverCmd.m_simulationParameterResultArgs.m_gravityAcceleration[1] = grav[1];
serverCmd.m_simulationParameterResultArgs.m_gravityAcceleration[2] = grav[2];
serverCmd.m_simulationParameterResultArgs.m_internalSimFlags = gInternalSimFlags;
serverCmd.m_simulationParameterResultArgs.m_jointFeedbackMode = 0;
if (m_data->m_dynamicsWorld->getSolverInfo().m_jointFeedbackInWorldSpace)
{
serverCmd.m_simulationParameterResultArgs.m_jointFeedbackMode |= JOINT_FEEDBACK_IN_WORLD_SPACE;
}
if (m_data->m_dynamicsWorld->getSolverInfo().m_jointFeedbackInJointFrame)
{
serverCmd.m_simulationParameterResultArgs.m_jointFeedbackMode |= JOINT_FEEDBACK_IN_JOINT_FRAME;
}
serverCmd.m_simulationParameterResultArgs.m_numSimulationSubSteps = m_data->m_numSimulationSubSteps;
serverCmd.m_simulationParameterResultArgs.m_numSolverIterations = m_data->m_dynamicsWorld->getSolverInfo().m_numIterations;
serverCmd.m_simulationParameterResultArgs.m_numNonContactInnerIterations = m_data->m_dynamicsWorld->getSolverInfo().m_numNonContactInnerIterations;
serverCmd.m_simulationParameterResultArgs.m_restitutionVelocityThreshold = m_data->m_dynamicsWorld->getSolverInfo().m_restitutionVelocityThreshold;
serverCmd.m_simulationParameterResultArgs.m_solverResidualThreshold = m_data->m_dynamicsWorld->getSolverInfo().m_leastSquaresResidualThreshold;
serverCmd.m_simulationParameterResultArgs.m_splitImpulsePenetrationThreshold = m_data->m_dynamicsWorld->getSolverInfo().m_splitImpulsePenetrationThreshold;
serverCmd.m_simulationParameterResultArgs.m_useRealTimeSimulation = m_data->m_useRealTimeSimulation;
serverCmd.m_simulationParameterResultArgs.m_useSplitImpulse = m_data->m_dynamicsWorld->getSolverInfo().m_splitImpulse;
return hasStatus;
}
bool PhysicsServerCommandProcessor::processSendPhysicsParametersCommand(const struct SharedMemoryCommand& clientCmd, struct SharedMemoryStatus& serverStatusOut, char* bufferServerToClient, int bufferSizeInBytes)
{
bool hasStatus = true;
BT_PROFILE("CMD_SEND_PHYSICS_SIMULATION_PARAMETERS");
if (clientCmd.m_updateFlags & SIM_PARAM_ENABLE_CONE_FRICTION)
{
if (clientCmd.m_physSimParamArgs.m_enableConeFriction)
{
m_data->m_dynamicsWorld->getSolverInfo().m_solverMode &= ~SOLVER_DISABLE_IMPLICIT_CONE_FRICTION;
}
else
{
m_data->m_dynamicsWorld->getSolverInfo().m_solverMode |= SOLVER_DISABLE_IMPLICIT_CONE_FRICTION;
}
}
if (clientCmd.m_updateFlags & SIM_PARAM_UPDATE_DETERMINISTIC_OVERLAPPING_PAIRS)
{
m_data->m_dynamicsWorld->getDispatchInfo().m_deterministicOverlappingPairs = (clientCmd.m_physSimParamArgs.m_deterministicOverlappingPairs != 0);
}
if (clientCmd.m_updateFlags & SIM_PARAM_UPDATE_CCD_ALLOWED_PENETRATION)
{
m_data->m_dynamicsWorld->getDispatchInfo().m_allowedCcdPenetration = clientCmd.m_physSimParamArgs.m_allowedCcdPenetration;
}
if (clientCmd.m_updateFlags & SIM_PARAM_UPDATE_JOINT_FEEDBACK_MODE)
{
m_data->m_dynamicsWorld->getSolverInfo().m_jointFeedbackInWorldSpace = (clientCmd.m_physSimParamArgs.m_jointFeedbackMode & JOINT_FEEDBACK_IN_WORLD_SPACE) != 0;
m_data->m_dynamicsWorld->getSolverInfo().m_jointFeedbackInJointFrame = (clientCmd.m_physSimParamArgs.m_jointFeedbackMode & JOINT_FEEDBACK_IN_JOINT_FRAME) != 0;
}
if (clientCmd.m_updateFlags & SIM_PARAM_UPDATE_DELTA_TIME)
{
m_data->m_physicsDeltaTime = clientCmd.m_physSimParamArgs.m_deltaTime;
}
if (clientCmd.m_updateFlags & SIM_PARAM_UPDATE_REAL_TIME_SIMULATION)
{
m_data->m_useRealTimeSimulation = (clientCmd.m_physSimParamArgs.m_useRealTimeSimulation != 0);
}
//see
if (clientCmd.m_updateFlags & SIM_PARAM_UPDATE_INTERNAL_SIMULATION_FLAGS)
{
//these flags are for internal/temporary/easter-egg/experimental demo purposes, use at own risk
gInternalSimFlags = clientCmd.m_physSimParamArgs.m_internalSimFlags;
m_data->m_useAlternativeDeformableIndexing =
(clientCmd.m_physSimParamArgs.m_internalSimFlags & eDeformableAlternativeIndexing) != 0;
}
if (clientCmd.m_updateFlags & SIM_PARAM_UPDATE_GRAVITY)
{
btVector3 grav(clientCmd.m_physSimParamArgs.m_gravityAcceleration[0],
clientCmd.m_physSimParamArgs.m_gravityAcceleration[1],
clientCmd.m_physSimParamArgs.m_gravityAcceleration[2]);
this->m_data->m_dynamicsWorld->setGravity(grav);
#ifndef SKIP_SOFT_BODY_MULTI_BODY_DYNAMICS_WORLD
btSoftMultiBodyDynamicsWorld* softWorld = getSoftWorld();
if (softWorld)
{
softWorld->getWorldInfo().m_gravity = grav;
}
btDeformableMultiBodyDynamicsWorld* deformWorld = getDeformableWorld();
if (deformWorld)
{
deformWorld->getWorldInfo().m_gravity = grav;
for (int i = 0; i < m_data->m_lf.size(); ++i)
{
btDeformableLagrangianForce* force = m_data->m_lf[i];
if (force->getForceType() == BT_GRAVITY_FORCE)
{
btDeformableGravityForce* gforce = (btDeformableGravityForce*)force;
gforce->m_gravity = grav;
}
}
}
#endif
if (m_data->m_verboseOutput)
{
b3Printf("Updated Gravity: %f,%f,%f", grav[0], grav[1], grav[2]);
}
}
if (clientCmd.m_updateFlags & SIM_PARAM_UPDATE_NUM_SOLVER_ITERATIONS)
{
m_data->m_dynamicsWorld->getSolverInfo().m_numIterations = clientCmd.m_physSimParamArgs.m_numSolverIterations;
}
if (clientCmd.m_updateFlags & SIM_PARAM_UPDATE_NUM_NONCONTACT_INNER_ITERATIONS)
{
m_data->m_dynamicsWorld->getSolverInfo().m_numNonContactInnerIterations = clientCmd.m_physSimParamArgs.m_numNonContactInnerIterations;
}
if (clientCmd.m_updateFlags & SIM_PARAM_UPDATE_SOLVER_RESIDULAL_THRESHOLD)
{
m_data->m_dynamicsWorld->getSolverInfo().m_leastSquaresResidualThreshold = clientCmd.m_physSimParamArgs.m_solverResidualThreshold;
}
if (clientCmd.m_updateFlags & SIM_PARAM_UPDATE_CONTACT_BREAKING_THRESHOLD)
{
gContactBreakingThreshold = clientCmd.m_physSimParamArgs.m_contactBreakingThreshold;
}
if (clientCmd.m_updateFlags & SIM_PARAM_UPDATE_CONTACT_SLOP)
{
m_data->m_dynamicsWorld->getSolverInfo().m_linearSlop = clientCmd.m_physSimParamArgs.m_contactSlop;
}
if (clientCmd.m_updateFlags & SIM_PARAM_ENABLE_SAT)
{
m_data->m_dynamicsWorld->getDispatchInfo().m_enableSatConvex = clientCmd.m_physSimParamArgs.m_enableSAT != 0;
}
if (clientCmd.m_updateFlags & SIM_PARAM_CONSTRAINT_SOLVER_TYPE)
{
//check if the current type is different from requested one
if (m_data->m_constraintSolverType != clientCmd.m_physSimParamArgs.m_constraintSolverType)
{
m_data->m_constraintSolverType = clientCmd.m_physSimParamArgs.m_constraintSolverType;
btConstraintSolver* oldSolver = m_data->m_dynamicsWorld->getConstraintSolver();
#ifdef USE_DISCRETE_DYNAMICS_WORLD
btSequentialImpulseConstraintSolver* newSolver = 0;
#else
btMultiBodyConstraintSolver* newSolver = 0;
#endif
switch (clientCmd.m_physSimParamArgs.m_constraintSolverType)
{
case eConstraintSolverLCP_SI:
{
newSolver = new btMultiBodyConstraintSolver;
b3Printf("PyBullet: Constraint Solver: btMultiBodyConstraintSolver\n");
break;
}
case eConstraintSolverLCP_PGS:
{
btSolveProjectedGaussSeidel* mlcp = new btSolveProjectedGaussSeidel();
#ifdef USE_DISCRETE_DYNAMICS_WORLD
newSolver = new btMLCPSolver(mlcp);
#else
newSolver = new btMultiBodyMLCPConstraintSolver(mlcp);
#endif
b3Printf("PyBullet: Constraint Solver: MLCP + PGS\n");
break;
}
case eConstraintSolverLCP_DANTZIG:
{
btDantzigSolver* mlcp = new btDantzigSolver();
newSolver = new btMultiBodyMLCPConstraintSolver(mlcp);
b3Printf("PyBullet: Constraint Solver: MLCP + Dantzig\n");
break;
}
case eConstraintSolverLCP_BLOCK_PGS:
{
break;
}
default:
{
}
};
if (newSolver)
{
delete oldSolver;
#ifdef USE_DISCRETE_DYNAMICS_WORLD
m_data->m_dynamicsWorld->setConstraintSolver(newSolver);
#else
m_data->m_dynamicsWorld->setMultiBodyConstraintSolver(newSolver);
#endif
m_data->m_solver = newSolver;
printf("switched solver\n");
}
}
}
if (clientCmd.m_updateFlags & SIM_PARAM_CONSTRAINT_MIN_SOLVER_ISLAND_SIZE)
{
m_data->m_dynamicsWorld->getSolverInfo().m_minimumSolverBatchSize = clientCmd.m_physSimParamArgs.m_minimumSolverIslandSize;
}
if (clientCmd.m_updateFlags & SIM_PARAM_UPDATE_COLLISION_FILTER_MODE)
{
m_data->m_broadphaseCollisionFilterCallback->m_filterMode = clientCmd.m_physSimParamArgs.m_collisionFilterMode;
}
if (clientCmd.m_updateFlags & SIM_PARAM_UPDATE_USE_SPLIT_IMPULSE)
{
m_data->m_dynamicsWorld->getSolverInfo().m_splitImpulse = clientCmd.m_physSimParamArgs.m_useSplitImpulse;
}
if (clientCmd.m_updateFlags & SIM_PARAM_UPDATE_SPLIT_IMPULSE_PENETRATION_THRESHOLD)
{
m_data->m_dynamicsWorld->getSolverInfo().m_splitImpulsePenetrationThreshold = clientCmd.m_physSimParamArgs.m_splitImpulsePenetrationThreshold;
}
if (clientCmd.m_updateFlags & SIM_PARAM_UPDATE_NUM_SIMULATION_SUB_STEPS)
{
m_data->m_numSimulationSubSteps = clientCmd.m_physSimParamArgs.m_numSimulationSubSteps;
}
if (clientCmd.m_updateFlags & SIM_PARAM_UPDATE_DEFAULT_CONTACT_ERP)
{
m_data->m_dynamicsWorld->getSolverInfo().m_erp2 = clientCmd.m_physSimParamArgs.m_defaultContactERP;
}
if (clientCmd.m_updateFlags & SIM_PARAM_UPDATE_DEFAULT_NON_CONTACT_ERP)
{
m_data->m_dynamicsWorld->getSolverInfo().m_erp = clientCmd.m_physSimParamArgs.m_defaultNonContactERP;
}
if (clientCmd.m_updateFlags & SIM_PARAM_UPDATE_DEFAULT_FRICTION_ERP)
{
m_data->m_dynamicsWorld->getSolverInfo().m_frictionERP = clientCmd.m_physSimParamArgs.m_frictionERP;
}
if (clientCmd.m_updateFlags & SIM_PARAM_UPDATE_DEFAULT_GLOBAL_CFM)
{
m_data->m_dynamicsWorld->getSolverInfo().m_globalCfm = clientCmd.m_physSimParamArgs.m_defaultGlobalCFM;
}
if (clientCmd.m_updateFlags & SIM_PARAM_UPDATE_DEFAULT_FRICTION_CFM)
{
m_data->m_dynamicsWorld->getSolverInfo().m_frictionCFM = clientCmd.m_physSimParamArgs.m_frictionCFM;
}
if (clientCmd.m_updateFlags & SIM_PARAM_UPDATE_SPARSE_SDF)
{
#ifndef SKIP_DEFORMABLE_BODY
{
btDeformableMultiBodyDynamicsWorld* deformWorld = getDeformableWorld();
if (deformWorld)
{
deformWorld->getWorldInfo().m_sparsesdf.setDefaultVoxelsz(clientCmd.m_physSimParamArgs.m_sparseSdfVoxelSize);
deformWorld->getWorldInfo().m_sparsesdf.Reset();
}
}
#endif
#ifndef SKIP_SOFT_BODY_MULTI_BODY_DYNAMICS_WORLD
{
btSoftMultiBodyDynamicsWorld* softWorld = getSoftWorld();
if (softWorld)
{
softWorld->getWorldInfo().m_sparsesdf.setDefaultVoxelsz(clientCmd.m_physSimParamArgs.m_sparseSdfVoxelSize);
softWorld->getWorldInfo().m_sparsesdf.Reset();
}
}
#endif
}
if (clientCmd.m_updateFlags & SIM_PARAM_UPDATE_RESTITUTION_VELOCITY_THRESHOLD)
{
m_data->m_dynamicsWorld->getSolverInfo().m_restitutionVelocityThreshold = clientCmd.m_physSimParamArgs.m_restitutionVelocityThreshold;
}
if (clientCmd.m_updateFlags & SIM_PARAM_ENABLE_FILE_CACHING)
{
b3EnableFileCaching(clientCmd.m_physSimParamArgs.m_enableFileCaching);
m_data->m_pluginManager.getFileIOInterface()->enableFileCaching(clientCmd.m_physSimParamArgs.m_enableFileCaching != 0);
}
if (clientCmd.m_updateFlags & SIM_PARAM_REPORT_CONSTRAINT_SOLVER_ANALYTICS)
{
m_data->m_dynamicsWorld->getSolverInfo().m_reportSolverAnalytics = clientCmd.m_physSimParamArgs.m_reportSolverAnalytics;
}
if (clientCmd.m_updateFlags & SIM_PARAM_UPDATE_WARM_STARTING_FACTOR)
{
m_data->m_dynamicsWorld->getSolverInfo().m_warmstartingFactor = clientCmd.m_physSimParamArgs.m_warmStartingFactor;
}
if (clientCmd.m_updateFlags & SIM_PARAM_UPDATE_ARTICULATED_WARM_STARTING_FACTOR)
{
m_data->m_dynamicsWorld->getSolverInfo().m_solverMode |= SOLVER_USE_ARTICULATED_WARMSTARTING;
m_data->m_dynamicsWorld->getSolverInfo().m_articulatedWarmstartingFactor = clientCmd.m_physSimParamArgs.m_articulatedWarmStartingFactor;
}
SharedMemoryStatus& serverCmd = serverStatusOut;
serverCmd.m_type = CMD_CLIENT_COMMAND_COMPLETED;
return hasStatus;
}
bool PhysicsServerCommandProcessor::processInitPoseCommand(const struct SharedMemoryCommand& clientCmd, struct SharedMemoryStatus& serverStatusOut, char* bufferServerToClient, int bufferSizeInBytes)
{
bool hasStatus = true;
BT_PROFILE("CMD_INIT_POSE");
if (m_data->m_verboseOutput)
{
b3Printf("Server Init Pose not implemented yet");
}
int bodyUniqueId = clientCmd.m_initPoseArgs.m_bodyUniqueId;
InternalBodyData* body = m_data->m_bodyHandles.getHandle(bodyUniqueId);
btVector3 baseLinVel(0, 0, 0);
btVector3 baseAngVel(0, 0, 0);
if (clientCmd.m_updateFlags & INIT_POSE_HAS_BASE_LINEAR_VELOCITY)
{
baseLinVel.setValue(clientCmd.m_initPoseArgs.m_initialStateQdot[0],
clientCmd.m_initPoseArgs.m_initialStateQdot[1],
clientCmd.m_initPoseArgs.m_initialStateQdot[2]);
}
if (clientCmd.m_updateFlags & INIT_POSE_HAS_BASE_ANGULAR_VELOCITY)
{
baseAngVel.setValue(clientCmd.m_initPoseArgs.m_initialStateQdot[3],
clientCmd.m_initPoseArgs.m_initialStateQdot[4],
clientCmd.m_initPoseArgs.m_initialStateQdot[5]);
}
btVector3 basePos(0, 0, 0);
if (clientCmd.m_updateFlags & INIT_POSE_HAS_INITIAL_POSITION)
{
basePos = btVector3(
clientCmd.m_initPoseArgs.m_initialStateQ[0],
clientCmd.m_initPoseArgs.m_initialStateQ[1],
clientCmd.m_initPoseArgs.m_initialStateQ[2]);
}
btQuaternion baseOrn(0, 0, 0, 1);
if (clientCmd.m_updateFlags & INIT_POSE_HAS_INITIAL_ORIENTATION)
{
baseOrn.setValue(clientCmd.m_initPoseArgs.m_initialStateQ[3],
clientCmd.m_initPoseArgs.m_initialStateQ[4],
clientCmd.m_initPoseArgs.m_initialStateQ[5],
clientCmd.m_initPoseArgs.m_initialStateQ[6]);
}
if (body && body->m_multiBody)
{
btMultiBody* mb = body->m_multiBody;
if (clientCmd.m_updateFlags & INIT_POSE_HAS_SCALING)
{
btVector3 scaling(clientCmd.m_initPoseArgs.m_scaling[0], clientCmd.m_initPoseArgs.m_scaling[1], clientCmd.m_initPoseArgs.m_scaling[2]);
mb->getBaseCollider()->getCollisionShape()->setLocalScaling(scaling);
//refresh broadphase
m_data->m_dynamicsWorld->getBroadphase()->getOverlappingPairCache()->cleanProxyFromPairs(
mb->getBaseCollider()->getBroadphaseHandle(),
m_data->m_dynamicsWorld->getDispatcher());
//also visuals
int graphicsIndex = mb->getBaseCollider()->getUserIndex();
m_data->m_guiHelper->changeScaling(graphicsIndex, clientCmd.m_initPoseArgs.m_scaling);
}
if (clientCmd.m_updateFlags & INIT_POSE_HAS_BASE_LINEAR_VELOCITY)
{
mb->setBaseVel(baseLinVel);
}
if (clientCmd.m_updateFlags & INIT_POSE_HAS_BASE_ANGULAR_VELOCITY)
{
mb->setBaseOmega(baseAngVel);
}
if (clientCmd.m_updateFlags & INIT_POSE_HAS_INITIAL_POSITION)
{
btVector3 zero(0, 0, 0);
btAssert(clientCmd.m_initPoseArgs.m_hasInitialStateQ[0] &&
clientCmd.m_initPoseArgs.m_hasInitialStateQ[1] &&
clientCmd.m_initPoseArgs.m_hasInitialStateQ[2]);
mb->setBaseVel(baseLinVel);
mb->setBasePos(basePos);
}
if (clientCmd.m_updateFlags & INIT_POSE_HAS_INITIAL_ORIENTATION)
{
btAssert(clientCmd.m_initPoseArgs.m_hasInitialStateQ[3] &&
clientCmd.m_initPoseArgs.m_hasInitialStateQ[4] &&
clientCmd.m_initPoseArgs.m_hasInitialStateQ[5] &&
clientCmd.m_initPoseArgs.m_hasInitialStateQ[6]);
mb->setBaseOmega(baseAngVel);
btQuaternion invOrn(baseOrn);
mb->setWorldToBaseRot(invOrn.inverse());
}
if (clientCmd.m_updateFlags & INIT_POSE_HAS_JOINT_STATE)
{
int uDofIndex = 6;
int posVarCountIndex = 7;
for (int i = 0; i < mb->getNumLinks(); i++)
{
int posVarCount = mb->getLink(i).m_posVarCount;
bool hasPosVar = posVarCount > 0;
for (int j = 0; j < posVarCount; j++)
{
if (clientCmd.m_initPoseArgs.m_hasInitialStateQ[posVarCountIndex + j] == 0)
{
hasPosVar = false;
break;
}
}
if (hasPosVar)
{
if (mb->getLink(i).m_dofCount == 1)
{
mb->setJointPos(i, clientCmd.m_initPoseArgs.m_initialStateQ[posVarCountIndex]);
mb->setJointVel(i, 0); //backwards compatibility
}
if (mb->getLink(i).m_dofCount == 3)
{
btQuaternion q(
clientCmd.m_initPoseArgs.m_initialStateQ[posVarCountIndex],
clientCmd.m_initPoseArgs.m_initialStateQ[posVarCountIndex + 1],
clientCmd.m_initPoseArgs.m_initialStateQ[posVarCountIndex + 2],
clientCmd.m_initPoseArgs.m_initialStateQ[posVarCountIndex + 3]);
q.normalize();
mb->setJointPosMultiDof(i, &q[0]);
double vel[6] = {0, 0, 0, 0, 0, 0};
mb->setJointVelMultiDof(i, vel);
}
}
bool hasVel = true;
for (int j = 0; j < mb->getLink(i).m_dofCount; j++)
{
if (clientCmd.m_initPoseArgs.m_hasInitialStateQdot[uDofIndex + j] == 0)
{
hasVel = false;
break;
}
}
if (hasVel)
{
if (mb->getLink(i).m_dofCount == 1)
{
btScalar vel = clientCmd.m_initPoseArgs.m_initialStateQdot[uDofIndex];
mb->setJointVel(i, vel);
}
if (mb->getLink(i).m_dofCount == 3)
{
mb->setJointVelMultiDof(i, &clientCmd.m_initPoseArgs.m_initialStateQdot[uDofIndex]);
}
}
posVarCountIndex += mb->getLink(i).m_posVarCount;
uDofIndex += mb->getLink(i).m_dofCount;
}
}
btAlignedObjectArray<btQuaternion> scratch_q;
btAlignedObjectArray<btVector3> scratch_m;
mb->forwardKinematics(scratch_q, scratch_m);
int nLinks = mb->getNumLinks();
scratch_q.resize(nLinks + 1);
scratch_m.resize(nLinks + 1);
mb->updateCollisionObjectWorldTransforms(scratch_q, scratch_m);
m_data->m_dynamicsWorld->updateSingleAabb(mb->getBaseCollider());
for (int i=0;i<mb->getNumLinks();i++)
{
m_data->m_dynamicsWorld->updateSingleAabb(mb->getLinkCollider(i));
}
}
if (body && body->m_rigidBody)
{
if (clientCmd.m_updateFlags & INIT_POSE_HAS_BASE_LINEAR_VELOCITY)
{
body->m_rigidBody->setLinearVelocity(baseLinVel);
}
if (clientCmd.m_updateFlags & INIT_POSE_HAS_BASE_ANGULAR_VELOCITY)
{
body->m_rigidBody->setAngularVelocity(baseAngVel);
}
if (clientCmd.m_updateFlags & INIT_POSE_HAS_INITIAL_POSITION)
{
body->m_rigidBody->getWorldTransform().setOrigin(basePos);
body->m_rigidBody->setLinearVelocity(baseLinVel);
}
if (clientCmd.m_updateFlags & INIT_POSE_HAS_INITIAL_ORIENTATION)
{
body->m_rigidBody->getWorldTransform().setRotation(baseOrn);
body->m_rigidBody->setAngularVelocity(baseAngVel);
}
m_data->m_dynamicsWorld->updateSingleAabb(body->m_rigidBody);
}
#ifndef SKIP_SOFT_BODY_MULTI_BODY_DYNAMICS_WORLD
if (body && body->m_softBody)
{
if (clientCmd.m_updateFlags & INIT_POSE_HAS_BASE_LINEAR_VELOCITY)
{
body->m_softBody->setLinearVelocity(baseLinVel);
}
if (clientCmd.m_updateFlags & INIT_POSE_HAS_BASE_ANGULAR_VELOCITY)
{
body->m_softBody->setAngularVelocity(baseAngVel);
}
if (clientCmd.m_updateFlags & INIT_POSE_HAS_INITIAL_POSITION || clientCmd.m_updateFlags & INIT_POSE_HAS_INITIAL_ORIENTATION)
{
btTransform tr;
tr.setIdentity();
if (clientCmd.m_updateFlags & INIT_POSE_HAS_INITIAL_POSITION)
{
tr.setOrigin(basePos);
}
if (clientCmd.m_updateFlags & INIT_POSE_HAS_INITIAL_ORIENTATION)
{
tr.setRotation(baseOrn);
}
body->m_softBody->transformTo(tr);
}
m_data->m_dynamicsWorld->updateSingleAabb(body->m_softBody);
}
#endif
syncPhysicsToGraphics2();
SharedMemoryStatus& serverCmd = serverStatusOut;
serverCmd.m_type = CMD_CLIENT_COMMAND_COMPLETED;
return hasStatus;
}
bool PhysicsServerCommandProcessor::processResetSimulationCommand(const struct SharedMemoryCommand& clientCmd, struct SharedMemoryStatus& serverStatusOut, char* bufferServerToClient, int bufferSizeInBytes)
{
bool hasStatus = true;
BT_PROFILE("CMD_RESET_SIMULATION");
m_data->m_guiHelper->setVisualizerFlag(COV_ENABLE_SYNC_RENDERING_INTERNAL, 0);
resetSimulation(clientCmd.m_updateFlags);
m_data->m_guiHelper->setVisualizerFlag(COV_ENABLE_SYNC_RENDERING_INTERNAL, 1);
SharedMemoryStatus& serverCmd = serverStatusOut;
serverCmd.m_type = CMD_RESET_SIMULATION_COMPLETED;
return hasStatus;
}
bool PhysicsServerCommandProcessor::processCreateRigidBodyCommand(const struct SharedMemoryCommand& clientCmd, struct SharedMemoryStatus& serverStatusOut, char* bufferServerToClient, int bufferSizeInBytes)
{
bool hasStatus = true;
SharedMemoryStatus& serverCmd = serverStatusOut;
serverCmd.m_type = CMD_RIGID_BODY_CREATION_COMPLETED;
BT_PROFILE("CMD_CREATE_RIGID_BODY");
btVector3 halfExtents(1, 1, 1);
if (clientCmd.m_updateFlags & BOX_SHAPE_HAS_HALF_EXTENTS)
{
halfExtents = btVector3(
clientCmd.m_createBoxShapeArguments.m_halfExtentsX,
clientCmd.m_createBoxShapeArguments.m_halfExtentsY,
clientCmd.m_createBoxShapeArguments.m_halfExtentsZ);
}
btTransform startTrans;
startTrans.setIdentity();
if (clientCmd.m_updateFlags & BOX_SHAPE_HAS_INITIAL_POSITION)
{
startTrans.setOrigin(btVector3(
clientCmd.m_createBoxShapeArguments.m_initialPosition[0],
clientCmd.m_createBoxShapeArguments.m_initialPosition[1],
clientCmd.m_createBoxShapeArguments.m_initialPosition[2]));
}
if (clientCmd.m_updateFlags & BOX_SHAPE_HAS_INITIAL_ORIENTATION)
{
startTrans.setRotation(btQuaternion(
clientCmd.m_createBoxShapeArguments.m_initialOrientation[0],
clientCmd.m_createBoxShapeArguments.m_initialOrientation[1],
clientCmd.m_createBoxShapeArguments.m_initialOrientation[2],
clientCmd.m_createBoxShapeArguments.m_initialOrientation[3]));
}
btScalar mass = 0.f;
if (clientCmd.m_updateFlags & BOX_SHAPE_HAS_MASS)
{
mass = clientCmd.m_createBoxShapeArguments.m_mass;
}
int shapeType = COLLISION_SHAPE_TYPE_BOX;
if (clientCmd.m_updateFlags & BOX_SHAPE_HAS_COLLISION_SHAPE_TYPE)
{
shapeType = clientCmd.m_createBoxShapeArguments.m_collisionShapeType;
}
#ifdef USE_DISCRETE_DYNAMICS_WORLD
btWorldImporter* worldImporter = new btWorldImporter(m_data->m_dynamicsWorld);
#else
btMultiBodyWorldImporter* worldImporter = new btMultiBodyWorldImporter(m_data->m_dynamicsWorld);
#endif
m_data->m_worldImporters.push_back(worldImporter);
btCollisionShape* shape = 0;
switch (shapeType)
{
case COLLISION_SHAPE_TYPE_CYLINDER_X:
{
btScalar radius = halfExtents[1];
btScalar height = halfExtents[0];
shape = worldImporter->createCylinderShapeX(radius, height);
break;
}
case COLLISION_SHAPE_TYPE_CYLINDER_Y:
{
btScalar radius = halfExtents[0];
btScalar height = halfExtents[1];
shape = worldImporter->createCylinderShapeY(radius, height);
break;
}
case COLLISION_SHAPE_TYPE_CYLINDER_Z:
{
btScalar radius = halfExtents[1];
btScalar height = halfExtents[2];
shape = worldImporter->createCylinderShapeZ(radius, height);
break;
}
case COLLISION_SHAPE_TYPE_CAPSULE_X:
{
btScalar radius = halfExtents[1];
btScalar height = halfExtents[0];
shape = worldImporter->createCapsuleShapeX(radius, height);
break;
}
case COLLISION_SHAPE_TYPE_CAPSULE_Y:
{
btScalar radius = halfExtents[0];
btScalar height = halfExtents[1];
shape = worldImporter->createCapsuleShapeY(radius, height);
break;
}
case COLLISION_SHAPE_TYPE_CAPSULE_Z:
{
btScalar radius = halfExtents[1];
btScalar height = halfExtents[2];
shape = worldImporter->createCapsuleShapeZ(radius, height);
break;
}
case COLLISION_SHAPE_TYPE_SPHERE:
{
btScalar radius = halfExtents[0];
shape = worldImporter->createSphereShape(radius);
break;
}
case COLLISION_SHAPE_TYPE_BOX:
default:
{
shape = worldImporter->createBoxShape(halfExtents);
}
}
bool isDynamic = (mass > 0);
btRigidBody* rb = worldImporter->createRigidBody(isDynamic, mass, startTrans, shape, 0);
//m_data->m_guiHelper->autogenerateGraphicsObjects(this->m_data->m_dynamicsWorld);
btVector4 colorRGBA(1, 0, 0, 1);
if (clientCmd.m_updateFlags & BOX_SHAPE_HAS_COLOR)
{
colorRGBA[0] = clientCmd.m_createBoxShapeArguments.m_colorRGBA[0];
colorRGBA[1] = clientCmd.m_createBoxShapeArguments.m_colorRGBA[1];
colorRGBA[2] = clientCmd.m_createBoxShapeArguments.m_colorRGBA[2];
colorRGBA[3] = clientCmd.m_createBoxShapeArguments.m_colorRGBA[3];
}
m_data->m_guiHelper->createCollisionShapeGraphicsObject(rb->getCollisionShape());
m_data->m_guiHelper->createCollisionObjectGraphicsObject(rb, colorRGBA);
int bodyUniqueId = m_data->m_bodyHandles.allocHandle();
InternalBodyHandle* bodyHandle = m_data->m_bodyHandles.getHandle(bodyUniqueId);
serverCmd.m_rigidBodyCreateArgs.m_bodyUniqueId = bodyUniqueId;
rb->setUserIndex2(bodyUniqueId);
bodyHandle->m_rootLocalInertialFrame.setIdentity();
bodyHandle->m_rigidBody = rb;
b3Notification notification;
notification.m_notificationType = BODY_ADDED;
notification.m_bodyArgs.m_bodyUniqueId = bodyUniqueId;
m_data->m_pluginManager.addNotification(notification);
return hasStatus;
}
bool PhysicsServerCommandProcessor::processPickBodyCommand(const struct SharedMemoryCommand& clientCmd, struct SharedMemoryStatus& serverStatusOut, char* bufferServerToClient, int bufferSizeInBytes)
{
bool hasStatus = true;
BT_PROFILE("CMD_PICK_BODY");
pickBody(btVector3(clientCmd.m_pickBodyArguments.m_rayFromWorld[0],
clientCmd.m_pickBodyArguments.m_rayFromWorld[1],
clientCmd.m_pickBodyArguments.m_rayFromWorld[2]),
btVector3(clientCmd.m_pickBodyArguments.m_rayToWorld[0],
clientCmd.m_pickBodyArguments.m_rayToWorld[1],
clientCmd.m_pickBodyArguments.m_rayToWorld[2]));
SharedMemoryStatus& serverCmd = serverStatusOut;
serverCmd.m_type = CMD_CLIENT_COMMAND_COMPLETED;
return hasStatus;
}
bool PhysicsServerCommandProcessor::processMovePickedBodyCommand(const struct SharedMemoryCommand& clientCmd, struct SharedMemoryStatus& serverStatusOut, char* bufferServerToClient, int bufferSizeInBytes)
{
bool hasStatus = true;
BT_PROFILE("CMD_MOVE_PICKED_BODY");
movePickedBody(btVector3(clientCmd.m_pickBodyArguments.m_rayFromWorld[0],
clientCmd.m_pickBodyArguments.m_rayFromWorld[1],
clientCmd.m_pickBodyArguments.m_rayFromWorld[2]),
btVector3(clientCmd.m_pickBodyArguments.m_rayToWorld[0],
clientCmd.m_pickBodyArguments.m_rayToWorld[1],
clientCmd.m_pickBodyArguments.m_rayToWorld[2]));
SharedMemoryStatus& serverCmd = serverStatusOut;
serverCmd.m_type = CMD_CLIENT_COMMAND_COMPLETED;
return hasStatus;
}
bool PhysicsServerCommandProcessor::processRemovePickingConstraintCommand(const struct SharedMemoryCommand& clientCmd, struct SharedMemoryStatus& serverStatusOut, char* bufferServerToClient, int bufferSizeInBytes)
{
bool hasStatus = true;
BT_PROFILE("CMD_REMOVE_PICKING_CONSTRAINT_BODY");
removePickingConstraint();
SharedMemoryStatus& serverCmd = serverStatusOut;
serverCmd.m_type = CMD_CLIENT_COMMAND_COMPLETED;
return hasStatus;
}
bool PhysicsServerCommandProcessor::processRequestAabbOverlapCommand(const struct SharedMemoryCommand& clientCmd, struct SharedMemoryStatus& serverStatusOut, char* bufferServerToClient, int bufferSizeInBytes)
{
bool hasStatus = true;
BT_PROFILE("CMD_REQUEST_AABB_OVERLAP");
SharedMemoryStatus& serverCmd = serverStatusOut;
int curObjectIndex = clientCmd.m_requestOverlappingObjectsArgs.m_startingOverlappingObjectIndex;
if (0 == curObjectIndex)
{
//clientCmd.m_requestContactPointArguments.m_aabbQueryMin
btVector3 aabbMin, aabbMax;
aabbMin.setValue(clientCmd.m_requestOverlappingObjectsArgs.m_aabbQueryMin[0],
clientCmd.m_requestOverlappingObjectsArgs.m_aabbQueryMin[1],
clientCmd.m_requestOverlappingObjectsArgs.m_aabbQueryMin[2]);
aabbMax.setValue(clientCmd.m_requestOverlappingObjectsArgs.m_aabbQueryMax[0],
clientCmd.m_requestOverlappingObjectsArgs.m_aabbQueryMax[1],
clientCmd.m_requestOverlappingObjectsArgs.m_aabbQueryMax[2]);
m_data->m_cachedOverlappingObjects.clear();
m_data->m_dynamicsWorld->getBroadphase()->aabbTest(aabbMin, aabbMax, m_data->m_cachedOverlappingObjects);
}
int totalBytesPerObject = sizeof(b3OverlappingObject);
int overlapCapacity = bufferSizeInBytes / totalBytesPerObject - 1;
int numOverlap = m_data->m_cachedOverlappingObjects.m_bodyUniqueIds.size();
int remainingObjects = numOverlap - curObjectIndex;
int curNumObjects = btMin(overlapCapacity, remainingObjects);
if (numOverlap < overlapCapacity)
{
b3OverlappingObject* overlapStorage = (b3OverlappingObject*)bufferServerToClient;
for (int i = 0; i < m_data->m_cachedOverlappingObjects.m_bodyUniqueIds.size(); i++)
{
overlapStorage[i].m_objectUniqueId = m_data->m_cachedOverlappingObjects.m_bodyUniqueIds[i];
overlapStorage[i].m_linkIndex = m_data->m_cachedOverlappingObjects.m_links[i];
}
serverCmd.m_numDataStreamBytes = numOverlap * totalBytesPerObject;
serverCmd.m_type = CMD_REQUEST_AABB_OVERLAP_COMPLETED;
//int m_startingOverlappingObjectIndex;
//int m_numOverlappingObjectsCopied;
//int m_numRemainingOverlappingObjects;
serverCmd.m_sendOverlappingObjectsArgs.m_startingOverlappingObjectIndex = clientCmd.m_requestOverlappingObjectsArgs.m_startingOverlappingObjectIndex;
serverCmd.m_sendOverlappingObjectsArgs.m_numOverlappingObjectsCopied = m_data->m_cachedOverlappingObjects.m_bodyUniqueIds.size();
serverCmd.m_sendOverlappingObjectsArgs.m_numRemainingOverlappingObjects = remainingObjects - curNumObjects;
}
else
{
serverCmd.m_type = CMD_REQUEST_AABB_OVERLAP_FAILED;
}
return hasStatus;
}
bool PhysicsServerCommandProcessor::processRequestOpenGLVisualizeCameraCommand(const struct SharedMemoryCommand& clientCmd, struct SharedMemoryStatus& serverStatusOut, char* bufferServerToClient, int bufferSizeInBytes)
{
bool hasStatus = true;
BT_PROFILE("CMD_REQUEST_OPENGL_VISUALIZER_CAMERA");
SharedMemoryStatus& serverCmd = serverStatusOut;
bool result = this->m_data->m_guiHelper->getCameraInfo(
&serverCmd.m_visualizerCameraResultArgs.m_width,
&serverCmd.m_visualizerCameraResultArgs.m_height,
serverCmd.m_visualizerCameraResultArgs.m_viewMatrix,
serverCmd.m_visualizerCameraResultArgs.m_projectionMatrix,
serverCmd.m_visualizerCameraResultArgs.m_camUp,
serverCmd.m_visualizerCameraResultArgs.m_camForward,
serverCmd.m_visualizerCameraResultArgs.m_horizontal,
serverCmd.m_visualizerCameraResultArgs.m_vertical,
&serverCmd.m_visualizerCameraResultArgs.m_yaw,
&serverCmd.m_visualizerCameraResultArgs.m_pitch,
&serverCmd.m_visualizerCameraResultArgs.m_dist,
serverCmd.m_visualizerCameraResultArgs.m_target);
serverCmd.m_type = result ? CMD_REQUEST_OPENGL_VISUALIZER_CAMERA_COMPLETED : CMD_REQUEST_OPENGL_VISUALIZER_CAMERA_FAILED;
return hasStatus;
}
bool PhysicsServerCommandProcessor::processConfigureOpenGLVisualizerCommand(const struct SharedMemoryCommand& clientCmd, struct SharedMemoryStatus& serverStatusOut, char* bufferServerToClient, int bufferSizeInBytes)
{
bool hasStatus = true;
BT_PROFILE("CMD_CONFIGURE_OPENGL_VISUALIZER");
SharedMemoryStatus& serverCmd = serverStatusOut;
serverCmd.m_type = CMD_CLIENT_COMMAND_COMPLETED;
hasStatus = true;
if (clientCmd.m_updateFlags & COV_SET_FLAGS)
{
if (clientCmd.m_configureOpenGLVisualizerArguments.m_setFlag == COV_ENABLE_TINY_RENDERER)
{
m_data->m_enableTinyRenderer = clientCmd.m_configureOpenGLVisualizerArguments.m_setEnabled != 0;
}
m_data->m_guiHelper->setVisualizerFlag(clientCmd.m_configureOpenGLVisualizerArguments.m_setFlag,
clientCmd.m_configureOpenGLVisualizerArguments.m_setEnabled);
}
if (clientCmd.m_updateFlags & COV_SET_CAMERA_VIEW_MATRIX)
{
m_data->m_guiHelper->resetCamera(clientCmd.m_configureOpenGLVisualizerArguments.m_cameraDistance,
clientCmd.m_configureOpenGLVisualizerArguments.m_cameraYaw,
clientCmd.m_configureOpenGLVisualizerArguments.m_cameraPitch,
clientCmd.m_configureOpenGLVisualizerArguments.m_cameraTargetPosition[0],
clientCmd.m_configureOpenGLVisualizerArguments.m_cameraTargetPosition[1],
clientCmd.m_configureOpenGLVisualizerArguments.m_cameraTargetPosition[2]);
}
if (m_data->m_guiHelper->getRenderInterface())
{
if (clientCmd.m_updateFlags & COV_SET_LIGHT_POSITION)
{
m_data->m_guiHelper->getRenderInterface()->setLightPosition(clientCmd.m_configureOpenGLVisualizerArguments.m_lightPosition);
}
if (clientCmd.m_updateFlags & COV_SET_RGB_BACKGROUND)
{
m_data->m_guiHelper->setBackgroundColor(clientCmd.m_configureOpenGLVisualizerArguments.m_rgbBackground);
}
if (clientCmd.m_updateFlags & COV_SET_SHADOWMAP_RESOLUTION)
{
m_data->m_guiHelper->getRenderInterface()->setShadowMapResolution(clientCmd.m_configureOpenGLVisualizerArguments.m_shadowMapResolution);
}
if (clientCmd.m_updateFlags & COV_SET_SHADOWMAP_INTENSITY)
{
m_data->m_guiHelper->getRenderInterface()->setShadowMapIntensity(clientCmd.m_configureOpenGLVisualizerArguments.m_shadowMapIntensity);
}
if (clientCmd.m_updateFlags & COV_SET_SHADOWMAP_WORLD_SIZE)
{
float worldSize = clientCmd.m_configureOpenGLVisualizerArguments.m_shadowMapWorldSize;
m_data->m_guiHelper->getRenderInterface()->setShadowMapWorldSize(worldSize);
}
}
if (clientCmd.m_updateFlags & COV_SET_REMOTE_SYNC_TRANSFORM_INTERVAL)
{
m_data->m_remoteSyncTransformInterval = clientCmd.m_configureOpenGLVisualizerArguments.m_remoteSyncTransformInterval;
}
return hasStatus;
}
bool PhysicsServerCommandProcessor::processInverseDynamicsCommand(const struct SharedMemoryCommand& clientCmd, struct SharedMemoryStatus& serverStatusOut, char* bufferServerToClient, int bufferSizeInBytes)
{
bool hasStatus = true;
BT_PROFILE("CMD_CALCULATE_INVERSE_DYNAMICS");
SharedMemoryStatus& serverCmd = serverStatusOut;
InternalBodyHandle* bodyHandle = m_data->m_bodyHandles.getHandle(clientCmd.m_calculateInverseDynamicsArguments.m_bodyUniqueId);
serverCmd.m_type = CMD_CALCULATED_INVERSE_DYNAMICS_FAILED;
if (bodyHandle && bodyHandle->m_multiBody)
{
if (clientCmd.m_calculateInverseDynamicsArguments.m_flags & 1)
{
#ifdef STATIC_LINK_SPD_PLUGIN
{
cRBDModel* rbdModel = m_data->findOrCreateRBDModel(bodyHandle->m_multiBody,
clientCmd.m_calculateInverseDynamicsArguments.m_jointPositionsQ,
clientCmd.m_calculateInverseDynamicsArguments.m_jointVelocitiesQdot);
if (rbdModel)
{
int posVal = bodyHandle->m_multiBody->getNumPosVars();
Eigen::VectorXd acc2 = Eigen::VectorXd::Zero(7 + posVal);
Eigen::VectorXd out_tau = Eigen::VectorXd::Zero(7 + posVal);
cRBDUtil::SolveInvDyna(*rbdModel, acc2, out_tau);
int dof = 7 + bodyHandle->m_multiBody->getNumPosVars();
for (int i = 0; i < dof; i++)
{
serverCmd.m_inverseDynamicsResultArgs.m_jointForces[i] = out_tau[i];
}
serverCmd.m_inverseDynamicsResultArgs.m_bodyUniqueId = clientCmd.m_calculateInverseDynamicsArguments.m_bodyUniqueId;
serverCmd.m_inverseDynamicsResultArgs.m_dofCount = dof;
serverCmd.m_type = CMD_CALCULATED_INVERSE_DYNAMICS_COMPLETED;
}
}
#endif
}
else
{
btInverseDynamics::MultiBodyTree* tree = m_data->findOrCreateTree(bodyHandle->m_multiBody);
int baseDofQ = bodyHandle->m_multiBody->hasFixedBase() ? 0 : 7;
int baseDofQdot = bodyHandle->m_multiBody->hasFixedBase() ? 0 : 6;
const int num_dofs = bodyHandle->m_multiBody->getNumDofs();
if (tree && clientCmd.m_calculateInverseDynamicsArguments.m_dofCountQ == (baseDofQ + num_dofs) &&
clientCmd.m_calculateInverseDynamicsArguments.m_dofCountQdot == (baseDofQdot + num_dofs))
{
btInverseDynamics::vecx nu(num_dofs + baseDofQdot), qdot(num_dofs + baseDofQdot), q(num_dofs + baseDofQdot), joint_force(num_dofs + baseDofQdot);
//for floating base, inverse dynamics expects euler angle x,y,z and position x,y,z in that order
//PyBullet expects quaternion, so convert and swap to have a more consistent PyBullet API
if (baseDofQ)
{
btVector3 pos(clientCmd.m_calculateInverseDynamicsArguments.m_jointPositionsQ[0],
clientCmd.m_calculateInverseDynamicsArguments.m_jointPositionsQ[1],
clientCmd.m_calculateInverseDynamicsArguments.m_jointPositionsQ[2]);
btQuaternion orn(clientCmd.m_calculateInverseDynamicsArguments.m_jointPositionsQ[0],
clientCmd.m_calculateInverseDynamicsArguments.m_jointPositionsQ[1],
clientCmd.m_calculateInverseDynamicsArguments.m_jointPositionsQ[2],
clientCmd.m_calculateInverseDynamicsArguments.m_jointPositionsQ[3]);
btScalar yawZ, pitchY, rollX;
orn.getEulerZYX(yawZ, pitchY, rollX);
q[0] = rollX;
q[1] = pitchY;
q[2] = yawZ;
q[3] = pos[0];
q[4] = pos[1];
q[5] = pos[2];
}
else
{
for (int i = 0; i < num_dofs; i++)
{
q[i] = clientCmd.m_calculateInverseDynamicsArguments.m_jointPositionsQ[i];
}
}
for (int i = 0; i < num_dofs + baseDofQdot; i++)
{
qdot[i] = clientCmd.m_calculateInverseDynamicsArguments.m_jointVelocitiesQdot[i];
nu[i] = clientCmd.m_calculateInverseDynamicsArguments.m_jointAccelerations[i];
}
// Set the gravity to correspond to the world gravity
btInverseDynamics::vec3 id_grav(m_data->m_dynamicsWorld->getGravity());
if (-1 != tree->setGravityInWorldFrame(id_grav) &&
-1 != tree->calculateInverseDynamics(q, qdot, nu, &joint_force))
{
serverCmd.m_inverseDynamicsResultArgs.m_bodyUniqueId = clientCmd.m_calculateInverseDynamicsArguments.m_bodyUniqueId;
serverCmd.m_inverseDynamicsResultArgs.m_dofCount = num_dofs + baseDofQdot;
//inverse dynamics stores angular before linear, swap it to have a consistent PyBullet API.
if (baseDofQdot)
{
serverCmd.m_inverseDynamicsResultArgs.m_jointForces[0] = joint_force[3];
serverCmd.m_inverseDynamicsResultArgs.m_jointForces[1] = joint_force[4];
serverCmd.m_inverseDynamicsResultArgs.m_jointForces[2] = joint_force[5];
serverCmd.m_inverseDynamicsResultArgs.m_jointForces[3] = joint_force[0];
serverCmd.m_inverseDynamicsResultArgs.m_jointForces[4] = joint_force[1];
serverCmd.m_inverseDynamicsResultArgs.m_jointForces[5] = joint_force[2];
}
for (int i = baseDofQdot; i < num_dofs + baseDofQdot; i++)
{
serverCmd.m_inverseDynamicsResultArgs.m_jointForces[i] = joint_force[i];
}
serverCmd.m_type = CMD_CALCULATED_INVERSE_DYNAMICS_COMPLETED;
}
else
{
serverCmd.m_type = CMD_CALCULATED_INVERSE_DYNAMICS_FAILED;
}
}
}
}
else
{
serverCmd.m_type = CMD_CALCULATED_INVERSE_DYNAMICS_FAILED;
}
return hasStatus;
}
bool PhysicsServerCommandProcessor::processCalculateJacobianCommand(const struct SharedMemoryCommand& clientCmd, struct SharedMemoryStatus& serverStatusOut, char* bufferServerToClient, int bufferSizeInBytes)
{
bool hasStatus = true;
BT_PROFILE("CMD_CALCULATE_JACOBIAN");
SharedMemoryStatus& serverCmd = serverStatusOut;
InternalBodyHandle* bodyHandle = m_data->m_bodyHandles.getHandle(clientCmd.m_calculateJacobianArguments.m_bodyUniqueId);
if (bodyHandle && bodyHandle->m_multiBody)
{
serverCmd.m_type = CMD_CALCULATED_JACOBIAN_FAILED;
btInverseDynamics::MultiBodyTree* tree = m_data->findOrCreateTree(bodyHandle->m_multiBody);
if (tree)
{
int baseDofs = bodyHandle->m_multiBody->hasFixedBase() ? 0 : 6;
const int numDofs = bodyHandle->m_multiBody->getNumDofs();
btInverseDynamics::vecx q(numDofs + baseDofs);
btInverseDynamics::vecx qdot(numDofs + baseDofs);
btInverseDynamics::vecx nu(numDofs + baseDofs);
btInverseDynamics::vecx joint_force(numDofs + baseDofs);
for (int i = 0; i < numDofs; i++)
{
q[i + baseDofs] = clientCmd.m_calculateJacobianArguments.m_jointPositionsQ[i];
qdot[i + baseDofs] = clientCmd.m_calculateJacobianArguments.m_jointVelocitiesQdot[i];
nu[i + baseDofs] = clientCmd.m_calculateJacobianArguments.m_jointAccelerations[i];
}
// Set the gravity to correspond to the world gravity
btInverseDynamics::vec3 id_grav(m_data->m_dynamicsWorld->getGravity());
if (-1 != tree->setGravityInWorldFrame(id_grav) &&
-1 != tree->calculateInverseDynamics(q, qdot, nu, &joint_force))
{
serverCmd.m_jacobianResultArgs.m_dofCount = numDofs + baseDofs;
// Set jacobian value
tree->calculateJacobians(q);
btInverseDynamics::mat3x jac_t(3, numDofs + baseDofs);
btInverseDynamics::mat3x jac_r(3, numDofs + baseDofs);
// Note that inverse dynamics uses zero-based indexing of bodies, not starting from -1 for the base link.
tree->getBodyJacobianTrans(clientCmd.m_calculateJacobianArguments.m_linkIndex + 1, &jac_t);
tree->getBodyJacobianRot(clientCmd.m_calculateJacobianArguments.m_linkIndex + 1, &jac_r);
// Update the translational jacobian based on the desired local point.
// v_pt = v_frame + w x pt
// v_pt = J_t * qd + (J_r * qd) x pt
// v_pt = J_t * qd - pt x (J_r * qd)
// v_pt = J_t * qd - pt_x * J_r * qd)
// v_pt = (J_t - pt_x * J_r) * qd
// J_t_new = J_t - pt_x * J_r
btInverseDynamics::vec3 localPosition;
for (int i = 0; i < 3; ++i)
{
localPosition(i) = clientCmd.m_calculateJacobianArguments.m_localPosition[i];
}
// Only calculate if the localPosition is non-zero.
if (btInverseDynamics::maxAbs(localPosition) > 0.0)
{
// Write the localPosition into world coordinates.
btInverseDynamics::mat33 world_rotation_body;
tree->getBodyTransform(clientCmd.m_calculateJacobianArguments.m_linkIndex + 1, &world_rotation_body);
localPosition = world_rotation_body * localPosition;
// Correct the translational jacobian.
btInverseDynamics::mat33 skewCrossProduct;
btInverseDynamics::skew(localPosition, &skewCrossProduct);
btInverseDynamics::mat3x jac_l(3, numDofs + baseDofs);
btInverseDynamics::mul(skewCrossProduct, jac_r, &jac_l);
btInverseDynamics::mat3x jac_t_new(3, numDofs + baseDofs);
btInverseDynamics::sub(jac_t, jac_l, &jac_t_new);
jac_t = jac_t_new;
}
// Fill in the result into the shared memory.
for (int i = 0; i < 3; ++i)
{
for (int j = 0; j < (numDofs + baseDofs); ++j)
{
int element = (numDofs + baseDofs) * i + j;
serverCmd.m_jacobianResultArgs.m_linearJacobian[element] = jac_t(i, j);
serverCmd.m_jacobianResultArgs.m_angularJacobian[element] = jac_r(i, j);
}
}
serverCmd.m_type = CMD_CALCULATED_JACOBIAN_COMPLETED;
}
else
{
serverCmd.m_type = CMD_CALCULATED_JACOBIAN_FAILED;
}
}
}
else
{
serverCmd.m_type = CMD_CALCULATED_JACOBIAN_FAILED;
}
return hasStatus;
}
bool PhysicsServerCommandProcessor::processCalculateMassMatrixCommand(const struct SharedMemoryCommand& clientCmd, struct SharedMemoryStatus& serverStatusOut, char* bufferServerToClient, int bufferSizeInBytes)
{
bool hasStatus = true;
BT_PROFILE("CMD_CALCULATE_MASS_MATRIX");
SharedMemoryStatus& serverCmd = serverStatusOut;
serverCmd.m_type = CMD_CALCULATED_MASS_MATRIX_FAILED;
InternalBodyHandle* bodyHandle = m_data->m_bodyHandles.getHandle(clientCmd.m_calculateMassMatrixArguments.m_bodyUniqueId);
if (bodyHandle && bodyHandle->m_multiBody)
{
if (clientCmd.m_calculateMassMatrixArguments.m_flags & 1)
{
#ifdef STATIC_LINK_SPD_PLUGIN
{
int posVal = bodyHandle->m_multiBody->getNumPosVars();
btAlignedObjectArray<double> zeroVel;
int dof = 7 + posVal;
zeroVel.resize(dof);
cRBDModel* rbdModel = m_data->findOrCreateRBDModel(bodyHandle->m_multiBody, clientCmd.m_calculateMassMatrixArguments.m_jointPositionsQ,
&zeroVel[0]);
if (rbdModel)
{
//Eigen::MatrixXd out_mass;
//cRBDUtil::BuildMassMat(*rbdModel, out_mass);
const Eigen::MatrixXd& out_mass = rbdModel->GetMassMat();
int skipDofs = 0; // 7 - baseDofQ;
int totDofs = dof;
serverCmd.m_massMatrixResultArgs.m_dofCount = totDofs - skipDofs;
// Fill in the result into the shared memory.
double* sharedBuf = (double*)bufferServerToClient;
int sizeInBytes = totDofs * totDofs * sizeof(double);
if (sizeInBytes < bufferSizeInBytes)
{
for (int i = skipDofs; i < (totDofs); ++i)
{
for (int j = skipDofs; j < (totDofs); ++j)
{
int element = (totDofs - skipDofs) * (i - skipDofs) + (j - skipDofs);
double v = out_mass(i, j);
if (i == j && v == 0)
{
v = 1;
}
sharedBuf[element] = v;
}
}
serverCmd.m_type = CMD_CALCULATED_MASS_MATRIX_COMPLETED;
}
}
}
#endif
}
else
{
btInverseDynamics::MultiBodyTree* tree = m_data->findOrCreateTree(bodyHandle->m_multiBody);
if (tree)
{
int baseDofs = bodyHandle->m_multiBody->hasFixedBase() ? 0 : 6;
const int numDofs = bodyHandle->m_multiBody->getNumDofs();
const int totDofs = numDofs + baseDofs;
btInverseDynamics::vecx q(totDofs);
btInverseDynamics::matxx massMatrix(totDofs, totDofs);
for (int i = 0; i < numDofs; i++)
{
q[i + baseDofs] = clientCmd.m_calculateMassMatrixArguments.m_jointPositionsQ[i];
}
if (-1 != tree->calculateMassMatrix(q, &massMatrix))
{
serverCmd.m_massMatrixResultArgs.m_dofCount = totDofs;
// Fill in the result into the shared memory.
double* sharedBuf = (double*)bufferServerToClient;
int sizeInBytes = totDofs * totDofs * sizeof(double);
if (sizeInBytes < bufferSizeInBytes)
{
for (int i = 0; i < (totDofs); ++i)
{
for (int j = 0; j < (totDofs); ++j)
{
int element = (totDofs)*i + j;
sharedBuf[element] = massMatrix(i, j);
}
}
serverCmd.m_numDataStreamBytes = sizeInBytes;
serverCmd.m_type = CMD_CALCULATED_MASS_MATRIX_COMPLETED;
}
}
}
}
}
else
{
serverCmd.m_type = CMD_CALCULATED_MASS_MATRIX_FAILED;
}
return hasStatus;
}
bool PhysicsServerCommandProcessor::processApplyExternalForceCommand(const struct SharedMemoryCommand& clientCmd, struct SharedMemoryStatus& serverStatusOut, char* bufferServerToClient, int bufferSizeInBytes)
{
bool hasStatus = true;
BT_PROFILE("CMD_APPLY_EXTERNAL_FORCE");
if (m_data->m_verboseOutput)
{
b3Printf("CMD_APPLY_EXTERNAL_FORCE clientCmd = %d\n", clientCmd.m_sequenceNumber);
}
for (int i = 0; i < clientCmd.m_externalForceArguments.m_numForcesAndTorques; ++i)
{
InternalBodyData* body = m_data->m_bodyHandles.getHandle(clientCmd.m_externalForceArguments.m_bodyUniqueIds[i]);
bool isLinkFrame = ((clientCmd.m_externalForceArguments.m_forceFlags[i] & EF_LINK_FRAME) != 0);
if (body && body->m_multiBody)
{
btMultiBody* mb = body->m_multiBody;
if ((clientCmd.m_externalForceArguments.m_forceFlags[i] & EF_FORCE) != 0)
{
btVector3 tmpForce(clientCmd.m_externalForceArguments.m_forcesAndTorques[i * 3 + 0],
clientCmd.m_externalForceArguments.m_forcesAndTorques[i * 3 + 1],
clientCmd.m_externalForceArguments.m_forcesAndTorques[i * 3 + 2]);
btVector3 tmpPosition(
clientCmd.m_externalForceArguments.m_positions[i * 3 + 0],
clientCmd.m_externalForceArguments.m_positions[i * 3 + 1],
clientCmd.m_externalForceArguments.m_positions[i * 3 + 2]);
if (clientCmd.m_externalForceArguments.m_linkIds[i] == -1)
{
btVector3 forceWorld = isLinkFrame ? mb->getBaseWorldTransform().getBasis() * tmpForce : tmpForce;
btVector3 relPosWorld = isLinkFrame ? mb->getBaseWorldTransform().getBasis() * tmpPosition : tmpPosition - mb->getBaseWorldTransform().getOrigin();
mb->addBaseForce(forceWorld);
mb->addBaseTorque(relPosWorld.cross(forceWorld));
//b3Printf("apply base force of %f,%f,%f at %f,%f,%f\n", forceWorld[0],forceWorld[1],forceWorld[2],positionLocal[0],positionLocal[1],positionLocal[2]);
}
else
{
int link = clientCmd.m_externalForceArguments.m_linkIds[i];
btVector3 forceWorld = isLinkFrame ? mb->getLink(link).m_cachedWorldTransform.getBasis() * tmpForce : tmpForce;
btVector3 relPosWorld = isLinkFrame ? mb->getLink(link).m_cachedWorldTransform.getBasis() * tmpPosition : tmpPosition - mb->getLink(link).m_cachedWorldTransform.getOrigin();
mb->addLinkForce(link, forceWorld);
mb->addLinkTorque(link, relPosWorld.cross(forceWorld));
//b3Printf("apply link force of %f,%f,%f at %f,%f,%f\n", forceWorld[0],forceWorld[1],forceWorld[2], positionLocal[0],positionLocal[1],positionLocal[2]);
}
}
if ((clientCmd.m_externalForceArguments.m_forceFlags[i] & EF_TORQUE) != 0)
{
btVector3 tmpTorque(clientCmd.m_externalForceArguments.m_forcesAndTorques[i * 3 + 0],
clientCmd.m_externalForceArguments.m_forcesAndTorques[i * 3 + 1],
clientCmd.m_externalForceArguments.m_forcesAndTorques[i * 3 + 2]);
if (clientCmd.m_externalForceArguments.m_linkIds[i] == -1)
{
btVector3 torqueWorld = isLinkFrame ? mb->getBaseWorldTransform().getBasis() * tmpTorque : tmpTorque;
mb->addBaseTorque(torqueWorld);
//b3Printf("apply base torque of %f,%f,%f\n", torqueWorld[0],torqueWorld[1],torqueWorld[2]);
}
else
{
int link = clientCmd.m_externalForceArguments.m_linkIds[i];
btVector3 torqueWorld = isLinkFrame ? mb->getLink(link).m_cachedWorldTransform.getBasis() * tmpTorque : tmpTorque;
mb->addLinkTorque(link, torqueWorld);
//b3Printf("apply link torque of %f,%f,%f\n", torqueWorld[0],torqueWorld[1],torqueWorld[2]);
}
}
}
if (body && body->m_rigidBody)
{
btRigidBody* rb = body->m_rigidBody;
if ((clientCmd.m_externalForceArguments.m_forceFlags[i] & EF_FORCE) != 0)
{
btVector3 tmpForce(clientCmd.m_externalForceArguments.m_forcesAndTorques[i * 3 + 0],
clientCmd.m_externalForceArguments.m_forcesAndTorques[i * 3 + 1],
clientCmd.m_externalForceArguments.m_forcesAndTorques[i * 3 + 2]);
btVector3 tmpPosition(
clientCmd.m_externalForceArguments.m_positions[i * 3 + 0],
clientCmd.m_externalForceArguments.m_positions[i * 3 + 1],
clientCmd.m_externalForceArguments.m_positions[i * 3 + 2]);
btVector3 forceWorld = isLinkFrame ? rb->getWorldTransform().getBasis() * tmpForce : tmpForce;
btVector3 relPosWorld = isLinkFrame ? rb->getWorldTransform().getBasis() * tmpPosition : tmpPosition - rb->getWorldTransform().getOrigin();
rb->applyForce(forceWorld, relPosWorld);
}
if ((clientCmd.m_externalForceArguments.m_forceFlags[i] & EF_TORQUE) != 0)
{
btVector3 tmpTorque(clientCmd.m_externalForceArguments.m_forcesAndTorques[i * 3 + 0],
clientCmd.m_externalForceArguments.m_forcesAndTorques[i * 3 + 1],
clientCmd.m_externalForceArguments.m_forcesAndTorques[i * 3 + 2]);
btVector3 torqueWorld = isLinkFrame ? rb->getWorldTransform().getBasis() * tmpTorque : tmpTorque;
rb->applyTorque(torqueWorld);
}
}
#ifndef SKIP_SOFT_BODY_MULTI_BODY_DYNAMICS_WORLD
if (body && body->m_softBody)
{
btSoftBody* sb = body->m_softBody;
int link = clientCmd.m_externalForceArguments.m_linkIds[i];
if ((clientCmd.m_externalForceArguments.m_forceFlags[i] & EF_FORCE) != 0)
{
btVector3 tmpForce(clientCmd.m_externalForceArguments.m_forcesAndTorques[i * 3 + 0],
clientCmd.m_externalForceArguments.m_forcesAndTorques[i * 3 + 1],
clientCmd.m_externalForceArguments.m_forcesAndTorques[i * 3 + 2]);
btVector3 tmpPosition(
clientCmd.m_externalForceArguments.m_positions[i * 3 + 0],
clientCmd.m_externalForceArguments.m_positions[i * 3 + 1],
clientCmd.m_externalForceArguments.m_positions[i * 3 + 2]);
btVector3 forceWorld = isLinkFrame ? sb->getWorldTransform().getBasis() * tmpForce : tmpForce;
btVector3 relPosWorld = isLinkFrame ? sb->getWorldTransform().getBasis() * tmpPosition : tmpPosition - sb->getWorldTransform().getOrigin();
if (link >= 0 && link < sb->m_nodes.size())
{
sb->addForce(forceWorld, link);
}
}
}
#endif
}
SharedMemoryStatus& serverCmd = serverStatusOut;
serverCmd.m_type = CMD_CLIENT_COMMAND_COMPLETED;
return hasStatus;
}
bool PhysicsServerCommandProcessor::processRemoveBodyCommand(const struct SharedMemoryCommand& clientCmd, struct SharedMemoryStatus& serverStatusOut, char* bufferServerToClient, int bufferSizeInBytes)
{
bool hasStatus = true;
SharedMemoryStatus& serverCmd = serverStatusOut;
serverCmd.m_type = CMD_REMOVE_BODY_FAILED;
serverCmd.m_removeObjectArgs.m_numBodies = 0;
serverCmd.m_removeObjectArgs.m_numUserConstraints = 0;
m_data->m_guiHelper->setVisualizerFlag(COV_ENABLE_SYNC_RENDERING_INTERNAL, 0);
for (int i = 0; i < clientCmd.m_removeObjectArgs.m_numBodies; i++)
{
int bodyUniqueId = clientCmd.m_removeObjectArgs.m_bodyUniqueIds[i];
InternalBodyHandle* bodyHandle = m_data->m_bodyHandles.getHandle(bodyUniqueId);
if (bodyHandle)
{
#ifndef USE_DISCRETE_DYNAMICS_WORLD
if (bodyHandle->m_multiBody)
{
serverCmd.m_removeObjectArgs.m_bodyUniqueIds[serverCmd.m_removeObjectArgs.m_numBodies++] = bodyUniqueId;
if (m_data->m_pickingMultiBodyPoint2Point && m_data->m_pickingMultiBodyPoint2Point->getMultiBodyA() == bodyHandle->m_multiBody)
{
//memory will be deleted in the code that follows
m_data->m_pickingMultiBodyPoint2Point = 0;
}
//also remove user constraints...
for (int i = m_data->m_dynamicsWorld->getNumMultiBodyConstraints() - 1; i >= 0; i--)
{
btMultiBodyConstraint* mbc = m_data->m_dynamicsWorld->getMultiBodyConstraint(i);
if ((mbc->getMultiBodyA() == bodyHandle->m_multiBody) || (mbc->getMultiBodyB() == bodyHandle->m_multiBody))
{
m_data->m_dynamicsWorld->removeMultiBodyConstraint(mbc);
//also remove user constraint and submit it as removed
for (int c = m_data->m_userConstraints.size() - 1; c >= 0; c--)
{
InteralUserConstraintData* userConstraintPtr = m_data->m_userConstraints.getAtIndex(c);
int userConstraintKey = m_data->m_userConstraints.getKeyAtIndex(c).getUid1();
if (userConstraintPtr->m_mbConstraint == mbc)
{
m_data->m_userConstraints.remove(userConstraintKey);
serverCmd.m_removeObjectArgs.m_userConstraintUniqueIds[serverCmd.m_removeObjectArgs.m_numUserConstraints++] = userConstraintKey;
}
}
delete mbc;
}
}
if (bodyHandle->m_multiBody->getBaseCollider())
{
if (m_data->m_pluginManager.getRenderInterface())
{
m_data->m_pluginManager.getRenderInterface()->removeVisualShape(bodyHandle->m_multiBody->getBaseCollider()->getUserIndex3());
}
m_data->m_dynamicsWorld->removeCollisionObject(bodyHandle->m_multiBody->getBaseCollider());
int graphicsIndex = bodyHandle->m_multiBody->getBaseCollider()->getUserIndex();
m_data->m_guiHelper->removeGraphicsInstance(graphicsIndex);
delete bodyHandle->m_multiBody->getBaseCollider();
}
for (int link = 0; link < bodyHandle->m_multiBody->getNumLinks(); link++)
{
btCollisionObject* colObj = bodyHandle->m_multiBody->getLink(link).m_collider;
if (colObj)
{
if (m_data->m_pluginManager.getRenderInterface())
{
m_data->m_pluginManager.getRenderInterface()->removeVisualShape(bodyHandle->m_multiBody->getLink(link).m_collider->getUserIndex3());
}
m_data->m_dynamicsWorld->removeCollisionObject(bodyHandle->m_multiBody->getLink(link).m_collider);
int graphicsIndex = bodyHandle->m_multiBody->getLink(link).m_collider->getUserIndex();
m_data->m_guiHelper->removeGraphicsInstance(graphicsIndex);
delete colObj;
}
}
int numCollisionObjects = m_data->m_dynamicsWorld->getNumCollisionObjects();
m_data->m_dynamicsWorld->removeMultiBody(bodyHandle->m_multiBody);
numCollisionObjects = m_data->m_dynamicsWorld->getNumCollisionObjects();
delete bodyHandle->m_multiBody;
bodyHandle->m_multiBody = 0;
serverCmd.m_type = CMD_REMOVE_BODY_COMPLETED;
}
#endif
if (bodyHandle->m_rigidBody)
{
if (m_data->m_pluginManager.getRenderInterface())
{
m_data->m_pluginManager.getRenderInterface()->removeVisualShape(bodyHandle->m_rigidBody->getUserIndex3());
}
serverCmd.m_removeObjectArgs.m_bodyUniqueIds[serverCmd.m_removeObjectArgs.m_numBodies++] = bodyUniqueId;
if (m_data->m_pickedConstraint && m_data->m_pickedBody == bodyHandle->m_rigidBody)
{
m_data->m_pickedConstraint = 0;
m_data->m_pickedBody = 0;
}
//todo: clear all other remaining data...
m_data->m_dynamicsWorld->removeRigidBody(bodyHandle->m_rigidBody);
int graphicsInstance = bodyHandle->m_rigidBody->getUserIndex2();
m_data->m_guiHelper->removeGraphicsInstance(graphicsInstance);
delete bodyHandle->m_rigidBody;
bodyHandle->m_rigidBody = 0;
serverCmd.m_type = CMD_REMOVE_BODY_COMPLETED;
}
#ifndef SKIP_SOFT_BODY_MULTI_BODY_DYNAMICS_WORLD
if (bodyHandle->m_softBody)
{
btSoftBody* psb = bodyHandle->m_softBody;
if (m_data->m_pluginManager.getRenderInterface())
{
m_data->m_pluginManager.getRenderInterface()->removeVisualShape(psb->getUserIndex3());
}
serverCmd.m_removeObjectArgs.m_bodyUniqueIds[serverCmd.m_removeObjectArgs.m_numBodies++] = bodyUniqueId;
btSoftMultiBodyDynamicsWorld* softWorld = getSoftWorld();
if (softWorld)
{
softWorld->removeSoftBody(psb);
}
btDeformableMultiBodyDynamicsWorld* deformWorld = getDeformableWorld();
if (deformWorld)
{
deformWorld->removeSoftBody(psb);
}
int graphicsInstance = psb->getUserIndex2();
m_data->m_guiHelper->removeGraphicsInstance(graphicsInstance);
delete psb;
psb = 0;
serverCmd.m_type = CMD_REMOVE_BODY_COMPLETED;
}
#endif
for (int i = 0; i < bodyHandle->m_userDataHandles.size(); i++)
{
int userDataHandle = bodyHandle->m_userDataHandles[i];
SharedMemoryUserData* userData = m_data->m_userDataHandles.getHandle(userDataHandle);
m_data->m_userDataHandleLookup.remove(SharedMemoryUserDataHashKey(userData));
m_data->m_userDataHandles.freeHandle(userDataHandle);
}
m_data->m_bodyHandles.freeHandle(bodyUniqueId);
}
}
for (int i = 0; i < clientCmd.m_removeObjectArgs.m_numUserCollisionShapes; i++)
{
int removeCollisionShapeId = clientCmd.m_removeObjectArgs.m_userCollisionShapes[i];
InternalCollisionShapeHandle* handle = m_data->m_userCollisionShapeHandles.getHandle(removeCollisionShapeId);
if (handle && handle->m_collisionShape)
{
if (handle->m_used)
{
b3Warning("Don't remove collision shape: it is used.");
}
else
{
b3Warning("TODO: dealloc");
int foundIndex = -1;
for (int i = 0; i < m_data->m_worldImporters.size(); i++)
{
#ifdef USE_DISCRETE_DYNAMICS_WORLD
btWorldImporter* importer = m_data->m_worldImporters[i];
#else
btMultiBodyWorldImporter* importer = m_data->m_worldImporters[i];
#endif
for (int c = 0; c < importer->getNumCollisionShapes(); c++)
{
if (importer->getCollisionShapeByIndex(c) == handle->m_collisionShape)
{
if ((importer->getNumRigidBodies() == 0) &&
(importer->getNumConstraints() == 0))
{
foundIndex = i;
break;
}
}
}
}
if (foundIndex >= 0)
{
#ifdef USE_DISCRETE_DYNAMICS_WORLD
btWorldImporter* importer = m_data->m_worldImporters[foundIndex];
#else
btMultiBodyWorldImporter* importer = m_data->m_worldImporters[foundIndex];
#endif
m_data->m_worldImporters.removeAtIndex(foundIndex);
importer->deleteAllData();
delete importer;
m_data->m_userCollisionShapeHandles.freeHandle(removeCollisionShapeId);
serverCmd.m_type = CMD_REMOVE_BODY_COMPLETED;
}
}
}
}
m_data->m_guiHelper->setVisualizerFlag(COV_ENABLE_SYNC_RENDERING_INTERNAL, 1);
for (int i = 0; i < serverCmd.m_removeObjectArgs.m_numBodies; i++)
{
b3Notification notification;
notification.m_notificationType = BODY_REMOVED;
notification.m_bodyArgs.m_bodyUniqueId = serverCmd.m_removeObjectArgs.m_bodyUniqueIds[i];
m_data->m_pluginManager.addNotification(notification);
}
return hasStatus;
}
bool PhysicsServerCommandProcessor::processCreateUserConstraintCommand(const struct SharedMemoryCommand& clientCmd, struct SharedMemoryStatus& serverStatusOut, char* bufferServerToClient, int bufferSizeInBytes)
{
bool hasStatus = true;
BT_PROFILE("CMD_USER_CONSTRAINT");
SharedMemoryStatus& serverCmd = serverStatusOut;
serverCmd.m_type = CMD_USER_CONSTRAINT_FAILED;
hasStatus = true;
if (clientCmd.m_updateFlags & USER_CONSTRAINT_ADD_SOFT_BODY_ANCHOR)
{
#ifndef SKIP_DEFORMABLE_BODY
InternalBodyHandle* sbodyHandle = m_data->m_bodyHandles.getHandle(clientCmd.m_userConstraintArguments.m_parentBodyIndex);
if (sbodyHandle)
{
if (sbodyHandle->m_softBody)
{
int nodeIndex = clientCmd.m_userConstraintArguments.m_parentJointIndex;
if (nodeIndex >= 0 && nodeIndex < sbodyHandle->m_softBody->m_nodes.size())
{
int bodyUniqueId = clientCmd.m_userConstraintArguments.m_childBodyIndex;
if (bodyUniqueId < 0)
{
//fixed anchor (mass = 0)
InteralUserConstraintData userConstraintData;
userConstraintData.m_sbHandle = clientCmd.m_userConstraintArguments.m_parentBodyIndex;
userConstraintData.m_sbNodeIndex = nodeIndex;
userConstraintData.m_sbNodeMass = sbodyHandle->m_softBody->getMass(nodeIndex);
sbodyHandle->m_softBody->setMass(nodeIndex, 0.0);
int uid = m_data->m_userConstraintUIDGenerator++;
m_data->m_userConstraints.insert(uid, userConstraintData);
serverCmd.m_userConstraintResultArgs.m_userConstraintUniqueId = uid;
serverCmd.m_type = CMD_USER_CONSTRAINT_COMPLETED;
}
else
{
InternalBodyHandle* mbodyHandle = m_data->m_bodyHandles.getHandle(bodyUniqueId);
if (mbodyHandle && mbodyHandle->m_multiBody)
{
btDeformableMultiBodyDynamicsWorld* deformWorld = getDeformableWorld();
if (deformWorld)
{
int linkIndex = clientCmd.m_userConstraintArguments.m_childJointIndex;
if (linkIndex < 0)
{
sbodyHandle->m_softBody->appendDeformableAnchor(nodeIndex, mbodyHandle->m_multiBody->getBaseCollider());
}
else
{
if (linkIndex < mbodyHandle->m_multiBody->getNumLinks())
{
sbodyHandle->m_softBody->appendDeformableAnchor(nodeIndex, mbodyHandle->m_multiBody->getLinkCollider(linkIndex));
}
}
}
}
if (mbodyHandle && mbodyHandle->m_rigidBody)
{
btDeformableMultiBodyDynamicsWorld* deformWorld = getDeformableWorld();
if (deformWorld)
{
//todo: expose those values
bool disableCollisionBetweenLinkedBodies = true;
//btVector3 localPivot(0,0,0);
sbodyHandle->m_softBody->appendDeformableAnchor(nodeIndex, mbodyHandle->m_rigidBody);
}
#if 1
btSoftMultiBodyDynamicsWorld* softWorld = getSoftWorld();
if (softWorld)
{
bool disableCollisionBetweenLinkedBodies = true;
btVector3 localPivot(clientCmd.m_userConstraintArguments.m_childFrame[0],
clientCmd.m_userConstraintArguments.m_childFrame[1],
clientCmd.m_userConstraintArguments.m_childFrame[2]);
sbodyHandle->m_softBody->appendAnchor(nodeIndex, mbodyHandle->m_rigidBody, localPivot, disableCollisionBetweenLinkedBodies);
}
#endif
}
int uid = m_data->m_userConstraintUIDGenerator++;
serverCmd.m_userConstraintResultArgs.m_userConstraintUniqueId = uid;
InteralUserConstraintData userConstraintData;
userConstraintData.m_sbHandle = clientCmd.m_userConstraintArguments.m_parentBodyIndex;
userConstraintData.m_sbNodeIndex = nodeIndex;
m_data->m_userConstraints.insert(uid, userConstraintData);
serverCmd.m_type = CMD_USER_CONSTRAINT_COMPLETED;
}
}
}
}
#endif
}
if (clientCmd.m_updateFlags & USER_CONSTRAINT_REQUEST_STATE)
{
int constraintUid = clientCmd.m_userConstraintArguments.m_userConstraintUniqueId;
InteralUserConstraintData* userConstraintPtr = m_data->m_userConstraints.find(constraintUid);
if (userConstraintPtr)
{
serverCmd.m_userConstraintStateResultArgs.m_numDofs = 0;
for (int i = 0; i < 6; i++)
{
serverCmd.m_userConstraintStateResultArgs.m_appliedConstraintForces[i] = 0;
}
if (userConstraintPtr->m_mbConstraint)
{
serverCmd.m_userConstraintStateResultArgs.m_numDofs = userConstraintPtr->m_mbConstraint->getNumRows();
for (int i = 0; i < userConstraintPtr->m_mbConstraint->getNumRows(); i++)
{
serverCmd.m_userConstraintStateResultArgs.m_appliedConstraintForces[i] = userConstraintPtr->m_mbConstraint->getAppliedImpulse(i) / m_data->m_dynamicsWorld->getSolverInfo().m_timeStep;
}
serverCmd.m_type = CMD_USER_CONSTRAINT_REQUEST_STATE_COMPLETED;
}
}
};
if (clientCmd.m_updateFlags & USER_CONSTRAINT_REQUEST_INFO)
{
int userConstraintUidChange = clientCmd.m_userConstraintArguments.m_userConstraintUniqueId;
InteralUserConstraintData* userConstraintPtr = m_data->m_userConstraints.find(userConstraintUidChange);
if (userConstraintPtr)
{
serverCmd.m_userConstraintResultArgs = userConstraintPtr->m_userConstraintData;
serverCmd.m_type = CMD_USER_CONSTRAINT_INFO_COMPLETED;
}
}
if (clientCmd.m_updateFlags & USER_CONSTRAINT_ADD_CONSTRAINT)
{
btScalar defaultMaxForce = 500.0;
InternalBodyData* parentBody = m_data->m_bodyHandles.getHandle(clientCmd.m_userConstraintArguments.m_parentBodyIndex);
#ifndef USE_DISCRETE_DYNAMICS_WORLD
if (parentBody && parentBody->m_multiBody)
{
if ((clientCmd.m_userConstraintArguments.m_parentJointIndex >= -1) && clientCmd.m_userConstraintArguments.m_parentJointIndex < parentBody->m_multiBody->getNumLinks())
{
InternalBodyData* childBody = clientCmd.m_userConstraintArguments.m_childBodyIndex >= 0 ? m_data->m_bodyHandles.getHandle(clientCmd.m_userConstraintArguments.m_childBodyIndex) : 0;
//also create a constraint with just a single multibody/rigid body without child
//if (childBody)
{
btVector3 pivotInParent(clientCmd.m_userConstraintArguments.m_parentFrame[0], clientCmd.m_userConstraintArguments.m_parentFrame[1], clientCmd.m_userConstraintArguments.m_parentFrame[2]);
btVector3 pivotInChild(clientCmd.m_userConstraintArguments.m_childFrame[0], clientCmd.m_userConstraintArguments.m_childFrame[1], clientCmd.m_userConstraintArguments.m_childFrame[2]);
btMatrix3x3 frameInParent(btQuaternion(clientCmd.m_userConstraintArguments.m_parentFrame[3], clientCmd.m_userConstraintArguments.m_parentFrame[4], clientCmd.m_userConstraintArguments.m_parentFrame[5], clientCmd.m_userConstraintArguments.m_parentFrame[6]));
btMatrix3x3 frameInChild(btQuaternion(clientCmd.m_userConstraintArguments.m_childFrame[3], clientCmd.m_userConstraintArguments.m_childFrame[4], clientCmd.m_userConstraintArguments.m_childFrame[5], clientCmd.m_userConstraintArguments.m_childFrame[6]));
btVector3 jointAxis(clientCmd.m_userConstraintArguments.m_jointAxis[0], clientCmd.m_userConstraintArguments.m_jointAxis[1], clientCmd.m_userConstraintArguments.m_jointAxis[2]);
if (clientCmd.m_userConstraintArguments.m_jointType == eGearType)
{
if (childBody && childBody->m_multiBody)
{
if ((clientCmd.m_userConstraintArguments.m_childJointIndex >= -1) && (clientCmd.m_userConstraintArguments.m_childJointIndex < childBody->m_multiBody->getNumLinks()))
{
btMultiBodyGearConstraint* multibodyGear = new btMultiBodyGearConstraint(parentBody->m_multiBody, clientCmd.m_userConstraintArguments.m_parentJointIndex, childBody->m_multiBody, clientCmd.m_userConstraintArguments.m_childJointIndex, pivotInParent, pivotInChild, frameInParent, frameInChild);
multibodyGear->setMaxAppliedImpulse(defaultMaxForce);
m_data->m_dynamicsWorld->addMultiBodyConstraint(multibodyGear);
InteralUserConstraintData userConstraintData;
userConstraintData.m_mbConstraint = multibodyGear;
int uid = m_data->m_userConstraintUIDGenerator++;
serverCmd.m_userConstraintResultArgs = clientCmd.m_userConstraintArguments;
serverCmd.m_userConstraintResultArgs.m_userConstraintUniqueId = uid;
serverCmd.m_userConstraintResultArgs.m_maxAppliedForce = defaultMaxForce;
userConstraintData.m_userConstraintData = serverCmd.m_userConstraintResultArgs;
m_data->m_userConstraints.insert(uid, userConstraintData);
serverCmd.m_type = CMD_USER_CONSTRAINT_COMPLETED;
}
}
}
else if (clientCmd.m_userConstraintArguments.m_jointType == eFixedType)
{
if (childBody && childBody->m_multiBody)
{
if ((clientCmd.m_userConstraintArguments.m_childJointIndex >= -1) && (clientCmd.m_userConstraintArguments.m_childJointIndex < childBody->m_multiBody->getNumLinks()))
{
btMultiBodyFixedConstraint* multibodyFixed = new btMultiBodyFixedConstraint(parentBody->m_multiBody, clientCmd.m_userConstraintArguments.m_parentJointIndex, childBody->m_multiBody, clientCmd.m_userConstraintArguments.m_childJointIndex, pivotInParent, pivotInChild, frameInParent, frameInChild);
multibodyFixed->setMaxAppliedImpulse(defaultMaxForce);
m_data->m_dynamicsWorld->addMultiBodyConstraint(multibodyFixed);
InteralUserConstraintData userConstraintData;
userConstraintData.m_mbConstraint = multibodyFixed;
int uid = m_data->m_userConstraintUIDGenerator++;
serverCmd.m_userConstraintResultArgs = clientCmd.m_userConstraintArguments;
serverCmd.m_userConstraintResultArgs.m_userConstraintUniqueId = uid;
serverCmd.m_userConstraintResultArgs.m_maxAppliedForce = defaultMaxForce;
userConstraintData.m_userConstraintData = serverCmd.m_userConstraintResultArgs;
m_data->m_userConstraints.insert(uid, userConstraintData);
serverCmd.m_type = CMD_USER_CONSTRAINT_COMPLETED;
}
}
else
{
btRigidBody* rb = childBody ? childBody->m_rigidBody : 0;
btMultiBodyFixedConstraint* rigidbodyFixed = new btMultiBodyFixedConstraint(parentBody->m_multiBody, clientCmd.m_userConstraintArguments.m_parentJointIndex, rb, pivotInParent, pivotInChild, frameInParent, frameInChild);
rigidbodyFixed->setMaxAppliedImpulse(defaultMaxForce);
btMultiBodyDynamicsWorld* world = (btMultiBodyDynamicsWorld*)m_data->m_dynamicsWorld;
world->addMultiBodyConstraint(rigidbodyFixed);
InteralUserConstraintData userConstraintData;
userConstraintData.m_mbConstraint = rigidbodyFixed;
int uid = m_data->m_userConstraintUIDGenerator++;
serverCmd.m_userConstraintResultArgs = clientCmd.m_userConstraintArguments;
serverCmd.m_userConstraintResultArgs.m_userConstraintUniqueId = uid;
serverCmd.m_userConstraintResultArgs.m_maxAppliedForce = defaultMaxForce;
userConstraintData.m_userConstraintData = serverCmd.m_userConstraintResultArgs;
m_data->m_userConstraints.insert(uid, userConstraintData);
serverCmd.m_type = CMD_USER_CONSTRAINT_COMPLETED;
}
}
else if (clientCmd.m_userConstraintArguments.m_jointType == ePrismaticType)
{
if (childBody && childBody->m_multiBody)
{
btMultiBodySliderConstraint* multibodySlider = new btMultiBodySliderConstraint(parentBody->m_multiBody, clientCmd.m_userConstraintArguments.m_parentJointIndex, childBody->m_multiBody, clientCmd.m_userConstraintArguments.m_childJointIndex, pivotInParent, pivotInChild, frameInParent, frameInChild, jointAxis);
multibodySlider->setMaxAppliedImpulse(defaultMaxForce);
m_data->m_dynamicsWorld->addMultiBodyConstraint(multibodySlider);
InteralUserConstraintData userConstraintData;
userConstraintData.m_mbConstraint = multibodySlider;
int uid = m_data->m_userConstraintUIDGenerator++;
serverCmd.m_userConstraintResultArgs = clientCmd.m_userConstraintArguments;
serverCmd.m_userConstraintResultArgs.m_userConstraintUniqueId = uid;
serverCmd.m_userConstraintResultArgs.m_maxAppliedForce = defaultMaxForce;
userConstraintData.m_userConstraintData = serverCmd.m_userConstraintResultArgs;
m_data->m_userConstraints.insert(uid, userConstraintData);
serverCmd.m_type = CMD_USER_CONSTRAINT_COMPLETED;
}
else
{
btRigidBody* rb = childBody ? childBody->m_rigidBody : 0;
btMultiBodySliderConstraint* rigidbodySlider = new btMultiBodySliderConstraint(parentBody->m_multiBody, clientCmd.m_userConstraintArguments.m_parentJointIndex, rb, pivotInParent, pivotInChild, frameInParent, frameInChild, jointAxis);
rigidbodySlider->setMaxAppliedImpulse(defaultMaxForce);
btMultiBodyDynamicsWorld* world = (btMultiBodyDynamicsWorld*)m_data->m_dynamicsWorld;
world->addMultiBodyConstraint(rigidbodySlider);
InteralUserConstraintData userConstraintData;
userConstraintData.m_mbConstraint = rigidbodySlider;
int uid = m_data->m_userConstraintUIDGenerator++;
serverCmd.m_userConstraintResultArgs = clientCmd.m_userConstraintArguments;
serverCmd.m_userConstraintResultArgs.m_userConstraintUniqueId = uid;
serverCmd.m_userConstraintResultArgs.m_maxAppliedForce = defaultMaxForce;
userConstraintData.m_userConstraintData = serverCmd.m_userConstraintResultArgs;
m_data->m_userConstraints.insert(uid, userConstraintData);
serverCmd.m_type = CMD_USER_CONSTRAINT_COMPLETED;
}
}
else if (clientCmd.m_userConstraintArguments.m_jointType == ePoint2PointType)
{
if (childBody && childBody->m_multiBody)
{
btMultiBodyPoint2Point* p2p = new btMultiBodyPoint2Point(parentBody->m_multiBody, clientCmd.m_userConstraintArguments.m_parentJointIndex, childBody->m_multiBody, clientCmd.m_userConstraintArguments.m_childJointIndex, pivotInParent, pivotInChild);
p2p->setMaxAppliedImpulse(defaultMaxForce);
m_data->m_dynamicsWorld->addMultiBodyConstraint(p2p);
InteralUserConstraintData userConstraintData;
userConstraintData.m_mbConstraint = p2p;
int uid = m_data->m_userConstraintUIDGenerator++;
serverCmd.m_userConstraintResultArgs = clientCmd.m_userConstraintArguments;
serverCmd.m_userConstraintResultArgs.m_userConstraintUniqueId = uid;
serverCmd.m_userConstraintResultArgs.m_maxAppliedForce = defaultMaxForce;
userConstraintData.m_userConstraintData = serverCmd.m_userConstraintResultArgs;
m_data->m_userConstraints.insert(uid, userConstraintData);
serverCmd.m_type = CMD_USER_CONSTRAINT_COMPLETED;
}
else
{
btRigidBody* rb = childBody ? childBody->m_rigidBody : 0;
btMultiBodyPoint2Point* p2p = new btMultiBodyPoint2Point(parentBody->m_multiBody, clientCmd.m_userConstraintArguments.m_parentJointIndex, rb, pivotInParent, pivotInChild);
p2p->setMaxAppliedImpulse(defaultMaxForce);
btMultiBodyDynamicsWorld* world = (btMultiBodyDynamicsWorld*)m_data->m_dynamicsWorld;
world->addMultiBodyConstraint(p2p);
InteralUserConstraintData userConstraintData;
userConstraintData.m_mbConstraint = p2p;
int uid = m_data->m_userConstraintUIDGenerator++;
serverCmd.m_userConstraintResultArgs = clientCmd.m_userConstraintArguments;
serverCmd.m_userConstraintResultArgs.m_userConstraintUniqueId = uid;
serverCmd.m_userConstraintResultArgs.m_maxAppliedForce = defaultMaxForce;
userConstraintData.m_userConstraintData = serverCmd.m_userConstraintResultArgs;
m_data->m_userConstraints.insert(uid, userConstraintData);
serverCmd.m_type = CMD_USER_CONSTRAINT_COMPLETED;
}
}
else
{
b3Warning("unknown constraint type");
}
}
}
}
else
#endif
{
InternalBodyData* childBody = clientCmd.m_userConstraintArguments.m_childBodyIndex >= 0 ? m_data->m_bodyHandles.getHandle(clientCmd.m_userConstraintArguments.m_childBodyIndex) : 0;
if (parentBody && childBody)
{
if (parentBody->m_rigidBody)
{
btRigidBody* parentRb = 0;
if (clientCmd.m_userConstraintArguments.m_parentJointIndex == -1)
{
parentRb = parentBody->m_rigidBody;
}
else
{
if ((clientCmd.m_userConstraintArguments.m_parentJointIndex >= 0) &&
(clientCmd.m_userConstraintArguments.m_parentJointIndex < parentBody->m_rigidBodyJoints.size()))
{
parentRb = &parentBody->m_rigidBodyJoints[clientCmd.m_userConstraintArguments.m_parentJointIndex]->getRigidBodyB();
}
}
btRigidBody* childRb = 0;
if (childBody->m_rigidBody)
{
if (clientCmd.m_userConstraintArguments.m_childJointIndex == -1)
{
childRb = childBody->m_rigidBody;
}
else
{
if ((clientCmd.m_userConstraintArguments.m_childJointIndex >= 0) && (clientCmd.m_userConstraintArguments.m_childJointIndex < childBody->m_rigidBodyJoints.size()))
{
childRb = &childBody->m_rigidBodyJoints[clientCmd.m_userConstraintArguments.m_childJointIndex]->getRigidBodyB();
}
}
}
switch (clientCmd.m_userConstraintArguments.m_jointType)
{
case eRevoluteType:
{
break;
}
case ePrismaticType:
{
break;
}
case eFixedType:
{
if (childRb && parentRb && (childRb != parentRb))
{
btVector3 pivotInParent(clientCmd.m_userConstraintArguments.m_parentFrame[0], clientCmd.m_userConstraintArguments.m_parentFrame[1], clientCmd.m_userConstraintArguments.m_parentFrame[2]);
btVector3 pivotInChild(clientCmd.m_userConstraintArguments.m_childFrame[0], clientCmd.m_userConstraintArguments.m_childFrame[1], clientCmd.m_userConstraintArguments.m_childFrame[2]);
btTransform offsetTrA, offsetTrB;
offsetTrA.setIdentity();
offsetTrA.setOrigin(pivotInParent);
offsetTrB.setIdentity();
offsetTrB.setOrigin(pivotInChild);
btGeneric6DofSpring2Constraint* dof6 = new btGeneric6DofSpring2Constraint(*parentRb, *childRb, offsetTrA, offsetTrB);
dof6->setLinearLowerLimit(btVector3(0, 0, 0));
dof6->setLinearUpperLimit(btVector3(0, 0, 0));
dof6->setAngularLowerLimit(btVector3(0, 0, 0));
dof6->setAngularUpperLimit(btVector3(0, 0, 0));
m_data->m_dynamicsWorld->addConstraint(dof6);
InteralUserConstraintData userConstraintData;
userConstraintData.m_rbConstraint = dof6;
int uid = m_data->m_userConstraintUIDGenerator++;
serverCmd.m_userConstraintResultArgs = clientCmd.m_userConstraintArguments;
serverCmd.m_userConstraintResultArgs.m_userConstraintUniqueId = uid;
serverCmd.m_userConstraintResultArgs.m_maxAppliedForce = defaultMaxForce;
userConstraintData.m_userConstraintData = serverCmd.m_userConstraintResultArgs;
m_data->m_userConstraints.insert(uid, userConstraintData);
serverCmd.m_type = CMD_USER_CONSTRAINT_COMPLETED;
}
break;
}
case ePoint2PointType:
{
if (childRb && parentRb && (childRb != parentRb))
{
btVector3 pivotInParent(clientCmd.m_userConstraintArguments.m_parentFrame[0], clientCmd.m_userConstraintArguments.m_parentFrame[1], clientCmd.m_userConstraintArguments.m_parentFrame[2]);
btVector3 pivotInChild(clientCmd.m_userConstraintArguments.m_childFrame[0], clientCmd.m_userConstraintArguments.m_childFrame[1], clientCmd.m_userConstraintArguments.m_childFrame[2]);
btPoint2PointConstraint* p2p = new btPoint2PointConstraint(*parentRb, *childRb, pivotInParent, pivotInChild);
p2p->m_setting.m_impulseClamp = defaultMaxForce;
m_data->m_dynamicsWorld->addConstraint(p2p);
InteralUserConstraintData userConstraintData;
userConstraintData.m_rbConstraint = p2p;
int uid = m_data->m_userConstraintUIDGenerator++;
serverCmd.m_userConstraintResultArgs = clientCmd.m_userConstraintArguments;
serverCmd.m_userConstraintResultArgs.m_userConstraintUniqueId = uid;
serverCmd.m_userConstraintResultArgs.m_maxAppliedForce = defaultMaxForce;
userConstraintData.m_userConstraintData = serverCmd.m_userConstraintResultArgs;
m_data->m_userConstraints.insert(uid, userConstraintData);
serverCmd.m_type = CMD_USER_CONSTRAINT_COMPLETED;
}
break;
}
case eGearType:
{
if (childRb && parentRb && (childRb != parentRb))
{
btVector3 axisA(clientCmd.m_userConstraintArguments.m_jointAxis[0],
clientCmd.m_userConstraintArguments.m_jointAxis[1],
clientCmd.m_userConstraintArguments.m_jointAxis[2]);
//for now we use the same local axis for both objects
btVector3 axisB(clientCmd.m_userConstraintArguments.m_jointAxis[0],
clientCmd.m_userConstraintArguments.m_jointAxis[1],
clientCmd.m_userConstraintArguments.m_jointAxis[2]);
btScalar ratio = 1;
btGearConstraint* gear = new btGearConstraint(*parentRb, *childRb, axisA, axisB, ratio);
m_data->m_dynamicsWorld->addConstraint(gear, true);
InteralUserConstraintData userConstraintData;
userConstraintData.m_rbConstraint = gear;
int uid = m_data->m_userConstraintUIDGenerator++;
serverCmd.m_userConstraintResultArgs = clientCmd.m_userConstraintArguments;
serverCmd.m_userConstraintResultArgs.m_userConstraintUniqueId = uid;
serverCmd.m_userConstraintResultArgs.m_maxAppliedForce = defaultMaxForce;
userConstraintData.m_userConstraintData = serverCmd.m_userConstraintResultArgs;
m_data->m_userConstraints.insert(uid, userConstraintData);
serverCmd.m_type = CMD_USER_CONSTRAINT_COMPLETED;
}
break;
}
case eSphericalType:
{
b3Warning("constraint type not handled yet");
break;
}
case ePlanarType:
{
b3Warning("constraint type not handled yet");
break;
}
default:
{
b3Warning("unknown constraint type");
}
};
}
}
}
}
if (clientCmd.m_updateFlags & USER_CONSTRAINT_CHANGE_CONSTRAINT)
{
btScalar fixedTimeSubStep = m_data->m_numSimulationSubSteps > 0 ? m_data->m_physicsDeltaTime / m_data->m_numSimulationSubSteps : m_data->m_physicsDeltaTime;
serverCmd.m_type = CMD_CHANGE_USER_CONSTRAINT_FAILED;
int userConstraintUidChange = clientCmd.m_userConstraintArguments.m_userConstraintUniqueId;
InteralUserConstraintData* userConstraintPtr = m_data->m_userConstraints.find(userConstraintUidChange);
if (userConstraintPtr)
{
if (userConstraintPtr->m_mbConstraint)
{
if (clientCmd.m_updateFlags & USER_CONSTRAINT_CHANGE_PIVOT_IN_B)
{
btVector3 pivotInB(clientCmd.m_userConstraintArguments.m_childFrame[0],
clientCmd.m_userConstraintArguments.m_childFrame[1],
clientCmd.m_userConstraintArguments.m_childFrame[2]);
userConstraintPtr->m_userConstraintData.m_childFrame[0] = clientCmd.m_userConstraintArguments.m_childFrame[0];
userConstraintPtr->m_userConstraintData.m_childFrame[1] = clientCmd.m_userConstraintArguments.m_childFrame[1];
userConstraintPtr->m_userConstraintData.m_childFrame[2] = clientCmd.m_userConstraintArguments.m_childFrame[2];
userConstraintPtr->m_mbConstraint->setPivotInB(pivotInB);
}
if (clientCmd.m_updateFlags & USER_CONSTRAINT_CHANGE_FRAME_ORN_IN_B)
{
btQuaternion childFrameOrn(clientCmd.m_userConstraintArguments.m_childFrame[3],
clientCmd.m_userConstraintArguments.m_childFrame[4],
clientCmd.m_userConstraintArguments.m_childFrame[5],
clientCmd.m_userConstraintArguments.m_childFrame[6]);
userConstraintPtr->m_userConstraintData.m_childFrame[3] = clientCmd.m_userConstraintArguments.m_childFrame[3];
userConstraintPtr->m_userConstraintData.m_childFrame[4] = clientCmd.m_userConstraintArguments.m_childFrame[4];
userConstraintPtr->m_userConstraintData.m_childFrame[5] = clientCmd.m_userConstraintArguments.m_childFrame[5];
userConstraintPtr->m_userConstraintData.m_childFrame[6] = clientCmd.m_userConstraintArguments.m_childFrame[6];
btMatrix3x3 childFrameBasis(childFrameOrn);
userConstraintPtr->m_mbConstraint->setFrameInB(childFrameBasis);
}
if (clientCmd.m_updateFlags & USER_CONSTRAINT_CHANGE_MAX_FORCE)
{
btScalar maxImp = clientCmd.m_userConstraintArguments.m_maxAppliedForce * fixedTimeSubStep;
userConstraintPtr->m_userConstraintData.m_maxAppliedForce = clientCmd.m_userConstraintArguments.m_maxAppliedForce;
userConstraintPtr->m_mbConstraint->setMaxAppliedImpulse(maxImp);
}
if (clientCmd.m_updateFlags & USER_CONSTRAINT_CHANGE_GEAR_RATIO)
{
userConstraintPtr->m_mbConstraint->setGearRatio(clientCmd.m_userConstraintArguments.m_gearRatio);
userConstraintPtr->m_userConstraintData.m_gearRatio = clientCmd.m_userConstraintArguments.m_gearRatio;
}
if (clientCmd.m_updateFlags & USER_CONSTRAINT_CHANGE_RELATIVE_POSITION_TARGET)
{
userConstraintPtr->m_mbConstraint->setRelativePositionTarget(clientCmd.m_userConstraintArguments.m_relativePositionTarget);
userConstraintPtr->m_userConstraintData.m_relativePositionTarget = clientCmd.m_userConstraintArguments.m_relativePositionTarget;
}
if (clientCmd.m_updateFlags & USER_CONSTRAINT_CHANGE_ERP)
{
userConstraintPtr->m_mbConstraint->setErp(clientCmd.m_userConstraintArguments.m_erp);
userConstraintPtr->m_userConstraintData.m_erp = clientCmd.m_userConstraintArguments.m_erp;
}
if (clientCmd.m_updateFlags & USER_CONSTRAINT_CHANGE_GEAR_AUX_LINK)
{
userConstraintPtr->m_mbConstraint->setGearAuxLink(clientCmd.m_userConstraintArguments.m_gearAuxLink);
userConstraintPtr->m_userConstraintData.m_gearAuxLink = clientCmd.m_userConstraintArguments.m_gearAuxLink;
}
}
if (userConstraintPtr->m_rbConstraint)
{
if (clientCmd.m_updateFlags & USER_CONSTRAINT_CHANGE_MAX_FORCE)
{
btScalar maxImp = clientCmd.m_userConstraintArguments.m_maxAppliedForce * fixedTimeSubStep;
userConstraintPtr->m_userConstraintData.m_maxAppliedForce = clientCmd.m_userConstraintArguments.m_maxAppliedForce;
//userConstraintPtr->m_rbConstraint->setMaxAppliedImpulse(maxImp);
}
if (clientCmd.m_updateFlags & USER_CONSTRAINT_CHANGE_GEAR_RATIO)
{
if (userConstraintPtr->m_rbConstraint->getObjectType() == GEAR_CONSTRAINT_TYPE)
{
btGearConstraint* gear = (btGearConstraint*)userConstraintPtr->m_rbConstraint;
gear->setRatio(clientCmd.m_userConstraintArguments.m_gearRatio);
}
}
}
serverCmd.m_userConstraintResultArgs = clientCmd.m_userConstraintArguments;
serverCmd.m_userConstraintResultArgs.m_userConstraintUniqueId = userConstraintUidChange;
serverCmd.m_updateFlags = clientCmd.m_updateFlags;
serverCmd.m_type = CMD_CHANGE_USER_CONSTRAINT_COMPLETED;
}
}
if (clientCmd.m_updateFlags & USER_CONSTRAINT_REMOVE_CONSTRAINT)
{
serverCmd.m_type = CMD_REMOVE_USER_CONSTRAINT_FAILED;
int userConstraintUidRemove = clientCmd.m_userConstraintArguments.m_userConstraintUniqueId;
InteralUserConstraintData* userConstraintPtr = m_data->m_userConstraints.find(userConstraintUidRemove);
if (userConstraintPtr)
{
#ifndef USE_DISCRETE_DYNAMICS_WORLD
if (userConstraintPtr->m_mbConstraint)
{
m_data->m_dynamicsWorld->removeMultiBodyConstraint(userConstraintPtr->m_mbConstraint);
delete userConstraintPtr->m_mbConstraint;
m_data->m_userConstraints.remove(userConstraintUidRemove);
}
#endif//USE_DISCRETE_DYNAMICS_WORLD
if (userConstraintPtr->m_rbConstraint)
{
m_data->m_dynamicsWorld->removeConstraint(userConstraintPtr->m_rbConstraint);
delete userConstraintPtr->m_rbConstraint;
m_data->m_userConstraints.remove(userConstraintUidRemove);
}
#ifndef SKIP_SOFT_BODY_MULTI_BODY_DYNAMICS_WORLD
if (userConstraintPtr->m_sbHandle >= 0)
{
InternalBodyHandle* sbodyHandle = m_data->m_bodyHandles.getHandle(userConstraintPtr->m_sbHandle);
if (sbodyHandle)
{
if (sbodyHandle->m_softBody)
{
if (userConstraintPtr->m_sbNodeMass >= 0)
{
sbodyHandle->m_softBody->setMass(userConstraintPtr->m_sbNodeIndex, userConstraintPtr->m_sbNodeMass);
}
else
{
sbodyHandle->m_softBody->removeAnchor(userConstraintPtr->m_sbNodeIndex);
}
}
}
}
#endif
serverCmd.m_userConstraintResultArgs.m_userConstraintUniqueId = userConstraintUidRemove;
serverCmd.m_type = CMD_REMOVE_USER_CONSTRAINT_COMPLETED;
}
}
return hasStatus;
}
bool PhysicsServerCommandProcessor::processCalculateInverseKinematicsCommand(const struct SharedMemoryCommand& clientCmd, struct SharedMemoryStatus& serverStatusOut, char* bufferServerToClient, int bufferSizeInBytes)
{
bool hasStatus = true;
BT_PROFILE("CMD_CALCULATE_INVERSE_KINEMATICS");
SharedMemoryStatus& serverCmd = serverStatusOut;
serverCmd.m_type = CMD_CALCULATE_INVERSE_KINEMATICS_FAILED;
InternalBodyHandle* bodyHandle = m_data->m_bodyHandles.getHandle(clientCmd.m_calculateInverseKinematicsArguments.m_bodyUniqueId);
if (bodyHandle && bodyHandle->m_multiBody)
{
IKTrajectoryHelper** ikHelperPtrPtr = m_data->m_inverseKinematicsHelpers.find(bodyHandle->m_multiBody);
IKTrajectoryHelper* ikHelperPtr = 0;
if (ikHelperPtrPtr)
{
ikHelperPtr = *ikHelperPtrPtr;
}
else
{
IKTrajectoryHelper* tmpHelper = new IKTrajectoryHelper;
m_data->m_inverseKinematicsHelpers.insert(bodyHandle->m_multiBody, tmpHelper);
ikHelperPtr = tmpHelper;
}
int endEffectorLinkIndex = clientCmd.m_calculateInverseKinematicsArguments.m_endEffectorLinkIndices[0];
btAlignedObjectArray<double> startingPositions;
startingPositions.reserve(bodyHandle->m_multiBody->getNumLinks());
btVector3 targetPosWorld(clientCmd.m_calculateInverseKinematicsArguments.m_targetPositions[0],
clientCmd.m_calculateInverseKinematicsArguments.m_targetPositions[1],
clientCmd.m_calculateInverseKinematicsArguments.m_targetPositions[2]);
btQuaternion targetOrnWorld(clientCmd.m_calculateInverseKinematicsArguments.m_targetOrientation[0],
clientCmd.m_calculateInverseKinematicsArguments.m_targetOrientation[1],
clientCmd.m_calculateInverseKinematicsArguments.m_targetOrientation[2],
clientCmd.m_calculateInverseKinematicsArguments.m_targetOrientation[3]);
btTransform targetBaseCoord;
if (clientCmd.m_updateFlags & IK_HAS_CURRENT_JOINT_POSITIONS)
{
targetBaseCoord.setOrigin(targetPosWorld);
targetBaseCoord.setRotation(targetOrnWorld);
}
else
{
btTransform targetWorld;
targetWorld.setOrigin(targetPosWorld);
targetWorld.setRotation(targetOrnWorld);
btTransform tr = bodyHandle->m_multiBody->getBaseWorldTransform();
targetBaseCoord = tr.inverse() * targetWorld;
}
{
int DofIndex = 0;
for (int i = 0; i < bodyHandle->m_multiBody->getNumLinks(); ++i)
{
if (bodyHandle->m_multiBody->getLink(i).m_jointType >= 0 && bodyHandle->m_multiBody->getLink(i).m_jointType <= 2)
{
// 0, 1, 2 represent revolute, prismatic, and spherical joint types respectively. Skip the fixed joints.
double curPos = 0;
if (clientCmd.m_updateFlags & IK_HAS_CURRENT_JOINT_POSITIONS)
{
curPos = clientCmd.m_calculateInverseKinematicsArguments.m_currentPositions[DofIndex];
}
else
{
curPos = bodyHandle->m_multiBody->getJointPos(i);
}
startingPositions.push_back(curPos);
DofIndex++;
}
}
}
int numIterations = 20;
if (clientCmd.m_updateFlags & IK_HAS_MAX_ITERATIONS)
{
numIterations = clientCmd.m_calculateInverseKinematicsArguments.m_maxNumIterations;
}
double residualThreshold = 1e-4;
if (clientCmd.m_updateFlags & IK_HAS_RESIDUAL_THRESHOLD)
{
residualThreshold = clientCmd.m_calculateInverseKinematicsArguments.m_residualThreshold;
}
btScalar currentDiff = 1e30f;
b3AlignedObjectArray<double> jacobian_linear;
b3AlignedObjectArray<double> jacobian_angular;
btAlignedObjectArray<double> q_current;
btAlignedObjectArray<double> q_new;
btAlignedObjectArray<double> lower_limit;
btAlignedObjectArray<double> upper_limit;
btAlignedObjectArray<double> joint_range;
btAlignedObjectArray<double> rest_pose;
const int numDofs = bodyHandle->m_multiBody->getNumDofs();
int baseDofs = bodyHandle->m_multiBody->hasFixedBase() ? 0 : 6;
btInverseDynamics::vecx nu(numDofs + baseDofs), qdot(numDofs + baseDofs), q(numDofs + baseDofs), joint_force(numDofs + baseDofs);
for (int i = 0; i < numIterations && currentDiff > residualThreshold; i++)
{
BT_PROFILE("InverseKinematics1Step");
if (ikHelperPtr && (endEffectorLinkIndex < bodyHandle->m_multiBody->getNumLinks()))
{
jacobian_linear.resize(3 * numDofs);
jacobian_angular.resize(3 * numDofs);
int jacSize = 0;
btInverseDynamics::MultiBodyTree* tree = m_data->findOrCreateTree(bodyHandle->m_multiBody);
q_current.resize(numDofs);
if (tree && ((numDofs + baseDofs) == tree->numDoFs()))
{
btInverseDynamics::vec3 world_origin;
btInverseDynamics::mat33 world_rot;
jacSize = jacobian_linear.size();
// Set jacobian value
int DofIndex = 0;
for (int i = 0; i < bodyHandle->m_multiBody->getNumLinks(); ++i)
{
if (bodyHandle->m_multiBody->getLink(i).m_jointType >= 0 && bodyHandle->m_multiBody->getLink(i).m_jointType <= 2)
{
// 0, 1, 2 represent revolute, prismatic, and spherical joint types respectively. Skip the fixed joints.
double curPos = startingPositions[DofIndex];
q_current[DofIndex] = curPos;
q[DofIndex + baseDofs] = curPos;
qdot[DofIndex + baseDofs] = 0;
nu[DofIndex + baseDofs] = 0;
DofIndex++;
}
} // Set the gravity to correspond to the world gravity
btInverseDynamics::vec3 id_grav(m_data->m_dynamicsWorld->getGravity());
{
BT_PROFILE("calculateInverseDynamics");
if (-1 != tree->setGravityInWorldFrame(id_grav) &&
-1 != tree->calculateInverseDynamics(q, qdot, nu, &joint_force))
{
tree->calculateJacobians(q);
btInverseDynamics::mat3x jac_t(3, numDofs + baseDofs);
btInverseDynamics::mat3x jac_r(3, numDofs + baseDofs);
// Note that inverse dynamics uses zero-based indexing of bodies, not starting from -1 for the base link.
tree->getBodyJacobianTrans(endEffectorLinkIndex + 1, &jac_t);
tree->getBodyJacobianRot(endEffectorLinkIndex + 1, &jac_r);
//calculatePositionKinematics is already done inside calculateInverseDynamics
tree->getBodyOrigin(endEffectorLinkIndex + 1, &world_origin);
tree->getBodyTransform(endEffectorLinkIndex + 1, &world_rot);
for (int i = 0; i < 3; ++i)
{
for (int j = 0; j < numDofs; ++j)
{
jacobian_linear[i * numDofs + j] = jac_t(i, (baseDofs + j));
jacobian_angular[i * numDofs + j] = jac_r(i, (baseDofs + j));
}
}
}
}
q_new.resize(numDofs);
int ikMethod = 0;
if ((clientCmd.m_updateFlags & IK_HAS_TARGET_ORIENTATION) && (clientCmd.m_updateFlags & IK_HAS_NULL_SPACE_VELOCITY))
{
//Nullspace task only works with DLS now. TODO: add nullspace task to SDLS.
ikMethod = IK2_VEL_DLS_WITH_ORIENTATION_NULLSPACE;
}
else if (clientCmd.m_updateFlags & IK_HAS_TARGET_ORIENTATION)
{
if (clientCmd.m_updateFlags & IK_SDLS)
{
ikMethod = IK2_VEL_SDLS_WITH_ORIENTATION;
}
else
{
ikMethod = IK2_VEL_DLS_WITH_ORIENTATION;
}
}
else if (clientCmd.m_updateFlags & IK_HAS_NULL_SPACE_VELOCITY)
{
//Nullspace task only works with DLS now. TODO: add nullspace task to SDLS.
ikMethod = IK2_VEL_DLS_WITH_NULLSPACE;
}
else
{
if (clientCmd.m_updateFlags & IK_SDLS)
{
ikMethod = IK2_VEL_SDLS;
}
else
{
ikMethod = IK2_VEL_DLS;
;
}
}
if (clientCmd.m_updateFlags & IK_HAS_NULL_SPACE_VELOCITY)
{
lower_limit.resize(numDofs);
upper_limit.resize(numDofs);
joint_range.resize(numDofs);
rest_pose.resize(numDofs);
for (int i = 0; i < numDofs; ++i)
{
lower_limit[i] = clientCmd.m_calculateInverseKinematicsArguments.m_lowerLimit[i];
upper_limit[i] = clientCmd.m_calculateInverseKinematicsArguments.m_upperLimit[i];
joint_range[i] = clientCmd.m_calculateInverseKinematicsArguments.m_jointRange[i];
rest_pose[i] = clientCmd.m_calculateInverseKinematicsArguments.m_restPose[i];
}
{
BT_PROFILE("computeNullspaceVel");
ikHelperPtr->computeNullspaceVel(numDofs, &q_current[0], &lower_limit[0], &upper_limit[0], &joint_range[0], &rest_pose[0]);
}
}
//btTransform endEffectorTransformWorld = bodyHandle->m_multiBody->getLink(endEffectorLinkIndex).m_cachedWorldTransform * bodyHandle->m_linkLocalInertialFrames[endEffectorLinkIndex].inverse();
btVector3DoubleData endEffectorWorldPosition;
btQuaternionDoubleData endEffectorWorldOrientation;
//get the position from the inverse dynamics (based on q) instead of endEffectorTransformWorld
btVector3 endEffectorPosWorldOrg = world_origin;
btQuaternion endEffectorOriWorldOrg;
world_rot.getRotation(endEffectorOriWorldOrg);
btTransform endEffectorBaseCoord;
endEffectorBaseCoord.setOrigin(endEffectorPosWorldOrg);
endEffectorBaseCoord.setRotation(endEffectorOriWorldOrg);
//don't need the next two lines
//btTransform linkInertiaInv = bodyHandle->m_linkLocalInertialFrames[endEffectorLinkIndex].inverse();
//endEffectorBaseCoord = endEffectorBaseCoord * linkInertiaInv;
//btTransform tr = bodyHandle->m_multiBody->getBaseWorldTransform();
//endEffectorBaseCoord = tr.inverse()*endEffectorTransformWorld;
//endEffectorBaseCoord = tr.inverse()*endEffectorTransformWorld;
btQuaternion endEffectorOriBaseCoord = endEffectorBaseCoord.getRotation();
//btVector4 endEffectorOri(endEffectorOriBaseCoord.x(), endEffectorOriBaseCoord.y(), endEffectorOriBaseCoord.z(), endEffectorOriBaseCoord.w());
endEffectorBaseCoord.getOrigin().serializeDouble(endEffectorWorldPosition);
endEffectorBaseCoord.getRotation().serializeDouble(endEffectorWorldOrientation);
//diff
currentDiff = (endEffectorBaseCoord.getOrigin() - targetBaseCoord.getOrigin()).length();
btVector3DoubleData targetPosBaseCoord;
btQuaternionDoubleData targetOrnBaseCoord;
targetBaseCoord.getOrigin().serializeDouble(targetPosBaseCoord);
targetBaseCoord.getRotation().serializeDouble(targetOrnBaseCoord);
// Set joint damping coefficents. A small default
// damping constant is added to prevent singularity
// with pseudo inverse. The user can set joint damping
// coefficients differently for each joint. The larger
// the damping coefficient is, the less we rely on
// this joint to achieve the IK target.
btAlignedObjectArray<double> joint_damping;
joint_damping.resize(numDofs, 0.5);
if (clientCmd.m_updateFlags & IK_HAS_JOINT_DAMPING)
{
for (int i = 0; i < numDofs; ++i)
{
joint_damping[i] = clientCmd.m_calculateInverseKinematicsArguments.m_jointDamping[i];
}
}
ikHelperPtr->setDampingCoeff(numDofs, &joint_damping[0]);
double targetDampCoeff[6] = {1.0, 1.0, 1.0, 1.0, 1.0, 1.0};
{
BT_PROFILE("computeIK");
ikHelperPtr->computeIK(targetPosBaseCoord.m_floats, targetOrnBaseCoord.m_floats,
endEffectorWorldPosition.m_floats, endEffectorWorldOrientation.m_floats,
&q_current[0],
numDofs, clientCmd.m_calculateInverseKinematicsArguments.m_endEffectorLinkIndices[0],
&q_new[0], ikMethod, &jacobian_linear[0], &jacobian_angular[0], jacSize * 2, targetDampCoeff);
}
serverCmd.m_inverseKinematicsResultArgs.m_bodyUniqueId = clientCmd.m_calculateInverseDynamicsArguments.m_bodyUniqueId;
for (int i = 0; i < numDofs; i++)
{
serverCmd.m_inverseKinematicsResultArgs.m_jointPositions[i] = q_new[i];
}
serverCmd.m_inverseKinematicsResultArgs.m_dofCount = numDofs;
serverCmd.m_type = CMD_CALCULATE_INVERSE_KINEMATICS_COMPLETED;
for (int i = 0; i < numDofs; i++)
{
startingPositions[i] = q_new[i];
}
}
}
}
}
return hasStatus;
}
bool PhysicsServerCommandProcessor::processCalculateInverseKinematicsCommand2(const struct SharedMemoryCommand& clientCmd, struct SharedMemoryStatus& serverStatusOut, char* bufferServerToClient, int bufferSizeInBytes)
{
bool hasStatus = true;
BT_PROFILE("CMD_CALCULATE_INVERSE_KINEMATICS");
SharedMemoryStatus& serverCmd = serverStatusOut;
serverCmd.m_type = CMD_CALCULATE_INVERSE_KINEMATICS_FAILED;
InternalBodyHandle* bodyHandle = m_data->m_bodyHandles.getHandle(clientCmd.m_calculateInverseKinematicsArguments.m_bodyUniqueId);
if (bodyHandle && bodyHandle->m_multiBody)
{
IKTrajectoryHelper** ikHelperPtrPtr = m_data->m_inverseKinematicsHelpers.find(bodyHandle->m_multiBody);
IKTrajectoryHelper* ikHelperPtr = 0;
if (ikHelperPtrPtr)
{
ikHelperPtr = *ikHelperPtrPtr;
}
else
{
IKTrajectoryHelper* tmpHelper = new IKTrajectoryHelper;
m_data->m_inverseKinematicsHelpers.insert(bodyHandle->m_multiBody, tmpHelper);
ikHelperPtr = tmpHelper;
}
btAlignedObjectArray<double> startingPositions;
startingPositions.reserve(bodyHandle->m_multiBody->getNumLinks());
{
int DofIndex = 0;
for (int i = 0; i < bodyHandle->m_multiBody->getNumLinks(); ++i)
{
if (bodyHandle->m_multiBody->getLink(i).m_jointType >= 0 && bodyHandle->m_multiBody->getLink(i).m_jointType <= 2)
{
// 0, 1, 2 represent revolute, prismatic, and spherical joint types respectively. Skip the fixed joints.
double curPos = 0;
if (clientCmd.m_updateFlags & IK_HAS_CURRENT_JOINT_POSITIONS)
{
curPos = clientCmd.m_calculateInverseKinematicsArguments.m_currentPositions[DofIndex];
}
else
{
curPos = bodyHandle->m_multiBody->getJointPos(i);
}
startingPositions.push_back(curPos);
DofIndex++;
}
}
}
int numIterations = 20;
if (clientCmd.m_updateFlags & IK_HAS_MAX_ITERATIONS)
{
numIterations = clientCmd.m_calculateInverseKinematicsArguments.m_maxNumIterations;
}
double residualThreshold = 1e-4;
if (clientCmd.m_updateFlags & IK_HAS_RESIDUAL_THRESHOLD)
{
residualThreshold = clientCmd.m_calculateInverseKinematicsArguments.m_residualThreshold;
}
btScalar currentDiff = 1e30f;
b3AlignedObjectArray<double> endEffectorTargetWorldPositions;
b3AlignedObjectArray<double> endEffectorTargetWorldOrientations;
b3AlignedObjectArray<double> endEffectorCurrentWorldPositions;
b3AlignedObjectArray<double> jacobian_linear;
b3AlignedObjectArray<double> jacobian_angular;
btAlignedObjectArray<double> q_current;
btAlignedObjectArray<double> q_new;
btAlignedObjectArray<double> lower_limit;
btAlignedObjectArray<double> upper_limit;
btAlignedObjectArray<double> joint_range;
btAlignedObjectArray<double> rest_pose;
const int numDofs = bodyHandle->m_multiBody->getNumDofs();
int baseDofs = bodyHandle->m_multiBody->hasFixedBase() ? 0 : 6;
btInverseDynamics::vecx nu(numDofs + baseDofs), qdot(numDofs + baseDofs), q(numDofs + baseDofs), joint_force(numDofs + baseDofs);
endEffectorTargetWorldPositions.resize(0);
endEffectorTargetWorldPositions.reserve(clientCmd.m_calculateInverseKinematicsArguments.m_numEndEffectorLinkIndices * 3);
endEffectorTargetWorldOrientations.resize(0);
endEffectorTargetWorldOrientations.reserve(clientCmd.m_calculateInverseKinematicsArguments.m_numEndEffectorLinkIndices * 4);
bool validEndEffectorLinkIndices = true;
for (int ne = 0; ne < clientCmd.m_calculateInverseKinematicsArguments.m_numEndEffectorLinkIndices; ne++)
{
int endEffectorLinkIndex = clientCmd.m_calculateInverseKinematicsArguments.m_endEffectorLinkIndices[ne];
validEndEffectorLinkIndices = validEndEffectorLinkIndices && (endEffectorLinkIndex < bodyHandle->m_multiBody->getNumLinks());
btVector3 targetPosWorld(clientCmd.m_calculateInverseKinematicsArguments.m_targetPositions[ne * 3 + 0],
clientCmd.m_calculateInverseKinematicsArguments.m_targetPositions[ne * 3 + 1],
clientCmd.m_calculateInverseKinematicsArguments.m_targetPositions[ne * 3 + 2]);
btQuaternion targetOrnWorld(clientCmd.m_calculateInverseKinematicsArguments.m_targetOrientation[ne * 4 + 0],
clientCmd.m_calculateInverseKinematicsArguments.m_targetOrientation[ne * 4 + 1],
clientCmd.m_calculateInverseKinematicsArguments.m_targetOrientation[ne * 4 + 2],
clientCmd.m_calculateInverseKinematicsArguments.m_targetOrientation[ne * 4 + 3]);
btTransform targetBaseCoord;
if (clientCmd.m_updateFlags & IK_HAS_CURRENT_JOINT_POSITIONS)
{
targetBaseCoord.setOrigin(targetPosWorld);
targetBaseCoord.setRotation(targetOrnWorld);
}
else
{
btTransform targetWorld;
targetWorld.setOrigin(targetPosWorld);
targetWorld.setRotation(targetOrnWorld);
btTransform tr = bodyHandle->m_multiBody->getBaseWorldTransform();
targetBaseCoord = tr.inverse() * targetWorld;
}
btVector3DoubleData targetPosBaseCoord;
btQuaternionDoubleData targetOrnBaseCoord;
targetBaseCoord.getOrigin().serializeDouble(targetPosBaseCoord);
targetBaseCoord.getRotation().serializeDouble(targetOrnBaseCoord);
endEffectorTargetWorldPositions.push_back(targetPosBaseCoord.m_floats[0]);
endEffectorTargetWorldPositions.push_back(targetPosBaseCoord.m_floats[1]);
endEffectorTargetWorldPositions.push_back(targetPosBaseCoord.m_floats[2]);
endEffectorTargetWorldOrientations.push_back(targetOrnBaseCoord.m_floats[0]);
endEffectorTargetWorldOrientations.push_back(targetOrnBaseCoord.m_floats[1]);
endEffectorTargetWorldOrientations.push_back(targetOrnBaseCoord.m_floats[2]);
endEffectorTargetWorldOrientations.push_back(targetOrnBaseCoord.m_floats[3]);
}
for (int i = 0; i < numIterations && currentDiff > residualThreshold; i++)
{
BT_PROFILE("InverseKinematics1Step");
if (ikHelperPtr && validEndEffectorLinkIndices)
{
jacobian_linear.resize(clientCmd.m_calculateInverseKinematicsArguments.m_numEndEffectorLinkIndices * 3 * numDofs);
jacobian_angular.resize(clientCmd.m_calculateInverseKinematicsArguments.m_numEndEffectorLinkIndices * 3 * numDofs);
int jacSize = 0;
btInverseDynamics::MultiBodyTree* tree = m_data->findOrCreateTree(bodyHandle->m_multiBody);
q_current.resize(numDofs);
if (tree && ((numDofs + baseDofs) == tree->numDoFs()))
{
btInverseDynamics::vec3 world_origin;
btInverseDynamics::mat33 world_rot;
jacSize = jacobian_linear.size();
// Set jacobian value
int DofIndex = 0;
for (int i = 0; i < bodyHandle->m_multiBody->getNumLinks(); ++i)
{
if (bodyHandle->m_multiBody->getLink(i).m_jointType >= 0 && bodyHandle->m_multiBody->getLink(i).m_jointType <= 2)
{
// 0, 1, 2 represent revolute, prismatic, and spherical joint types respectively. Skip the fixed joints.
double curPos = startingPositions[DofIndex];
q_current[DofIndex] = curPos;
q[DofIndex + baseDofs] = curPos;
qdot[DofIndex + baseDofs] = 0;
nu[DofIndex + baseDofs] = 0;
DofIndex++;
}
} // Set the gravity to correspond to the world gravity
btInverseDynamics::vec3 id_grav(m_data->m_dynamicsWorld->getGravity());
{
BT_PROFILE("calculateInverseDynamics");
if (-1 != tree->setGravityInWorldFrame(id_grav) &&
-1 != tree->calculateInverseDynamics(q, qdot, nu, &joint_force))
{
tree->calculateJacobians(q);
btInverseDynamics::mat3x jac_t(3, numDofs + baseDofs);
btInverseDynamics::mat3x jac_r(3, numDofs + baseDofs);
currentDiff = 0;
endEffectorCurrentWorldPositions.resize(0);
endEffectorCurrentWorldPositions.reserve(clientCmd.m_calculateInverseKinematicsArguments.m_numEndEffectorLinkIndices * 3);
for (int ne = 0; ne < clientCmd.m_calculateInverseKinematicsArguments.m_numEndEffectorLinkIndices; ne++)
{
int endEffectorLinkIndex2 = clientCmd.m_calculateInverseKinematicsArguments.m_endEffectorLinkIndices[ne];
// Note that inverse dynamics uses zero-based indexing of bodies, not starting from -1 for the base link.
tree->getBodyJacobianTrans(endEffectorLinkIndex2 + 1, &jac_t);
tree->getBodyJacobianRot(endEffectorLinkIndex2 + 1, &jac_r);
//calculatePositionKinematics is already done inside calculateInverseDynamics
tree->getBodyOrigin(endEffectorLinkIndex2 + 1, &world_origin);
tree->getBodyTransform(endEffectorLinkIndex2 + 1, &world_rot);
for (int i = 0; i < 3; ++i)
{
for (int j = 0; j < numDofs; ++j)
{
jacobian_linear[(ne * 3 + i) * numDofs + j] = jac_t(i, (baseDofs + j));
jacobian_angular[(ne * 3 + i) * numDofs + j] = jac_r(i, (baseDofs + j));
}
}
endEffectorCurrentWorldPositions.push_back(world_origin[0]);
endEffectorCurrentWorldPositions.push_back(world_origin[1]);
endEffectorCurrentWorldPositions.push_back(world_origin[2]);
btInverseDynamics::vec3 targetPos(btVector3(endEffectorTargetWorldPositions[ne * 3 + 0],
endEffectorTargetWorldPositions[ne * 3 + 1],
endEffectorTargetWorldPositions[ne * 3 + 2]));
//diff
currentDiff = btMax(currentDiff, (world_origin - targetPos).length());
}
}
}
q_new.resize(numDofs);
int ikMethod = 0;
if ((clientCmd.m_updateFlags & IK_HAS_TARGET_ORIENTATION) && (clientCmd.m_updateFlags & IK_HAS_NULL_SPACE_VELOCITY))
{
//Nullspace task only works with DLS now. TODO: add nullspace task to SDLS.
ikMethod = IK2_VEL_DLS_WITH_ORIENTATION_NULLSPACE;
}
else if (clientCmd.m_updateFlags & IK_HAS_TARGET_ORIENTATION)
{
if (clientCmd.m_updateFlags & IK_SDLS)
{
ikMethod = IK2_VEL_SDLS_WITH_ORIENTATION;
}
else
{
ikMethod = IK2_VEL_DLS_WITH_ORIENTATION;
}
}
else if (clientCmd.m_updateFlags & IK_HAS_NULL_SPACE_VELOCITY)
{
//Nullspace task only works with DLS now. TODO: add nullspace task to SDLS.
ikMethod = IK2_VEL_DLS_WITH_NULLSPACE;
}
else
{
if (clientCmd.m_updateFlags & IK_SDLS)
{
ikMethod = IK2_VEL_SDLS;
}
else
{
ikMethod = IK2_VEL_DLS;
;
}
}
if (clientCmd.m_updateFlags & IK_HAS_NULL_SPACE_VELOCITY)
{
lower_limit.resize(numDofs);
upper_limit.resize(numDofs);
joint_range.resize(numDofs);
rest_pose.resize(numDofs);
for (int i = 0; i < numDofs; ++i)
{
lower_limit[i] = clientCmd.m_calculateInverseKinematicsArguments.m_lowerLimit[i];
upper_limit[i] = clientCmd.m_calculateInverseKinematicsArguments.m_upperLimit[i];
joint_range[i] = clientCmd.m_calculateInverseKinematicsArguments.m_jointRange[i];
rest_pose[i] = clientCmd.m_calculateInverseKinematicsArguments.m_restPose[i];
}
{
BT_PROFILE("computeNullspaceVel");
ikHelperPtr->computeNullspaceVel(numDofs, &q_current[0], &lower_limit[0], &upper_limit[0], &joint_range[0], &rest_pose[0]);
}
}
//btTransform endEffectorTransformWorld = bodyHandle->m_multiBody->getLink(endEffectorLinkIndex).m_cachedWorldTransform * bodyHandle->m_linkLocalInertialFrames[endEffectorLinkIndex].inverse();
btVector3DoubleData endEffectorWorldPosition;
btQuaternionDoubleData endEffectorWorldOrientation;
//get the position from the inverse dynamics (based on q) instead of endEffectorTransformWorld
btVector3 endEffectorPosWorldOrg = world_origin;
btQuaternion endEffectorOriWorldOrg;
world_rot.getRotation(endEffectorOriWorldOrg);
btTransform endEffectorBaseCoord;
endEffectorBaseCoord.setOrigin(endEffectorPosWorldOrg);
endEffectorBaseCoord.setRotation(endEffectorOriWorldOrg);
//don't need the next two lines
//btTransform linkInertiaInv = bodyHandle->m_linkLocalInertialFrames[endEffectorLinkIndex].inverse();
//endEffectorBaseCoord = endEffectorBaseCoord * linkInertiaInv;
//btTransform tr = bodyHandle->m_multiBody->getBaseWorldTransform();
//endEffectorBaseCoord = tr.inverse()*endEffectorTransformWorld;
//endEffectorBaseCoord = tr.inverse()*endEffectorTransformWorld;
btQuaternion endEffectorOriBaseCoord = endEffectorBaseCoord.getRotation();
//btVector4 endEffectorOri(endEffectorOriBaseCoord.x(), endEffectorOriBaseCoord.y(), endEffectorOriBaseCoord.z(), endEffectorOriBaseCoord.w());
endEffectorBaseCoord.getOrigin().serializeDouble(endEffectorWorldPosition);
endEffectorBaseCoord.getRotation().serializeDouble(endEffectorWorldOrientation);
// Set joint damping coefficents. A small default
// damping constant is added to prevent singularity
// with pseudo inverse. The user can set joint damping
// coefficients differently for each joint. The larger
// the damping coefficient is, the less we rely on
// this joint to achieve the IK target.
btAlignedObjectArray<double> joint_damping;
joint_damping.resize(numDofs, 0.5);
if (clientCmd.m_updateFlags & IK_HAS_JOINT_DAMPING)
{
for (int i = 0; i < numDofs; ++i)
{
joint_damping[i] = clientCmd.m_calculateInverseKinematicsArguments.m_jointDamping[i];
}
}
ikHelperPtr->setDampingCoeff(numDofs, &joint_damping[0]);
double targetDampCoeff[6] = {1.0, 1.0, 1.0, 1.0, 1.0, 1.0};
bool performedIK = false;
if (clientCmd.m_calculateInverseKinematicsArguments.m_numEndEffectorLinkIndices == 1)
{
BT_PROFILE("computeIK");
ikHelperPtr->computeIK(&endEffectorTargetWorldPositions[0],
&endEffectorTargetWorldOrientations[0],
endEffectorWorldPosition.m_floats, endEffectorWorldOrientation.m_floats,
&q_current[0],
numDofs, clientCmd.m_calculateInverseKinematicsArguments.m_endEffectorLinkIndices[0],
&q_new[0], ikMethod, &jacobian_linear[0], &jacobian_angular[0], jacSize * 2, targetDampCoeff);
performedIK = true;
}
else
{
if (clientCmd.m_calculateInverseKinematicsArguments.m_numEndEffectorLinkIndices > 1)
{
ikHelperPtr->computeIK2(&endEffectorTargetWorldPositions[0],
&endEffectorCurrentWorldPositions[0],
clientCmd.m_calculateInverseKinematicsArguments.m_numEndEffectorLinkIndices,
//endEffectorWorldOrientation.m_floats,
&q_current[0],
numDofs,
&q_new[0], ikMethod, &jacobian_linear[0], targetDampCoeff);
performedIK = true;
}
}
if (performedIK)
{
serverCmd.m_inverseKinematicsResultArgs.m_bodyUniqueId = clientCmd.m_calculateInverseDynamicsArguments.m_bodyUniqueId;
for (int i = 0; i < numDofs; i++)
{
serverCmd.m_inverseKinematicsResultArgs.m_jointPositions[i] = q_new[i];
}
serverCmd.m_inverseKinematicsResultArgs.m_dofCount = numDofs;
serverCmd.m_type = CMD_CALCULATE_INVERSE_KINEMATICS_COMPLETED;
for (int i = 0; i < numDofs; i++)
{
startingPositions[i] = q_new[i];
}
}
}
}
}
}
return hasStatus;
}
// PyModule_AddIntConstant(m, "GEOM_SPHERE", GEOM_SPHERE);
// PyModule_AddIntConstant(m, "GEOM_BOX", GEOM_BOX);
// PyModule_AddIntConstant(m, "GEOM_CYLINDER", GEOM_CYLINDER);
// PyModule_AddIntConstant(m, "GEOM_MESH", GEOM_MESH);
// PyModule_AddIntConstant(m, "GEOM_PLANE", GEOM_PLANE);
// PyModule_AddIntConstant(m, "GEOM_CAPSULE", GEOM_CAPSULE);
int PhysicsServerCommandProcessor::extractCollisionShapes(const btCollisionShape* colShape, const btTransform& transform, b3CollisionShapeData* collisionShapeBuffer, int maxCollisionShapes)
{
if (maxCollisionShapes <= 0)
{
b3Warning("No space in buffer");
return 0;
}
int numConverted = 0;
collisionShapeBuffer[0].m_localCollisionFrame[0] = transform.getOrigin()[0];
collisionShapeBuffer[0].m_localCollisionFrame[1] = transform.getOrigin()[1];
collisionShapeBuffer[0].m_localCollisionFrame[2] = transform.getOrigin()[2];
collisionShapeBuffer[0].m_localCollisionFrame[3] = transform.getRotation()[0];
collisionShapeBuffer[0].m_localCollisionFrame[4] = transform.getRotation()[1];
collisionShapeBuffer[0].m_localCollisionFrame[5] = transform.getRotation()[2];
collisionShapeBuffer[0].m_localCollisionFrame[6] = transform.getRotation()[3];
collisionShapeBuffer[0].m_meshAssetFileName[0] = 0;
switch (colShape->getShapeType())
{
case MULTI_SPHERE_SHAPE_PROXYTYPE:
{
btCapsuleShapeZ* capsule = (btCapsuleShapeZ*)colShape;
collisionShapeBuffer[0].m_collisionGeometryType = GEOM_CAPSULE;
collisionShapeBuffer[0].m_dimensions[0] = 2. * capsule->getHalfHeight();
collisionShapeBuffer[0].m_dimensions[1] = capsule->getRadius();
collisionShapeBuffer[0].m_dimensions[2] = 0;
numConverted++;
break;
break;
}
case STATIC_PLANE_PROXYTYPE:
{
btStaticPlaneShape* plane = (btStaticPlaneShape*)colShape;
collisionShapeBuffer[0].m_collisionGeometryType = GEOM_PLANE;
collisionShapeBuffer[0].m_dimensions[0] = plane->getPlaneNormal()[0];
collisionShapeBuffer[0].m_dimensions[1] = plane->getPlaneNormal()[1];
collisionShapeBuffer[0].m_dimensions[2] = plane->getPlaneNormal()[2];
numConverted += 1;
break;
}
case TRIANGLE_MESH_SHAPE_PROXYTYPE:
case SCALED_TRIANGLE_MESH_SHAPE_PROXYTYPE:
case CONVEX_HULL_SHAPE_PROXYTYPE:
{
UrdfCollision* urdfCol = m_data->m_bulletCollisionShape2UrdfCollision.find(colShape);
if (urdfCol && (urdfCol->m_geometry.m_type == URDF_GEOM_MESH))
{
collisionShapeBuffer[0].m_collisionGeometryType = GEOM_MESH;
collisionShapeBuffer[0].m_dimensions[0] = urdfCol->m_geometry.m_meshScale[0];
collisionShapeBuffer[0].m_dimensions[1] = urdfCol->m_geometry.m_meshScale[1];
collisionShapeBuffer[0].m_dimensions[2] = urdfCol->m_geometry.m_meshScale[2];
strcpy(collisionShapeBuffer[0].m_meshAssetFileName, urdfCol->m_geometry.m_meshFileName.c_str());
numConverted += 1;
}
else
{
collisionShapeBuffer[0].m_collisionGeometryType = GEOM_MESH;
sprintf(collisionShapeBuffer[0].m_meshAssetFileName, "unknown_file");
collisionShapeBuffer[0].m_dimensions[0] = 1;
collisionShapeBuffer[0].m_dimensions[1] = 1;
collisionShapeBuffer[0].m_dimensions[2] = 1;
numConverted++;
}
break;
}
case CAPSULE_SHAPE_PROXYTYPE:
{
btCapsuleShapeZ* capsule = (btCapsuleShapeZ*)colShape;
collisionShapeBuffer[0].m_collisionGeometryType = GEOM_CAPSULE;
collisionShapeBuffer[0].m_dimensions[0] = 2. * capsule->getHalfHeight();
collisionShapeBuffer[0].m_dimensions[1] = capsule->getRadius();
collisionShapeBuffer[0].m_dimensions[2] = 0;
numConverted++;
break;
}
case CYLINDER_SHAPE_PROXYTYPE:
{
btCylinderShapeZ* cyl = (btCylinderShapeZ*)colShape;
collisionShapeBuffer[0].m_collisionGeometryType = GEOM_CYLINDER;
collisionShapeBuffer[0].m_dimensions[0] = 2. * cyl->getHalfExtentsWithMargin().getZ();
collisionShapeBuffer[0].m_dimensions[1] = cyl->getHalfExtentsWithMargin().getX();
collisionShapeBuffer[0].m_dimensions[2] = 0;
numConverted++;
break;
}
case BOX_SHAPE_PROXYTYPE:
{
btBoxShape* box = (btBoxShape*)colShape;
btVector3 halfExtents = box->getHalfExtentsWithMargin();
collisionShapeBuffer[0].m_collisionGeometryType = GEOM_BOX;
collisionShapeBuffer[0].m_dimensions[0] = 2. * halfExtents[0];
collisionShapeBuffer[0].m_dimensions[1] = 2. * halfExtents[1];
collisionShapeBuffer[0].m_dimensions[2] = 2. * halfExtents[2];
numConverted++;
break;
}
case SPHERE_SHAPE_PROXYTYPE:
{
btSphereShape* sphere = (btSphereShape*)colShape;
collisionShapeBuffer[0].m_collisionGeometryType = GEOM_SPHERE;
collisionShapeBuffer[0].m_dimensions[0] = sphere->getRadius();
collisionShapeBuffer[0].m_dimensions[1] = sphere->getRadius();
collisionShapeBuffer[0].m_dimensions[2] = sphere->getRadius();
numConverted++;
break;
}
case COMPOUND_SHAPE_PROXYTYPE:
{
//it could be a compound mesh from a wavefront OBJ, check it
UrdfCollision* urdfCol = m_data->m_bulletCollisionShape2UrdfCollision.find(colShape);
if (urdfCol && (urdfCol->m_geometry.m_type == URDF_GEOM_MESH))
{
collisionShapeBuffer[0].m_collisionGeometryType = GEOM_MESH;
collisionShapeBuffer[0].m_dimensions[0] = urdfCol->m_geometry.m_meshScale[0];
collisionShapeBuffer[0].m_dimensions[1] = urdfCol->m_geometry.m_meshScale[1];
collisionShapeBuffer[0].m_dimensions[2] = urdfCol->m_geometry.m_meshScale[2];
strcpy(collisionShapeBuffer[0].m_meshAssetFileName, urdfCol->m_geometry.m_meshFileName.c_str());
numConverted += 1;
}
else
{
//recurse, accumulate childTransform
btCompoundShape* compound = (btCompoundShape*)colShape;
for (int i = 0; i < compound->getNumChildShapes(); i++)
{
btTransform childTrans = transform * compound->getChildTransform(i);
int remain = maxCollisionShapes - numConverted;
int converted = extractCollisionShapes(compound->getChildShape(i), childTrans, &collisionShapeBuffer[numConverted], remain);
numConverted += converted;
}
}
break;
}
default:
{
b3Warning("Unexpected collision shape type in PhysicsServerCommandProcessor::extractCollisionShapes");
}
};
return numConverted;
}
bool PhysicsServerCommandProcessor::processRequestCollisionShapeInfoCommand(const struct SharedMemoryCommand& clientCmd, struct SharedMemoryStatus& serverStatusOut, char* bufferServerToClient, int bufferSizeInBytes)
{
bool hasStatus = true;
BT_PROFILE("CMD_REQUEST_COLLISION_SHAPE_INFO");
SharedMemoryStatus& serverCmd = serverStatusOut;
serverCmd.m_type = CMD_COLLISION_SHAPE_INFO_FAILED;
int bodyUniqueId = clientCmd.m_requestCollisionShapeDataArguments.m_bodyUniqueId;
int linkIndex = clientCmd.m_requestCollisionShapeDataArguments.m_linkIndex;
InternalBodyHandle* bodyHandle = m_data->m_bodyHandles.getHandle(bodyUniqueId);
if (bodyHandle)
{
if (bodyHandle->m_multiBody)
{
b3CollisionShapeData* collisionShapeStoragePtr = (b3CollisionShapeData*)bufferServerToClient;
collisionShapeStoragePtr->m_objectUniqueId = bodyUniqueId;
collisionShapeStoragePtr->m_linkIndex = linkIndex;
int totalBytesPerObject = sizeof(b3CollisionShapeData);
int maxNumColObjects = bufferSizeInBytes / totalBytesPerObject - 1;
btTransform childTrans;
childTrans.setIdentity();
serverCmd.m_sendCollisionShapeArgs.m_bodyUniqueId = bodyUniqueId;
serverCmd.m_sendCollisionShapeArgs.m_linkIndex = linkIndex;
if (linkIndex == -1)
{
if (bodyHandle->m_multiBody->getBaseCollider())
{
//extract shape info from base collider
int numConvertedCollisionShapes = extractCollisionShapes(bodyHandle->m_multiBody->getBaseCollider()->getCollisionShape(), childTrans, collisionShapeStoragePtr, maxNumColObjects);
serverCmd.m_numDataStreamBytes = numConvertedCollisionShapes * sizeof(b3CollisionShapeData);
serverCmd.m_sendCollisionShapeArgs.m_numCollisionShapes = numConvertedCollisionShapes;
serverCmd.m_type = CMD_COLLISION_SHAPE_INFO_COMPLETED;
}
}
else
{
if (linkIndex >= 0 && linkIndex < bodyHandle->m_multiBody->getNumLinks() && bodyHandle->m_multiBody->getLinkCollider(linkIndex))
{
int numConvertedCollisionShapes = extractCollisionShapes(bodyHandle->m_multiBody->getLinkCollider(linkIndex)->getCollisionShape(), childTrans, collisionShapeStoragePtr, maxNumColObjects);
serverCmd.m_numDataStreamBytes = numConvertedCollisionShapes * sizeof(b3CollisionShapeData);
serverCmd.m_sendCollisionShapeArgs.m_numCollisionShapes = numConvertedCollisionShapes;
serverCmd.m_type = CMD_COLLISION_SHAPE_INFO_COMPLETED;
}
}
}
}
return hasStatus;
}
bool PhysicsServerCommandProcessor::processRequestVisualShapeInfoCommand(const struct SharedMemoryCommand& clientCmd, struct SharedMemoryStatus& serverStatusOut, char* bufferServerToClient, int bufferSizeInBytes)
{
bool hasStatus = true;
BT_PROFILE("CMD_REQUEST_VISUAL_SHAPE_INFO");
SharedMemoryStatus& serverCmd = serverStatusOut;
serverCmd.m_type = CMD_VISUAL_SHAPE_INFO_FAILED;
//retrieve the visual shape information for a specific body
if (m_data->m_pluginManager.getRenderInterface())
{
int totalNumVisualShapes = m_data->m_pluginManager.getRenderInterface()->getNumVisualShapes(clientCmd.m_requestVisualShapeDataArguments.m_bodyUniqueId);
//int totalBytesPerVisualShape = sizeof (b3VisualShapeData);
//int visualShapeStorage = bufferSizeInBytes / totalBytesPerVisualShape - 1;
//set serverCmd.m_sendVisualShapeArgs when totalNumVisualShapes is zero
if (totalNumVisualShapes == 0)
{
serverCmd.m_sendVisualShapeArgs.m_numRemainingVisualShapes = 0;
serverCmd.m_sendVisualShapeArgs.m_numVisualShapesCopied = 0;
serverCmd.m_sendVisualShapeArgs.m_startingVisualShapeIndex = clientCmd.m_requestVisualShapeDataArguments.m_startingVisualShapeIndex;
serverCmd.m_sendVisualShapeArgs.m_bodyUniqueId = clientCmd.m_requestVisualShapeDataArguments.m_bodyUniqueId;
serverCmd.m_numDataStreamBytes = sizeof(b3VisualShapeData) * serverCmd.m_sendVisualShapeArgs.m_numVisualShapesCopied;
serverCmd.m_type = CMD_VISUAL_SHAPE_INFO_COMPLETED;
}
else
{
b3VisualShapeData* visualShapeStoragePtr = (b3VisualShapeData*)bufferServerToClient;
int remain = totalNumVisualShapes - clientCmd.m_requestVisualShapeDataArguments.m_startingVisualShapeIndex;
int shapeIndex = clientCmd.m_requestVisualShapeDataArguments.m_startingVisualShapeIndex;
int success = m_data->m_pluginManager.getRenderInterface()->getVisualShapesData(clientCmd.m_requestVisualShapeDataArguments.m_bodyUniqueId,
shapeIndex,
visualShapeStoragePtr);
if (success)
{
//find the matching texture unique ids.
if (visualShapeStoragePtr->m_tinyRendererTextureId >= 0)
{
b3AlignedObjectArray<int> usedHandles;
m_data->m_textureHandles.getUsedHandles(usedHandles);
for (int i = 0; i < usedHandles.size(); i++)
{
int texHandle = usedHandles[i];
InternalTextureHandle* texH = m_data->m_textureHandles.getHandle(texHandle);
if (texH && (texH->m_tinyRendererTextureId == visualShapeStoragePtr->m_tinyRendererTextureId))
{
visualShapeStoragePtr->m_openglTextureId = texH->m_openglTextureId;
visualShapeStoragePtr->m_textureUniqueId = texHandle;
}
}
}
serverCmd.m_sendVisualShapeArgs.m_numRemainingVisualShapes = remain - 1;
serverCmd.m_sendVisualShapeArgs.m_numVisualShapesCopied = 1;
serverCmd.m_sendVisualShapeArgs.m_startingVisualShapeIndex = clientCmd.m_requestVisualShapeDataArguments.m_startingVisualShapeIndex;
serverCmd.m_sendVisualShapeArgs.m_bodyUniqueId = clientCmd.m_requestVisualShapeDataArguments.m_bodyUniqueId;
serverCmd.m_numDataStreamBytes = sizeof(b3VisualShapeData) * serverCmd.m_sendVisualShapeArgs.m_numVisualShapesCopied;
serverCmd.m_type = CMD_VISUAL_SHAPE_INFO_COMPLETED;
}
else
{
b3Warning("failed to get shape info");
}
}
}
return hasStatus;
}
bool PhysicsServerCommandProcessor::processUpdateVisualShapeCommand(const struct SharedMemoryCommand& clientCmd, struct SharedMemoryStatus& serverStatusOut, char* bufferServerToClient, int bufferSizeInBytes)
{
bool hasStatus = true;
BT_PROFILE("CMD_UPDATE_VISUAL_SHAPE");
SharedMemoryStatus& serverCmd = serverStatusOut;
serverCmd.m_type = CMD_VISUAL_SHAPE_UPDATE_FAILED;
InternalTextureHandle* texHandle = 0;
if (clientCmd.m_updateFlags & CMD_UPDATE_VISUAL_SHAPE_TEXTURE)
{
if (clientCmd.m_updateVisualShapeDataArguments.m_textureUniqueId >= 0)
{
texHandle = m_data->m_textureHandles.getHandle(clientCmd.m_updateVisualShapeDataArguments.m_textureUniqueId);
}
if (clientCmd.m_updateVisualShapeDataArguments.m_textureUniqueId >= -1)
{
if (texHandle)
{
if (m_data->m_pluginManager.getRenderInterface())
{
m_data->m_pluginManager.getRenderInterface()->changeShapeTexture(clientCmd.m_updateVisualShapeDataArguments.m_bodyUniqueId,
clientCmd.m_updateVisualShapeDataArguments.m_jointIndex,
clientCmd.m_updateVisualShapeDataArguments.m_shapeIndex,
texHandle->m_tinyRendererTextureId);
}
}
else
{
m_data->m_pluginManager.getRenderInterface()->changeShapeTexture(clientCmd.m_updateVisualShapeDataArguments.m_bodyUniqueId,
clientCmd.m_updateVisualShapeDataArguments.m_jointIndex,
clientCmd.m_updateVisualShapeDataArguments.m_shapeIndex,-1);
}
}
}
{
int bodyUniqueId = clientCmd.m_updateVisualShapeDataArguments.m_bodyUniqueId;
int linkIndex = clientCmd.m_updateVisualShapeDataArguments.m_jointIndex;
InternalBodyHandle* bodyHandle = m_data->m_bodyHandles.getHandle(bodyUniqueId);
if (bodyHandle)
{
if (bodyHandle->m_multiBody)
{
if (linkIndex == -1)
{
if (bodyHandle->m_multiBody->getBaseCollider())
{
int graphicsIndex = bodyHandle->m_multiBody->getBaseCollider()->getUserIndex();
if (clientCmd.m_updateFlags & CMD_UPDATE_VISUAL_SHAPE_TEXTURE)
{
int shapeIndex = m_data->m_guiHelper->getShapeIndexFromInstance(graphicsIndex);
if (texHandle)
{
m_data->m_guiHelper->replaceTexture(shapeIndex, texHandle->m_openglTextureId);
}
else
{
m_data->m_guiHelper->replaceTexture(shapeIndex, -1);
}
}
if (clientCmd.m_updateFlags & CMD_UPDATE_VISUAL_SHAPE_RGBA_COLOR)
{
if (m_data->m_pluginManager.getRenderInterface())
{
m_data->m_pluginManager.getRenderInterface()->changeRGBAColor(bodyUniqueId, linkIndex,
clientCmd.m_updateVisualShapeDataArguments.m_shapeIndex,
clientCmd.m_updateVisualShapeDataArguments.m_rgbaColor);
}
m_data->m_guiHelper->changeRGBAColor(graphicsIndex, clientCmd.m_updateVisualShapeDataArguments.m_rgbaColor);
}
if (clientCmd.m_updateFlags & CMD_UPDATE_VISUAL_SHAPE_SPECULAR_COLOR)
{
m_data->m_guiHelper->changeSpecularColor(graphicsIndex, clientCmd.m_updateVisualShapeDataArguments.m_specularColor);
}
}
}
else
{
if (linkIndex < bodyHandle->m_multiBody->getNumLinks())
{
if (bodyHandle->m_multiBody->getLink(linkIndex).m_collider)
{
int graphicsIndex = bodyHandle->m_multiBody->getLink(linkIndex).m_collider->getUserIndex();
if (clientCmd.m_updateFlags & CMD_UPDATE_VISUAL_SHAPE_TEXTURE)
{
int shapeIndex = m_data->m_guiHelper->getShapeIndexFromInstance(graphicsIndex);
if (texHandle)
{
m_data->m_guiHelper->replaceTexture(shapeIndex, texHandle->m_openglTextureId);
}
else
{
m_data->m_guiHelper->replaceTexture(shapeIndex, -1);
}
}
if (clientCmd.m_updateFlags & CMD_UPDATE_VISUAL_SHAPE_RGBA_COLOR)
{
if (m_data->m_pluginManager.getRenderInterface())
{
m_data->m_pluginManager.getRenderInterface()->changeRGBAColor(bodyUniqueId, linkIndex,
clientCmd.m_updateVisualShapeDataArguments.m_shapeIndex, clientCmd.m_updateVisualShapeDataArguments.m_rgbaColor);
}
m_data->m_guiHelper->changeRGBAColor(graphicsIndex, clientCmd.m_updateVisualShapeDataArguments.m_rgbaColor);
}
if (clientCmd.m_updateFlags & CMD_UPDATE_VISUAL_SHAPE_SPECULAR_COLOR)
{
m_data->m_guiHelper->changeSpecularColor(graphicsIndex, clientCmd.m_updateVisualShapeDataArguments.m_specularColor);
}
}
}
}
}
else
{
if (bodyHandle->m_rigidBody)
{
int graphicsIndex = bodyHandle->m_rigidBody->getUserIndex();
if (clientCmd.m_updateFlags & CMD_UPDATE_VISUAL_SHAPE_TEXTURE)
{
if (texHandle)
{
int shapeIndex = m_data->m_guiHelper->getShapeIndexFromInstance(graphicsIndex);
m_data->m_guiHelper->replaceTexture(shapeIndex, texHandle->m_openglTextureId);
}
}
if (clientCmd.m_updateFlags & CMD_UPDATE_VISUAL_SHAPE_RGBA_COLOR)
{
if (m_data->m_pluginManager.getRenderInterface())
{
m_data->m_pluginManager.getRenderInterface()->changeRGBAColor(bodyUniqueId, linkIndex,
clientCmd.m_updateVisualShapeDataArguments.m_shapeIndex, clientCmd.m_updateVisualShapeDataArguments.m_rgbaColor);
}
m_data->m_guiHelper->changeRGBAColor(graphicsIndex, clientCmd.m_updateVisualShapeDataArguments.m_rgbaColor);
}
if (clientCmd.m_updateFlags & CMD_UPDATE_VISUAL_SHAPE_SPECULAR_COLOR)
{
m_data->m_guiHelper->changeSpecularColor(graphicsIndex, clientCmd.m_updateVisualShapeDataArguments.m_specularColor);
}
}
#ifndef SKIP_SOFT_BODY_MULTI_BODY_DYNAMICS_WORLD
else if (bodyHandle->m_softBody)
{
int graphicsIndex = bodyHandle->m_softBody->getUserIndex();
if (clientCmd.m_updateFlags & CMD_UPDATE_VISUAL_SHAPE_TEXTURE)
{
int shapeIndex = m_data->m_guiHelper->getShapeIndexFromInstance(graphicsIndex);
if (texHandle)
{
m_data->m_guiHelper->replaceTexture(shapeIndex, texHandle->m_openglTextureId);
}
else
{
m_data->m_guiHelper->replaceTexture(shapeIndex, -1);
}
}
if (clientCmd.m_updateFlags & CMD_UPDATE_VISUAL_SHAPE_RGBA_COLOR)
{
if (m_data->m_pluginManager.getRenderInterface())
{
m_data->m_pluginManager.getRenderInterface()->changeRGBAColor(bodyUniqueId, linkIndex,
clientCmd.m_updateVisualShapeDataArguments.m_shapeIndex, clientCmd.m_updateVisualShapeDataArguments.m_rgbaColor);
}
m_data->m_guiHelper->changeRGBAColor(graphicsIndex, clientCmd.m_updateVisualShapeDataArguments.m_rgbaColor);
}
if (clientCmd.m_updateFlags & CMD_UPDATE_VISUAL_SHAPE_FLAGS)
{
if (m_data->m_pluginManager.getRenderInterface())
{
m_data->m_pluginManager.getRenderInterface()->changeInstanceFlags(bodyUniqueId, linkIndex,
clientCmd.m_updateVisualShapeDataArguments.m_shapeIndex,
clientCmd.m_updateVisualShapeDataArguments.m_flags);
}
m_data->m_guiHelper->changeInstanceFlags(graphicsIndex,
clientCmd.m_updateVisualShapeDataArguments.m_flags);
}
}
#endif
}
}
}
serverCmd.m_type = CMD_VISUAL_SHAPE_UPDATE_COMPLETED;
b3Notification notification;
notification.m_notificationType = VISUAL_SHAPE_CHANGED;
notification.m_visualShapeArgs.m_bodyUniqueId = clientCmd.m_updateVisualShapeDataArguments.m_bodyUniqueId;
notification.m_visualShapeArgs.m_linkIndex = clientCmd.m_updateVisualShapeDataArguments.m_jointIndex;
notification.m_visualShapeArgs.m_visualShapeIndex = clientCmd.m_updateVisualShapeDataArguments.m_shapeIndex;
m_data->m_pluginManager.addNotification(notification);
return hasStatus;
}
bool PhysicsServerCommandProcessor::processChangeTextureCommand(const struct SharedMemoryCommand& clientCmd, struct SharedMemoryStatus& serverStatusOut, char* bufferServerToClient, int bufferSizeInBytes)
{
bool hasStatus = true;
SharedMemoryStatus& serverCmd = serverStatusOut;
serverCmd.m_type = CMD_CHANGE_TEXTURE_COMMAND_FAILED;
InternalTextureHandle* texH = m_data->m_textureHandles.getHandle(clientCmd.m_changeTextureArgs.m_textureUniqueId);
if (texH)
{
int gltex = texH->m_openglTextureId;
m_data->m_guiHelper->changeTexture(gltex,
(const unsigned char*)bufferServerToClient, clientCmd.m_changeTextureArgs.m_width, clientCmd.m_changeTextureArgs.m_height);
serverCmd.m_type = CMD_CLIENT_COMMAND_COMPLETED;
}
return hasStatus;
}
bool PhysicsServerCommandProcessor::processLoadTextureCommand(const struct SharedMemoryCommand& clientCmd, struct SharedMemoryStatus& serverStatusOut, char* bufferServerToClient, int bufferSizeInBytes)
{
bool hasStatus = true;
BT_PROFILE("CMD_LOAD_TEXTURE");
SharedMemoryStatus& serverCmd = serverStatusOut;
serverCmd.m_type = CMD_LOAD_TEXTURE_FAILED;
char relativeFileName[1024];
char pathPrefix[1024];
CommonFileIOInterface* fileIO(m_data->m_pluginManager.getFileIOInterface());
if (fileIO->findResourcePath(clientCmd.m_loadTextureArguments.m_textureFileName, relativeFileName, 1024))
{
b3FileUtils::extractPath(relativeFileName, pathPrefix, 1024);
int texHandle = m_data->m_textureHandles.allocHandle();
InternalTextureHandle* texH = m_data->m_textureHandles.getHandle(texHandle);
if (texH)
{
texH->m_tinyRendererTextureId = -1;
texH->m_openglTextureId = -1;
int uid = -1;
if (m_data->m_pluginManager.getRenderInterface())
{
uid = m_data->m_pluginManager.getRenderInterface()->loadTextureFile(relativeFileName, fileIO);
}
if (uid >= 0)
{
texH->m_tinyRendererTextureId = uid;
}
{
int width, height, n;
unsigned char* imageData = 0;
CommonFileIOInterface* fileIO = m_data->m_pluginManager.getFileIOInterface();
if (fileIO)
{
b3AlignedObjectArray<char> buffer;
buffer.reserve(1024);
int fileId = fileIO->fileOpen(relativeFileName, "rb");
if (fileId >= 0)
{
int size = fileIO->getFileSize(fileId);
if (size > 0)
{
buffer.resize(size);
int actual = fileIO->fileRead(fileId, &buffer[0], size);
if (actual != size)
{
b3Warning("image filesize mismatch!\n");
buffer.resize(0);
}
}
fileIO->fileClose(fileId);
}
if (buffer.size())
{
imageData = stbi_load_from_memory((const unsigned char*)&buffer[0], buffer.size(), &width, &height, &n, 3);
}
}
else
{
imageData = stbi_load(relativeFileName, &width, &height, &n, 3);
}
if (imageData)
{
texH->m_openglTextureId = m_data->m_guiHelper->registerTexture(imageData, width, height);
m_data->m_allocatedTexturesRequireFree.push_back(imageData);
}
else
{
b3Warning("Unsupported texture image format [%s]\n", relativeFileName);
}
}
serverCmd.m_loadTextureResultArguments.m_textureUniqueId = texHandle;
serverCmd.m_type = CMD_LOAD_TEXTURE_COMPLETED;
}
}
else
{
serverCmd.m_type = CMD_LOAD_TEXTURE_FAILED;
}
return hasStatus;
}
bool PhysicsServerCommandProcessor::processSaveStateCommand(const struct SharedMemoryCommand& clientCmd, struct SharedMemoryStatus& serverStatusOut, char* bufferServerToClient, int bufferSizeInBytes)
{
BT_PROFILE("CMD_SAVE_STATE");
bool hasStatus = true;
SharedMemoryStatus& serverCmd = serverStatusOut;
serverCmd.m_type = CMD_SAVE_STATE_FAILED;
btDefaultSerializer* ser = new btDefaultSerializer();
int currentFlags = ser->getSerializationFlags();
ser->setSerializationFlags(currentFlags | BT_SERIALIZE_CONTACT_MANIFOLDS);
m_data->m_dynamicsWorld->serialize(ser);
bParse::btBulletFile* bulletFile = new bParse::btBulletFile((char*)ser->getBufferPointer(), ser->getCurrentBufferSize());
bulletFile->parse(false);
if (bulletFile->ok())
{
serverCmd.m_type = CMD_SAVE_STATE_COMPLETED;
//re-use state if available
int reuseStateId = -1;
for (int i = 0; i < m_data->m_savedStates.size(); i++)
{
if (m_data->m_savedStates[i].m_bulletFile == 0)
{
reuseStateId = i;
break;
}
}
SaveStateData sd;
sd.m_bulletFile = bulletFile;
sd.m_serializer = ser;
if (reuseStateId >= 0)
{
serverCmd.m_saveStateResultArgs.m_stateId = reuseStateId;
m_data->m_savedStates[reuseStateId] = sd;
}
else
{
serverCmd.m_saveStateResultArgs.m_stateId = m_data->m_savedStates.size();
m_data->m_savedStates.push_back(sd);
}
}
return hasStatus;
}
bool PhysicsServerCommandProcessor::processRemoveStateCommand(const struct SharedMemoryCommand& clientCmd, struct SharedMemoryStatus& serverStatusOut, char* bufferServerToClient, int bufferSizeInBytes)
{
BT_PROFILE("CMD_REMOVE_STATE");
bool hasStatus = true;
SharedMemoryStatus& serverCmd = serverStatusOut;
serverCmd.m_type = CMD_REMOVE_STATE_FAILED;
if (clientCmd.m_loadStateArguments.m_stateId >= 0)
{
if (clientCmd.m_loadStateArguments.m_stateId < m_data->m_savedStates.size())
{
SaveStateData& sd = m_data->m_savedStates[clientCmd.m_loadStateArguments.m_stateId];
delete sd.m_bulletFile;
delete sd.m_serializer;
sd.m_bulletFile = 0;
sd.m_serializer = 0;
serverCmd.m_type = CMD_REMOVE_STATE_COMPLETED;
}
}
return hasStatus;
}
bool PhysicsServerCommandProcessor::processRestoreStateCommand(const struct SharedMemoryCommand& clientCmd, struct SharedMemoryStatus& serverStatusOut, char* bufferServerToClient, int bufferSizeInBytes)
{
BT_PROFILE("CMD_RESTORE_STATE");
bool hasStatus = true;
SharedMemoryStatus& serverCmd = serverStatusOut;
serverCmd.m_type = CMD_RESTORE_STATE_FAILED;
#ifndef USE_DISCRETE_DYNAMICS_WORLD
btMultiBodyWorldImporter* importer = new btMultiBodyWorldImporter(m_data->m_dynamicsWorld);
importer->setImporterFlags(eRESTORE_EXISTING_OBJECTS);
bool ok = false;
if (clientCmd.m_loadStateArguments.m_stateId >= 0)
{
if (clientCmd.m_loadStateArguments.m_stateId < m_data->m_savedStates.size())
{
bParse::btBulletFile* bulletFile = m_data->m_savedStates[clientCmd.m_loadStateArguments.m_stateId].m_bulletFile;
if (bulletFile)
{
ok = importer->convertAllObjects(bulletFile);
}
}
}
else
{
bool found = false;
char fileName[1024];
fileName[0] = 0;
CommonFileIOInterface* fileIO = m_data->m_pluginManager.getFileIOInterface();
b3AlignedObjectArray<char> buffer;
buffer.reserve(1024);
if (fileIO)
{
int fileId = -1;
found = fileIO->findResourcePath(clientCmd.m_fileArguments.m_fileName, fileName, 1024);
if (found)
{
fileId = fileIO->fileOpen(fileName, "rb");
}
if (fileId >= 0)
{
int size = fileIO->getFileSize(fileId);
if (size > 0)
{
buffer.resize(size);
int actual = fileIO->fileRead(fileId, &buffer[0], size);
if (actual != size)
{
b3Warning("image filesize mismatch!\n");
buffer.resize(0);
}
else
{
found = true;
}
}
fileIO->fileClose(fileId);
}
}
if (found && buffer.size())
{
ok = importer->loadFileFromMemory(&buffer[0], buffer.size());
}
else
{
b3Error("Error in restoreState: cannot load file %s\n", clientCmd.m_fileArguments.m_fileName);
}
}
delete importer;
if (ok)
{
serverCmd.m_type = CMD_RESTORE_STATE_COMPLETED;
}
#endif
return hasStatus;
}
bool PhysicsServerCommandProcessor::processLoadBulletCommand(const struct SharedMemoryCommand& clientCmd, struct SharedMemoryStatus& serverStatusOut, char* bufferServerToClient, int bufferSizeInBytes)
{
BT_PROFILE("CMD_LOAD_BULLET");
bool hasStatus = true;
SharedMemoryStatus& serverCmd = serverStatusOut;
serverCmd.m_type = CMD_BULLET_LOADING_FAILED;
#ifndef USE_DISCRETE_DYNAMICS_WORLD
//btBulletWorldImporter* importer = new btBulletWorldImporter(m_data->m_dynamicsWorld);
btMultiBodyWorldImporter* importer = new btMultiBodyWorldImporter(m_data->m_dynamicsWorld);
bool found = false;
CommonFileIOInterface* fileIO = m_data->m_pluginManager.getFileIOInterface();
b3AlignedObjectArray<char> buffer;
buffer.reserve(1024);
if (fileIO)
{
char fileName[1024];
int fileId = -1;
found = fileIO->findResourcePath(clientCmd.m_fileArguments.m_fileName, fileName, 1024);
if (found)
{
fileId = fileIO->fileOpen(fileName, "rb");
}
if (fileId >= 0)
{
int size = fileIO->getFileSize(fileId);
if (size > 0)
{
buffer.resize(size);
int actual = fileIO->fileRead(fileId, &buffer[0], size);
if (actual != size)
{
b3Warning("image filesize mismatch!\n");
buffer.resize(0);
}
else
{
found = true;
}
}
fileIO->fileClose(fileId);
}
}
if (found && buffer.size())
{
bool ok = importer->loadFileFromMemory(&buffer[0], buffer.size());
if (ok)
{
int numRb = importer->getNumRigidBodies();
serverStatusOut.m_sdfLoadedArgs.m_numBodies = 0;
serverStatusOut.m_sdfLoadedArgs.m_numUserConstraints = 0;
for (int i = 0; i < numRb; i++)
{
btCollisionObject* colObj = importer->getRigidBodyByIndex(i);
if (colObj)
{
btRigidBody* rb = btRigidBody::upcast(colObj);
if (rb)
{
int bodyUniqueId = m_data->m_bodyHandles.allocHandle();
InternalBodyHandle* bodyHandle = m_data->m_bodyHandles.getHandle(bodyUniqueId);
colObj->setUserIndex2(bodyUniqueId);
bodyHandle->m_rigidBody = rb;
if (serverStatusOut.m_sdfLoadedArgs.m_numBodies < MAX_SDF_BODIES)
{
serverStatusOut.m_sdfLoadedArgs.m_numBodies++;
serverStatusOut.m_sdfLoadedArgs.m_bodyUniqueIds[i] = bodyUniqueId;
}
b3Notification notification;
notification.m_notificationType = BODY_ADDED;
notification.m_bodyArgs.m_bodyUniqueId = bodyUniqueId;
m_data->m_pluginManager.addNotification(notification);
}
}
}
serverCmd.m_type = CMD_BULLET_LOADING_COMPLETED;
m_data->m_guiHelper->autogenerateGraphicsObjects(m_data->m_dynamicsWorld);
}
}
#endif
return hasStatus;
}
bool PhysicsServerCommandProcessor::processLoadMJCFCommand(const struct SharedMemoryCommand& clientCmd, struct SharedMemoryStatus& serverStatusOut, char* bufferServerToClient, int bufferSizeInBytes)
{
bool hasStatus = true;
BT_PROFILE("CMD_LOAD_MJCF");
SharedMemoryStatus& serverCmd = serverStatusOut;
serverCmd.m_type = CMD_MJCF_LOADING_FAILED;
const MjcfArgs& mjcfArgs = clientCmd.m_mjcfArguments;
if (m_data->m_verboseOutput)
{
b3Printf("Processed CMD_LOAD_MJCF:%s", mjcfArgs.m_mjcfFileName);
}
bool useMultiBody = (clientCmd.m_updateFlags & URDF_ARGS_USE_MULTIBODY) ? (mjcfArgs.m_useMultiBody != 0) : true;
int flags = CUF_USE_MJCF;
if (clientCmd.m_updateFlags & URDF_ARGS_HAS_CUSTOM_URDF_FLAGS)
{
flags |= clientCmd.m_mjcfArguments.m_flags;
}
bool completedOk = loadMjcf(mjcfArgs.m_mjcfFileName, bufferServerToClient, bufferSizeInBytes, useMultiBody, flags);
if (completedOk)
{
m_data->m_guiHelper->autogenerateGraphicsObjects(this->m_data->m_dynamicsWorld);
serverStatusOut.m_sdfLoadedArgs.m_numBodies = m_data->m_sdfRecentLoadedBodies.size();
serverStatusOut.m_sdfLoadedArgs.m_numUserConstraints = 0;
int maxBodies = btMin(MAX_SDF_BODIES, serverStatusOut.m_sdfLoadedArgs.m_numBodies);
for (int i = 0; i < maxBodies; i++)
{
serverStatusOut.m_sdfLoadedArgs.m_bodyUniqueIds[i] = m_data->m_sdfRecentLoadedBodies[i];
}
serverStatusOut.m_type = CMD_MJCF_LOADING_COMPLETED;
}
else
{
serverStatusOut.m_type = CMD_MJCF_LOADING_FAILED;
}
return hasStatus;
}
bool PhysicsServerCommandProcessor::processSaveBulletCommand(const struct SharedMemoryCommand& clientCmd, struct SharedMemoryStatus& serverStatusOut, char* bufferServerToClient, int bufferSizeInBytes)
{
bool hasStatus = true;
BT_PROFILE("CMD_SAVE_BULLET");
SharedMemoryStatus& serverCmd = serverStatusOut;
FILE* f = fopen(clientCmd.m_fileArguments.m_fileName, "wb");
if (f)
{
btDefaultSerializer* ser = new btDefaultSerializer();
int currentFlags = ser->getSerializationFlags();
ser->setSerializationFlags(currentFlags | BT_SERIALIZE_CONTACT_MANIFOLDS);
m_data->m_dynamicsWorld->serialize(ser);
fwrite(ser->getBufferPointer(), ser->getCurrentBufferSize(), 1, f);
fclose(f);
serverCmd.m_type = CMD_BULLET_SAVING_COMPLETED;
delete ser;
return hasStatus;
}
serverCmd.m_type = CMD_BULLET_SAVING_FAILED;
return hasStatus;
}
bool PhysicsServerCommandProcessor::processCommand(const struct SharedMemoryCommand& clientCmd, struct SharedMemoryStatus& serverStatusOut, char* bufferServerToClient, int bufferSizeInBytes)
{
// BT_PROFILE("processCommand");
int sz = sizeof(SharedMemoryStatus);
int sz2 = sizeof(SharedMemoryCommand);
bool hasStatus = false;
if (m_data->m_commandLogger)
{
m_data->m_commandLogger->logCommand(clientCmd);
}
serverStatusOut.m_type = CMD_INVALID_STATUS;
serverStatusOut.m_numDataStreamBytes = 0;
serverStatusOut.m_dataStream = 0;
//consume the command
switch (clientCmd.m_type)
{
case CMD_STATE_LOGGING:
{
hasStatus = processStateLoggingCommand(clientCmd, serverStatusOut, bufferServerToClient, bufferSizeInBytes);
break;
}
case CMD_SET_VR_CAMERA_STATE:
{
hasStatus = processSetVRCameraStateCommand(clientCmd, serverStatusOut, bufferServerToClient, bufferSizeInBytes);
break;
}
case CMD_REQUEST_VR_EVENTS_DATA:
{
hasStatus = processRequestVREventsCommand(clientCmd, serverStatusOut, bufferServerToClient, bufferSizeInBytes);
break;
};
case CMD_REQUEST_MOUSE_EVENTS_DATA:
{
hasStatus = processRequestMouseEventsCommand(clientCmd, serverStatusOut, bufferServerToClient, bufferSizeInBytes);
break;
};
case CMD_REQUEST_KEYBOARD_EVENTS_DATA:
{
hasStatus = processRequestKeyboardEventsCommand(clientCmd, serverStatusOut, bufferServerToClient, bufferSizeInBytes);
break;
};
case CMD_REQUEST_RAY_CAST_INTERSECTIONS:
{
hasStatus = processRequestRaycastIntersectionsCommand(clientCmd, serverStatusOut, bufferServerToClient, bufferSizeInBytes);
break;
};
case CMD_REQUEST_DEBUG_LINES:
{
hasStatus = processRequestDebugLinesCommand(clientCmd, serverStatusOut, bufferServerToClient, bufferSizeInBytes);
break;
}
case CMD_REQUEST_CAMERA_IMAGE_DATA:
{
hasStatus = processRequestCameraImageCommand(clientCmd, serverStatusOut, bufferServerToClient, bufferSizeInBytes);
break;
}
case CMD_SYNC_BODY_INFO:
{
hasStatus = processSyncBodyInfoCommand(clientCmd, serverStatusOut, bufferServerToClient, bufferSizeInBytes);
break;
}
case CMD_REQUEST_BODY_INFO:
{
hasStatus = processRequestBodyInfoCommand(clientCmd, serverStatusOut, bufferServerToClient, bufferSizeInBytes);
break;
}
case CMD_SAVE_WORLD:
{
hasStatus = processSaveWorldCommand(clientCmd, serverStatusOut, bufferServerToClient, bufferSizeInBytes);
break;
}
case CMD_LOAD_SDF:
{
hasStatus = processLoadSDFCommand(clientCmd, serverStatusOut, bufferServerToClient, bufferSizeInBytes);
break;
}
case CMD_CREATE_COLLISION_SHAPE:
{
hasStatus = processCreateCollisionShapeCommand(clientCmd, serverStatusOut, bufferServerToClient, bufferSizeInBytes);
break;
}
case CMD_CREATE_VISUAL_SHAPE:
{
hasStatus = processCreateVisualShapeCommand(clientCmd, serverStatusOut, bufferServerToClient, bufferSizeInBytes);
break;
}
case CMD_REQUEST_MESH_DATA:
{
hasStatus = processRequestMeshDataCommand(clientCmd, serverStatusOut, bufferServerToClient, bufferSizeInBytes);
break;
}
case CMD_RESET_MESH_DATA:
{
hasStatus = processResetMeshDataCommand(clientCmd, serverStatusOut, bufferServerToClient, bufferSizeInBytes);
break;
}
case CMD_CREATE_MULTI_BODY:
{
hasStatus = processCreateMultiBodyCommand(clientCmd, serverStatusOut, bufferServerToClient, bufferSizeInBytes);
break;
}
case CMD_SET_ADDITIONAL_SEARCH_PATH:
{
hasStatus = processSetAdditionalSearchPathCommand(clientCmd, serverStatusOut, bufferServerToClient, bufferSizeInBytes);
break;
}
case CMD_LOAD_URDF:
{
hasStatus = processLoadURDFCommand(clientCmd, serverStatusOut, bufferServerToClient, bufferSizeInBytes);
break;
}
case CMD_LOAD_SOFT_BODY:
{
hasStatus = processLoadSoftBodyCommand(clientCmd, serverStatusOut, bufferServerToClient, bufferSizeInBytes);
break;
}
case CMD_CREATE_SENSOR:
{
hasStatus = processCreateSensorCommand(clientCmd, serverStatusOut, bufferServerToClient, bufferSizeInBytes);
break;
}
case CMD_PROFILE_TIMING:
{
hasStatus = processProfileTimingCommand(clientCmd, serverStatusOut, bufferServerToClient, bufferSizeInBytes);
break;
}
case CMD_SEND_DESIRED_STATE:
{
hasStatus = processSendDesiredStateCommand(clientCmd, serverStatusOut, bufferServerToClient, bufferSizeInBytes);
break;
}
case CMD_REQUEST_COLLISION_INFO:
{
hasStatus = processRequestCollisionInfoCommand(clientCmd, serverStatusOut, bufferServerToClient, bufferSizeInBytes);
break;
}
case CMD_REQUEST_ACTUAL_STATE:
{
hasStatus = processRequestActualStateCommand(clientCmd, serverStatusOut, bufferServerToClient, bufferSizeInBytes);
break;
}
case CMD_STEP_FORWARD_SIMULATION:
{
hasStatus = processForwardDynamicsCommand(clientCmd, serverStatusOut, bufferServerToClient, bufferSizeInBytes);
break;
}
case CMD_PERFORM_COLLISION_DETECTION:
{
hasStatus = performCollisionDetectionCommand(clientCmd, serverStatusOut, bufferServerToClient, bufferSizeInBytes);
break;
}
case CMD_REQUEST_INTERNAL_DATA:
{
hasStatus = processRequestInternalDataCommand(clientCmd, serverStatusOut, bufferServerToClient, bufferSizeInBytes);
break;
};
case CMD_CHANGE_DYNAMICS_INFO:
{
hasStatus = processChangeDynamicsInfoCommand(clientCmd, serverStatusOut, bufferServerToClient, bufferSizeInBytes);
break;
};
case CMD_GET_DYNAMICS_INFO:
{
hasStatus = processGetDynamicsInfoCommand(clientCmd, serverStatusOut, bufferServerToClient, bufferSizeInBytes);
break;
}
case CMD_REQUEST_PHYSICS_SIMULATION_PARAMETERS:
{
hasStatus = processRequestPhysicsSimulationParametersCommand(clientCmd, serverStatusOut, bufferServerToClient, bufferSizeInBytes);
break;
}
case CMD_SEND_PHYSICS_SIMULATION_PARAMETERS:
{
hasStatus = processSendPhysicsParametersCommand(clientCmd, serverStatusOut, bufferServerToClient, bufferSizeInBytes);
break;
};
case CMD_INIT_POSE:
{
hasStatus = processInitPoseCommand(clientCmd, serverStatusOut, bufferServerToClient, bufferSizeInBytes);
break;
}
case CMD_RESET_SIMULATION:
{
hasStatus = processResetSimulationCommand(clientCmd, serverStatusOut, bufferServerToClient, bufferSizeInBytes);
break;
}
case CMD_CREATE_RIGID_BODY:
{
hasStatus = processCreateRigidBodyCommand(clientCmd, serverStatusOut, bufferServerToClient, bufferSizeInBytes);
break;
}
case CMD_CREATE_BOX_COLLISION_SHAPE:
{
//for backward compatibility, CMD_CREATE_BOX_COLLISION_SHAPE is the same as CMD_CREATE_RIGID_BODY
hasStatus = processCreateRigidBodyCommand(clientCmd, serverStatusOut, bufferServerToClient, bufferSizeInBytes);
break;
}
case CMD_PICK_BODY:
{
hasStatus = processPickBodyCommand(clientCmd, serverStatusOut, bufferServerToClient, bufferSizeInBytes);
break;
}
case CMD_MOVE_PICKED_BODY:
{
hasStatus = processMovePickedBodyCommand(clientCmd, serverStatusOut, bufferServerToClient, bufferSizeInBytes);
break;
}
case CMD_REMOVE_PICKING_CONSTRAINT_BODY:
{
hasStatus = processRemovePickingConstraintCommand(clientCmd, serverStatusOut, bufferServerToClient, bufferSizeInBytes);
break;
}
case CMD_REQUEST_AABB_OVERLAP:
{
hasStatus = processRequestAabbOverlapCommand(clientCmd, serverStatusOut, bufferServerToClient, bufferSizeInBytes);
break;
}
case CMD_REQUEST_OPENGL_VISUALIZER_CAMERA:
{
hasStatus = processRequestOpenGLVisualizeCameraCommand(clientCmd, serverStatusOut, bufferServerToClient, bufferSizeInBytes);
break;
}
case CMD_CONFIGURE_OPENGL_VISUALIZER:
{
hasStatus = processConfigureOpenGLVisualizerCommand(clientCmd, serverStatusOut, bufferServerToClient, bufferSizeInBytes);
break;
}
case CMD_REQUEST_CONTACT_POINT_INFORMATION:
{
hasStatus = processRequestContactpointInformationCommand(clientCmd, serverStatusOut, bufferServerToClient, bufferSizeInBytes);
break;
}
case CMD_CALCULATE_INVERSE_DYNAMICS:
{
hasStatus = processInverseDynamicsCommand(clientCmd, serverStatusOut, bufferServerToClient, bufferSizeInBytes);
break;
}
case CMD_CALCULATE_JACOBIAN:
{
hasStatus = processCalculateJacobianCommand(clientCmd, serverStatusOut, bufferServerToClient, bufferSizeInBytes);
break;
}
case CMD_CALCULATE_MASS_MATRIX:
{
hasStatus = processCalculateMassMatrixCommand(clientCmd, serverStatusOut, bufferServerToClient, bufferSizeInBytes);
break;
}
case CMD_APPLY_EXTERNAL_FORCE:
{
hasStatus = processApplyExternalForceCommand(clientCmd, serverStatusOut, bufferServerToClient, bufferSizeInBytes);
break;
}
case CMD_REMOVE_BODY:
{
hasStatus = processRemoveBodyCommand(clientCmd, serverStatusOut, bufferServerToClient, bufferSizeInBytes);
break;
}
case CMD_USER_CONSTRAINT:
{
hasStatus = processCreateUserConstraintCommand(clientCmd, serverStatusOut, bufferServerToClient, bufferSizeInBytes);
break;
}
case CMD_CALCULATE_INVERSE_KINEMATICS:
{
if (clientCmd.m_calculateInverseKinematicsArguments.m_numEndEffectorLinkIndices == 1)
{
hasStatus = processCalculateInverseKinematicsCommand(clientCmd, serverStatusOut, bufferServerToClient, bufferSizeInBytes);
}
else
{
hasStatus = processCalculateInverseKinematicsCommand2(clientCmd, serverStatusOut, bufferServerToClient, bufferSizeInBytes);
}
break;
}
case CMD_REQUEST_VISUAL_SHAPE_INFO:
{
hasStatus = processRequestVisualShapeInfoCommand(clientCmd, serverStatusOut, bufferServerToClient, bufferSizeInBytes);
break;
}
case CMD_REQUEST_COLLISION_SHAPE_INFO:
{
hasStatus = processRequestCollisionShapeInfoCommand(clientCmd, serverStatusOut, bufferServerToClient, bufferSizeInBytes);
break;
}
case CMD_UPDATE_VISUAL_SHAPE:
{
hasStatus = processUpdateVisualShapeCommand(clientCmd, serverStatusOut, bufferServerToClient, bufferSizeInBytes);
break;
}
case CMD_CHANGE_TEXTURE:
{
hasStatus = processChangeTextureCommand(clientCmd, serverStatusOut, bufferServerToClient, bufferSizeInBytes);
break;
}
case CMD_LOAD_TEXTURE:
{
hasStatus = processLoadTextureCommand(clientCmd, serverStatusOut, bufferServerToClient, bufferSizeInBytes);
break;
}
case CMD_RESTORE_STATE:
{
hasStatus = processRestoreStateCommand(clientCmd, serverStatusOut, bufferServerToClient, bufferSizeInBytes);
break;
}
case CMD_SAVE_STATE:
{
hasStatus = processSaveStateCommand(clientCmd, serverStatusOut, bufferServerToClient, bufferSizeInBytes);
break;
}
case CMD_REMOVE_STATE:
{
hasStatus = processRemoveStateCommand(clientCmd, serverStatusOut, bufferServerToClient, bufferSizeInBytes);
break;
}
case CMD_LOAD_BULLET:
{
hasStatus = processLoadBulletCommand(clientCmd, serverStatusOut, bufferServerToClient, bufferSizeInBytes);
break;
}
case CMD_SAVE_BULLET:
{
hasStatus = processSaveBulletCommand(clientCmd, serverStatusOut, bufferServerToClient, bufferSizeInBytes);
break;
}
case CMD_LOAD_MJCF:
{
hasStatus = processLoadMJCFCommand(clientCmd, serverStatusOut, bufferServerToClient, bufferSizeInBytes);
break;
}
case CMD_USER_DEBUG_DRAW:
{
hasStatus = processUserDebugDrawCommand(clientCmd, serverStatusOut, bufferServerToClient, bufferSizeInBytes);
break;
}
case CMD_CUSTOM_COMMAND:
{
hasStatus = processCustomCommand(clientCmd, serverStatusOut, bufferServerToClient, bufferSizeInBytes);
break;
}
case CMD_SYNC_USER_DATA:
{
hasStatus = processSyncUserDataCommand(clientCmd, serverStatusOut, bufferServerToClient, bufferSizeInBytes);
break;
}
case CMD_REQUEST_USER_DATA:
{
hasStatus = processRequestUserDataCommand(clientCmd, serverStatusOut, bufferServerToClient, bufferSizeInBytes);
break;
}
case CMD_ADD_USER_DATA:
{
hasStatus = processAddUserDataCommand(clientCmd, serverStatusOut, bufferServerToClient, bufferSizeInBytes);
break;
}
case CMD_REMOVE_USER_DATA:
{
hasStatus = processRemoveUserDataCommand(clientCmd, serverStatusOut, bufferServerToClient, bufferSizeInBytes);
break;
}
case CMD_COLLISION_FILTER:
{
hasStatus = processCollisionFilterCommand(clientCmd, serverStatusOut, bufferServerToClient, bufferSizeInBytes);
break;
}
default:
{
BT_PROFILE("CMD_UNKNOWN");
b3Error("Unknown command encountered");
SharedMemoryStatus& serverCmd = serverStatusOut;
serverCmd.m_type = CMD_UNKNOWN_COMMAND_FLUSHED;
hasStatus = true;
}
};
return hasStatus;
}
void PhysicsServerCommandProcessor::syncPhysicsToGraphics()
{
m_data->m_guiHelper->syncPhysicsToGraphics(m_data->m_dynamicsWorld);
}
void PhysicsServerCommandProcessor::syncPhysicsToGraphics2()
{
m_data->m_guiHelper->syncPhysicsToGraphics2(m_data->m_dynamicsWorld);
}
void PhysicsServerCommandProcessor::renderScene(int renderFlags)
{
if (m_data->m_guiHelper)
{
if (0 == (renderFlags & COV_DISABLE_SYNC_RENDERING))
{
m_data->m_guiHelper->syncPhysicsToGraphics(m_data->m_dynamicsWorld);
}
m_data->m_guiHelper->render(m_data->m_dynamicsWorld);
}
}
void PhysicsServerCommandProcessor::physicsDebugDraw(int debugDrawFlags)
{
if (m_data->m_dynamicsWorld)
{
if (m_data->m_dynamicsWorld->getDebugDrawer())
{
m_data->m_dynamicsWorld->getDebugDrawer()->setDebugMode(debugDrawFlags);
m_data->m_dynamicsWorld->debugDrawWorld();
#ifndef SKIP_SOFT_BODY_MULTI_BODY_DYNAMICS_WORLD
{
btDeformableMultiBodyDynamicsWorld* deformWorld = getDeformableWorld();
if (deformWorld)
{
for (int i = 0; i < deformWorld->getSoftBodyArray().size(); i++)
{
btSoftBody* psb = (btSoftBody*)deformWorld->getSoftBodyArray()[i];
if (m_data->m_dynamicsWorld->getDebugDrawer() && !(m_data->m_dynamicsWorld->getDebugDrawer()->getDebugMode() & (btIDebugDraw::DBG_DrawWireframe)))
{
//btSoftBodyHelpers::DrawFrame(psb,m_data->m_dynamicsWorld->getDebugDrawer());
btSoftBodyHelpers::Draw(psb, m_data->m_dynamicsWorld->getDebugDrawer(), deformWorld->getDrawFlags());
}
}
}
}
{
btSoftMultiBodyDynamicsWorld* softWorld = getSoftWorld();
if (softWorld)
{
for (int i = 0; i < softWorld->getSoftBodyArray().size(); i++)
{
btSoftBody* psb = (btSoftBody*)softWorld->getSoftBodyArray()[i];
if (m_data->m_dynamicsWorld->getDebugDrawer() && !(m_data->m_dynamicsWorld->getDebugDrawer()->getDebugMode() & (btIDebugDraw::DBG_DrawWireframe)))
{
//btSoftBodyHelpers::DrawFrame(psb,m_data->m_dynamicsWorld->getDebugDrawer());
btSoftBodyHelpers::Draw(psb, m_data->m_dynamicsWorld->getDebugDrawer(), softWorld->getDrawFlags());
}
}
}
}
#endif
}
}
}
struct MyResultCallback : public btCollisionWorld::ClosestRayResultCallback
{
int m_faceId;
MyResultCallback(const btVector3& rayFromWorld, const btVector3& rayToWorld)
: btCollisionWorld::ClosestRayResultCallback(rayFromWorld, rayToWorld),
m_faceId(-1)
{
}
virtual bool needsCollision(btBroadphaseProxy* proxy0) const
{
return true;
}
virtual btScalar addSingleResult(btCollisionWorld::LocalRayResult& rayResult, bool normalInWorldSpace)
{
//caller already does the filter on the m_closestHitFraction
btAssert(rayResult.m_hitFraction <= m_closestHitFraction);
m_closestHitFraction = rayResult.m_hitFraction;
m_collisionObject = rayResult.m_collisionObject;
if (rayResult.m_localShapeInfo)
{
m_faceId = rayResult.m_localShapeInfo->m_triangleIndex;
}
else
{
m_faceId = -1;
}
if (normalInWorldSpace)
{
m_hitNormalWorld = rayResult.m_hitNormalLocal;
}
else
{
///need to transform normal into worldspace
m_hitNormalWorld = m_collisionObject->getWorldTransform().getBasis() * rayResult.m_hitNormalLocal;
}
m_hitPointWorld.setInterpolate3(m_rayFromWorld, m_rayToWorld, rayResult.m_hitFraction);
return rayResult.m_hitFraction;
}
};
bool PhysicsServerCommandProcessor::pickBody(const btVector3& rayFromWorld, const btVector3& rayToWorld)
{
if (m_data->m_dynamicsWorld == 0)
return false;
//btCollisionWorld::ClosestRayResultCallback rayCallback(rayFromWorld, rayToWorld);
MyResultCallback rayCallback(rayFromWorld, rayToWorld);
rayCallback.m_flags |= btTriangleRaycastCallback::kF_UseGjkConvexCastRaytest;
m_data->m_dynamicsWorld->rayTest(rayFromWorld, rayToWorld, rayCallback);
if (rayCallback.hasHit())
{
btVector3 pickPos = rayCallback.m_hitPointWorld;
btRigidBody* body = (btRigidBody*)btRigidBody::upcast(rayCallback.m_collisionObject);
if (body)
{
//other exclusions?
if (!(body->isStaticObject() || body->isKinematicObject()))
{
m_data->m_pickedBody = body;
m_data->m_savedActivationState = body->getActivationState();
if (m_data->m_savedActivationState==ISLAND_SLEEPING)
{
m_data->m_savedActivationState = ACTIVE_TAG;
}
m_data->m_pickedBody->setActivationState(DISABLE_DEACTIVATION);
m_data->m_pickedBody->setDeactivationTime(0);
//printf("pickPos=%f,%f,%f\n",pickPos.getX(),pickPos.getY(),pickPos.getZ());
btVector3 localPivot = body->getCenterOfMassTransform().inverse() * pickPos;
btPoint2PointConstraint* p2p = new btPoint2PointConstraint(*body, localPivot);
m_data->m_dynamicsWorld->addConstraint(p2p, true);
m_data->m_pickedConstraint = p2p;
btScalar mousePickClamping = 30.f;
p2p->m_setting.m_impulseClamp = mousePickClamping;
//very weak constraint for picking
p2p->m_setting.m_tau = 0.001f;
}
}
else
{
btMultiBodyLinkCollider* multiCol = (btMultiBodyLinkCollider*)btMultiBodyLinkCollider::upcast(rayCallback.m_collisionObject);
if (multiCol && multiCol->m_multiBody)
{
m_data->m_prevCanSleep = multiCol->m_multiBody->getCanSleep();
multiCol->m_multiBody->setCanSleep(false);
btVector3 pivotInA = multiCol->m_multiBody->worldPosToLocal(multiCol->m_link, pickPos);
btMultiBodyPoint2Point* p2p = new btMultiBodyPoint2Point(multiCol->m_multiBody, multiCol->m_link, 0, pivotInA, pickPos);
//if you add too much energy to the system, causing high angular velocities, simulation 'explodes'
//see also http://www.bulletphysics.org/Bullet/phpBB3/viewtopic.php?f=4&t=949
//so we try to avoid it by clamping the maximum impulse (force) that the mouse pick can apply
//it is not satisfying, hopefully we find a better solution (higher order integrator, using joint friction using a zero-velocity target motor with limited force etc?)
btScalar scaling = 10;
p2p->setMaxAppliedImpulse(2 * scaling);
btMultiBodyDynamicsWorld* world = (btMultiBodyDynamicsWorld*)m_data->m_dynamicsWorld;
world->addMultiBodyConstraint(p2p);
m_data->m_pickingMultiBodyPoint2Point = p2p;
}
else
{
#ifndef SKIP_SOFT_BODY_MULTI_BODY_DYNAMICS_WORLD
//deformable/soft body?
btSoftBody* psb = (btSoftBody*)btSoftBody::upcast(rayCallback.m_collisionObject);
if (psb)
{
btDeformableMultiBodyDynamicsWorld* deformWorld = getDeformableWorld();
if (deformWorld)
{
int face_id = rayCallback.m_faceId;
if (face_id >= 0 && face_id < psb->m_faces.size())
{
m_data->m_pickedSoftBody = psb;
psb->setActivationState(DISABLE_DEACTIVATION);
const btSoftBody::Face& f = psb->m_faces[face_id];
btDeformableMousePickingForce* mouse_force = new btDeformableMousePickingForce(100, 0, f, pickPos, m_data->m_maxPickingForce);
m_data->m_mouseForce = mouse_force;
deformWorld->addForce(psb, mouse_force);
}
}
}
#endif
}
}
// pickObject(pickPos, rayCallback.m_collisionObject);
m_data->m_oldPickingPos = rayToWorld;
m_data->m_hitPos = pickPos;
m_data->m_oldPickingDist = (pickPos - rayFromWorld).length();
// printf("hit !\n");
//add p2p
}
return false;
}
bool PhysicsServerCommandProcessor::movePickedBody(const btVector3& rayFromWorld, const btVector3& rayToWorld)
{
if (m_data->m_pickedBody && m_data->m_pickedConstraint)
{
btPoint2PointConstraint* pickCon = static_cast<btPoint2PointConstraint*>(m_data->m_pickedConstraint);
if (pickCon)
{
//keep it at the same picking distance
btVector3 dir = rayToWorld - rayFromWorld;
dir.normalize();
dir *= m_data->m_oldPickingDist;
btVector3 newPivotB = rayFromWorld + dir;
pickCon->setPivotB(newPivotB);
}
}
if (m_data->m_pickingMultiBodyPoint2Point)
{
//keep it at the same picking distance
btVector3 dir = rayToWorld - rayFromWorld;
dir.normalize();
dir *= m_data->m_oldPickingDist;
btVector3 newPivotB = rayFromWorld + dir;
m_data->m_pickingMultiBodyPoint2Point->setPivotInB(newPivotB);
}
#ifndef SKIP_DEFORMABLE_BODY
if (m_data->m_pickedSoftBody)
{
if (m_data->m_pickedSoftBody && m_data->m_mouseForce)
{
btVector3 newPivot;
btVector3 dir = rayToWorld - rayFromWorld;
dir.normalize();
dir *= m_data->m_oldPickingDist;
newPivot = rayFromWorld + dir;
m_data->m_mouseForce->setMousePos(newPivot);
}
}
#endif
return false;
}
void PhysicsServerCommandProcessor::removePickingConstraint()
{
if (m_data->m_pickedConstraint)
{
m_data->m_dynamicsWorld->removeConstraint(m_data->m_pickedConstraint);
delete m_data->m_pickedConstraint;
m_data->m_pickedConstraint = 0;
m_data->m_pickedBody->forceActivationState(m_data->m_savedActivationState);
m_data->m_pickedBody = 0;
}
if (m_data->m_pickingMultiBodyPoint2Point)
{
m_data->m_pickingMultiBodyPoint2Point->getMultiBodyA()->setCanSleep(m_data->m_prevCanSleep);
btMultiBodyDynamicsWorld* world = (btMultiBodyDynamicsWorld*)m_data->m_dynamicsWorld;
world->removeMultiBodyConstraint(m_data->m_pickingMultiBodyPoint2Point);
delete m_data->m_pickingMultiBodyPoint2Point;
m_data->m_pickingMultiBodyPoint2Point = 0;
}
#ifndef SKIP_SOFT_BODY_MULTI_BODY_DYNAMICS_WORLD
//deformable/soft body?
btDeformableMultiBodyDynamicsWorld* deformWorld = getDeformableWorld();
if (deformWorld && m_data->m_mouseForce)
{
deformWorld->removeForce(m_data->m_pickedSoftBody, m_data->m_mouseForce);
delete m_data->m_mouseForce;
m_data->m_mouseForce = 0;
m_data->m_pickedSoftBody = 0;
}
#endif
}
void PhysicsServerCommandProcessor::enableCommandLogging(bool enable, const char* fileName)
{
if (enable)
{
if (0 == m_data->m_commandLogger)
{
m_data->m_commandLogger = new CommandLogger(fileName);
}
}
else
{
if (0 != m_data->m_commandLogger)
{
delete m_data->m_commandLogger;
m_data->m_commandLogger = 0;
}
}
}
void PhysicsServerCommandProcessor::replayFromLogFile(const char* fileName)
{
CommandLogPlayback* pb = new CommandLogPlayback(fileName);
m_data->m_logPlayback = pb;
}
int gDroppedSimulationSteps = 0;
int gNumSteps = 0;
double gDtInSec = 0.f;
double gSubStep = 0.f;
void PhysicsServerCommandProcessor::enableRealTimeSimulation(bool enableRealTimeSim)
{
m_data->m_useRealTimeSimulation = enableRealTimeSim;
}
bool PhysicsServerCommandProcessor::isRealTimeSimulationEnabled() const
{
return m_data->m_useRealTimeSimulation;
}
void PhysicsServerCommandProcessor::stepSimulationRealTime(double dtInSec, const struct b3VRControllerEvent* vrControllerEvents, int numVRControllerEvents, const struct b3KeyboardEvent* keyEvents, int numKeyEvents, const struct b3MouseEvent* mouseEvents, int numMouseEvents)
{
m_data->m_vrControllerEvents.addNewVREvents(vrControllerEvents, numVRControllerEvents);
m_data->m_pluginManager.addEvents(vrControllerEvents, numVRControllerEvents, keyEvents, numKeyEvents, mouseEvents, numMouseEvents);
for (int i = 0; i < m_data->m_stateLoggers.size(); i++)
{
if (m_data->m_stateLoggers[i]->m_loggingType == STATE_LOGGING_VR_CONTROLLERS)
{
VRControllerStateLogger* vrLogger = (VRControllerStateLogger*)m_data->m_stateLoggers[i];
vrLogger->m_vrEvents.addNewVREvents(vrControllerEvents, numVRControllerEvents);
}
}
for (int ii = 0; ii < numMouseEvents; ii++)
{
const b3MouseEvent& event = mouseEvents[ii];
bool found = false;
//search a matching one first, otherwise add new event
for (int e = 0; e < m_data->m_mouseEvents.size(); e++)
{
if (event.m_eventType == m_data->m_mouseEvents[e].m_eventType)
{
if (event.m_eventType == MOUSE_MOVE_EVENT)
{
m_data->m_mouseEvents[e].m_mousePosX = event.m_mousePosX;
m_data->m_mouseEvents[e].m_mousePosY = event.m_mousePosY;
found = true;
}
else if ((event.m_eventType == MOUSE_BUTTON_EVENT) && event.m_buttonIndex == m_data->m_mouseEvents[e].m_buttonIndex)
{
m_data->m_mouseEvents[e].m_buttonState |= event.m_buttonState;
if (event.m_buttonState & eButtonIsDown)
{
m_data->m_mouseEvents[e].m_buttonState |= eButtonIsDown;
}
else
{
m_data->m_mouseEvents[e].m_buttonState &= ~eButtonIsDown;
}
found = true;
}
}
}
if (!found)
{
m_data->m_mouseEvents.push_back(event);
}
}
for (int i = 0; i < numKeyEvents; i++)
{
const b3KeyboardEvent& event = keyEvents[i];
bool found = false;
//search a matching one first, otherwise add new event
for (int e = 0; e < m_data->m_keyboardEvents.size(); e++)
{
if (event.m_keyCode == m_data->m_keyboardEvents[e].m_keyCode)
{
m_data->m_keyboardEvents[e].m_keyState |= event.m_keyState;
if (event.m_keyState & eButtonIsDown)
{
m_data->m_keyboardEvents[e].m_keyState |= eButtonIsDown;
}
else
{
m_data->m_keyboardEvents[e].m_keyState &= ~eButtonIsDown;
}
found = true;
}
}
if (!found)
{
m_data->m_keyboardEvents.push_back(event);
}
}
if (gResetSimulation)
{
resetSimulation();
gResetSimulation = false;
}
if (gVRTrackingObjectUniqueId >= 0)
{
InternalBodyHandle* bodyHandle = m_data->m_bodyHandles.getHandle(gVRTrackingObjectUniqueId);
if (bodyHandle && bodyHandle->m_multiBody)
{
// gVRTrackingObjectTr = bodyHandle->m_multiBody->getBaseWorldTransform();
if (gVRTrackingObjectUniqueId >= 0)
{
gVRTrackingObjectTr.setOrigin(bodyHandle->m_multiBody->getBaseWorldTransform().getOrigin());
gVRTeleportPos1 = gVRTrackingObjectTr.getOrigin();
}
if (gVRTrackingObjectFlag & VR_CAMERA_TRACK_OBJECT_ORIENTATION)
{
gVRTrackingObjectTr.setBasis(bodyHandle->m_multiBody->getBaseWorldTransform().getBasis());
gVRTeleportOrn = gVRTrackingObjectTr.getRotation();
}
}
}
if ((m_data->m_useRealTimeSimulation) && m_data->m_guiHelper)
{
int maxSteps = m_data->m_numSimulationSubSteps + 3;
if (m_data->m_numSimulationSubSteps)
{
gSubStep = m_data->m_physicsDeltaTime / m_data->m_numSimulationSubSteps;
}
else
{
gSubStep = m_data->m_physicsDeltaTime;
}
btScalar deltaTimeScaled = dtInSec * simTimeScalingFactor;
int numSteps = m_data->m_dynamicsWorld->stepSimulation(deltaTimeScaled, maxSteps, gSubStep);
m_data->m_simulationTimestamp += deltaTimeScaled;
gDroppedSimulationSteps += numSteps > maxSteps ? numSteps - maxSteps : 0;
if (numSteps)
{
gNumSteps = numSteps;
gDtInSec = dtInSec;
addBodyChangedNotifications();
}
}
}
b3Notification createTransformChangedNotification(int bodyUniqueId, int linkIndex, const btCollisionObject* colObj)
{
b3Notification notification;
notification.m_notificationType = TRANSFORM_CHANGED;
notification.m_transformChangeArgs.m_bodyUniqueId = bodyUniqueId;
notification.m_transformChangeArgs.m_linkIndex = linkIndex;
const btTransform& tr = colObj->getWorldTransform();
notification.m_transformChangeArgs.m_worldPosition[0] = tr.getOrigin()[0];
notification.m_transformChangeArgs.m_worldPosition[1] = tr.getOrigin()[1];
notification.m_transformChangeArgs.m_worldPosition[2] = tr.getOrigin()[2];
notification.m_transformChangeArgs.m_worldRotation[0] = tr.getRotation()[0];
notification.m_transformChangeArgs.m_worldRotation[1] = tr.getRotation()[1];
notification.m_transformChangeArgs.m_worldRotation[2] = tr.getRotation()[2];
notification.m_transformChangeArgs.m_worldRotation[3] = tr.getRotation()[3];
const btVector3& scaling = colObj->getCollisionShape()->getLocalScaling();
notification.m_transformChangeArgs.m_localScaling[0] = scaling[0];
notification.m_transformChangeArgs.m_localScaling[1] = scaling[1];
notification.m_transformChangeArgs.m_localScaling[2] = scaling[2];
return notification;
}
#ifndef SKIP_SOFT_BODY_MULTI_BODY_DYNAMICS_WORLD
b3Notification createSoftBodyChangedNotification(int bodyUniqueId, int linkIndex)
{
b3Notification notification;
notification.m_notificationType = SOFTBODY_CHANGED;
notification.m_softBodyChangeArgs.m_bodyUniqueId = bodyUniqueId;
notification.m_softBodyChangeArgs.m_linkIndex = linkIndex;
return notification;
}
#endif
void PhysicsServerCommandProcessor::addBodyChangedNotifications()
{
b3Notification notification;
notification.m_notificationType = SIMULATION_STEPPED;
m_data->m_pluginManager.addNotification(notification);
b3AlignedObjectArray<int> usedHandles;
m_data->m_bodyHandles.getUsedHandles(usedHandles);
for (int i = 0; i < usedHandles.size(); i++)
{
int bodyUniqueId = usedHandles[i];
InternalBodyData* bodyData = m_data->m_bodyHandles.getHandle(bodyUniqueId);
if (!bodyData)
{
continue;
}
if (bodyData->m_multiBody)
{
btMultiBody* mb = bodyData->m_multiBody;
if (mb->getBaseCollider()->isActive())
{
m_data->m_pluginManager.addNotification(createTransformChangedNotification(bodyUniqueId, -1, mb->getBaseCollider()));
}
for (int linkIndex = 0; linkIndex < mb->getNumLinks(); linkIndex++)
{
if (mb->getLinkCollider(linkIndex)->isActive())
{
m_data->m_pluginManager.addNotification(createTransformChangedNotification(bodyUniqueId, linkIndex, mb->getLinkCollider(linkIndex)));
}
}
}
else if (bodyData->m_rigidBody && bodyData->m_rigidBody->isActive())
{
m_data->m_pluginManager.addNotification(createTransformChangedNotification(bodyUniqueId, -1, bodyData->m_rigidBody));
}
#ifndef SKIP_SOFT_BODY_MULTI_BODY_DYNAMICS_WORLD
else if (bodyData->m_softBody)
{
int linkIndex = -1;
m_data->m_pluginManager.addNotification(createSoftBodyChangedNotification(bodyUniqueId, linkIndex));
}
#endif
}
}
void PhysicsServerCommandProcessor::resetSimulation(int flags)
{
//clean up all data
m_data->m_remoteSyncTransformTime = m_data->m_remoteSyncTransformInterval;
m_data->m_simulationTimestamp = 0;
m_data->m_cachedVUrdfisualShapes.clear();
#ifndef SKIP_SOFT_BODY_MULTI_BODY_DYNAMICS_WORLD
if (m_data && m_data->m_dynamicsWorld)
{
{
btDeformableMultiBodyDynamicsWorld* deformWorld = getDeformableWorld();
if (deformWorld)
{
deformWorld->getWorldInfo().m_sparsesdf.Reset();
}
}
{
btSoftMultiBodyDynamicsWorld* softWorld = getSoftWorld();
if (softWorld)
{
softWorld->getWorldInfo().m_sparsesdf.Reset();
}
}
}
#endif
if (m_data && m_data->m_guiHelper)
{
m_data->m_guiHelper->removeAllGraphicsInstances();
m_data->m_guiHelper->removeAllUserDebugItems();
}
if (m_data)
{
if (m_data->m_pluginManager.getRenderInterface())
{
m_data->m_pluginManager.getRenderInterface()->resetAll();
}
if (m_data->m_pluginManager.getCollisionInterface())
{
m_data->m_pluginManager.getCollisionInterface()->resetAll();
}
for (int i = 0; i < m_data->m_savedStates.size(); i++)
{
delete m_data->m_savedStates[i].m_bulletFile;
delete m_data->m_savedStates[i].m_serializer;
}
m_data->m_savedStates.clear();
}
removePickingConstraint();
deleteDynamicsWorld();
createEmptyDynamicsWorld(flags);
m_data->m_bodyHandles.exitHandles();
m_data->m_bodyHandles.initHandles();
m_data->m_userCollisionShapeHandles.exitHandles();
m_data->m_userCollisionShapeHandles.initHandles();
m_data->m_userDataHandles.exitHandles();
m_data->m_userDataHandles.initHandles();
m_data->m_userDataHandleLookup.clear();
b3Notification notification;
notification.m_notificationType = SIMULATION_RESET;
m_data->m_pluginManager.addNotification(notification);
syncPhysicsToGraphics2();
}
void PhysicsServerCommandProcessor::setTimeOut(double /*timeOutInSeconds*/)
{
}
const btVector3& PhysicsServerCommandProcessor::getVRTeleportPosition() const
{
return gVRTeleportPos1;
}
void PhysicsServerCommandProcessor::setVRTeleportPosition(const btVector3& vrTeleportPos)
{
gVRTeleportPos1 = vrTeleportPos;
}
const btQuaternion& PhysicsServerCommandProcessor::getVRTeleportOrientation() const
{
return gVRTeleportOrn;
}
void PhysicsServerCommandProcessor::setVRTeleportOrientation(const btQuaternion& vrTeleportOrn)
{
gVRTeleportOrn = vrTeleportOrn;
}
|
#include "Editor/LevelEditor/LevelToolbar/LevelToolbar.hpp"
#include "Editor/LevelEditor/LevelEditor.hpp"
namespace Editor
{
LevelToolbar::LevelToolbar(LevelEditor* levelEditor) : Framework::ToolBar(levelEditor)
{
}
}
|
/* 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/lite/delegates/nnapi/nnapi_delegate.h"
#include <algorithm>
#include <cstdarg>
#include <cstddef>
#include <cstdint>
#include <cstring>
#include <functional>
#include <initializer_list>
#include <iostream>
#include <iterator>
#include <map>
#include <memory>
#include <string>
#include <tuple>
#include <utility>
#include <vector>
#include "tensorflow/lite/nnapi/NeuralNetworksTypes.h"
#ifdef __ANDROID__
#include <sys/system_properties.h>
#endif
#if defined __ANDROID__ || defined __unix__
#define TFLITE_NNAPI_ALLOW_MMAP_SHARING
#include <sys/mman.h>
#include <unistd.h>
#endif
#include "absl/memory/memory.h"
#include "absl/types/optional.h"
#include "tensorflow/lite/allocation.h"
#include "tensorflow/lite/builtin_op_data.h"
#include "tensorflow/lite/builtin_ops.h"
#include "tensorflow/lite/c/builtin_op_data.h"
#include "tensorflow/lite/c/common.h"
#include "tensorflow/lite/context_util.h"
#include "tensorflow/lite/delegates/nnapi/nnapi_delegate_kernel.h"
#include "tensorflow/lite/delegates/nnapi/quant_lstm_sup.h"
#include "tensorflow/lite/kernels/kernel_util.h"
#include "tensorflow/lite/minimal_logging.h"
#include "tensorflow/lite/nnapi/nnapi_implementation.h"
#include "tensorflow/lite/nnapi/nnapi_util.h"
#include "tensorflow/lite/util.h"
namespace tflite {
namespace {
// Returns the enum name corresponding to the given error code if the given
// value corresponds to an of the error codes in the enumeration above or
// an message with the unknown code.
// LINT.IfChange(NnApiErrorDescription)
std::string NnApiErrorDescription(int error_code) {
switch (error_code) {
case ANEURALNETWORKS_NO_ERROR:
return "ANEURALNETWORKS_NO_ERROR";
case ANEURALNETWORKS_OUT_OF_MEMORY:
return "ANEURALNETWORKS_OUT_OF_MEMORY";
case ANEURALNETWORKS_INCOMPLETE:
return "ANEURALNETWORKS_INCOMPLETE";
case ANEURALNETWORKS_UNEXPECTED_NULL:
return "ANEURALNETWORKS_UNEXPECTED_NULL";
case ANEURALNETWORKS_BAD_DATA:
return "ANEURALNETWORKS_BAD_DATA";
case ANEURALNETWORKS_OP_FAILED:
return "ANEURALNETWORKS_OP_FAILED";
case ANEURALNETWORKS_BAD_STATE:
return "ANEURALNETWORKS_BAD_STATE";
case ANEURALNETWORKS_UNMAPPABLE:
return "ANEURALNETWORKS_UNMAPPABLE";
case ANEURALNETWORKS_OUTPUT_INSUFFICIENT_SIZE:
return "ANEURALNETWORKS_OUTPUT_INSUFFICIENT_SIZE";
case ANEURALNETWORKS_UNAVAILABLE_DEVICE:
return "ANEURALNETWORKS_UNAVAILABLE_DEVICE";
case ANEURALNETWORKS_MISSED_DEADLINE_TRANSIENT:
return "ANEURALNETWORKS_MISSED_DEADLINE_TRANSIENT";
case ANEURALNETWORKS_MISSED_DEADLINE_PERSISTENT:
return "ANEURALNETWORKS_MISSED_DEADLINE_PERSISTENT";
case ANEURALNETWORKS_RESOURCE_EXHAUSTED_TRANSIENT:
return "ANEURALNETWORKS_RESOURCE_EXHAUSTED_TRANSIENT";
case ANEURALNETWORKS_RESOURCE_EXHAUSTED_PERSISTENT:
return "ANEURALNETWORKS_RESOURCE_EXHAUSTED_PERSISTENT";
case ANEURALNETWORKS_DEAD_OBJECT:
return "ANEURALNETWORKS_DEAD_OBJECT";
default:
return "Unknown NNAPI error code: " + std::to_string(error_code);
}
}
// LINT.ThenChange()
#define RETURN_TFLITE_ERROR_IF_NN_ERROR(context, code, call_desc, p_errno) \
do { \
const auto _code = (code); \
const auto _call_desc = (call_desc); \
if (_code != ANEURALNETWORKS_NO_ERROR) { \
const auto error_desc = NnApiErrorDescription(_code); \
context->ReportError(context, \
"NN API returned error %s at line %d while %s.\n", \
error_desc.c_str(), __LINE__, _call_desc); \
*p_errno = _code; \
return kTfLiteError; \
} \
} while (0)
bool IsFloat(TfLiteType type) {
switch (type) {
case kTfLiteFloat32:
return true;
default:
return false;
}
}
bool IsFloatOrUInt8(TfLiteType type) {
switch (type) {
case kTfLiteFloat32:
case kTfLiteUInt8:
return true;
default:
return false;
}
}
bool IsQuantized(TfLiteType type) {
switch (type) {
case kTfLiteUInt8:
case kTfLiteInt8:
return true;
default:
// kTfLiteInt16 isn't supported as quantized type yet.
return false;
}
}
bool IsScalarInputSupported(int builtin_code) {
switch (builtin_code) {
case kTfLiteBuiltinAdd:
case kTfLiteBuiltinMul:
case kTfLiteBuiltinSub:
case kTfLiteBuiltinDiv:
case kTfLiteBuiltinEqual:
case kTfLiteBuiltinNotEqual:
case kTfLiteBuiltinGreater:
case kTfLiteBuiltinGreaterEqual:
case kTfLiteBuiltinLess:
case kTfLiteBuiltinLessEqual:
case kTfLiteBuiltinPow:
return true;
default:
return false;
}
}
// Check if the operation requires explicit conversion from int8 to uint8
// values.
bool NeedInt8Conversion(const TfLiteContext* context, int builtin_code,
const TfLiteNode* node) {
const int input_id = node->inputs->data[0];
const TfLiteType input_type = context->tensors[input_id].type;
switch (builtin_code) {
case kTfLiteBuiltinConv2d:
case kTfLiteBuiltinDepthwiseConv2d:
case kTfLiteBuiltinFullyConnected: {
if (input_type == kTfLiteInt8) {
const int weights_id = node->inputs->data[1];
const auto& weights_tensor = context->tensors[weights_id];
if ((weights_tensor.type == kTfLiteInt8 ||
weights_tensor.type == kTfLiteUInt8) &&
weights_tensor.quantization.type == kTfLiteAffineQuantization) {
return true;
}
}
return false;
}
case kTfLiteBuiltinSelect: {
const auto value_type = context->tensors[node->inputs->data[1]].type;
return value_type == kTfLiteInt8;
}
case kTfLiteBuiltinAdd:
case kTfLiteBuiltinArgMax:
case kTfLiteBuiltinArgMin:
case kTfLiteBuiltinAveragePool2d:
case kTfLiteBuiltinBatchToSpaceNd:
case kTfLiteBuiltinConcatenation:
case kTfLiteBuiltinEqual:
case kTfLiteBuiltinExpandDims:
case kTfLiteBuiltinGreater:
case kTfLiteBuiltinGreaterEqual:
case kTfLiteBuiltinHardSwish:
case kTfLiteBuiltinL2Normalization:
case kTfLiteBuiltinLess:
case kTfLiteBuiltinLessEqual:
case kTfLiteBuiltinLogistic:
case kTfLiteBuiltinMaximum:
case kTfLiteBuiltinMaxPool2d:
case kTfLiteBuiltinMean:
case kTfLiteBuiltinMinimum:
case kTfLiteBuiltinMul:
case kTfLiteBuiltinNotEqual:
case kTfLiteBuiltinPad:
case kTfLiteBuiltinPadv2:
case kTfLiteBuiltinReduceMax:
case kTfLiteBuiltinReduceMin:
case kTfLiteBuiltinRelu:
case kTfLiteBuiltinReluN1To1:
case kTfLiteBuiltinRelu6:
case kTfLiteBuiltinResizeBilinear:
case kTfLiteBuiltinResizeNearestNeighbor:
case kTfLiteBuiltinReshape:
case kTfLiteBuiltinSlice:
case kTfLiteBuiltinSoftmax:
case kTfLiteBuiltinSpaceToBatchNd:
case kTfLiteBuiltinSpaceToDepth:
case kTfLiteBuiltinDepthToSpace:
case kTfLiteBuiltinStridedSlice:
case kTfLiteBuiltinSub:
case kTfLiteBuiltinTanh:
case kTfLiteBuiltinTile:
case kTfLiteBuiltinTopkV2:
case kTfLiteBuiltinTranspose: {
return input_type == kTfLiteInt8;
}
default:
return false;
}
}
constexpr int kLstmFullKernelInputSize = 24;
// The 20 input version is deprecated and kept only to
// support old model. The latest version of the LSTM Full Kernel
// is the one with 24 inputs
constexpr int kLstmFullKernelNoOptionalParamsInputSize = 20;
constexpr int kLstmBasicKernelInputSize = 5;
inline bool isLstmBasicKernel(const TfLiteNode* node) {
return node->inputs->size == kLstmBasicKernelInputSize;
}
inline bool isLstmFullKernel(const TfLiteNode* node) {
return node->inputs->size == kLstmFullKernelInputSize ||
node->inputs->size == kLstmFullKernelNoOptionalParamsInputSize;
}
bool IsHybridOperator(const TfLiteContext* context, int builtin_code,
const TfLiteNode* node) {
switch (builtin_code) {
case kTfLiteBuiltinConv2d:
case kTfLiteBuiltinFullyConnected: {
const int input_id = node->inputs->data[0];
const int filter_id = node->inputs->data[1];
const TfLiteType input_type = context->tensors[input_id].type;
const TfLiteType filter_type = context->tensors[filter_id].type;
return IsFloat(input_type) && IsQuantized(filter_type);
}
case kTfLiteBuiltinLstm: {
const int input_id = node->inputs->data[0];
// Input #1 is optional so use #2 to determine if hybrid.
const int weights_id = node->inputs->data[2];
const TfLiteType input_type = context->tensors[input_id].type;
const TfLiteType weights_type = context->tensors[weights_id].type;
return isLstmFullKernel(node) && IsFloat(input_type) &&
IsQuantized(weights_type);
}
case kTfLiteBuiltinUnidirectionalSequenceLstm: {
const int input_id = node->inputs->data[0];
// Input #1 is optional so use #2 to determine if hybrid.
const int weights_id = node->inputs->data[2];
const TfLiteType input_type = context->tensors[input_id].type;
const TfLiteType weights_type = context->tensors[weights_id].type;
return IsFloat(input_type) && IsQuantized(weights_type);
}
case kTfLiteBuiltinBidirectionalSequenceLstm: {
const int input_id = node->inputs->data[0];
// Input #1 is optional so use #2 to determine if hybrid.
const int weights_id = node->inputs->data[2];
const TfLiteType input_type = context->tensors[input_id].type;
const TfLiteType weights_type = context->tensors[weights_id].type;
return IsFloat(input_type) && IsQuantized(weights_type);
}
case kTfLiteBuiltinUnidirectionalSequenceRnn: {
const int input_id = node->inputs->data[0];
const int weights_id = node->inputs->data[1];
const TfLiteType input_type = context->tensors[input_id].type;
const TfLiteType weights_type = context->tensors[weights_id].type;
return IsFloat(input_type) && IsQuantized(weights_type);
}
default:
return false;
}
}
constexpr size_t kDefaultByteAlignmentForNNAPI = 16;
static size_t getNumPaddingBytes(size_t byte_size) {
size_t num_padding_bytes = 0;
if (byte_size % kDefaultByteAlignmentForNNAPI) {
num_padding_bytes = kDefaultByteAlignmentForNNAPI -
(byte_size % kDefaultByteAlignmentForNNAPI);
}
return num_padding_bytes;
}
// Return NNAPI device handle with the provided null-terminated device name.
// Returns kTfLiteError in case of any NNAPI error and if no device with the
// given name can be found.
TfLiteStatus GetDeviceHandle(const NnApi* nnapi, TfLiteContext* context,
const char* device_name_ptr,
ANeuralNetworksDevice** result, int* nnapi_errno) {
if (!device_name_ptr) return kTfLiteError;
*result = nullptr;
std::string device_name(device_name_ptr);
uint32_t num_devices = 0;
nnapi->ANeuralNetworks_getDeviceCount(&num_devices);
for (uint32_t i = 0; i < num_devices; i++) {
ANeuralNetworksDevice* device = nullptr;
const char* buffer = nullptr;
RETURN_TFLITE_ERROR_IF_NN_ERROR(
context, nnapi->ANeuralNetworks_getDevice(i, &device),
"Searching for target device", nnapi_errno);
RETURN_TFLITE_ERROR_IF_NN_ERROR(
context, nnapi->ANeuralNetworksDevice_getName(device, &buffer),
"Searching for target device", nnapi_errno);
if (device_name == buffer) {
*result = device;
return kTfLiteOk;
}
}
context->ReportError(context,
"Could not find the specified NNAPI accelerator: %s. "
"Must be one of: {%s}.",
device_name_ptr,
nnapi::GetStringDeviceNamesList().c_str());
return kTfLiteError;
}
// Compute the hash of a TfLiteIntArray.
uint64_t GetHash(const TfLiteIntArray* int_array) {
constexpr auto kHashConst = 0x9e3779b97f4a7800ULL;
uint64_t result = 0;
for (auto i : TfLiteIntArrayView(int_array)) {
result = result ^ (i + kHashConst + (result << 10) + (result >> 4));
}
return result;
}
bool HasZeroes(TfLiteIntArrayView array) {
for (auto value : array) {
if (value == 0) {
return true;
}
}
return false;
}
// Bit mask for tensor flags.
enum {
NN_TENSOR_FLAG_SCALAR_AS_TENSOR = 1U << 0,
NN_TENSOR_FLAG_INT8_CONVERSION = 1U << 1,
};
// Returns the SDK level to target when delegating to the given devices.
// The SDK level is the max of the ones supported by the devices or
// the current Android SDK level if no device is present.
TfLiteStatus GetTargetSdkVersion(
TfLiteContext* context, const NnApi* nnapi,
const std::vector<ANeuralNetworksDevice*>& device_handles,
int* target_sdk_version, int* nnapi_errno) {
*target_sdk_version = nnapi->android_sdk_version;
int64_t devices_sdk_version = -1;
for (const auto* device_handle : device_handles) {
int64_t curr_device_sdk_version;
RETURN_TFLITE_ERROR_IF_NN_ERROR(
context,
nnapi->ANeuralNetworksDevice_getFeatureLevel(device_handle,
&curr_device_sdk_version),
"Searching for target device", nnapi_errno);
devices_sdk_version =
std::max(curr_device_sdk_version, devices_sdk_version);
}
if ((devices_sdk_version > 0) &&
// This second check is necessary since if the nnapi-reference device is
// in the list of target devices the devices_sdk_version value will be
// 1000.
(devices_sdk_version < nnapi->android_sdk_version)) {
TFLITE_LOG(TFLITE_LOG_INFO,
"Changing Android NN SDK version %d to version "
"supported by target devices: %d",
nnapi->android_sdk_version, devices_sdk_version);
*target_sdk_version = devices_sdk_version;
}
return kTfLiteOk;
}
// Returns true if this delegate is configured to use a specific set of devices.
// This will happen either if:
// - accelerator_name option has been specified
// - NNAPI CPU implementation has been explicitly disabled.
// If exclude_nnapi_reference is true this method will return false if the
// accelerator_name in the delegate options is equal to "nnapi-reference"
bool ShouldUseTargetDevices(StatefulNnApiDelegate::Options delegate_options,
bool exclude_nnapi_reference = false) {
const char* device_name_ptr = delegate_options.accelerator_name;
std::string nnapi_cpu("nnapi-reference");
bool has_selected_accelerator = device_name_ptr != nullptr;
if (exclude_nnapi_reference && has_selected_accelerator) {
has_selected_accelerator = nnapi_cpu != device_name_ptr;
}
return (delegate_options.disallow_nnapi_cpu) || has_selected_accelerator;
}
// Fills the given result vector with the list of devices the given delegate
// is referring to.
// There are three possible results:
// - an empty array (not the full list of available accelerators,
// for efficiency reasons) if no accelerator is chosen and the
// disallow_nnapi_cpu delegate option is false.
// - A single element array with the target processor, if an accelerator name
// is specified in the delegate options.
// - The full list of devices available on device less the nnapi reference
// implementation if the delegate option disallow_nnapi_cpu has been
// specified.
TfLiteStatus GetTargetDevices(TfLiteContext* context, TfLiteDelegate* delegate,
const NnApi* nnapi, int* nnapi_errno,
std::vector<ANeuralNetworksDevice*>* result) {
if (nnapi->android_sdk_version < delegate::nnapi::kMinSdkVersionForNNAPI12) {
return kTfLiteError;
}
const auto delegate_options = StatefulNnApiDelegate::GetOptions(delegate);
const char* device_name_ptr = delegate_options.accelerator_name;
if (device_name_ptr != nullptr) {
// User specified an accelerator to use.
ANeuralNetworksDevice* nnapi_device = nullptr;
TF_LITE_ENSURE_STATUS(GetDeviceHandle(nnapi, context, device_name_ptr,
&nnapi_device, nnapi_errno));
result->push_back(nnapi_device);
} else if (delegate_options.disallow_nnapi_cpu) {
std::string nnapi_cpu("nnapi-reference");
uint32_t num_devices = 0;
nnapi->ANeuralNetworks_getDeviceCount(&num_devices);
for (uint32_t i = 0; i < num_devices; i++) {
ANeuralNetworksDevice* device = nullptr;
const char* buffer = nullptr;
RETURN_TFLITE_ERROR_IF_NN_ERROR(
context, nnapi->ANeuralNetworks_getDevice(i, &device),
"Getting list of available devices", nnapi_errno);
RETURN_TFLITE_ERROR_IF_NN_ERROR(
context, nnapi->ANeuralNetworksDevice_getName(device, &buffer),
"Getting list of available devices", nnapi_errno);
if (nnapi_cpu != buffer) {
result->push_back(device);
}
}
}
return kTfLiteOk;
}
} // namespace
namespace delegate {
namespace nnapi {
#ifdef TFLITE_NNAPI_ALLOW_MMAP_SHARING
NNMemory::NNMemory(const NnApi* nnapi, const char* name, size_t size) {
if (name && size > 0) {
nnapi_ = nnapi;
byte_size_ = size;
fd_ = nnapi_->ASharedMemory_create(name, size);
data_ptr_ = reinterpret_cast<uint8_t*>(
mmap(nullptr, size, PROT_READ | PROT_WRITE, MAP_SHARED, fd_, 0));
nnapi_->ANeuralNetworksMemory_createFromFd(size, PROT_READ | PROT_WRITE,
fd_, 0, &nn_memory_handle_);
}
}
#else
NNMemory::NNMemory(const NnApi* /*nnapi*/, const char* /*name*/,
size_t /*size*/)
: nnapi_(nullptr) {}
#endif
NNMemory::~NNMemory() {
#ifdef TFLITE_NNAPI_ALLOW_MMAP_SHARING
if (data_ptr_) {
munmap(data_ptr_, byte_size_);
}
if (nn_memory_handle_) {
nnapi_->ANeuralNetworksMemory_free(nn_memory_handle_);
}
if (fd_ > 0) close(fd_);
#endif
}
class DequantizeMapping {
public:
int DequantizedAnnIndex(int ann_index, TfLiteType type) const {
for (const auto& element : mapping_) {
if (ann_index == std::get<0>(element) && type == std::get<1>(element)) {
return std::get<2>(element);
}
}
return -1;
}
void Add(int ann_index, TfLiteType type, int dequantized_ann_index) {
// This assumes it is not already mapped.
mapping_.emplace_back(ann_index, type, dequantized_ann_index);
}
private:
// Each tuple specifies the ANN (quantized) tensor index, the desired
// floating-point type and the matching ANN (dequantized) tensor index. This
// could use a map but instead std::vector is used to keep code size lower.
std::vector<std::tuple<int, TfLiteType, int>> mapping_;
};
// Abstract builder for building an op in the NN API graph. This handles
// the disparity between TFLite and NN API operand types. NN API has singular
// operands for both tensors and parameters, and TFLite separates the two.
class NNAPIOpBuilder {
public:
NNAPIOpBuilder(const NnApi* nnapi, TfLiteContext* context,
OperandMapping* tensor_mapping,
DequantizeMapping* dequantize_mapping,
std::map<const MMAPAllocation*, ANeuralNetworksMemory*>*
allocation_mapping,
std::vector<int>* nnapi_to_tflite_op_mapping,
ANeuralNetworksModel* nn_model, int* nnapi_errno)
: nnapi_(nnapi),
context_(context),
operand_mapping_(tensor_mapping),
dequantize_mapping_(dequantize_mapping),
allocation_memory_mapping_(allocation_mapping),
nnapi_to_tflite_op_mapping_(nnapi_to_tflite_op_mapping),
nn_model_(nn_model),
nnapi_errno_(nnapi_errno) {}
TfLiteStatus AddScalarBoolOperand(bool value) {
return AddScalarOperand<bool>(value, ANEURALNETWORKS_BOOL);
}
TfLiteStatus AddScalarInt32Operand(int32_t value) {
return AddScalarOperand<int32_t>(value, ANEURALNETWORKS_INT32);
}
TfLiteStatus AddScalarFloat32Operand(float value) {
return AddScalarOperand<float>(value, ANEURALNETWORKS_FLOAT32);
}
TfLiteStatus AddVectorInt32Operand(const int32_t* values,
uint32_t num_values) {
return AddVectorOperand<int32_t>(values, num_values,
ANEURALNETWORKS_TENSOR_INT32,
/*scale=*/0.f, /*zero_point=*/0);
}
TfLiteStatus AddVectorInt32Operand(const int32_t* values, uint32_t num_values,
float scale, int32_t zero_point) {
return AddVectorOperand<int32_t>(
values, num_values, ANEURALNETWORKS_TENSOR_INT32, scale, zero_point);
}
TfLiteStatus AddVectorFloat32Operand(const float* values,
uint32_t num_values) {
return AddVectorOperand<float>(values, num_values,
ANEURALNETWORKS_TENSOR_FLOAT32);
}
TfLiteStatus AddPoolingParams(void* data) {
auto builtin = reinterpret_cast<TfLitePoolParams*>(data);
AddScalarInt32Operand(builtin->padding);
AddScalarInt32Operand(builtin->stride_width);
AddScalarInt32Operand(builtin->stride_height);
AddScalarInt32Operand(builtin->filter_width);
AddScalarInt32Operand(builtin->filter_height);
AddScalarInt32Operand(builtin->activation);
return kTfLiteOk;
}
TfLiteStatus AddTensorInput(int tensor_index, bool hybrid_op,
int tensor_flags = 0) {
return AddTensor(tensor_index, hybrid_op, &augmented_inputs_, tensor_flags);
}
TfLiteStatus AddTensorOutput(int tensor_index, int tensor_flags = 0) {
return AddTensor(tensor_index, /*hybrid_op=*/false, &augmented_outputs_,
tensor_flags);
}
TfLiteStatus AddAdditionalFloat32OutputTensor(uint32_t dimension_count) {
std::vector<uint32_t> dims(dimension_count, 0);
return AddFloat32OutputTensor(dimension_count, dims.data(), nullptr);
}
TfLiteStatus AddStateFloat32Tensor(int tensor_index,
int* ann_tensor_index_out) {
TfLiteTensor* tensor = &context_->tensors[tensor_index];
return AddFloat32OutputTensor(
tensor->dims->size, reinterpret_cast<uint32_t*>(tensor->dims->data),
ann_tensor_index_out);
}
// Add a constant tensor with a single element, intended for broadcast capable
// ops.
TfLiteStatus AddSingleValueConstantTensor(float value, bool is_quantized) {
if (!is_quantized) {
return AddVectorFloat32Operand(&value, 1);
} else {
// in the case that we need to add a quantized tensor, set the value to
// 64, zero_point to be 0 and adjust scale accordingly.
const uint8_t quant8_value = 64;
return AddVectorOperand<uint8_t>(&quant8_value, 1,
ANEURALNETWORKS_TENSOR_QUANT8_ASYMM,
value / quant8_value, 0);
}
}
// Calculate the scale and zero_point for 8-bit unsigned tensor, given float
// min and max. zero_point is clamped to [0, 255].
TfLiteStatus CalculateQuantizationParams(float min, float max, float* scale,
int* zero_point) {
if (max < min) return kTfLiteError;
*scale = (max - min) / 255.f;
if (min > 0.f) {
*zero_point = 0;
} else if (max < 0.f) {
*zero_point = 255;
} else {
*zero_point = (0.f - min) / (*scale);
}
return kTfLiteOk;
}
// Lower hardswish according to the following equation:
// hard_swish[x] = x (ReLU6(x + 3)) / 6 == x * (Relu_N1_to_1(x/3) * 3 + 3) / 6
// = 0.5x * Relu_N1_to_1(x/3) + 0.5x
TfLiteStatus AddHardSwish(int lite_input_index, int lite_output_index,
bool need_int8_conversion, int lite_node_index) {
const TfLiteTensor& tensor = context_->tensors[lite_input_index];
float input_scale = tensor.params.scale;
int input_zero_point = tensor.params.zero_point;
float input_min = 0.f;
float input_max = 0.f;
int tensor_flags = 0;
if (need_int8_conversion) {
tensor_flags = tensor_flags | NN_TENSOR_FLAG_INT8_CONVERSION;
input_zero_point += 128;
}
bool is_quantized = false;
int nn_type = ANEURALNETWORKS_TENSOR_FLOAT32;
if (tensor.type == kTfLiteInt8 || tensor.type == kTfLiteUInt8) {
is_quantized = true;
nn_type = ANEURALNETWORKS_TENSOR_QUANT8_ASYMM;
input_min = (0 - input_zero_point) * input_scale;
input_max = (255 - input_zero_point) * input_scale;
}
// Stage1 : s1 = Relu1(x * 1/3)
float s1_output_min = 0.f;
float s1_output_max = 0.f;
int s1_out_ann_index = 0;
{
float s1_output_scale = 0.f;
int s1_output_zero_point = 0;
if (is_quantized) {
// clamp the output range to [-1, 1] if needed.
s1_output_min = input_min / 3.f < -1.f ? -1.f : input_min / 3.f;
s1_output_max = input_max / 3.f > 1.f ? 1.f : input_max / 3.f;
CalculateQuantizationParams(s1_output_min, s1_output_max,
&s1_output_scale, &s1_output_zero_point);
}
TF_LITE_ENSURE_OK(context_,
AddTensorInput(lite_input_index, false, tensor_flags));
const float value3f = 1.f / 3.f;
TF_LITE_ENSURE_OK(context_,
AddSingleValueConstantTensor(value3f, is_quantized));
TF_LITE_ENSURE_OK(context_,
AddScalarInt32Operand(ANEURALNETWORKS_FUSED_RELU1));
TF_LITE_ENSURE_OK(
context_,
AddAdditionalOutputTensor(
tensor.dims->size, reinterpret_cast<uint32_t*>(tensor.dims->data),
nn_type, s1_output_scale, s1_output_zero_point,
&s1_out_ann_index));
TF_LITE_ENSURE_OK(
context_, FinalizeAddOperation(ANEURALNETWORKS_MUL, lite_node_index));
}
// Stage2 : s2 = x / 2
float s2_output_min = input_min / 2.f;
float s2_output_max = input_max / 2.f;
int s2_out_ann_index = 0;
{
float s2_output_scale = input_scale / 2.0f;
int s2_output_zero_point = input_zero_point;
TF_LITE_ENSURE_OK(context_,
AddTensorInput(lite_input_index, false, tensor_flags));
const float value2f = 0.5f;
TF_LITE_ENSURE_OK(context_,
AddSingleValueConstantTensor(value2f, is_quantized));
TF_LITE_ENSURE_OK(context_,
AddScalarInt32Operand(ANEURALNETWORKS_FUSED_NONE));
TF_LITE_ENSURE_OK(
context_,
AddAdditionalOutputTensor(
tensor.dims->size, reinterpret_cast<uint32_t*>(tensor.dims->data),
nn_type, s2_output_scale, s2_output_zero_point,
&s2_out_ann_index));
TF_LITE_ENSURE_OK(
context_, FinalizeAddOperation(ANEURALNETWORKS_MUL, lite_node_index));
}
// Stage 3 : s3 = s1 * s2
int s3_out_ann_index = 0;
{
augmented_inputs_.push_back(s1_out_ann_index);
augmented_inputs_.push_back(s2_out_ann_index);
TF_LITE_ENSURE_OK(context_,
AddScalarInt32Operand(ANEURALNETWORKS_FUSED_NONE));
float s3_output_scale = 0.f;
int s3_output_zero_point = 0;
if (is_quantized) {
// the min for stage 3 is always 0.0f.
float s3_output_min = 0.f;
// the max for stage 3 is max(s1_min * s2_min, s1_max * s3_max).
float s3_output_max =
s1_output_max * s2_output_max > s1_output_min * s2_output_min
? s1_output_max * s2_output_max
: s1_output_min * s2_output_min;
CalculateQuantizationParams(s3_output_min, s3_output_max,
&s3_output_scale, &s3_output_zero_point);
}
TF_LITE_ENSURE_OK(
context_,
AddAdditionalOutputTensor(
tensor.dims->size, reinterpret_cast<uint32_t*>(tensor.dims->data),
nn_type, s3_output_scale, s3_output_zero_point,
&s3_out_ann_index));
TF_LITE_ENSURE_OK(
context_, FinalizeAddOperation(ANEURALNETWORKS_MUL, lite_node_index));
}
// Stage 4: y = s3 + s2
{
augmented_inputs_.push_back(s2_out_ann_index);
augmented_inputs_.push_back(s3_out_ann_index);
TF_LITE_ENSURE_OK(context_,
AddScalarInt32Operand(ANEURALNETWORKS_FUSED_NONE));
TF_LITE_ENSURE_OK(context_,
AddTensorOutput(lite_output_index, tensor_flags));
TF_LITE_ENSURE_OK(
context_, FinalizeAddOperation(ANEURALNETWORKS_ADD, lite_node_index));
}
return kTfLiteOk;
}
// Adds a Dequantize operator and replaces the input tensor index with the
// dequantized version. If the dequantized version of the operator already
// exists then it is not added again.
TfLiteStatus AddDequantize(int nn_input_index, int lite_index,
TfLiteType dequantized_type) {
const int ann_index = operand_mapping_->lite_index_to_ann(lite_index);
int dequantized_ann_index =
dequantize_mapping_->DequantizedAnnIndex(ann_index, dequantized_type);
if (dequantized_ann_index == -1) {
// The dequantized version does not exist yet, it has to be added: a new
// Dequantize operation is added, yielding a new tensor.
const TfLiteTensor& tensor = context_->tensors[lite_index];
ANeuralNetworksOperandType operand_type{
ANEURALNETWORKS_TENSOR_FLOAT32,
static_cast<uint32_t>(tensor.dims->size),
reinterpret_cast<uint32_t*>(tensor.dims->data), 0.f, 0};
RETURN_TFLITE_ERROR_IF_NN_ERROR(
context_,
nnapi_->ANeuralNetworksModel_addOperand(nn_model_, &operand_type),
"adding operand", nnapi_errno_);
dequantized_ann_index = operand_mapping_->add_new_non_tensor_operand();
// Add Dequantize operation.
const uint32_t dequantize_input[1] = {static_cast<uint32_t>(ann_index)};
const uint32_t dequantize_output[1] = {
static_cast<uint32_t>(dequantized_ann_index)};
RETURN_TFLITE_ERROR_IF_NN_ERROR(
context_,
nnapi_->ANeuralNetworksModel_addOperation(
nn_model_, ANEURALNETWORKS_DEQUANTIZE, 1, dequantize_input, 1,
dequantize_output),
"adding operation", nnapi_errno_);
dequantize_mapping_->Add(ann_index, dequantized_type,
dequantized_ann_index);
}
// The input for the original operation is modified so that the operation
// now uses the dequantized tensor as input.
augmented_inputs_[nn_input_index] = dequantized_ann_index;
return kTfLiteOk;
}
// Finish emitting the op (of type `type`) into the NN API.
TfLiteStatus FinalizeAddOperation(ANeuralNetworksOperationType type,
int lite_node_index) {
// Actually add a NN API operation
RETURN_TFLITE_ERROR_IF_NN_ERROR(
context_,
nnapi_->ANeuralNetworksModel_addOperation(
nn_model_, type, static_cast<uint32_t>(augmented_inputs_.size()),
augmented_inputs_.data(),
static_cast<uint32_t>(augmented_outputs_.size()),
augmented_outputs_.data()),
"adding operation", nnapi_errno_);
nnapi_to_tflite_op_mapping_->push_back(lite_node_index);
augmented_inputs_.clear();
augmented_outputs_.clear();
return kTfLiteOk;
}
TfLiteStatus AddSingleValueTensorAsScalarOperand(int tensor_index,
int nn_type) {
const TfLiteTensor* tensor = &context_->tensors[tensor_index];
TF_LITE_ENSURE_EQ(context_, NumElements(tensor), 1);
ANeuralNetworksOperandType operand_type{.type = nn_type};
RETURN_TFLITE_ERROR_IF_NN_ERROR(
context_,
nnapi_->ANeuralNetworksModel_addOperand(nn_model_, &operand_type),
"adding operand", nnapi_errno_);
int ann_tensor_index = operand_mapping_->lite_index_to_ann(tensor_index);
if (ann_tensor_index != -1) {
augmented_inputs_.push_back(ann_tensor_index);
return kTfLiteOk;
}
// Allocate a new tensor index
ann_tensor_index = operand_mapping_->add_new_ann_tensor_index(tensor_index);
augmented_inputs_.push_back(ann_tensor_index);
const TfLiteType tensor_type = tensor->type;
TfLiteType nn_type_equivalent;
TF_LITE_ENSURE_OK(context_, GetEquivalentToANNType(context_, nn_type,
&nn_type_equivalent));
if (tensor_type != nn_type_equivalent) {
operand_mapping_->add_type_conversion(tensor_index, nn_type_equivalent);
}
return kTfLiteOk;
}
template <typename T>
TfLiteStatus AddNewInputConstantTensor(
int32_t nn_type, TfLiteType type, const TfLiteIntArray* dims,
const std::vector<T>& tensor_value,
const TfLiteQuantizationParams& quant_params, int* tensor_index) {
TF_LITE_ENSURE_OK(context_,
context_->AddTensors(context_, 1, tensor_index));
TfLiteTensor* new_tensor = &context_->tensors[*tensor_index];
new_tensor->type = type;
new_tensor->allocation_type = kTfLiteDynamic;
new_tensor->params = quant_params;
// Not removing the new tensor in case of resizing errors since it will
// be cleared by the context
TF_LITE_ENSURE_OK(
context_,
context_->ResizeTensor(
context_, new_tensor,
// Resize Tensor takes ownership of the dims array passed as param
TfLiteIntArrayCopy(dims)));
memcpy(new_tensor->data.raw,
reinterpret_cast<const char*>(tensor_value.data()),
tensor_value.size() * sizeof(T));
const uint32_t tensor_rank = static_cast<uint32_t>(dims->size);
const uint32_t* tensor_dims = reinterpret_cast<const uint32_t*>(dims->data);
ANeuralNetworksOperandType operand_type{nn_type, tensor_rank, tensor_dims,
quant_params.scale,
quant_params.zero_point};
const int ann_tensor_index =
operand_mapping_->add_delegate_generated_input_ann_tensors_operand();
RETURN_TFLITE_ERROR_IF_NN_ERROR(
context_,
nnapi_->ANeuralNetworksModel_addOperand(nn_model_, &operand_type),
"adding operand", nnapi_errno_);
augmented_inputs_.push_back(ann_tensor_index);
RETURN_TFLITE_ERROR_IF_NN_ERROR(
context_,
nnapi_->ANeuralNetworksModel_setOperandValue(
nn_model_, ann_tensor_index, new_tensor->data.raw,
new_tensor->bytes),
"setting new operand value", nnapi_errno_);
return kTfLiteOk;
}
template <typename T>
TfLiteStatus AddNewInputConstantTensor(
int32_t nn_type, TfLiteType type, std::initializer_list<int> dims,
const std::vector<T>& tensor_value,
const TfLiteQuantizationParams& quant_params, int* tensor_index) {
TfLiteIntArray* dim_array = TfLiteIntArrayCreate(dims.size());
dim_array->size = dims.size();
std::copy(dims.begin(), dims.end(), dim_array->data);
const auto result = AddNewInputConstantTensor(
nn_type, type, dim_array, tensor_value, quant_params, tensor_index);
TfLiteIntArrayFree(dim_array);
return result;
}
private:
// Returns a TF Lite type which has the same memory representation as a
// provided NN API type.
TfLiteStatus GetEquivalentToANNType(TfLiteContext* context, int nn_type,
TfLiteType* type) {
switch (nn_type) {
case ANEURALNETWORKS_INT32:
*type = kTfLiteInt32;
return kTfLiteOk;
case ANEURALNETWORKS_FLOAT32:
*type = kTfLiteFloat32;
return kTfLiteOk;
default:
context->ReportError(context,
"NN API Delegate: Can't get an equivalent TF Lite "
"type for provided NN API type: %d.\n",
nn_type);
return kTfLiteError;
}
}
template <typename T>
TfLiteStatus AddScalarOperand(T value, int32_t nn_type) {
ANeuralNetworksOperandType operand_type{.type = nn_type};
RETURN_TFLITE_ERROR_IF_NN_ERROR(
context_,
nnapi_->ANeuralNetworksModel_addOperand(nn_model_, &operand_type),
"adding operand", nnapi_errno_);
const int ann_index = operand_mapping_->add_new_non_tensor_operand();
RETURN_TFLITE_ERROR_IF_NN_ERROR(
context_,
nnapi_->ANeuralNetworksModel_setOperandValue(nn_model_, ann_index,
&value, sizeof(T)),
"setting new operand value", nnapi_errno_);
augmented_inputs_.push_back(ann_index);
return kTfLiteOk;
}
template <typename T>
TfLiteStatus AddVectorOperand(const T* values, uint32_t num_values,
int32_t nn_type, float scale,
int32_t zero_point) {
ANeuralNetworksOperandType operand_type{.type = nn_type,
.dimensionCount = 1,
.dimensions = &num_values,
.scale = scale,
.zeroPoint = zero_point};
RETURN_TFLITE_ERROR_IF_NN_ERROR(
context_,
nnapi_->ANeuralNetworksModel_addOperand(nn_model_, &operand_type),
"adding operand", nnapi_errno_);
const int ann_index = operand_mapping_->add_new_non_tensor_operand();
RETURN_TFLITE_ERROR_IF_NN_ERROR(
context_,
nnapi_->ANeuralNetworksModel_setOperandValue(
nn_model_, ann_index, values, sizeof(T) * num_values),
"settings new operand value", nnapi_errno_);
augmented_inputs_.push_back(ann_index);
return kTfLiteOk;
}
template <typename T>
TfLiteStatus AddVectorOperand(const T* values, uint32_t num_values,
int32_t nn_type) {
return AddVectorOperand(values, num_values, nn_type, /*scale=*/0.f,
/*zero_point=*/0);
}
TfLiteStatus AddFloat32OutputTensor(uint32_t dimension_count,
const uint32_t* dimension_data,
int* ann_index_out) {
return AddAdditionalOutputTensor(
dimension_count, dimension_data, ANEURALNETWORKS_TENSOR_FLOAT32,
/*scale=*/0.f, /*zero_point=*/0, ann_index_out);
}
TfLiteStatus AddAdditionalOutputTensor(uint32_t dimension_count,
const uint32_t* dimension_data,
int32_t nn_type, float scale,
int32_t zero_point,
int* ann_index_out) {
ANeuralNetworksOperandType operand_type{
.type = nn_type,
.dimensionCount = dimension_count,
.dimensions = dimension_data,
.scale = scale,
.zeroPoint = zero_point,
};
RETURN_TFLITE_ERROR_IF_NN_ERROR(
context_,
nnapi_->ANeuralNetworksModel_addOperand(nn_model_, &operand_type),
"adding operand", nnapi_errno_);
const int ann_index = operand_mapping_->add_new_non_tensor_operand();
augmented_outputs_.push_back(ann_index);
if (ann_index_out) *ann_index_out = ann_index;
return kTfLiteOk;
}
// Adds a new NN API tensor that shadows the TF Lite tensor `tensor_index`.
// This returns the NN API tensor index corresponding to the created tensor.
// If another caller previously created a NN API tensor for `tensor_index`
// then the existing one is returned.
TfLiteStatus AddTensor(int tensor_index, bool hybrid_op,
std::vector<uint32_t>* indices, int tensor_flags = 0) {
const bool scalar_as_tensor =
tensor_flags & NN_TENSOR_FLAG_SCALAR_AS_TENSOR;
const bool need_int8_conversion =
tensor_flags & NN_TENSOR_FLAG_INT8_CONVERSION;
int ann_tensor_index = operand_mapping_->lite_index_to_ann(tensor_index);
if (ann_tensor_index != -1) {
indices->push_back(ann_tensor_index);
return kTfLiteOk;
}
// Allocate a new tensor index
ann_tensor_index = operand_mapping_->add_new_ann_tensor_index(tensor_index);
// Parameters needed for new type.
int32_t nn_type = 0;
float scale = 0.0f;
int32_t zeroPoint = 0;
ANeuralNetworksSymmPerChannelQuantParams ann_perchannel_params;
TfLiteTensor* tensor = &context_->tensors[tensor_index];
TfLiteType tensor_type = tensor->type;
if (hybrid_op && (tensor_type == kTfLiteUInt8)) {
// For legacy reason, UINT8 weights in hybrid operators are actually INT8
// values and should be interpreted as such.
tensor_type = kTfLiteInt8;
}
switch (tensor_type) {
case kTfLiteNoType:
// Tensors added during initialization of Ops don't have a type yet and
// should not be registered with the NNAPI.
indices->push_back(-1);
return kTfLiteOk;
case kTfLiteFloat32:
nn_type = ANEURALNETWORKS_TENSOR_FLOAT32;
break;
case kTfLiteUInt8:
case kTfLiteInt8:
// If explicit int8 conversion is needed, we still need
// ANEURALNETWORKS_TENSOR_QUANT8_ASYMM type.
nn_type = (tensor_type == kTfLiteUInt8 || need_int8_conversion)
? ANEURALNETWORKS_TENSOR_QUANT8_ASYMM
: ANEURALNETWORKS_TENSOR_QUANT8_SYMM;
scale = tensor->params.scale;
zeroPoint = tensor->params.zero_point;
if (tensor->quantization.type == kTfLiteAffineQuantization) {
TfLiteAffineQuantization* quantization_params =
static_cast<TfLiteAffineQuantization*>(
tensor->quantization.params);
if (quantization_params->scale->size > 1) {
// Set up per-channel quantization.
ann_perchannel_params = {
.channelDim = static_cast<uint32_t>(
quantization_params->quantized_dimension),
.scaleCount =
static_cast<uint32_t>(quantization_params->scale->size),
.scales = quantization_params->scale->data,
};
nn_type = ANEURALNETWORKS_TENSOR_QUANT8_SYMM_PER_CHANNEL;
scale = 0.0f;
zeroPoint = 0;
} else if (quantization_params->scale->size == 1) {
scale = quantization_params->scale->data[0];
zeroPoint = quantization_params->zero_point->data[0];
}
}
if (nn_type != ANEURALNETWORKS_TENSOR_QUANT8_SYMM_PER_CHANNEL) {
if (need_int8_conversion) {
zeroPoint += 128;
operand_mapping_->add_type_conversion(tensor_index, kTfLiteUInt8);
}
if (scale == 0) {
// TENSOR_QUANT8_ASYMM and ANEURALNETWORKS_TENSOR_QUANT8_ASYMM
// with zero scale are not valid in NNAPI.
scale = 1;
}
}
break;
case kTfLiteInt32:
nn_type = ANEURALNETWORKS_TENSOR_INT32;
scale = tensor->params.scale;
zeroPoint = tensor->params.zero_point;
break;
case kTfLiteBool:
nn_type = ANEURALNETWORKS_TENSOR_BOOL8;
break;
case kTfLiteInt16:
nn_type = ANEURALNETWORKS_TENSOR_QUANT16_SYMM;
scale = tensor->params.scale;
zeroPoint = tensor->params.zero_point;
break;
default:
context_->ReportError(
context_, "Failed to add NN API tensor: type %s is not supported.",
TfLiteTypeGetName(tensor_type));
return kTfLiteError;
}
uint32_t tensor_rank = static_cast<uint32_t>(tensor->dims->size);
uint32_t* tensor_dims = reinterpret_cast<uint32_t*>(tensor->dims->data);
if (scalar_as_tensor && tensor_rank == 0) {
// Use rank 1, shape {1} operand for TFLite scalar tensors.
tensor_rank = 1;
tensor_dims = &tensor_rank;
}
if (tensor_rank == 0) {
// if the tensor_rank is 0, the dimension ptr must be nullptr.
tensor_dims = nullptr;
}
ANeuralNetworksOperandType operand_type{nn_type, tensor_rank, tensor_dims,
scale, zeroPoint};
RETURN_TFLITE_ERROR_IF_NN_ERROR(
context_,
nnapi_->ANeuralNetworksModel_addOperand(nn_model_, &operand_type),
"adding operand", nnapi_errno_);
if (nn_type == ANEURALNETWORKS_TENSOR_QUANT8_SYMM_PER_CHANNEL) {
RETURN_TFLITE_ERROR_IF_NN_ERROR(
context_,
nnapi_->ANeuralNetworksModel_setOperandSymmPerChannelQuantParams(
nn_model_, ann_tensor_index, &ann_perchannel_params),
"setting new operand per channel quantization params", nnapi_errno_);
}
if (tensor->allocation_type == kTfLiteMmapRo) {
if (IsQuantized(tensor_type) && need_int8_conversion) {
// We need to to add a tensor and convert the weights into uint8.
// Currently this is only needed for fully_connected. The new_tensor is
// needed for lifetime management for the converted weights.
int new_tensor_index = -1;
TF_LITE_ENSURE_OK(context_,
context_->AddTensors(context_, 1, &new_tensor_index));
TfLiteTensor* new_tensor = &context_->tensors[new_tensor_index];
new_tensor->type = kTfLiteUInt8;
new_tensor->allocation_type = kTfLiteDynamic;
new_tensor->params.scale = scale;
new_tensor->params.zero_point = zeroPoint;
// Not removing the new tensor in case of resizing errors since it will
// be cleared by the context
TF_LITE_ENSURE_OK(
context_, context_->ResizeTensor(context_, new_tensor,
// Resize Tensor takes ownership of
// the dims array passed as param
TfLiteIntArrayCopy(tensor->dims)));
// Convert the int8 value into corresponding uint8 value;
const auto num_elements = NumElements(tensor);
for (int i = 0; i < num_elements; ++i) {
new_tensor->data.uint8[i] = static_cast<const uint8_t>(
static_cast<int32_t>(tensor->data.int8[i]) + 128);
}
RETURN_TFLITE_ERROR_IF_NN_ERROR(
context_,
nnapi_->ANeuralNetworksModel_setOperandValue(
nn_model_, ann_tensor_index, new_tensor->data.raw,
new_tensor->bytes),
"setting new operand value", nnapi_errno_);
#ifdef TFLITE_NNAPI_ALLOW_MMAP_SHARING
} else if (tensor->allocation &&
static_cast<const Allocation*>(tensor->allocation)->type() ==
Allocation::Type::kMMap) {
const MMAPAllocation* mmap_alloc =
static_cast<const MMAPAllocation*>(tensor->allocation);
if (allocation_memory_mapping_->count(mmap_alloc) == 0) {
ANeuralNetworksMemory* ann_memory_handle = nullptr;
nnapi_->ANeuralNetworksMemory_createFromFd(
mmap_alloc->bytes(), PROT_READ, mmap_alloc->fd(), 0,
&ann_memory_handle);
allocation_memory_mapping_->insert(
std::make_pair(mmap_alloc, ann_memory_handle));
}
ANeuralNetworksMemory* ann_memory_handle =
allocation_memory_mapping_->at(mmap_alloc);
// Compute the offset to the base pointer of the MMAPAllocation.
auto offset = reinterpret_cast<const uint8_t*>(tensor->data.raw) -
reinterpret_cast<const uint8_t*>(mmap_alloc->base());
RETURN_TFLITE_ERROR_IF_NN_ERROR(
context_,
nnapi_->ANeuralNetworksModel_setOperandValueFromMemory(
nn_model_, ann_tensor_index, ann_memory_handle, offset,
tensor->bytes),
"setting new operand value from memory", nnapi_errno_);
#endif
} else {
RETURN_TFLITE_ERROR_IF_NN_ERROR(
context_,
nnapi_->ANeuralNetworksModel_setOperandValue(
nn_model_, ann_tensor_index, tensor->data.raw, tensor->bytes),
"setting new operand value", nnapi_errno_);
}
}
indices->push_back(ann_tensor_index);
return kTfLiteOk;
}
// Access to NNAPI.
const NnApi* const nnapi_;
// TfLiteContext for error handling.
TfLiteContext* const context_;
// Tracks relationship between indices.
OperandMapping* const operand_mapping_;
// Keeps mapping of ANN quantized tensor and float data type to equivalent
// dequantized ANN tensor. For example, tensor #4 (UINT8) + FLOAT32 could map
// to tensor #10 (FLOAT32) because a DEQUANTIZE operator was added to convert
// tensor #4 to a FLOAT32 tensor.
DequantizeMapping* const dequantize_mapping_;
std::map<const MMAPAllocation*, ANeuralNetworksMemory*>* const
allocation_memory_mapping_;
// Tracks for every operation in the NNAPI model the source TfLite model
// node index.
std::vector<int>* const nnapi_to_tflite_op_mapping_;
// The NNAPI model.
ANeuralNetworksModel* const nn_model_;
// Inputs and outputs for the current op. These are augmented in the sense
// that NN API uses operands for all arguments, not just tensors, unlike
// TensorFlow Lite.
std::vector<uint32_t> augmented_inputs_;
std::vector<uint32_t> augmented_outputs_;
// Return status code of the latest NNAPI call.
int* nnapi_errno_;
}; // namespace nnapi
namespace {
struct OpValidationContext {
bool is_valid;
std::vector<NNAPIValidationFailure>* validation_failures;
};
#define EXPECT_INPUT_TYPE_IN(actual_type, ...) \
ExpectTypeIn(actual_type, {__VA_ARGS__}, \
NNAPIValidationFailureType::kUnsupportedInputType, \
"Input type not in expected list " #__VA_ARGS__, &val_ctx)
inline void AddValidationFailure(NNAPIValidationFailureType failure_type,
const char* message,
OpValidationContext* val_ctx) {
val_ctx->is_valid = false;
#ifdef NNAPI_VERBOSE_VALIDATION
if (val_ctx->validation_failures) {
val_ctx->validation_failures->push_back({failure_type, message});
}
#endif
}
template <typename... Args>
inline void AddValidationFailureFmt(OpValidationContext* val_ctx,
NNAPIValidationFailureType failure_type,
const char* message_fmt, Args... args) {
val_ctx->is_valid = false;
#ifdef NNAPI_VERBOSE_VALIDATION
if (val_ctx->validation_failures) {
size_t req_buf_size = snprintf(nullptr, 0, message_fmt, args...) + 1;
std::unique_ptr<char[]> tmp_buf(new char[req_buf_size]);
snprintf(tmp_buf.get(), req_buf_size, message_fmt, args...);
val_ctx->validation_failures->push_back({failure_type, tmp_buf.get()});
}
#endif
}
inline bool Expect(bool condition, NNAPIValidationFailureType failure_type,
const char* message, OpValidationContext* val_ctx) {
if (!condition) {
AddValidationFailure(failure_type, message, val_ctx);
return false;
}
return true;
}
template <typename... Args>
inline bool ExpectFmt(bool condition, OpValidationContext* val_ctx,
NNAPIValidationFailureType failure_type,
const char* message_fmt, Args... args) {
if (!condition) {
AddValidationFailureFmt(val_ctx, failure_type, message_fmt, args...);
return false;
}
return true;
}
inline bool ExpectTypeIn(TfLiteType actual_type,
std::initializer_list<TfLiteType> allowed_types,
NNAPIValidationFailureType failure_type,
const char* msg, OpValidationContext* val_ctx) {
return Expect(std::find(allowed_types.begin(), allowed_types.end(),
actual_type) != allowed_types.end(),
failure_type, msg, val_ctx);
}
inline bool ExpectMinAndroidSdkVersion(int curr_version, int min_version,
OpValidationContext* val_ctx) {
return ExpectFmt(curr_version >= min_version, val_ctx,
NNAPIValidationFailureType::kUnsupportedAndroidVersion,
"Android sdk version less than %d", min_version);
}
inline bool ExpectMaxOpVersion(int curr_version, int max_version,
OpValidationContext* val_ctx) {
return ExpectFmt(curr_version <= max_version, val_ctx,
NNAPIValidationFailureType::kUnsupportedOperatorVersion,
"OP Version higher than %d", max_version);
}
inline bool ExpectOpVersion(int curr_version, int max_version,
OpValidationContext* val_ctx) {
return ExpectFmt(curr_version <= max_version, val_ctx,
NNAPIValidationFailureType::kUnsupportedOperatorVersion,
"OP Version different from %d", max_version);
}
inline bool ExpectIsFloatOperator(const TfLiteContext* context,
const TfLiteNode* node,
OpValidationContext* val_ctx) {
const auto input_type = context->tensors[node->inputs->data[0]].type;
return Expect(IsFloat(input_type),
NNAPIValidationFailureType::kUnsupportedInputType,
"Input should be Float", val_ctx);
}
bool ExpectIsFloatOrUint8Operator(const TfLiteContext* context,
const TfLiteNode* node,
OpValidationContext* val_ctx) {
const auto input_type = context->tensors[node->inputs->data[0]].type;
return Expect(IsFloatOrUInt8(input_type),
NNAPIValidationFailureType::kUnsupportedInputType,
"Input should be Float or UINT8", val_ctx);
}
bool ExpectIsFloatOrQuant8Operator(const TfLiteContext* context,
const TfLiteNode* node,
OpValidationContext* val_ctx) {
const auto input_type = context->tensors[node->inputs->data[0]].type;
return Expect(IsFloat(input_type) || IsQuantized(input_type),
NNAPIValidationFailureType::kUnsupportedInputType,
"Input should be Float or Quant8", val_ctx);
}
// When using NN API version 1.0 or 1.1, the condition below must be true for
// quantized versions of the following ops:
// * CONV_2D
// * DEPTHWISE_CONV_2D
// * FULLY_CONNECTED (where filter actually stands for weights)
// The condition is relaxed and no longer required since version 1.2.
bool ExpectIsRestrictedScalesCompliant(const TfLiteContext* context,
const TfLiteNode* node,
OpValidationContext* val_ctx) {
const int input_id = node->inputs->data[0];
const int filter_id = node->inputs->data[1];
const int output_id = node->outputs->data[0];
const float input_scale = context->tensors[input_id].params.scale;
const float filter_scale = context->tensors[filter_id].params.scale;
const float output_scale = context->tensors[output_id].params.scale;
return Expect(input_scale * filter_scale < output_scale,
NNAPIValidationFailureType::kNotRestrictedScaleCompliant,
"When using NN API version 1.0 or 1.1, input_scale * "
"filter_scale < output_scale:",
val_ctx);
}
} // namespace
// Return a function that knows how to translate a node into its operands
// when called. You can use this function to see if a node is supported
// (i.e. if the returned MappingFn is null, then the node is not supported).
bool NNAPIDelegateKernel::Validate(
const TfLiteContext* context, int builtin_code, int version,
int android_sdk_version, const TfLiteNode* node,
bool is_accelerator_specified,
std::vector<NNAPIValidationFailure>* map_failures) {
OpValidationContext val_ctx{true, map_failures};
switch (builtin_code) {
case kTfLiteBuiltinAdd: {
ExpectMaxOpVersion(version, 2, &val_ctx);
ExpectIsFloatOrQuant8Operator(context, node, &val_ctx);
} break;
case kTfLiteBuiltinArgMax:
case kTfLiteBuiltinArgMin: {
ExpectMaxOpVersion(version, 2, &val_ctx);
// Those operators were introduced in NNAPI 1.2.
ExpectMinAndroidSdkVersion(android_sdk_version, kMinSdkVersionForNNAPI12,
&val_ctx);
const TfLiteType input_type =
context->tensors[node->inputs->data[(0)]].type;
EXPECT_INPUT_TYPE_IN(input_type, kTfLiteFloat16, kTfLiteFloat32,
kTfLiteInt32, kTfLiteUInt8, kTfLiteInt8);
const auto& axis_tensor = context->tensors[node->inputs->data[1]];
if (axis_tensor.type == kTfLiteInt64) {
Expect(
axis_tensor.allocation_type == kTfLiteMmapRo &&
*axis_tensor.data.i64 <= std::numeric_limits<int32_t>::max() &&
*axis_tensor.data.i64 >= std::numeric_limits<int32_t>::min(),
NNAPIValidationFailureType::kUnsupportedInputType,
"NNAPI only supports axis as int32. If the axis type is int64 and "
"constant we can convert it to int32 if the value isn't too "
"large.",
&val_ctx);
} else {
Expect(axis_tensor.type == kTfLiteInt32,
NNAPIValidationFailureType::kUnsupportedInputType,
"Axis should be Int32", &val_ctx);
}
if (builtin_code == kTfLiteBuiltinArgMax) {
auto builtin =
reinterpret_cast<TfLiteArgMaxParams*>(node->builtin_data);
Expect(builtin->output_type == kTfLiteInt32,
NNAPIValidationFailureType::kUnsupportedOutputType,
"NNAPI only supports int32 output.", &val_ctx);
} else {
auto builtin =
reinterpret_cast<TfLiteArgMinParams*>(node->builtin_data);
Expect(builtin->output_type == kTfLiteInt32,
NNAPIValidationFailureType::kUnsupportedOutputType,
"NNAPI only supports int32 output.", &val_ctx);
}
} break;
case kTfLiteBuiltinMul: {
ExpectMaxOpVersion(version, 2, &val_ctx);
ExpectIsFloatOrQuant8Operator(context, node, &val_ctx);
} break;
case kTfLiteBuiltinAveragePool2d: {
ExpectMaxOpVersion(version, 2, &val_ctx);
ExpectIsFloatOrQuant8Operator(context, node, &val_ctx);
auto builtin = reinterpret_cast<TfLitePoolParams*>(node->builtin_data);
// TODO(b/138756912): Large filter window would overflow on the
// quantized reference CPU path.
if (IsQuantized(context->tensors[node->inputs->data[0]].type)) {
Expect(is_accelerator_specified ||
(builtin->filter_width * builtin->filter_height <= 256),
NNAPIValidationFailureType::kUnsupportedOperandSize,
"Large filter window would overflow on the reference CPU path",
&val_ctx);
}
} break;
case kTfLiteBuiltinMaxPool2d: {
ExpectMaxOpVersion(version, 2, &val_ctx);
ExpectIsFloatOrQuant8Operator(context, node, &val_ctx);
} break;
case kTfLiteBuiltinL2Pool2d: {
ExpectOpVersion(version, 1, &val_ctx);
ExpectIsFloatOperator(context, node, &val_ctx);
if (android_sdk_version < kMinSdkVersionForNNAPI12) {
auto builtin = reinterpret_cast<TfLitePoolParams*>(node->builtin_data);
Expect(builtin->activation == kTfLiteActNone,
NNAPIValidationFailureType::kUnsupportedOperandValue,
"Before NNAPI 1.2 fused activation for l2_pool may not be "
"supported.",
&val_ctx);
}
} break;
case kTfLiteBuiltinConv2d: {
ExpectMaxOpVersion(version, 3, &val_ctx);
if (android_sdk_version < kMinSdkVersionForNNAPI12) {
Expect(!IsHybridOperator(context, builtin_code, node),
NNAPIValidationFailureType::kUnsupportedHybridOperator,
"Hybrid operators not supported before NNAPI 1.2", &val_ctx);
ExpectIsFloatOrUint8Operator(context, node, &val_ctx);
const auto& filter_tensor = context->tensors[node->inputs->data[1]];
if (filter_tensor.quantization.type == kTfLiteAffineQuantization) {
TfLiteAffineQuantization* quantization_params =
static_cast<TfLiteAffineQuantization*>(
filter_tensor.quantization.params);
Expect(quantization_params->scale->size <= 1,
NNAPIValidationFailureType::kUnsupportedQuantizationType,
"Per-channel quantized convolution not supported before NNAPI "
"1.2.",
&val_ctx);
}
}
const auto input_type = context->tensors[node->inputs->data[0]].type;
if (android_sdk_version < kMinSdkVersionForNNAPI12 &&
input_type == kTfLiteUInt8) {
ExpectIsRestrictedScalesCompliant(context, node, &val_ctx);
}
auto builtin = reinterpret_cast<TfLiteConvParams*>(node->builtin_data);
// TODO(b/132950584): Add support for Conv2D with omitted bias.
Expect(node->inputs->size == 3,
NNAPIValidationFailureType::kMissingRequiredOperand,
"Conv2D with omitted bias not supported", &val_ctx);
if (builtin->dilation_width_factor != 1 ||
builtin->dilation_height_factor != 1) {
Expect(android_sdk_version >= kMinSdkVersionForNNAPI12,
NNAPIValidationFailureType::kUnsupportedOperandValue,
"NNAPI supports dilated Conv2D since NNAPI 1.2.", &val_ctx);
}
} break;
case kTfLiteBuiltinDepthwiseConv2d: {
ExpectMaxOpVersion(version, 3, &val_ctx);
if (android_sdk_version < kMinSdkVersionForNNAPI12) {
ExpectIsFloatOrUint8Operator(context, node, &val_ctx);
const auto input_type = context->tensors[node->inputs->data[0]].type;
if (input_type == kTfLiteUInt8) {
ExpectIsRestrictedScalesCompliant(context, node, &val_ctx);
}
auto builtin =
reinterpret_cast<TfLiteDepthwiseConvParams*>(node->builtin_data);
Expect(builtin->dilation_width_factor == 1 &&
builtin->dilation_height_factor == 1,
NNAPIValidationFailureType::kUnsupportedOperandValue,
"dilation_width_factor and dilation_height_factor expected to "
"be equal to 1",
&val_ctx);
}
} break;
case kTfLiteBuiltinFullyConnected: {
ExpectMaxOpVersion(version, 4, &val_ctx);
// TODO(b/132950584): Add support for FullyConnected with no bias.
Expect(node->inputs->size == 3 &&
node->inputs->data[2] != kTfLiteOptionalTensor,
NNAPIValidationFailureType::kMissingRequiredOperand,
"FullyConnected with no bias not supported", &val_ctx);
const auto output_type = context->tensors[node->outputs->data[0]].type;
Expect(output_type != kTfLiteInt16,
NNAPIValidationFailureType::kUnsupportedOutputType,
"Unsupported output of type kTfLiteInt16", &val_ctx);
if (android_sdk_version < kMinSdkVersionForNNAPI12) {
Expect(!IsHybridOperator(context, builtin_code, node),
NNAPIValidationFailureType::kUnsupportedHybridOperator,
"Hybrid operators not supported before NNAPI 1.2", &val_ctx);
ExpectIsFloatOrUint8Operator(context, node, &val_ctx);
}
const auto input_type = context->tensors[node->inputs->data[0]].type;
if (android_sdk_version < kMinSdkVersionForNNAPI12 &&
input_type == kTfLiteUInt8) {
ExpectIsRestrictedScalesCompliant(context, node, &val_ctx);
}
auto builtin =
reinterpret_cast<TfLiteFullyConnectedParams*>(node->builtin_data);
Expect(!builtin->keep_num_dims,
NNAPIValidationFailureType::kUnsupportedOperandValue,
"keep_num_dims == true not supported", &val_ctx);
} break;
case kTfLiteBuiltinHardSwish: {
// Add support for hardswish. For Pre-Q devices, deconstructing it into
// basic ops. Though for some nnapi accelerators using optimized tflite
// kernels might even be faster.
ExpectIsFloatOrQuant8Operator(context, node, &val_ctx);
} break;
case kTfLiteBuiltinSoftmax: {
ExpectOpVersion(version, 2, &val_ctx);
const auto& input = context->tensors[node->outputs->data[0]];
ExpectIsFloatOrQuant8Operator(context, node, &val_ctx);
const int input_rank = input.dims->size;
Expect(input_rank <= 4,
NNAPIValidationFailureType::kUnsupportedOperandRank,
"Input rank should be <= 4", &val_ctx);
if (android_sdk_version < kMinSdkVersionForNNAPI12) {
Expect(
input_rank == 2 || input_rank == 4,
NNAPIValidationFailureType::kUnsupportedOperandRank,
"Before API level 29 only 2D and 4D input tensors were supported.",
&val_ctx);
}
} break;
case kTfLiteBuiltinReshape: {
ExpectOpVersion(version, 1, &val_ctx);
ExpectIsFloatOrQuant8Operator(context, node, &val_ctx);
Expect(node->inputs->size >= 2,
NNAPIValidationFailureType::kMissingRequiredOperand,
"Expected at least 2 inputs", &val_ctx);
if (node->inputs->size >= 2) {
Expect(context->tensors[node->inputs->data[1]].allocation_type ==
kTfLiteMmapRo,
NNAPIValidationFailureType::kInputTensorShouldHaveConstantShape,
"The shape input tensor must be constant.", &val_ctx);
}
} break;
case kTfLiteBuiltinResizeBilinear: {
ExpectMaxOpVersion(version, 2, &val_ctx);
const auto& input = context->tensors[node->inputs->data[0]];
const auto output_dims = context->tensors[node->outputs->data[0]].dims;
Expect(input.dims->size == 4,
NNAPIValidationFailureType::kUnsupportedOperandRank,
"Input should have rank 4", &val_ctx);
ExpectIsFloatOrQuant8Operator(context, node, &val_ctx);
Expect(node->inputs->size >= 2,
NNAPIValidationFailureType::kUnsupportedOperatorVariant,
"Expected at least 2 inputs", &val_ctx);
if (node->inputs->size >= 2) {
Expect(context->tensors[node->inputs->data[1]].allocation_type ==
kTfLiteMmapRo,
NNAPIValidationFailureType::kInputTensorShouldHaveConstantShape,
"The size input tensor must be constant.", &val_ctx);
}
if (android_sdk_version < kMinSdkVersionForNNAPI12) {
Expect(output_dims->data[1] == output_dims->data[2],
NNAPIValidationFailureType::kUnsupportedOperandValue,
"Require width == height due to driver differences in NNAPI "
"< 1.2",
&val_ctx);
}
auto builtin =
reinterpret_cast<TfLiteResizeBilinearParams*>(node->builtin_data);
if (android_sdk_version <= kMinSdkVersionForNNAPI12) {
Expect(!builtin->align_corners,
NNAPIValidationFailureType::kUnsupportedOperandValue,
"NNAPI does not support align_corners == true.", &val_ctx);
Expect(!builtin->half_pixel_centers,
NNAPIValidationFailureType::kUnsupportedOperandValue,
"NNAPI does not support half_pixel_centers == true.", &val_ctx);
}
if (android_sdk_version < kMinSdkVersionForNNAPI12) {
Expect(input.type == kTfLiteFloat32,
NNAPIValidationFailureType::kUnsupportedInputType,
"NNAPI 1.0 & 1.1 only supports float input.", &val_ctx);
}
} break;
case kTfLiteBuiltinResizeNearestNeighbor: {
ExpectMaxOpVersion(version, 2, &val_ctx);
ExpectMinAndroidSdkVersion(android_sdk_version, kMinSdkVersionForNNAPI12,
&val_ctx);
ExpectIsFloatOrQuant8Operator(context, node, &val_ctx);
auto builtin = reinterpret_cast<TfLiteResizeNearestNeighborParams*>(
node->builtin_data);
if (android_sdk_version <= kMinSdkVersionForNNAPI12) {
Expect(!builtin->align_corners,
NNAPIValidationFailureType::kUnsupportedOperandValue,
"NNAPI does not support align_corners == true.", &val_ctx);
Expect(!builtin->half_pixel_centers,
NNAPIValidationFailureType::kUnsupportedOperandValue,
"NNAPI does not support half_pixel_centers == true.", &val_ctx);
}
} break;
case kTfLiteBuiltinSqueeze: {
ExpectOpVersion(version, 1, &val_ctx);
ExpectMinAndroidSdkVersion(android_sdk_version, kMinSdkVersionForNNAPI11,
&val_ctx);
auto builtin = reinterpret_cast<TfLiteSqueezeParams*>(node->builtin_data);
if (android_sdk_version == kMinSdkVersionForNNAPI11) {
Expect(builtin->num_squeeze_dims != 0,
NNAPIValidationFailureType::kUnsupportedOperandValue,
"NNAPI 1.1 does not support null squeeze_dims properly.",
&val_ctx);
}
} break;
case kTfLiteBuiltinUnidirectionalSequenceLstm: {
ExpectMaxOpVersion(version, 2, &val_ctx);
ExpectMinAndroidSdkVersion(android_sdk_version, kMinSdkVersionForNNAPI12,
&val_ctx);
Expect(!IsHybridOperator(context, builtin_code, node),
NNAPIValidationFailureType::kUnsupportedHybridOperator,
"Hybrid version of this op is not supported by NN API.", &val_ctx);
Expect(node->inputs->size == 20 || node->inputs->size == 24,
NNAPIValidationFailureType::kUnsupportedOperatorVariant,
"Supporting only operation with 20 or 24 inputs", &val_ctx);
} break;
case kTfLiteBuiltinL2Normalization: {
ExpectMaxOpVersion(version, 2, &val_ctx);
if (android_sdk_version < kMinSdkVersionForNNAPI12) {
ExpectIsFloatOperator(context, node, &val_ctx);
const auto& input = context->tensors[node->inputs->data[0]];
Expect(input.dims->size == 4,
NNAPIValidationFailureType::kUnsupportedOperatorVariant,
"Expected 4 inputs", &val_ctx);
}
auto builtin = reinterpret_cast<TfLiteL2NormParams*>(node->builtin_data);
Expect(builtin->activation == kTfLiteActNone,
NNAPIValidationFailureType::kNoActivationExpected,
"Expected no activation", &val_ctx);
} break;
case kTfLiteBuiltinLocalResponseNormalization: {
ExpectOpVersion(version, 1, &val_ctx);
} break;
case kTfLiteBuiltinLshProjection: {
ExpectOpVersion(version, 1, &val_ctx);
if (reinterpret_cast<TfLiteLSHProjectionParams*>(node->builtin_data)
->type == kTfLiteLshProjectionSparse) {
// NNAPI does not support sparse projection correctly pre-Q
// (b/111751836).
Expect(android_sdk_version >= kMinSdkVersionForNNAPI12,
NNAPIValidationFailureType::kUnsupportedInputType,
"NNAPI does not support sparse projection correctly pre-Q",
&val_ctx);
Expect(node->inputs->size == 2,
NNAPIValidationFailureType::kUnsupportedOperatorVariant,
" NNAPI does not support weights for sparse projects.",
&val_ctx);
}
} break;
case kTfLiteBuiltinConcatenation: {
ExpectMaxOpVersion(version, 2, &val_ctx);
Expect(reinterpret_cast<TfLiteConcatenationParams*>(node->builtin_data)
->activation == kTfLiteActNone,
NNAPIValidationFailureType::kNoActivationExpected,
"No activation function supported", &val_ctx);
Expect(context->tensors[node->inputs->data[0]].dims->size <= 4,
NNAPIValidationFailureType::kUnsupportedOperandRank,
"Input rank should be less than 4", &val_ctx);
if (context->tensors[node->inputs->data[0]].type == kTfLiteUInt8 &&
android_sdk_version < kMinSdkVersionForNNAPI12) {
auto first_param = context->tensors[node->inputs->data[0]].params;
for (int i = 1; i < node->inputs->size; i++) {
auto curr_param = context->tensors[node->inputs->data[i]].params;
if (!Expect(curr_param.scale == first_param.scale &&
curr_param.zero_point == first_param.zero_point,
NNAPIValidationFailureType::kUnsupportedOperandValue,
"NNAPI 1.0-1 only supported concatenating quantized "
"tensor of the same scale and offset.",
&val_ctx)) {
break;
}
}
}
} break;
case kTfLiteBuiltinDequantize: {
Expect(version == 1 || version == 2,
NNAPIValidationFailureType::kUnsupportedOperatorVersion,
"Supported op versions are 1 and 2 only", &val_ctx);
const auto& input = context->tensors[node->inputs->data[0]];
Expect(input.type != kTfLiteFloat16,
NNAPIValidationFailureType::kUnsupportedInputType,
"kTfLiteFloat16 not supported as input", &val_ctx);
const auto zero_point = input.params.zero_point;
Expect(input.type != kTfLiteInt8 ||
(zero_point == 0 &&
android_sdk_version >= kMinSdkVersionForNNAPI12),
NNAPIValidationFailureType::kUnsupportedInputType,
"NN API supports int8 type since version 1.2 but only for "
"symmetric quantization.",
&val_ctx);
} break;
case kTfLiteBuiltinFloor: {
ExpectOpVersion(version, 1, &val_ctx);
} break;
case kTfLiteBuiltinRelu:
case kTfLiteBuiltinReluN1To1:
case kTfLiteBuiltinRelu6:
case kTfLiteBuiltinLogistic: {
ExpectMaxOpVersion(version, 2, &val_ctx);
ExpectIsFloatOrQuant8Operator(context, node, &val_ctx);
} break;
case kTfLiteBuiltinTanh: {
ExpectMaxOpVersion(version, 2, &val_ctx);
const TfLiteType input_type =
context->tensors[node->inputs->data[0]].type;
Expect(IsFloat(input_type) ||
(IsQuantized(input_type) &&
android_sdk_version >= kMinSdkVersionForNNAPI12),
NNAPIValidationFailureType::kUnsupportedInputType,
" NNAPI only support float tanh.", &val_ctx);
} break;
case kTfLiteBuiltinSub: {
ExpectMaxOpVersion(version, 3, &val_ctx);
const TfLiteType input_type =
context->tensors[node->inputs->data[0]].type;
Expect((android_sdk_version >= kMinSdkVersionForNNAPI11 &&
IsFloat(input_type)) ||
(android_sdk_version >= kMinSdkVersionForNNAPI12 &&
IsQuantized(input_type)),
NNAPIValidationFailureType::kUnsupportedInputType,
"NNAPI only support float sub.", &val_ctx);
const int input0_rank =
context->tensors[node->inputs->data[0]].dims->size;
const int input1_rank =
context->tensors[node->inputs->data[1]].dims->size;
Expect(input0_rank <= 4 && input1_rank <= 4,
NNAPIValidationFailureType::kUnsupportedOperandRank,
"Input rank must be <= 4", &val_ctx);
} break;
case kTfLiteBuiltinDiv: {
ExpectOpVersion(version, 1, &val_ctx);
ExpectMinAndroidSdkVersion(android_sdk_version, kMinSdkVersionForNNAPI11,
&val_ctx);
Expect(context->tensors[node->inputs->data[0]].type == kTfLiteFloat32,
NNAPIValidationFailureType::kUnsupportedInputType,
"NNAPI only support float div.", &val_ctx);
} break;
case kTfLiteBuiltinPad:
case kTfLiteBuiltinPadv2: {
ExpectMaxOpVersion(version, 2, &val_ctx);
ExpectIsFloatOrQuant8Operator(context, node, &val_ctx);
ExpectMinAndroidSdkVersion(android_sdk_version, kMinSdkVersionForNNAPI11,
&val_ctx);
const TfLiteIntArrayView input_shape(
context->tensors[node->inputs->data[0]].dims);
Expect(!HasZeroes(input_shape),
NNAPIValidationFailureType::kUnsupportedOperandValue,
"NN API pad ops do not support input tensors with no elements",
&val_ctx);
Expect(node->inputs->size >= 2,
NNAPIValidationFailureType::kUnsupportedOperatorVariant,
"Expecting at least 2 inputs", &val_ctx);
if (node->inputs->size == 3) {
// This is going to be mapped with a PadV2
Expect(
android_sdk_version >= kMinSdkVersionForNNAPI12,
NNAPIValidationFailureType::kUnsupportedOperatorVariant,
"Specification of the padding value is supported from NNAPI 1.2.",
&val_ctx);
} else { // this is going to be mapped as Pad
if (android_sdk_version < kMinSdkVersionForNNAPI12) {
Expect(context->tensors[node->inputs->data[0]].type == kTfLiteFloat32,
NNAPIValidationFailureType::kUnsupportedInputType,
"Only Float32 inputs are supported before NNAPI 1.2",
&val_ctx);
}
}
} break;
case kTfLiteBuiltinUnidirectionalSequenceRnn: {
ExpectOpVersion(version, 1, &val_ctx);
ExpectMinAndroidSdkVersion(android_sdk_version, kMinSdkVersionForNNAPI12,
&val_ctx);
Expect(!IsHybridOperator(context, builtin_code, node),
NNAPIValidationFailureType::kUnsupportedHybridOperator,
"Hybrid version of this op is not supported by NN API.", &val_ctx);
} break;
case kTfLiteBuiltinSpaceToBatchNd: {
ExpectMaxOpVersion(version, 2, &val_ctx);
ExpectMinAndroidSdkVersion(android_sdk_version, kMinSdkVersionForNNAPI11,
&val_ctx);
} break;
case kTfLiteBuiltinBatchToSpaceNd: {
ExpectMaxOpVersion(version, 2, &val_ctx);
ExpectMinAndroidSdkVersion(android_sdk_version, kMinSdkVersionForNNAPI11,
&val_ctx);
auto crops = context->tensors[node->inputs->data[2]];
auto crops_data = crops.data.i32;
Expect(crops_data && crops.bytes == 16 && crops_data[0] == 0 &&
crops_data[1] == 0 && crops_data[2] == 0 && crops_data[3] == 0,
NNAPIValidationFailureType::kUnsupportedOperandValue,
"All crops should be 0.", &val_ctx);
} break;
case kTfLiteBuiltinStridedSlice: {
ExpectMaxOpVersion(version, 2, &val_ctx);
ExpectMinAndroidSdkVersion(android_sdk_version, kMinSdkVersionForNNAPI11,
&val_ctx);
} break;
case kTfLiteBuiltinTranspose: {
ExpectMaxOpVersion(version, 2, &val_ctx);
ExpectMinAndroidSdkVersion(android_sdk_version, kMinSdkVersionForNNAPI11,
&val_ctx);
// Note that the permutation input tensor value dictates the output
// dimensions.
// TODO(b/110888333): Support dynamically-sized tensors in delegates.
Expect((node->inputs->size > 1) &&
(context->tensors[node->inputs->data[1]].allocation_type ==
kTfLiteMmapRo),
NNAPIValidationFailureType::kInputTensorShouldHaveConstantShape,
"Dynamically-sized tensors not supported.", &val_ctx);
} break;
case kTfLiteBuiltinAbs:
case kTfLiteBuiltinExp:
case kTfLiteBuiltinLog:
case kTfLiteBuiltinRsqrt:
case kTfLiteBuiltinPow: {
ExpectOpVersion(version, 1, &val_ctx);
ExpectMinAndroidSdkVersion(android_sdk_version, kMinSdkVersionForNNAPI12,
&val_ctx);
ExpectIsFloatOperator(context, node, &val_ctx);
} break;
case kTfLiteBuiltinSlice: {
ExpectMaxOpVersion(version, 2, &val_ctx);
ExpectMinAndroidSdkVersion(android_sdk_version, kMinSdkVersionForNNAPI12,
&val_ctx);
const auto input_type = context->tensors[node->inputs->data[0]].type;
const auto begin_type = context->tensors[node->inputs->data[1]].type;
const auto size_type = context->tensors[node->inputs->data[2]].type;
EXPECT_INPUT_TYPE_IN(input_type, kTfLiteFloat32, kTfLiteInt32,
kTfLiteUInt8, kTfLiteInt8);
Expect(begin_type == kTfLiteInt32,
NNAPIValidationFailureType::kUnsupportedInputType,
"Begin type should be Int32", &val_ctx);
Expect(size_type == kTfLiteInt32,
NNAPIValidationFailureType::kUnsupportedInputType,
"Size type should be Int32", &val_ctx);
} break;
case kTfLiteBuiltinSin: {
ExpectOpVersion(version, 1, &val_ctx);
ExpectMinAndroidSdkVersion(android_sdk_version, kMinSdkVersionForNNAPI12,
&val_ctx);
ExpectIsFloatOperator(context, node, &val_ctx);
} break;
case kTfLiteBuiltinTransposeConv: {
ExpectOpVersion(version, 1, &val_ctx);
ExpectMinAndroidSdkVersion(android_sdk_version, kMinSdkVersionForNNAPI12,
&val_ctx);
Expect((node->inputs->size > 1) &&
(context->tensors[node->inputs->data[0]].allocation_type ==
kTfLiteMmapRo) &&
(context->tensors[node->inputs->data[1]].allocation_type ==
kTfLiteMmapRo),
NNAPIValidationFailureType::kInputTensorShouldHaveConstantShape,
"Dynamically-sized tensors not supported.", &val_ctx);
} break;
case kTfLiteBuiltinSqrt: {
ExpectOpVersion(version, 1, &val_ctx);
ExpectMinAndroidSdkVersion(android_sdk_version, kMinSdkVersionForNNAPI12,
&val_ctx);
ExpectIsFloatOperator(context, node, &val_ctx);
} break;
case kTfLiteBuiltinRnn: {
ExpectOpVersion(version, 1, &val_ctx);
Expect(node->inputs->size == 5,
NNAPIValidationFailureType::kUnsupportedOperatorVariant,
"Expected 5 input", &val_ctx);
if (node->inputs->size >= 2) {
Expect(
context->tensors[node->inputs->data[/*kWeightsTensor*/ 1]].type ==
kTfLiteFloat32,
NNAPIValidationFailureType::kUnsupportedInputType,
"NNAPI only support float32 weights.", &val_ctx);
}
} break;
case kTfLiteBuiltinSpaceToDepth: {
ExpectMaxOpVersion(version, 2, &val_ctx);
const TfLiteType input_type =
context->tensors[node->inputs->data[0]].type;
EXPECT_INPUT_TYPE_IN(input_type, kTfLiteFloat32, kTfLiteUInt8,
kTfLiteInt8);
} break;
case kTfLiteBuiltinSvdf: {
ExpectOpVersion(version, 1, &val_ctx);
Expect(node->inputs->size == 5,
NNAPIValidationFailureType::kUnsupportedOperandRank,
"Expected input of rank 5", &val_ctx);
if (node->inputs->size >= 2) {
Expect(
context->tensors[node->inputs->data[/*kWeightsTensor*/ 1]].type ==
kTfLiteFloat32,
NNAPIValidationFailureType::kUnsupportedInputType,
"NNAPI only support float32 weights.", &val_ctx);
}
Expect(android_sdk_version >= kMinSdkVersionForNNAPI11,
NNAPIValidationFailureType::kUnsupportedOperandRank,
"SVDF does not support rank > 1 on NNAPI 1.0.", &val_ctx);
Expect(context->tensors[node->inputs->data[/*kWeightsFeatureTensor*/ 1]]
.type == kTfLiteFloat32,
NNAPIValidationFailureType::kUnsupportedInputType,
"Weights should be Float32", &val_ctx);
} break;
case kTfLiteBuiltinLstm: {
ExpectMaxOpVersion(version, 3, &val_ctx);
Expect(
android_sdk_version >= kMinSdkVersionForNNAPI11,
NNAPIValidationFailureType::kUnsupportedAndroidVersion,
"NNAPI 1.0 has a bug for optional tensors which would affect LSTM.",
&val_ctx);
Expect(android_sdk_version >= kMinSdkVersionForNNAPI12 ||
!IsHybridOperator(context, builtin_code, node),
NNAPIValidationFailureType::kUnsupportedHybridOperator,
"Hybrid operators not supported before NNAPI 1.2.", &val_ctx);
const auto weight_input_index =
isLstmBasicKernel(node) ? 2 /* basic::kInputWeights */
: 4 /* full::kInputToOutputWeightsTensor */;
const TfLiteType weight_type =
context->tensors[node->inputs->data[weight_input_index]].type;
if (isLstmBasicKernel(node)) {
Expect(weight_type == kTfLiteUInt8,
NNAPIValidationFailureType::kUnsupportedInputType,
"Basic LSTM Kernels support only UINT8 weights", &val_ctx);
const auto input_quantization_params =
context->tensors[node->inputs->data[0]].params;
Expect(input_quantization_params.scale == 1. / 128. &&
input_quantization_params.zero_point == 128,
NNAPIValidationFailureType::kUnsupportedQuantizationParameters,
"Invalid input quantization", &val_ctx);
const auto output_quantization_params =
context->tensors[node->outputs->data[0]].params;
Expect(output_quantization_params.scale == 1. / 128. &&
output_quantization_params.zero_point == 128,
NNAPIValidationFailureType::kUnsupportedQuantizationParameters,
"Invalid output quantization", &val_ctx);
const auto cell_state_quantization_params =
context->tensors[node->outputs->data[1]].params;
Expect(cell_state_quantization_params.scale == 16. / 32768. ||
cell_state_quantization_params.zero_point == 0,
NNAPIValidationFailureType::kUnsupportedQuantizationParameters,
"Invalid cell state quantization", &val_ctx);
auto is_const_tensor = [&node, &context](int tensor_idx) {
return context->tensors[node->inputs->data[tensor_idx]]
.allocation_type == kTfLiteMmapRo;
};
Expect(is_const_tensor(2 /* kInputWeights */),
NNAPIValidationFailureType::kInputTensorShouldHaveConstantShape,
"Weights tensor should be constant", &val_ctx);
Expect(is_const_tensor(3 /* kInputBiases */),
NNAPIValidationFailureType::kInputTensorShouldHaveConstantShape,
"Biases tensor should be constant", &val_ctx);
return val_ctx.is_valid;
} else {
if (node->inputs->size == 24) {
ExpectMinAndroidSdkVersion(android_sdk_version,
kMinSdkVersionForNNAPI12, &val_ctx);
}
Expect(weight_type == kTfLiteFloat32 || weight_type == kTfLiteUInt8,
NNAPIValidationFailureType::kUnsupportedInputType,
"Weight has to be Float32 or UINT8", &val_ctx);
}
} break;
case kTfLiteBuiltinMean: {
ExpectMaxOpVersion(version, 2, &val_ctx);
ExpectMinAndroidSdkVersion(android_sdk_version, kMinSdkVersionForNNAPI11,
&val_ctx);
if (android_sdk_version >= kMinSdkVersionForNNAPI12) {
Expect(context->tensors[node->inputs->data[0]].type == kTfLiteFloat32 ||
IsQuantized(context->tensors[node->inputs->data[0]].type),
NNAPIValidationFailureType::kUnsupportedInputType,
"Expected Float32 or Quantized input", &val_ctx);
} else {
Expect(context->tensors[node->inputs->data[0]].type == kTfLiteFloat32,
NNAPIValidationFailureType::kUnsupportedInputType,
"Expected Float32 input", &val_ctx);
}
Expect(context->tensors[node->outputs->data[0]].dims->size > 0,
NNAPIValidationFailureType::kUnsupportedOutputType,
"NNAPI does not support generating a scalar as output for MEAN.",
&val_ctx);
auto input_param = context->tensors[node->inputs->data[0]].params;
auto output_param = context->tensors[node->outputs->data[0]].params;
Expect(input_param.scale == output_param.scale &&
input_param.zero_point == output_param.zero_point,
NNAPIValidationFailureType::kUnsupportedOutputType,
"NNAPI requires that the input and output have the same "
"quantization parameters.",
&val_ctx);
} break;
case kTfLiteBuiltinEmbeddingLookup: {
ExpectOpVersion(version, 1, &val_ctx);
Expect(context->tensors[node->inputs->data[1]].type == kTfLiteFloat32,
NNAPIValidationFailureType::kUnsupportedInputType,
"NNAPI only support float32 values.", &val_ctx);
} break;
case kTfLiteBuiltinHashtableLookup: {
ExpectOpVersion(version, 1, &val_ctx);
Expect(context->tensors[node->outputs->data[0]].type == kTfLiteFloat32,
NNAPIValidationFailureType::kUnsupportedOutputType,
"NNAPI only support float32 output.", &val_ctx);
} break;
case kTfLiteBuiltinMaximum:
case kTfLiteBuiltinMinimum: {
ExpectMaxOpVersion(version, 3, &val_ctx);
ExpectMinAndroidSdkVersion(android_sdk_version, kMinSdkVersionForNNAPI12,
&val_ctx);
const auto input_type = context->tensors[node->inputs->data[0]].type;
EXPECT_INPUT_TYPE_IN(input_type, kTfLiteFloat32, kTfLiteUInt8,
kTfLiteInt8, kTfLiteInt32);
const TfLiteTensor& operand0 = context->tensors[node->inputs->data[0]];
if (operand0.dims->size == 0) {
Expect(operand0.allocation_type == kTfLiteMmapRo,
NNAPIValidationFailureType::kUnsupportedInputType,
"Scalar operand should be constant", &val_ctx);
}
const TfLiteTensor& operand1 = context->tensors[node->inputs->data[1]];
if (operand1.dims->size == 0) {
Expect(operand1.allocation_type == kTfLiteMmapRo,
NNAPIValidationFailureType::kUnsupportedInputType,
"Scalar operand should be constant", &val_ctx);
}
} break;
case kTfLiteBuiltinCast: {
ExpectOpVersion(version, 1, &val_ctx);
ExpectMinAndroidSdkVersion(android_sdk_version, kMinSdkVersionForNNAPI12,
&val_ctx);
const TfLiteType input_type =
context->tensors[node->inputs->data[0]].type;
EXPECT_INPUT_TYPE_IN(input_type, kTfLiteFloat32, kTfLiteInt32,
kTfLiteUInt8);
const TfLiteType output_type =
context->tensors[node->outputs->data[0]].type;
ExpectTypeIn(output_type, {kTfLiteFloat32, kTfLiteInt32, kTfLiteUInt8},
NNAPIValidationFailureType::kUnsupportedOutputType,
"Output type should be one of kTfLiteFloat32, kTfLiteInt32, "
"kTfLiteUInt8.",
&val_ctx);
} break;
case kTfLiteBuiltinPrelu: {
ExpectOpVersion(version, 1, &val_ctx);
ExpectMinAndroidSdkVersion(android_sdk_version, kMinSdkVersionForNNAPI12,
&val_ctx);
ExpectIsFloatOrUint8Operator(context, node, &val_ctx);
} break;
case kTfLiteBuiltinTile: {
ExpectOpVersion(version, 1, &val_ctx);
ExpectMinAndroidSdkVersion(android_sdk_version, kMinSdkVersionForNNAPI12,
&val_ctx);
const auto input_type = context->tensors[node->inputs->data[0]].type;
EXPECT_INPUT_TYPE_IN(input_type, kTfLiteFloat32, kTfLiteInt8,
kTfLiteUInt8, kTfLiteInt32);
const auto multipliers_type =
context->tensors[node->inputs->data[1]].type;
Expect(multipliers_type == kTfLiteInt32,
NNAPIValidationFailureType::kUnsupportedInputType,
"Multipliers should be Int32", &val_ctx);
} break;
case kTfLiteBuiltinLogicalOr:
case kTfLiteBuiltinLogicalAnd:
case kTfLiteBuiltinLogicalNot: {
ExpectOpVersion(version, 1, &val_ctx);
ExpectMinAndroidSdkVersion(android_sdk_version, kMinSdkVersionForNNAPI12,
&val_ctx);
const auto input_type = context->tensors[node->inputs->data[0]].type;
Expect(input_type == kTfLiteBool,
NNAPIValidationFailureType::kUnsupportedInputType,
"Input should be bool", &val_ctx);
} break;
case kTfLiteBuiltinLess:
case kTfLiteBuiltinLessEqual:
case kTfLiteBuiltinGreater:
case kTfLiteBuiltinGreaterEqual:
case kTfLiteBuiltinEqual:
case kTfLiteBuiltinNotEqual: {
ExpectMaxOpVersion(version, 2, &val_ctx);
ExpectMinAndroidSdkVersion(android_sdk_version, kMinSdkVersionForNNAPI11,
&val_ctx);
const auto input_type = context->tensors[node->inputs->data[0]].type;
EXPECT_INPUT_TYPE_IN(input_type, kTfLiteFloat32, kTfLiteUInt8,
kTfLiteInt8, kTfLiteBool, kTfLiteInt32);
} break;
case kTfLiteBuiltinNeg: {
ExpectMaxOpVersion(version, 2, &val_ctx);
ExpectMinAndroidSdkVersion(android_sdk_version, kMinSdkVersionForNNAPI11,
&val_ctx);
const auto input_type = context->tensors[node->inputs->data[0]].type;
EXPECT_INPUT_TYPE_IN(input_type, kTfLiteFloat32, kTfLiteInt32);
} break;
case kTfLiteBuiltinTopkV2: {
ExpectMaxOpVersion(version, 2, &val_ctx);
ExpectMinAndroidSdkVersion(android_sdk_version, kMinSdkVersionForNNAPI12,
&val_ctx);
const auto& input_type = context->tensors[node->inputs->data[0]].type;
EXPECT_INPUT_TYPE_IN(input_type, kTfLiteFloat32, kTfLiteInt32,
kTfLiteUInt8, kTfLiteInt8);
const auto& k_param = context->tensors[node->inputs->data[1]];
Expect(k_param.type == kTfLiteInt32 &&
k_param.allocation_type == kTfLiteMmapRo,
NNAPIValidationFailureType::kUnsupportedInputType,
"K param should be a constant of type Int32", &val_ctx);
} break;
case kTfLiteBuiltinSelect: {
ExpectMaxOpVersion(version, 2, &val_ctx);
ExpectMinAndroidSdkVersion(android_sdk_version, kMinSdkVersionForNNAPI11,
&val_ctx);
const auto value_type = context->tensors[node->inputs->data[1]].type;
EXPECT_INPUT_TYPE_IN(value_type, kTfLiteFloat32, kTfLiteInt32,
kTfLiteUInt8, kTfLiteInt8);
TfLiteIntArray* condition_shape =
context->tensors[node->inputs->data[0]].dims;
TfLiteIntArray* input_shape =
context->tensors[node->inputs->data[1]].dims;
Expect(TfLiteIntArrayEqual(condition_shape, input_shape),
NNAPIValidationFailureType::kUnsupportedOperandValue,
"Condition and inputs tensors shuld have the same shape",
&val_ctx);
} break;
case kTfLiteBuiltinGather: {
ExpectOpVersion(version, 1, &val_ctx);
ExpectMinAndroidSdkVersion(android_sdk_version, kMinSdkVersionForNNAPI12,
&val_ctx);
const auto input_type = context->tensors[node->inputs->data[0]].type;
const auto& positions = context->tensors[node->inputs->data[1]];
EXPECT_INPUT_TYPE_IN(input_type, kTfLiteFloat32, kTfLiteFloat16,
kTfLiteInt32, kTfLiteUInt8);
ExpectTypeIn(positions.type,
{kTfLiteFloat32, kTfLiteFloat16, kTfLiteInt32, kTfLiteUInt8},
NNAPIValidationFailureType::kUnsupportedInputType,
"Positions type should be one of kTfLiteFloat32, "
"kTfLiteFloat16, kTfLiteInt32, kTfLiteUInt8",
&val_ctx);
Expect(positions.dims->size != 0,
NNAPIValidationFailureType::kUnsupportedOperandRank,
"0-dimension args are not supported by NNAPI.", &val_ctx);
} break;
case kTfLiteBuiltinBidirectionalSequenceLstm: {
ExpectOpVersion(version, 1, &val_ctx);
ExpectMinAndroidSdkVersion(android_sdk_version, kMinSdkVersionForNNAPI12,
&val_ctx);
Expect(!IsHybridOperator(context, builtin_code, node),
NNAPIValidationFailureType::kUnsupportedHybridOperator,
"Hybrid version of this op is not supported by NN API.", &val_ctx);
} break;
case kTfLiteBuiltinExpandDims: {
ExpectOpVersion(version, 1, &val_ctx);
ExpectMinAndroidSdkVersion(android_sdk_version, kMinSdkVersionForNNAPI12,
&val_ctx);
const auto input_type = context->tensors[node->inputs->data[0]].type;
EXPECT_INPUT_TYPE_IN(input_type, kTfLiteFloat32, kTfLiteFloat16,
kTfLiteInt32, kTfLiteUInt8, kTfLiteInt8);
const auto axis = context->tensors[node->inputs->data[1]];
Expect(axis.type == kTfLiteInt32 && axis.allocation_type == kTfLiteMmapRo,
NNAPIValidationFailureType::kUnsupportedInputType,
"NNAPI only supports constant int32 axis tensor.", &val_ctx);
} break;
case kTfLiteBuiltinSplit: {
ExpectOpVersion(version, 3, &val_ctx);
ExpectMinAndroidSdkVersion(android_sdk_version, kMinSdkVersionForNNAPI12,
&val_ctx);
// Tensor indices: split_dim: 0, value: 1
const TfLiteTensor& input = context->tensors[node->inputs->data[1]];
EXPECT_INPUT_TYPE_IN(input.type, kTfLiteFloat32, kTfLiteUInt8,
kTfLiteInt32);
const TfLiteTensor& axis = context->tensors[node->inputs->data[0]];
Expect(axis.type == kTfLiteInt32 && axis.allocation_type == kTfLiteMmapRo,
NNAPIValidationFailureType::kUnsupportedInputType,
"NNAPI only supports constant int32 axis tensor.", &val_ctx);
} break;
case kTfLiteBuiltinLogSoftmax: {
ExpectOpVersion(version, 1, &val_ctx);
ExpectMinAndroidSdkVersion(android_sdk_version, kMinSdkVersionForNNAPI12,
&val_ctx);
const auto input_type = context->tensors[node->inputs->data[0]].type;
Expect(input_type == kTfLiteFloat32,
NNAPIValidationFailureType::kUnsupportedInputType,
"Input should be Float32.", &val_ctx);
} break;
case kTfLiteBuiltinQuantize: {
ExpectOpVersion(version, 1, &val_ctx);
ExpectMinAndroidSdkVersion(android_sdk_version, kMinSdkVersionForNNAPI12,
&val_ctx);
const auto value_type = context->tensors[node->inputs->data[0]].type;
Expect(value_type == kTfLiteFloat32,
NNAPIValidationFailureType::kUnsupportedInputType,
"Value should be Float32.", &val_ctx);
const auto output_type = context->tensors[node->outputs->data[0]].type;
Expect(output_type == kTfLiteUInt8,
NNAPIValidationFailureType::kUnsupportedOutputType,
"Output should be kTfLiteUInt8.", &val_ctx);
const auto quantization_params =
context->tensors[node->outputs->data[0]].params;
Expect(quantization_params.scale > 0.f,
NNAPIValidationFailureType::kUnsupportedQuantizationParameters,
"Quantization scale should be > 0.", &val_ctx);
} break;
case kTfLiteBuiltinReduceAny:
case kTfLiteBuiltinReduceMin:
case kTfLiteBuiltinReduceMax: {
ExpectOpVersion(version, 1, &val_ctx);
ExpectMinAndroidSdkVersion(android_sdk_version, kMinSdkVersionForNNAPI12,
&val_ctx);
Expect(context->tensors[node->outputs->data[0]].dims->size != 0,
NNAPIValidationFailureType::kUnsupportedOutputType,
"NNAPI does not support generating a scalar as output.", &val_ctx);
if (builtin_code == kTfLiteBuiltinReduceProd) {
const auto input_type = context->tensors[node->inputs->data[0]].type;
Expect(input_type == kTfLiteFloat32,
NNAPIValidationFailureType::kUnsupportedInputType,
"NNAPI only supports floating point REDUCE_PROD.", &val_ctx);
}
} break;
case kTfLiteBuiltinDepthToSpace: {
const TfLiteType input_type =
context->tensors[node->inputs->data[0]].type;
EXPECT_INPUT_TYPE_IN(input_type, kTfLiteFloat32, kTfLiteUInt8,
kTfLiteInt8);
} break;
case kTfLiteBuiltinReduceProd:
case kTfLiteBuiltinSum: {
ExpectOpVersion(version, 1, &val_ctx);
ExpectMinAndroidSdkVersion(android_sdk_version, kMinSdkVersionForNNAPI12,
&val_ctx);
Expect(context->tensors[node->outputs->data[0]].dims->size != 0,
NNAPIValidationFailureType::kUnsupportedOutputType,
"NNAPI does not support generating a scalar as output", &val_ctx);
const auto input_type = context->tensors[node->inputs->data[0]].type;
Expect(input_type == kTfLiteFloat32,
NNAPIValidationFailureType::kUnsupportedInputType,
"NNAPI only supports floating point input.", &val_ctx);
} break;
default:
// All other operators are not mapped.
AddValidationFailure(NNAPIValidationFailureType::kUnsupportedOperator,
"Unsupported operation type.", &val_ctx);
}
return val_ctx.is_valid;
} // NOLINT(readability/fn_size)
TfLiteStatus NNAPIDelegateKernel::Map(
TfLiteContext* context, int builtin_code, int version,
int android_sdk_version, const NNAPIOpMappingArgs& mapping_args,
ANeuralNetworksOperationType* nn_op_type) {
switch (builtin_code) {
case kTfLiteBuiltinAdd: {
auto builtin =
reinterpret_cast<TfLiteAddParams*>(mapping_args.node->builtin_data);
mapping_args.builder->AddScalarInt32Operand(builtin->activation);
*nn_op_type = ANEURALNETWORKS_ADD;
} break;
case kTfLiteBuiltinArgMax: {
*nn_op_type = ANEURALNETWORKS_ARGMAX;
} break;
case kTfLiteBuiltinArgMin: {
*nn_op_type = ANEURALNETWORKS_ARGMIN;
} break;
case kTfLiteBuiltinMul: {
auto builtin =
reinterpret_cast<TfLiteMulParams*>(mapping_args.node->builtin_data);
mapping_args.builder->AddScalarInt32Operand(builtin->activation);
*nn_op_type = ANEURALNETWORKS_MUL;
} break;
case kTfLiteBuiltinAveragePool2d: {
mapping_args.builder->AddPoolingParams(mapping_args.node->builtin_data);
*nn_op_type = ANEURALNETWORKS_AVERAGE_POOL_2D;
} break;
case kTfLiteBuiltinMaxPool2d: {
mapping_args.builder->AddPoolingParams(mapping_args.node->builtin_data);
*nn_op_type = ANEURALNETWORKS_MAX_POOL_2D;
} break;
case kTfLiteBuiltinL2Pool2d: {
mapping_args.builder->AddPoolingParams(mapping_args.node->builtin_data);
*nn_op_type = ANEURALNETWORKS_L2_POOL_2D;
} break;
case kTfLiteBuiltinConv2d: {
auto builtin =
reinterpret_cast<TfLiteConvParams*>(mapping_args.node->builtin_data);
mapping_args.builder->AddScalarInt32Operand(builtin->padding);
mapping_args.builder->AddScalarInt32Operand(builtin->stride_width);
mapping_args.builder->AddScalarInt32Operand(builtin->stride_height);
mapping_args.builder->AddScalarInt32Operand(builtin->activation);
// NNAPI supports dilated Conv2D since NNAPI 1.2.
if (builtin->dilation_width_factor != 1 ||
builtin->dilation_height_factor != 1) {
mapping_args.builder->AddScalarBoolOperand(false); // Use NHWC format
mapping_args.builder->AddScalarInt32Operand(
builtin->dilation_width_factor);
mapping_args.builder->AddScalarInt32Operand(
builtin->dilation_height_factor);
}
*nn_op_type = ANEURALNETWORKS_CONV_2D;
} break;
case kTfLiteBuiltinDepthwiseConv2d: {
auto builtin = reinterpret_cast<TfLiteDepthwiseConvParams*>(
mapping_args.node->builtin_data);
mapping_args.builder->AddScalarInt32Operand(builtin->padding);
mapping_args.builder->AddScalarInt32Operand(builtin->stride_width);
mapping_args.builder->AddScalarInt32Operand(builtin->stride_height);
mapping_args.builder->AddScalarInt32Operand(builtin->depth_multiplier);
mapping_args.builder->AddScalarInt32Operand(builtin->activation);
if (builtin->dilation_width_factor != 1 ||
builtin->dilation_height_factor != 1) {
mapping_args.builder->AddScalarBoolOperand(false); // Use NHWC format.
mapping_args.builder->AddScalarInt32Operand(
builtin->dilation_width_factor);
mapping_args.builder->AddScalarInt32Operand(
builtin->dilation_height_factor);
}
*nn_op_type = ANEURALNETWORKS_DEPTHWISE_CONV_2D;
} break;
case kTfLiteBuiltinFullyConnected: {
auto builtin = reinterpret_cast<TfLiteFullyConnectedParams*>(
mapping_args.node->builtin_data);
mapping_args.builder->AddScalarInt32Operand(builtin->activation);
*nn_op_type = ANEURALNETWORKS_FULLY_CONNECTED;
} break;
case kTfLiteBuiltinSoftmax: {
auto builtin = reinterpret_cast<TfLiteSoftmaxParams*>(
mapping_args.node->builtin_data);
mapping_args.builder->AddScalarFloat32Operand(builtin->beta);
// Optional scalar specifying the dimension the activation would be
// performed on is not added. Default to -1.
*nn_op_type = ANEURALNETWORKS_SOFTMAX;
} break;
case kTfLiteBuiltinReshape: {
*nn_op_type = ANEURALNETWORKS_RESHAPE;
} break;
case kTfLiteBuiltinResizeBilinear: {
const int output_id = mapping_args.node->outputs->data[0];
auto& output = mapping_args.context->tensors[output_id];
const int output_height = output.dims->data[1];
const int output_width = output.dims->data[2];
mapping_args.builder->AddScalarInt32Operand(output_width);
mapping_args.builder->AddScalarInt32Operand(output_height);
auto builtin = reinterpret_cast<TfLiteResizeBilinearParams*>(
mapping_args.node->builtin_data);
if (builtin->align_corners == true ||
builtin->half_pixel_centers == true) {
mapping_args.builder->AddScalarBoolOperand(false); // Use NHWC format
mapping_args.builder->AddScalarBoolOperand(builtin->align_corners);
mapping_args.builder->AddScalarBoolOperand(builtin->half_pixel_centers);
}
*nn_op_type = ANEURALNETWORKS_RESIZE_BILINEAR;
} break;
case kTfLiteBuiltinResizeNearestNeighbor: {
const TfLiteTensor& new_shape =
mapping_args.context->tensors[mapping_args.node->inputs->data[1]];
// NNAPI uses scalar inputs for height and width.
mapping_args.builder->AddScalarInt32Operand(new_shape.data.i32[1]);
mapping_args.builder->AddScalarInt32Operand(new_shape.data.i32[0]);
mapping_args.builder->AddScalarBoolOperand(false); // Use NHWC format
auto builtin = reinterpret_cast<TfLiteResizeNearestNeighborParams*>(
mapping_args.node->builtin_data);
if (builtin->align_corners == true ||
builtin->half_pixel_centers == true) {
mapping_args.builder->AddScalarBoolOperand(builtin->align_corners);
mapping_args.builder->AddScalarBoolOperand(builtin->half_pixel_centers);
}
*nn_op_type = ANEURALNETWORKS_RESIZE_NEAREST_NEIGHBOR;
} break;
case kTfLiteBuiltinSqueeze: {
auto builtin = reinterpret_cast<TfLiteSqueezeParams*>(
mapping_args.node->builtin_data);
// Note that we add the squeeze dimensions even if the dimensions
// were unspecified (empty), as NNAPI requires the operand.
mapping_args.builder->AddVectorInt32Operand(
builtin->num_squeeze_dims ? builtin->squeeze_dims : nullptr,
static_cast<uint32_t>(builtin->num_squeeze_dims));
*nn_op_type = ANEURALNETWORKS_SQUEEZE;
} break;
case kTfLiteBuiltinUnidirectionalSequenceLstm: {
auto builtin = reinterpret_cast<TfLiteUnidirectionalSequenceLSTMParams*>(
mapping_args.node->builtin_data);
mapping_args.builder->AddScalarInt32Operand(builtin->activation);
mapping_args.builder->AddScalarFloat32Operand(builtin->cell_clip);
mapping_args.builder->AddScalarFloat32Operand(builtin->proj_clip);
mapping_args.builder->AddScalarBoolOperand(builtin->time_major);
const bool hybrid_op = IsHybridOperator(
mapping_args.context, kTfLiteBuiltinUnidirectionalSequenceLstm,
mapping_args.node);
if (mapping_args.node->inputs->size == 24) {
// Add layer normalization tensors if they are provided.
for (int i = 20; i < 24; ++i) {
const int input_index = mapping_args.node->inputs->data[i];
if (input_index != kTfLiteOptionalTensor) {
mapping_args.builder->AddTensorInput(input_index, hybrid_op);
} else {
mapping_args.builder->AddVectorFloat32Operand(nullptr, 0);
}
}
} else {
for (int i = 0; i < 4; ++i) {
mapping_args.builder->AddVectorFloat32Operand(nullptr, 0);
}
}
*nn_op_type = ANEURALNETWORKS_UNIDIRECTIONAL_SEQUENCE_LSTM;
} break;
case kTfLiteBuiltinL2Normalization: {
*nn_op_type = ANEURALNETWORKS_L2_NORMALIZATION;
} break;
case kTfLiteBuiltinLocalResponseNormalization: {
auto builtin = reinterpret_cast<TfLiteLocalResponseNormParams*>(
mapping_args.node->builtin_data);
mapping_args.builder->AddScalarInt32Operand(builtin->radius);
mapping_args.builder->AddScalarFloat32Operand(builtin->bias);
mapping_args.builder->AddScalarFloat32Operand(builtin->alpha);
mapping_args.builder->AddScalarFloat32Operand(builtin->beta);
*nn_op_type = ANEURALNETWORKS_LOCAL_RESPONSE_NORMALIZATION;
} break;
case kTfLiteBuiltinLshProjection: {
auto builtin = reinterpret_cast<TfLiteLSHProjectionParams*>(
mapping_args.node->builtin_data);
int type = builtin->type;
// In Android Q+, NNAPI uses 3 to denote
// kTfLiteLshProjectionSparse.
const int kNNAPILshProjectionSparse = 3;
if (builtin->type == kTfLiteLshProjectionSparse) {
type = kNNAPILshProjectionSparse;
// Add NNAPI null weight operand.
mapping_args.builder->AddVectorFloat32Operand(nullptr, 0);
}
mapping_args.builder->AddScalarInt32Operand(type);
*nn_op_type = ANEURALNETWORKS_LSH_PROJECTION;
} break;
case kTfLiteBuiltinConcatenation: {
auto builtin = reinterpret_cast<TfLiteConcatenationParams*>(
mapping_args.node->builtin_data);
int axis = builtin->axis < 0
? mapping_args.context
->tensors[mapping_args.node->inputs->data[0]]
.dims->size +
builtin->axis
: builtin->axis;
mapping_args.builder->AddScalarInt32Operand(axis);
*nn_op_type = ANEURALNETWORKS_CONCATENATION;
} break;
case kTfLiteBuiltinDequantize: {
*nn_op_type = ANEURALNETWORKS_DEQUANTIZE;
} break;
case kTfLiteBuiltinFloor: {
*nn_op_type = ANEURALNETWORKS_FLOOR;
} break;
case kTfLiteBuiltinRelu: {
*nn_op_type = ANEURALNETWORKS_RELU;
} break;
case kTfLiteBuiltinReluN1To1: {
*nn_op_type = ANEURALNETWORKS_RELU1;
} break;
case kTfLiteBuiltinRelu6: {
*nn_op_type = ANEURALNETWORKS_RELU6;
} break;
case kTfLiteBuiltinLogistic: {
*nn_op_type = ANEURALNETWORKS_LOGISTIC;
} break;
case kTfLiteBuiltinTanh: {
*nn_op_type = ANEURALNETWORKS_TANH;
} break;
case kTfLiteBuiltinSub: {
auto builtin =
reinterpret_cast<TfLiteSubParams*>(mapping_args.node->builtin_data);
mapping_args.builder->AddScalarInt32Operand(builtin->activation);
*nn_op_type = ANEURALNETWORKS_SUB;
} break;
case kTfLiteBuiltinDiv: {
auto builtin =
reinterpret_cast<TfLiteDivParams*>(mapping_args.node->builtin_data);
mapping_args.builder->AddScalarInt32Operand(builtin->activation);
*nn_op_type = ANEURALNETWORKS_DIV;
} break;
case kTfLiteBuiltinPad:
case kTfLiteBuiltinPadv2: {
// We want to map to PAD as much as possible since it is more widely
// supported. We map to PadV2 only when there is the need to specify
// the padding value
if (mapping_args.node->inputs->size == 2) {
*nn_op_type = ANEURALNETWORKS_PAD;
} else {
const int constant_value_id = mapping_args.node->inputs->data[2];
if (constant_value_id == kTfLiteOptionalTensor) {
*nn_op_type = ANEURALNETWORKS_PAD;
} else {
*nn_op_type = ANEURALNETWORKS_PAD_V2;
}
}
} break;
case kTfLiteBuiltinUnidirectionalSequenceRnn: {
auto builtin = reinterpret_cast<TfLiteSequenceRNNParams*>(
mapping_args.node->builtin_data);
mapping_args.builder->AddScalarInt32Operand(builtin->activation);
mapping_args.builder->AddScalarInt32Operand(builtin->time_major);
*nn_op_type = ANEURALNETWORKS_UNIDIRECTIONAL_SEQUENCE_RNN;
} break;
case kTfLiteBuiltinSpaceToBatchNd: {
*nn_op_type = ANEURALNETWORKS_SPACE_TO_BATCH_ND;
} break;
case kTfLiteBuiltinBatchToSpaceNd: {
*nn_op_type = ANEURALNETWORKS_BATCH_TO_SPACE_ND;
} break;
case kTfLiteBuiltinStridedSlice: {
auto builtin = reinterpret_cast<TfLiteStridedSliceParams*>(
mapping_args.node->builtin_data);
mapping_args.builder->AddScalarInt32Operand(builtin->begin_mask);
mapping_args.builder->AddScalarInt32Operand(builtin->end_mask);
mapping_args.builder->AddScalarInt32Operand(builtin->shrink_axis_mask);
*nn_op_type = ANEURALNETWORKS_STRIDED_SLICE;
} break;
case kTfLiteBuiltinTranspose: {
*nn_op_type = ANEURALNETWORKS_TRANSPOSE;
} break;
case kTfLiteBuiltinAbs: {
*nn_op_type = ANEURALNETWORKS_ABS;
} break;
case kTfLiteBuiltinExp: {
*nn_op_type = ANEURALNETWORKS_EXP;
} break;
case kTfLiteBuiltinLog: {
*nn_op_type = ANEURALNETWORKS_LOG;
} break;
case kTfLiteBuiltinRsqrt: {
*nn_op_type = ANEURALNETWORKS_RSQRT;
} break;
case kTfLiteBuiltinPow: {
*nn_op_type = ANEURALNETWORKS_POW;
} break;
case kTfLiteBuiltinSlice: {
*nn_op_type = ANEURALNETWORKS_SLICE;
} break;
case kTfLiteBuiltinSin: {
*nn_op_type = ANEURALNETWORKS_SIN;
} break;
case kTfLiteBuiltinTransposeConv: {
const bool hybrid_op = IsHybridOperator(
mapping_args.context, kTfLiteBuiltinTransposeConv, mapping_args.node);
int input_tensor_flags = 0;
const int input_tensor_id =
mapping_args.node->inputs->data[/*kDataInputTensor*/ 2];
const int weight_tensor_id =
mapping_args.node->inputs->data[/*kWeightsTensor*/ 1];
if (context->tensors[input_tensor_id].type == kTfLiteInt8) {
const auto& weights_tensor = context->tensors[weight_tensor_id];
if ((weights_tensor.type == kTfLiteInt8 ||
weights_tensor.type == kTfLiteUInt8) &&
weights_tensor.quantization.type == kTfLiteAffineQuantization) {
input_tensor_flags |= NN_TENSOR_FLAG_SCALAR_AS_TENSOR;
}
}
mapping_args.builder->AddTensorInput(input_tensor_id, hybrid_op,
input_tensor_flags);
mapping_args.builder->AddTensorInput(weight_tensor_id, hybrid_op,
input_tensor_flags);
// NNAPI requires a bias tensor, so we allocate a new tensor to fill
// it with zeroes. It is deleted with other tensors in the context
// during subgraph destructor call.
int bias_index = -1;
mapping_args.context->AddTensors(mapping_args.context, 1, &bias_index);
TfLiteTensor* bias_tensor = &mapping_args.context->tensors[bias_index];
const auto input_type =
mapping_args.context
->tensors[mapping_args.node->inputs->data[/*kDataInputTensor*/ 2]]
.type;
if (input_type == kTfLiteFloat32) {
bias_tensor->type = kTfLiteFloat32;
} else {
bias_tensor->type = kTfLiteInt32;
}
// Create an array with a required bias shape and resize the bias
// tensor.
TfLiteIntArray* bias_shape = TfLiteIntArrayCreate(1);
const TfLiteTensor& output_shape =
mapping_args.context->tensors[mapping_args.node->inputs
->data[/*kOutputShapeTensor*/ 0]];
const int output_depth = output_shape.data.i32[3];
bias_shape->data[0] = output_depth;
bias_tensor->allocation_type = kTfLiteDynamic;
mapping_args.context->ResizeTensor(mapping_args.context, bias_tensor,
bias_shape);
// Set tensor's values to zeroes and add it using AddVector*, so
// that the values are copied to NNAPI. We don't use the AddTensor
// function because it doesn't copy values and the tensor we just
// created is not in the node->inputs.
if (input_type == kTfLiteFloat32) {
memset(bias_tensor->data.f, 0, output_depth * sizeof(float));
mapping_args.builder->AddVectorFloat32Operand(bias_tensor->data.f,
output_depth);
} else {
memset(bias_tensor->data.i32, 0, output_depth * sizeof(int));
const TfLiteTensor& input_tensor =
mapping_args.context->tensors[mapping_args.node->inputs
->data[/*kDataInputTensor*/ 2]];
const TfLiteTensor& filter_tensor =
mapping_args.context->tensors[mapping_args.node->inputs
->data[/*kWeightsTensor*/ 1]];
// NNAPI requires bias scale to be a product of an input scale and
// a filter scale.
bias_tensor->params.scale =
input_tensor.params.scale * filter_tensor.params.scale;
mapping_args.builder->AddVectorInt32Operand(
bias_tensor->data.i32, output_depth,
input_tensor.params.scale * filter_tensor.params.scale,
/*zero_point=*/0);
}
mapping_args.builder->AddTensorInput(
mapping_args.node->inputs->data[/*kOutputShapeTensor*/ 0], hybrid_op);
auto builtin = reinterpret_cast<TfLiteTransposeConvParams*>(
mapping_args.node->builtin_data);
mapping_args.builder->AddScalarInt32Operand(builtin->padding);
mapping_args.builder->AddScalarInt32Operand(builtin->stride_width);
mapping_args.builder->AddScalarInt32Operand(builtin->stride_height);
mapping_args.builder->AddScalarInt32Operand(
/*ANEURALNETWORKS_FUSED_NONE*/ 0);
// Use NHWC layout for input and output.
mapping_args.builder->AddScalarBoolOperand(false);
*nn_op_type = ANEURALNETWORKS_TRANSPOSE_CONV;
} break;
case kTfLiteBuiltinSqrt: {
*nn_op_type = ANEURALNETWORKS_SQRT;
} break;
case kTfLiteBuiltinRnn: {
// NNAPI need both state_in and state_out.
int ann_index;
mapping_args.builder->AddStateFloat32Tensor(
mapping_args.node->inputs->data[/*kHiddenStateTensor*/ 4],
&ann_index);
mapping_args.model_state_outputs->push_back(ann_index);
mapping_args.model_state_tfl_inputs->push_back(
mapping_args.node->inputs->data[/*kHiddenStateTensor*/ 4]);
auto builtin =
reinterpret_cast<TfLiteRNNParams*>(mapping_args.node->builtin_data);
mapping_args.builder->AddScalarInt32Operand(builtin->activation);
*nn_op_type = ANEURALNETWORKS_RNN;
} break;
case kTfLiteBuiltinSpaceToDepth: {
auto builtin = reinterpret_cast<TfLiteSpaceToDepthParams*>(
mapping_args.node->builtin_data);
mapping_args.builder->AddScalarInt32Operand(builtin->block_size);
*nn_op_type = ANEURALNETWORKS_SPACE_TO_DEPTH;
} break;
case kTfLiteBuiltinSvdf: {
// NNAPI need both state_in and state_out.
int ann_index;
mapping_args.builder->AddStateFloat32Tensor(
mapping_args.node->inputs->data[/*kInputActivationStateTensor*/ 4],
&ann_index);
mapping_args.model_state_outputs->push_back(ann_index);
mapping_args.model_state_tfl_inputs->push_back(
mapping_args.node->inputs->data[/*kInputActivationStateTensor*/ 4]);
auto builtin =
reinterpret_cast<TfLiteSVDFParams*>(mapping_args.node->builtin_data);
mapping_args.builder->AddScalarInt32Operand(builtin->rank);
mapping_args.builder->AddScalarInt32Operand(builtin->activation);
*nn_op_type = ANEURALNETWORKS_SVDF;
} break;
case kTfLiteBuiltinLstm: {
if (isLstmBasicKernel(mapping_args.node)) {
const auto output_dims =
mapping_args.context->tensors[mapping_args.node->outputs->data[1]]
.dims;
// Inputs kInputData
mapping_args.builder->AddTensorInput(
mapping_args.node->inputs->data[0 /* kInputData */],
/* hybrid_op */ false,
/* scalar_as_tensor */ false);
// The 8 weights tensors are set decomposing the
// kInputWeights param
const auto weight_tensor =
mapping_args.context->tensors[mapping_args.node->inputs
->data[2 /* kInputWeights */]];
std::vector<uint8_t> recurrent_to_input;
std::vector<uint8_t> input_to_input;
std::vector<uint8_t> recurrent_to_cell;
std::vector<uint8_t> input_to_cell;
std::vector<uint8_t> recurrent_to_forget;
std::vector<uint8_t> input_to_forget;
std::vector<uint8_t> recurrent_to_output;
std::vector<uint8_t> input_to_output;
tflite::delegate::nnapi::DecomposeQuantLstmWeightsTensor(
weight_tensor.data.uint8, weight_tensor.dims, &recurrent_to_input,
&input_to_input, &recurrent_to_cell, &input_to_cell,
&recurrent_to_forget, &input_to_forget, &recurrent_to_output,
&input_to_output);
TfLiteIntArray* recurrent_weight_dims = TfLiteIntArrayCreate(2);
TfLiteIntArray* input_weight_dims = TfLiteIntArrayCreate(2);
tflite::delegate::nnapi::SetWeightSubmatrixDims(
weight_tensor.dims, recurrent_weight_dims, input_weight_dims);
int new_tensor_index = -1;
mapping_args.builder->AddNewInputConstantTensor<uint8_t>(
ANEURALNETWORKS_TENSOR_QUANT8_ASYMM, kTfLiteUInt8,
input_weight_dims, input_to_input, weight_tensor.params,
&new_tensor_index);
mapping_args.builder->AddNewInputConstantTensor<uint8_t>(
ANEURALNETWORKS_TENSOR_QUANT8_ASYMM, kTfLiteUInt8,
input_weight_dims, input_to_forget, weight_tensor.params,
&new_tensor_index);
mapping_args.builder->AddNewInputConstantTensor<uint8_t>(
ANEURALNETWORKS_TENSOR_QUANT8_ASYMM, kTfLiteUInt8,
input_weight_dims, input_to_cell, weight_tensor.params,
&new_tensor_index);
mapping_args.builder->AddNewInputConstantTensor<uint8_t>(
ANEURALNETWORKS_TENSOR_QUANT8_ASYMM, kTfLiteUInt8,
input_weight_dims, input_to_output, weight_tensor.params,
&new_tensor_index);
mapping_args.builder->AddNewInputConstantTensor<uint8_t>(
ANEURALNETWORKS_TENSOR_QUANT8_ASYMM, kTfLiteUInt8,
recurrent_weight_dims, recurrent_to_input, weight_tensor.params,
&new_tensor_index);
mapping_args.builder->AddNewInputConstantTensor<uint8_t>(
ANEURALNETWORKS_TENSOR_QUANT8_ASYMM, kTfLiteUInt8,
recurrent_weight_dims, recurrent_to_forget, weight_tensor.params,
&new_tensor_index);
mapping_args.builder->AddNewInputConstantTensor<uint8_t>(
ANEURALNETWORKS_TENSOR_QUANT8_ASYMM, kTfLiteUInt8,
recurrent_weight_dims, recurrent_to_cell, weight_tensor.params,
&new_tensor_index);
mapping_args.builder->AddNewInputConstantTensor<uint8_t>(
ANEURALNETWORKS_TENSOR_QUANT8_ASYMM, kTfLiteUInt8,
recurrent_weight_dims, recurrent_to_output, weight_tensor.params,
&new_tensor_index);
TfLiteIntArrayFree(input_weight_dims);
TfLiteIntArrayFree(recurrent_weight_dims);
// Biases have to be split in four.
const auto bias_size = output_dims->data[1];
const TfLiteTensor& biases_tensor =
mapping_args.context->tensors[mapping_args.node->inputs
->data[3 /* kInputBiases */]];
std::vector<int32_t> input_bias;
std::vector<int32_t> cell_bias;
std::vector<int32_t> forget_bias;
std::vector<int32_t> output_bias;
delegate::nnapi::DecomposeBiasTensor(biases_tensor.data.i32, bias_size,
&input_bias, &cell_bias,
&forget_bias, &output_bias);
int input_bias_tensor = -1;
mapping_args.builder->AddNewInputConstantTensor<int32_t>(
ANEURALNETWORKS_TENSOR_INT32, kTfLiteInt32, {bias_size}, input_bias,
biases_tensor.params, &input_bias_tensor);
int forget_bias_tensor = -1;
mapping_args.builder->AddNewInputConstantTensor(
ANEURALNETWORKS_TENSOR_INT32, kTfLiteInt32, {bias_size},
forget_bias, biases_tensor.params, &forget_bias_tensor);
int cell_gate_bias_tensor = -1;
mapping_args.builder->AddNewInputConstantTensor(
ANEURALNETWORKS_TENSOR_INT32, kTfLiteInt32, {bias_size}, cell_bias,
biases_tensor.params, &cell_gate_bias_tensor);
int output_gate_bias_tensor = -1;
mapping_args.builder->AddNewInputConstantTensor(
ANEURALNETWORKS_TENSOR_INT32, kTfLiteInt32, {bias_size},
output_bias, biases_tensor.params, &output_gate_bias_tensor);
mapping_args.builder->AddTensorInput(
mapping_args.node->inputs->data[4 /* kInputPrevState */],
/* hybrid_op */ false,
/* scalar_as_tensor */ false);
// kInputPrevActivation
mapping_args.builder->AddTensorInput(
mapping_args.node->inputs->data[1 /* kInputPrevActivation */],
/* hybrid_op */ false,
/* scalar_as_tensor */ false);
// Configuring the copy from the activation, state outputs
// to their associated inputs
mapping_args.feedback_loops->push_back(std::make_tuple(
mapping_args.node->outputs->data[0 /*kOutputActivation*/],
mapping_args.node->inputs->data[1 /*kInputPrevActivation*/]));
mapping_args.feedback_loops->push_back(std::make_tuple(
mapping_args.node->outputs->data[1 /*kOutputState*/],
mapping_args.node->inputs->data[4 /*kInputPrevState*/]));
// OUTPUTS
// Setting only the first two since the remaining ones are
// ignored by NNAPI
mapping_args.builder->AddTensorOutput(
mapping_args.node->outputs->data[1 /* kOutputState */], 0);
mapping_args.builder->AddTensorOutput(
mapping_args.node->outputs->data[0 /* kOutputActivation */], 0);
*nn_op_type = ANEURALNETWORKS_QUANTIZED_16BIT_LSTM;
} else {
auto builtin = reinterpret_cast<TfLiteLSTMParams*>(
mapping_args.node->builtin_data);
mapping_args.builder->AddScalarInt32Operand(builtin->activation);
mapping_args.builder->AddScalarFloat32Operand(builtin->cell_clip);
mapping_args.builder->AddScalarFloat32Operand(builtin->proj_clip);
// Current NNAPI implementation requires the scratch_buffer as
// output.
mapping_args.builder->AddAdditionalFloat32OutputTensor(2);
// NNAPI need both state_in and state_out for cell_state and
// output_state.
int ann_index;
mapping_args.builder->AddStateFloat32Tensor(
mapping_args.node->inputs->data[/*kInputActivationStateTensor*/ 18],
&ann_index);
mapping_args.model_state_outputs->push_back(ann_index);
mapping_args.model_state_tfl_inputs->push_back(
mapping_args.node->inputs
->data[/*kInputActivationStateTensor*/ 18]);
mapping_args.builder->AddStateFloat32Tensor(
mapping_args.node->inputs->data[/*kInputCellStateTensor*/ 19],
&ann_index);
mapping_args.model_state_outputs->push_back(ann_index);
mapping_args.model_state_tfl_inputs->push_back(
mapping_args.node->inputs->data[/*kInputCellStateTensor*/ 19]);
const bool hybrid_op = IsHybridOperator(
mapping_args.context, kTfLiteBuiltinLstm, mapping_args.node);
if (mapping_args.node->inputs->size == 24) {
for (int i = 20; i < 24; ++i) {
const auto input_index = mapping_args.node->inputs->data[i];
if (input_index != kTfLiteOptionalTensor) {
mapping_args.builder->AddTensorInput(input_index, hybrid_op);
} else {
mapping_args.builder->AddVectorFloat32Operand(nullptr, 0);
}
}
}
*nn_op_type = ANEURALNETWORKS_LSTM;
}
} break;
case kTfLiteBuiltinMean: {
auto builtin = reinterpret_cast<TfLiteReducerParams*>(
mapping_args.node->builtin_data);
int32_t keep_dims = 0;
if (builtin->keep_dims) keep_dims = 1;
mapping_args.builder->AddScalarInt32Operand(keep_dims);
*nn_op_type = ANEURALNETWORKS_MEAN;
} break;
case kTfLiteBuiltinEmbeddingLookup: {
*nn_op_type = ANEURALNETWORKS_EMBEDDING_LOOKUP;
} break;
case kTfLiteBuiltinHashtableLookup: {
*nn_op_type = ANEURALNETWORKS_HASHTABLE_LOOKUP;
} break;
case kTfLiteBuiltinMaximum: {
*nn_op_type = ANEURALNETWORKS_MAXIMUM;
} break;
case kTfLiteBuiltinMinimum: {
*nn_op_type = ANEURALNETWORKS_MINIMUM;
} break;
case kTfLiteBuiltinCast: {
*nn_op_type = ANEURALNETWORKS_CAST;
} break;
case kTfLiteBuiltinPrelu: {
*nn_op_type = ANEURALNETWORKS_PRELU;
} break;
case kTfLiteBuiltinTile: {
*nn_op_type = ANEURALNETWORKS_TILE;
} break;
case kTfLiteBuiltinLogicalOr: {
*nn_op_type = ANEURALNETWORKS_LOGICAL_OR;
} break;
case kTfLiteBuiltinLogicalAnd: {
*nn_op_type = ANEURALNETWORKS_LOGICAL_AND;
} break;
case kTfLiteBuiltinLogicalNot: {
*nn_op_type = ANEURALNETWORKS_LOGICAL_NOT;
} break;
case kTfLiteBuiltinLess: {
*nn_op_type = ANEURALNETWORKS_LESS;
} break;
case kTfLiteBuiltinLessEqual: {
*nn_op_type = ANEURALNETWORKS_LESS_EQUAL;
} break;
case kTfLiteBuiltinGreater: {
*nn_op_type = ANEURALNETWORKS_GREATER;
} break;
case kTfLiteBuiltinGreaterEqual: {
*nn_op_type = ANEURALNETWORKS_GREATER_EQUAL;
} break;
case kTfLiteBuiltinEqual: {
*nn_op_type = ANEURALNETWORKS_EQUAL;
} break;
case kTfLiteBuiltinNotEqual: {
*nn_op_type = ANEURALNETWORKS_NOT_EQUAL;
} break;
case kTfLiteBuiltinNeg: {
*nn_op_type = ANEURALNETWORKS_NEG;
} break;
case kTfLiteBuiltinTopkV2: {
const TfLiteTensor& k_param =
mapping_args.context->tensors[mapping_args.node->inputs->data[1]];
mapping_args.builder->AddScalarInt32Operand(*k_param.data.i32);
*nn_op_type = ANEURALNETWORKS_TOPK_V2;
} break;
case kTfLiteBuiltinSelect: {
*nn_op_type = ANEURALNETWORKS_SELECT;
} break;
case kTfLiteBuiltinGather: {
auto builtin = reinterpret_cast<TfLiteGatherParams*>(
mapping_args.node->builtin_data);
mapping_args.builder->AddTensorInput(mapping_args.node->inputs->data[0],
/* hybrid_op */ false,
/* scalar_as_tensor */ false);
mapping_args.builder->AddScalarInt32Operand(builtin->axis);
mapping_args.builder->AddTensorInput(mapping_args.node->inputs->data[1],
/* hybrid_op */ false,
/* scalar_as_tensor */ false);
*nn_op_type = ANEURALNETWORKS_GATHER;
} break;
case kTfLiteBuiltinBidirectionalSequenceLstm: {
auto builtin = reinterpret_cast<TfLiteBidirectionalSequenceLSTMParams*>(
mapping_args.node->builtin_data);
mapping_args.builder->AddScalarInt32Operand(builtin->activation);
mapping_args.builder->AddScalarFloat32Operand(builtin->cell_clip);
mapping_args.builder->AddScalarFloat32Operand(builtin->proj_clip);
mapping_args.builder->AddScalarBoolOperand(builtin->merge_outputs);
mapping_args.builder->AddScalarBoolOperand(builtin->time_major);
// TF Lite doesn't support layer normalization in bidirectional
// sequence LSTM, so we insert optional tensors for NNAPI.
for (int i = 0; i < 8; ++i) {
mapping_args.builder->AddVectorFloat32Operand(nullptr, 0);
}
*nn_op_type = ANEURALNETWORKS_BIDIRECTIONAL_SEQUENCE_LSTM;
} break;
case kTfLiteBuiltinExpandDims: {
const TfLiteTensor& axis_param =
mapping_args.context->tensors[mapping_args.node->inputs->data[1]];
mapping_args.builder->AddScalarInt32Operand(*axis_param.data.i32);
*nn_op_type = ANEURALNETWORKS_EXPAND_DIMS;
} break;
case kTfLiteBuiltinSplit: {
const TfLiteTensor& axis =
mapping_args.context->tensors[mapping_args.node->inputs->data[0]];
auto builtin =
reinterpret_cast<TfLiteSplitParams*>(mapping_args.node->builtin_data);
mapping_args.builder->AddScalarInt32Operand(*axis.data.i32);
mapping_args.builder->AddScalarInt32Operand(builtin->num_splits);
*nn_op_type = ANEURALNETWORKS_SPLIT;
} break;
case kTfLiteBuiltinLogSoftmax: {
// Scaling and axis are hardcoded to respectively 1 and -1
// in TFLite.
mapping_args.builder->AddScalarFloat32Operand(1);
mapping_args.builder->AddScalarInt32Operand(-1);
*nn_op_type = ANEURALNETWORKS_LOG_SOFTMAX;
} break;
case kTfLiteBuiltinQuantize: {
*nn_op_type = ANEURALNETWORKS_QUANTIZE;
} break;
case kTfLiteBuiltinReduceAny: {
auto builtin = reinterpret_cast<TfLiteReducerParams*>(
mapping_args.node->builtin_data);
mapping_args.builder->AddScalarBoolOperand(builtin->keep_dims);
*nn_op_type = ANEURALNETWORKS_REDUCE_ANY;
} break;
case kTfLiteBuiltinReduceMin: {
auto builtin = reinterpret_cast<TfLiteReducerParams*>(
mapping_args.node->builtin_data);
mapping_args.builder->AddScalarBoolOperand(builtin->keep_dims);
*nn_op_type = ANEURALNETWORKS_REDUCE_MIN;
} break;
case kTfLiteBuiltinReduceMax: {
auto builtin = reinterpret_cast<TfLiteReducerParams*>(
mapping_args.node->builtin_data);
mapping_args.builder->AddScalarBoolOperand(builtin->keep_dims);
*nn_op_type = ANEURALNETWORKS_REDUCE_MAX;
} break;
case kTfLiteBuiltinDepthToSpace: {
auto builtin = reinterpret_cast<TfLiteDepthToSpaceParams*>(
mapping_args.node->builtin_data);
mapping_args.builder->AddScalarInt32Operand(builtin->block_size);
*nn_op_type = ANEURALNETWORKS_DEPTH_TO_SPACE;
} break;
case kTfLiteBuiltinReduceProd: {
auto builtin = reinterpret_cast<TfLiteReducerParams*>(
mapping_args.node->builtin_data);
mapping_args.builder->AddScalarBoolOperand(builtin->keep_dims);
*nn_op_type = ANEURALNETWORKS_REDUCE_PROD;
} break;
case kTfLiteBuiltinSum: {
auto builtin = reinterpret_cast<TfLiteReducerParams*>(
mapping_args.node->builtin_data);
mapping_args.builder->AddScalarBoolOperand(builtin->keep_dims);
*nn_op_type = ANEURALNETWORKS_REDUCE_SUM;
} break;
default:
// All other operators are not mapped.
return kTfLiteError;
}
return kTfLiteOk;
}
// Initialize the kernel (a NN model).
TfLiteStatus NNAPIDelegateKernel::Init(TfLiteContext* context,
const TfLiteDelegateParams* params,
int* nnapi_errno) {
for (auto node_index : TfLiteIntArrayView(params->nodes_to_replace)) {
nodes_.push_back(node_index);
}
const auto delegate_options =
StatefulNnApiDelegate::GetOptions(params->delegate);
if (nnapi_->android_sdk_version >= kMinSdkVersionForNNAPI12 &&
ShouldUseTargetDevices(delegate_options)) {
TF_LITE_ENSURE_STATUS(GetTargetDevices(context, params->delegate, nnapi_,
nnapi_errno, &nnapi_devices_));
if (nnapi_devices_.empty()) {
context->ReportError(
context, "NNAPI delegate requested but no accelerators available.");
return kTfLiteError;
}
}
// Mark the handle backed tensors.
tensor_memory_map_ =
&StatefulNnApiDelegate::GetTensorMemoryMap(params->delegate);
if (!nn_model_) {
ANeuralNetworksModel* model = nullptr;
RETURN_TFLITE_ERROR_IF_NN_ERROR(context,
nnapi_->ANeuralNetworksModel_create(&model),
"creating NNAPI model", nnapi_errno);
nn_model_.reset(model);
TF_LITE_ENSURE_STATUS(BuildGraph(context, delegate_options,
params->input_tensors,
params->output_tensors, nnapi_errno));
}
// Calculating model compilation cache here since the value depends on
// some of the TfLiteDelegateParams
nn_compilation_cache_token_.clear();
const char* cache_dir = delegate_options.cache_dir;
const char* model_token = delegate_options.model_token;
if (nnapi_->android_sdk_version >= kMinSdkVersionForNNAPI12 && cache_dir &&
model_token) {
// Compilation caching could be enabled, try construct the uint8
// token.
// TODO(b/133342794): use a generic token generator class.
uint64_t token_parts[4];
// bits from model_token.
token_parts[0] = std::hash<std::string>{}(model_token);
// bits from params->nodes_to_replace.
token_parts[1] = GetHash(params->nodes_to_replace);
// bits from params->input_tensors.
token_parts[2] = GetHash(params->input_tensors);
// bits from params->output_tensors.
token_parts[3] = GetHash(params->output_tensors);
// NNAPI requires the token to be 256bit long.
std::vector<uint8_t> nnapi_cache_token(32, 0);
// Copy the token bits.
uint8_t* p = reinterpret_cast<uint8_t*>(token_parts);
for (int i = 0; i < 4 * sizeof(uint64_t); i++) {
nnapi_cache_token[i] = p[i];
}
nn_compilation_cache_token_ = nnapi_cache_token;
}
initialised_ = true;
return kTfLiteOk;
}
TfLiteStatus NNAPIDelegateKernel::Prepare(TfLiteContext* context,
TfLiteNode* node, int* nnapi_errno) {
if (!initialised_) {
return kTfLiteError;
}
if (nn_compilation_) {
return kTfLiteOk;
}
const auto delegate_options =
StatefulNnApiDelegate::GetOptions(node->delegate);
ANeuralNetworksCompilation* compilation = nullptr;
if (!nnapi_devices_.empty()) {
// Compile for the selected accelerator.
RETURN_TFLITE_ERROR_IF_NN_ERROR(
context,
nnapi_->ANeuralNetworksCompilation_createForDevices(
nn_model_.get(), nnapi_devices_.data(), nnapi_devices_.size(),
&compilation),
"creating NNAPI model for given devices", nnapi_errno);
} else {
RETURN_TFLITE_ERROR_IF_NN_ERROR(context,
nnapi_->ANeuralNetworksCompilation_create(
nn_model_.get(), &compilation),
"creating NNAPI compilation", nnapi_errno);
}
auto preference = delegate_options.execution_preference;
if (preference !=
StatefulNnApiDelegate::Options::ExecutionPreference::kUndefined) {
const int preference_result =
nnapi_->ANeuralNetworksCompilation_setPreference(compilation,
preference);
if (preference_result != ANEURALNETWORKS_NO_ERROR) {
nnapi_->ANeuralNetworksCompilation_free(compilation);
compilation = nullptr;
}
RETURN_TFLITE_ERROR_IF_NN_ERROR(context, preference_result,
"setting compilation preferences",
nnapi_errno);
}
if (!nn_compilation_cache_token_.empty()) {
const char* cache_dir = delegate_options.cache_dir;
const int set_caching_result =
nnapi_->ANeuralNetworksCompilation_setCaching(
compilation, cache_dir, nn_compilation_cache_token_.data());
if (set_caching_result != ANEURALNETWORKS_NO_ERROR) {
nnapi_->ANeuralNetworksCompilation_free(compilation);
compilation = nullptr;
}
RETURN_TFLITE_ERROR_IF_NN_ERROR(context, set_caching_result,
"configuring NNAPI caching", nnapi_errno);
}
const int finish_result =
nnapi_->ANeuralNetworksCompilation_finish(compilation);
if (finish_result != ANEURALNETWORKS_NO_ERROR) {
nnapi_->ANeuralNetworksCompilation_free(compilation);
compilation = nullptr;
}
RETURN_TFLITE_ERROR_IF_NN_ERROR(context, finish_result,
"completing NNAPI compilation", nnapi_errno);
nn_compilation_.reset(compilation);
return kTfLiteOk;
}
TfLiteStatus NNAPIDelegateKernel::GetOperationsSupportedByTargetNnApiDevices(
TfLiteContext* context, std::vector<int>* supported_nodes,
int* nnapi_errno) {
if (!nnapi_->ANeuralNetworksModel_getSupportedOperationsForDevices) {
return kTfLiteError;
}
const auto nnapi_model_size = nnapi_to_tflite_op_mapping_.size();
// Determine the list of operations the device actually supports
auto nnapi_ops_support_flags = absl::make_unique<bool[]>(nnapi_model_size);
RETURN_TFLITE_ERROR_IF_NN_ERROR(
context,
nnapi_->ANeuralNetworksModel_getSupportedOperationsForDevices(
nn_model_.get(), nnapi_devices_.data(), nnapi_devices_.size(),
nnapi_ops_support_flags.get()),
"Checking supported operations for devices", nnapi_errno);
// A TfLite op is supported only if all the associated NNAPI ones are.
auto tflite_ops_support_status = std::map<int, bool>();
std::for_each(nodes_.begin(), nodes_.end(),
[&tflite_ops_support_status](int tflite_node_index) {
tflite_ops_support_status[tflite_node_index] = true;
});
for (int nnapi_op_index = 0; nnapi_op_index < nnapi_model_size;
nnapi_op_index++) {
const auto tflite_op_index = nnapi_to_tflite_op_mapping_[nnapi_op_index];
tflite_ops_support_status[tflite_op_index] &=
nnapi_ops_support_flags[nnapi_op_index];
}
supported_nodes->clear();
std::for_each(nodes_.begin(), nodes_.end(),
[&supported_nodes, &tflite_ops_support_status](int node_index) {
if (tflite_ops_support_status[node_index]) {
supported_nodes->push_back(node_index);
}
});
return kTfLiteOk;
}
TfLiteStatus NNAPIDelegateKernel::Invoke(TfLiteContext* context,
TfLiteNode* node, int* nnapi_errno) {
ANeuralNetworksExecution* execution = nullptr;
RETURN_TFLITE_ERROR_IF_NN_ERROR(context,
nnapi_->ANeuralNetworksExecution_create(
nn_compilation_.get(), &execution),
"creating NNAPI execution", nnapi_errno);
std::unique_ptr<ANeuralNetworksExecution, NNFreeExecution>
execution_unique_ptr(execution, NNFreeExecution(nnapi_));
// Set the input tensor buffers. Note: we access tflite tensors using
// absolute indices but NN api indices inputs by relative indices.
int relative_input_index = 0;
size_t input_offset = 0;
for (auto absolute_input_index : TfLiteIntArrayView(node->inputs)) {
if (absolute_input_index == kTfLiteOptionalTensor) {
continue;
}
TfLiteTensor* tensor = &context->tensors[absolute_input_index];
if (tensor->allocation_type != kTfLiteMmapRo) {
if (tensor->buffer_handle != kTfLiteNullBufferHandle &&
tensor->buffer_handle < tensor_memory_map_->size()) {
RETURN_TFLITE_ERROR_IF_NN_ERROR(
context,
nnapi_->ANeuralNetworksExecution_setInputFromMemory(
execution, relative_input_index, nullptr,
tensor_memory_map_->at(tensor->buffer_handle).memory, 0,
tensor->bytes),
"associating NNAPI execution input with a memory object",
nnapi_errno);
relative_input_index++;
continue;
}
TfLiteType ann_type_equivalent =
operand_mapping_.lite_index_to_ann_type_conversion(
absolute_input_index);
int tensor_size = 0;
if (ann_type_equivalent != kTfLiteNoType) {
const auto num_elements = NumElements(tensor);
uint8_t* input_ptr = nn_input_memory_->get_data_ptr() + input_offset;
if (tensor->type == kTfLiteUInt8 &&
ann_type_equivalent == kTfLiteInt32) {
for (int i = 0; i < num_elements; ++i) {
reinterpret_cast<int32_t*>(input_ptr)[i] =
static_cast<const int32_t>(tensor->data.uint8[i]);
}
} else if (tensor->type == kTfLiteInt8 &&
ann_type_equivalent == kTfLiteUInt8) {
// Explicitly convert int8 values to uint8 values.
for (int i = 0; i < num_elements; ++i) {
input_ptr[i] = static_cast<const uint8_t>(
static_cast<int32_t>(tensor->data.int8[i]) + 128);
}
} else if (tensor->type == kTfLiteInt8 &&
ann_type_equivalent == kTfLiteInt32) {
for (int i = 0; i < num_elements; ++i) {
reinterpret_cast<int32_t*>(input_ptr)[i] =
static_cast<const int32_t>(tensor->data.int8[i]) + 128;
}
} else {
context->ReportError(
context,
"NN API Delegate: unsupported tensor types conversion: "
"from type code %d to type code %d.\n",
tensor->type, ann_type_equivalent);
return kTfLiteError;
}
size_t type_size;
TF_LITE_ENSURE_OK(
context, GetSizeOfType(context, ann_type_equivalent, &type_size));
tensor_size = NumElements(tensor) * type_size;
RETURN_TFLITE_ERROR_IF_NN_ERROR(
context,
nnapi_->ANeuralNetworksExecution_setInputFromMemory(
execution, relative_input_index, nullptr,
nn_input_memory_->get_handle(), input_offset, tensor_size),
"associating NNAPI execution input with a memory object",
nnapi_errno);
} else {
// copy data to pre-allocated shared memory.
memcpy(nn_input_memory_->get_data_ptr() + input_offset,
tensor->data.raw, tensor->bytes);
RETURN_TFLITE_ERROR_IF_NN_ERROR(
context,
nnapi_->ANeuralNetworksExecution_setInputFromMemory(
execution, relative_input_index, nullptr,
nn_input_memory_->get_handle(), input_offset, tensor->bytes),
"associating NNAPI execution input with a memory object",
nnapi_errno);
tensor_size = tensor->bytes;
}
input_offset += tensor_size;
input_offset += getNumPaddingBytes(tensor_size);
relative_input_index++;
}
}
// Set the output tensor buffers.
int relative_output_index = 0;
size_t output_offset = 0;
for (auto output_index : TfLiteIntArrayView(node->outputs)) {
// If the NNAPI implementation doesn't have some of the outputs
// they are left unmapped and we should not try to read their value here
if (operand_mapping_.lite_index_to_ann(output_index) == -1) {
continue;
}
TfLiteTensor* tensor = &context->tensors[output_index];
if (tensor->buffer_handle != kTfLiteNullBufferHandle &&
tensor->buffer_handle < tensor_memory_map_->size()) {
RETURN_TFLITE_ERROR_IF_NN_ERROR(
context,
nnapi_->ANeuralNetworksExecution_setOutputFromMemory(
execution, relative_output_index, nullptr,
tensor_memory_map_->at(tensor->buffer_handle).memory, 0,
tensor->bytes),
"associating NNAPI execution output to a memory object", nnapi_errno);
} else {
RETURN_TFLITE_ERROR_IF_NN_ERROR(
context,
nnapi_->ANeuralNetworksExecution_setOutputFromMemory(
execution, relative_output_index, nullptr,
nn_output_memory_->get_handle(), output_offset, tensor->bytes),
"associating NNAPI execution output to a memory object", nnapi_errno);
output_offset += tensor->bytes;
output_offset += getNumPaddingBytes(tensor->bytes);
}
relative_output_index++;
}
// The state_out of previous invocation need to be mapped to state_in of
// current invocation.
for (size_t i = 0; i < model_state_tfl_inputs_.size(); i++) {
int state_tensor_idx = model_state_tfl_inputs_[i];
TfLiteTensor* tensor = &context->tensors[state_tensor_idx];
// Here we are using a deep copy for state_in tensors so that we are not
// reading and writing into the same buffer during a invocation.
// TODO(b/110369471): using double shared buffer to minimize the copies.
RETURN_TFLITE_ERROR_IF_NN_ERROR(
context,
nnapi_->ANeuralNetworksExecution_setOutput(
execution, relative_output_index, nullptr, tensor->data.raw,
tensor->bytes),
"associating NNAPI execution output to a buffer", nnapi_errno);
relative_output_index++;
}
// Invoke ANN in blocking fashion.
if (nnapi_->android_sdk_version < kMinSdkVersionForNNAPI12) {
ANeuralNetworksEvent* event = nullptr;
RETURN_TFLITE_ERROR_IF_NN_ERROR(
context,
nnapi_->ANeuralNetworksExecution_startCompute(execution, &event),
"starting async computation", nnapi_errno);
const int wait_result = nnapi_->ANeuralNetworksEvent_wait(event);
nnapi_->ANeuralNetworksEvent_free(event);
RETURN_TFLITE_ERROR_IF_NN_ERROR(context, wait_result,
"waiting for async computation completion",
nnapi_errno);
} else {
// Use synchronous execution for NNAPI 1.2+.
RETURN_TFLITE_ERROR_IF_NN_ERROR(
context, nnapi_->ANeuralNetworksExecution_compute(execution),
"running computation", nnapi_errno);
}
// copy results from shared memory to the destination.
output_offset = 0;
for (auto output_index : TfLiteIntArrayView(node->outputs)) {
TfLiteTensor* tensor = &context->tensors[output_index];
if (tensor->buffer_handle != kTfLiteNullBufferHandle) {
continue;
}
TfLiteType ann_type_equivalent =
operand_mapping_.lite_index_to_ann_type_conversion(output_index);
if (tensor->type == kTfLiteInt8 && ann_type_equivalent == kTfLiteUInt8) {
// Explicitly convert uint8 values to int8 values.
uint8_t* output_ptr = reinterpret_cast<uint8_t*>(
nn_output_memory_->get_data_ptr() + output_offset);
const auto num_elements = NumElements(tensor);
for (int i = 0; i < num_elements; ++i) {
output_ptr[i] =
static_cast<uint8_t>(static_cast<int32_t>(output_ptr[i]) - 128);
}
}
memcpy(tensor->data.raw, nn_output_memory_->get_data_ptr() + output_offset,
tensor->bytes);
output_offset += tensor->bytes;
output_offset += getNumPaddingBytes(tensor->bytes);
}
// copy output of all output tensors in feedback_loops_ into the
// associated input
for (auto feedback_loop : feedback_loops_) {
int output_tensor_idx;
int input_tensor_idx;
std::tie(output_tensor_idx, input_tensor_idx) = feedback_loop;
TfLiteTensor& src = context->tensors[output_tensor_idx];
TfLiteTensor& dest = context->tensors[input_tensor_idx];
memcpy(dest.data.raw, src.data.raw, src.bytes);
}
return kTfLiteOk;
}
void NNAPIDelegateKernel::AddDequantizeOperatorsWhereNeeded(
const TfLiteContext* context, int builtin_code, const TfLiteNode* node,
NNAPIOpBuilder* builder, int* nnapi_errno) {
// Depending on the operator and the input data format, Dequantize
// operators may need to be added. For example when the input is
// floating-point but weights are quantized then the weights will first be
// dequantized to the same format as the input before being passed to the
// operator.
// The tensor determining whether the inputs should be floating-point.
int input_tensor_index = -1;
std::vector<int> inputs_to_potentially_dequantize;
switch (builtin_code) {
case kTfLiteBuiltinConv2d:
case kTfLiteBuiltinFullyConnected: {
input_tensor_index = 0;
// Weights and bias are inputs #1 and #2 respectively and may require
// dequantization.
inputs_to_potentially_dequantize = {1, 2};
break;
}
case kTfLiteBuiltinLstm: {
input_tensor_index = 0;
inputs_to_potentially_dequantize = {1, 2, 3, 4, 5, 6, 7,
8, 9, 10, 11, 12, 13, 14,
15, 16, 17, 20, 21, 22, 23};
break;
}
default:
return;
}
int tensor_id = node->inputs->data[input_tensor_index];
if (tensor_id < 0) return;
// Nothing to do if the input is not floating-point.
if (!IsFloat(context->tensors[tensor_id].type)) return;
for (int i : inputs_to_potentially_dequantize) {
if (i < 0 || i >= node->inputs->size) continue; // Ignore invalid index.
tensor_id = node->inputs->data[i];
if (tensor_id < 0) continue; // Ignore optional input.
const TfLiteType type = context->tensors[tensor_id].type;
// Nothing to do for this tensor if it's not quantized.
if (!IsQuantized(type)) continue;
// Insert Dequantize operator if it hasn't been done already and change
// the node's input accordingly.
builder->AddDequantize(i, node->inputs->data[i], type);
}
}
TfLiteStatus NNAPIDelegateKernel::AddOpsAndTensors(TfLiteContext* context,
int* nnapi_errno) {
DequantizeMapping dequantize_mapping;
// The operand builder allows creating a single op. It is created outside
// the for loop to avoid reallocating the vectors.
NNAPIOpBuilder builder(nnapi_, context, &operand_mapping_,
&dequantize_mapping, &allocation_memory_mapping_,
&nnapi_to_tflite_op_mapping_, nn_model_.get(),
nnapi_errno);
// Add Tensors.
for (auto node_index : nodes_) {
// Obtain the op and registration.
TfLiteNode* node;
TfLiteRegistration* reg;
TF_LITE_ENSURE_STATUS(
context->GetNodeAndRegistration(context, node_index, &node, ®));
const bool hybrid_op = IsHybridOperator(context, reg->builtin_code, node);
const bool scalar_as_tensor = IsScalarInputSupported(reg->builtin_code);
const bool need_int8_conversion =
NeedInt8Conversion(context, reg->builtin_code, node);
int input_tensor_flags = 0;
if (scalar_as_tensor) {
input_tensor_flags |= NN_TENSOR_FLAG_SCALAR_AS_TENSOR;
}
// h_swish will be lowered into supported NNAPI operations.
if (reg->builtin_code == kTfLiteBuiltinHardSwish) {
builder.AddHardSwish(node->inputs->data[0], node->outputs->data[0],
need_int8_conversion, node_index);
continue;
}
// Map inputs to NN API tensor indices.
for (int input_pos = 0; input_pos < node->inputs->size; ++input_pos) {
const auto input_index = node->inputs->data[input_pos];
if (need_int8_conversion &&
(input_pos == 0 ||
reg->builtin_code == kTfLiteBuiltinFullyConnected ||
reg->builtin_code == kTfLiteBuiltinConv2d ||
reg->builtin_code == kTfLiteBuiltinDepthwiseConv2d ||
reg->builtin_code == kTfLiteBuiltinAdd ||
reg->builtin_code == kTfLiteBuiltinMul ||
reg->builtin_code == kTfLiteBuiltinSub ||
reg->builtin_code == kTfLiteBuiltinConcatenation ||
reg->builtin_code == kTfLiteBuiltinMaximum ||
reg->builtin_code == kTfLiteBuiltinMinimum ||
reg->builtin_code == kTfLiteBuiltinLess ||
reg->builtin_code == kTfLiteBuiltinLessEqual ||
reg->builtin_code == kTfLiteBuiltinGreater ||
reg->builtin_code == kTfLiteBuiltinGreaterEqual ||
reg->builtin_code == kTfLiteBuiltinEqual ||
reg->builtin_code == kTfLiteBuiltinNotEqual ||
reg->builtin_code == kTfLiteBuiltinSelect)) {
// Only selected inputs require int8 conversion.
TF_LITE_ENSURE_STATUS(builder.AddTensorInput(
input_index, hybrid_op,
input_tensor_flags | NN_TENSOR_FLAG_INT8_CONVERSION));
continue;
}
if (reg->builtin_code == kTfLiteBuiltinLstm && isLstmFullKernel(node) &&
input_pos >= 20) {
// Skip layer normalization weights. They are added in the Map
// function (after all the other inputs added there) since layer
// normalization weights are the last four inputs of the LSTM op in
// NNAPI.
continue;
}
if (reg->builtin_code == kTfLiteBuiltinLstm && isLstmBasicKernel(node)) {
// Configuring all inputs in the Map function
continue;
}
if (reg->builtin_code == kTfLiteBuiltinUnidirectionalSequenceLstm) {
if (input_pos >= 20) {
// Skip layer normalization weights. They are added in the Map
// function (after all the other inputs added there) since layer
// normalization weights are the last four inputs of the
// unidirectional sequence LSTM op in NNAPI.
continue;
}
if (input_index == kTfLiteOptionalTensor) {
TF_LITE_ENSURE_STATUS(builder.AddVectorFloat32Operand(nullptr, 0));
continue;
}
}
if ((reg->builtin_code == kTfLiteBuiltinSplit) &&
(input_index == node->inputs->data[0])) {
// Skip the axis input tensor; it will be added as a scalar operand
// by the Map() mapping.
continue;
}
if (reg->builtin_code == kTfLiteBuiltinTransposeConv) {
// Everything is added during Map since input tensors
// have different order.
continue;
}
// Pad and Padv2 have an optional parameter for a pad value which has
// to be converted to a scalar type in NN API.
if ((reg->builtin_code == kTfLiteBuiltinPadv2 ||
reg->builtin_code == kTfLiteBuiltinPad) &&
node->inputs->size == 3 && input_pos == 2) {
const int constant_value_id = node->inputs->data[2];
if (constant_value_id == kTfLiteOptionalTensor) {
continue;
}
const TfLiteTensor constant_value = context->tensors[constant_value_id];
switch (constant_value.type) {
case kTfLiteFloat32:
if (constant_value.allocation_type == kTfLiteMmapRo) {
builder.AddScalarFloat32Operand(*constant_value.data.f);
} else {
builder.AddSingleValueTensorAsScalarOperand(
constant_value_id, ANEURALNETWORKS_FLOAT32);
}
break;
case kTfLiteUInt8:
if (constant_value.allocation_type == kTfLiteMmapRo) {
builder.AddScalarInt32Operand(
static_cast<int32_t>(*constant_value.data.uint8));
} else {
builder.AddSingleValueTensorAsScalarOperand(
constant_value_id, ANEURALNETWORKS_INT32);
}
break;
case kTfLiteInt8:
if (constant_value.allocation_type == kTfLiteMmapRo) {
builder.AddScalarInt32Operand(
static_cast<int32_t>(*constant_value.data.int8) + 128);
} else {
builder.AddSingleValueTensorAsScalarOperand(
constant_value_id, ANEURALNETWORKS_INT32);
}
break;
default:
context->ReportError(context,
"Unsupported type of pad value for pad_v2\n");
return kTfLiteError;
}
continue;
}
if (input_index == kTfLiteOptionalTensor &&
(reg->builtin_code == kTfLiteBuiltinLstm ||
reg->builtin_code == kTfLiteBuiltinSvdf ||
reg->builtin_code == kTfLiteBuiltinBidirectionalSequenceLstm)) {
// properly handle the optional tensor for LSTM and SVDF.
// currently only support float32.
TF_LITE_ENSURE_STATUS(builder.AddVectorFloat32Operand(nullptr, 0));
} else if (reg->builtin_code == kTfLiteBuiltinResizeBilinear ||
reg->builtin_code == kTfLiteBuiltinResizeNearestNeighbor) {
if (input_pos == 0) {
// Only the first input tensor is added. The second one,
// specifying the output height and width, is not added and
// instead the height and width will be added individually as
// scalars by the mapping function returned by Map().
TF_LITE_ENSURE_STATUS(builder.AddTensorInput(input_index, hybrid_op));
}
} else if (reg->builtin_code == kTfLiteBuiltinTopkV2 && input_pos > 0) {
// The K parameter tensor is not handled here but by the functor
// returned by Map, the input tensor is instead added in
// the else clause below
continue;
} else if (reg->builtin_code == kTfLiteBuiltinGather) {
// Everything is added during Map since input tensors
// have different order.
continue;
} else if (reg->builtin_code == kTfLiteBuiltinExpandDims &&
input_pos == 1) {
// The axis param is added during Map
continue;
} else if (reg->builtin_code == kTfLiteBuiltinBatchToSpaceNd &&
input_pos == 2) {
// NNAPI does not support crops.
// The Map function will check if all crops are zero.
continue;
} else if (reg->builtin_code == kTfLiteBuiltinArgMin ||
reg->builtin_code == kTfLiteBuiltinArgMax) {
// The first input tensor is added as is. The second one, specifying
// the axis, needs to be converted to a scalar since TFLite uses a
// tensor but NNAPI uses a scalar as the axis.
if (input_pos == 0) {
TF_LITE_ENSURE_STATUS(builder.AddTensorInput(input_index, hybrid_op));
} else {
const int axis_id = node->inputs->data[1];
const TfLiteTensor& axis_tensor = context->tensors[axis_id];
switch (axis_tensor.type) {
case kTfLiteInt32:
if (axis_tensor.allocation_type == kTfLiteMmapRo) {
TF_LITE_ENSURE_STATUS(builder.AddScalarInt32Operand(
static_cast<int32_t>(*axis_tensor.data.i32)));
} else {
TF_LITE_ENSURE_STATUS(
builder.AddSingleValueTensorAsScalarOperand(
axis_id, ANEURALNETWORKS_INT32));
}
break;
case kTfLiteInt64:
// Map() function already makes sure int64 input is constant.
TF_LITE_ENSURE_STATUS(builder.AddScalarInt32Operand(
static_cast<int32_t>(*axis_tensor.data.i64)));
break;
default:
return kTfLiteError;
}
}
} else if (reg->builtin_code == kTfLiteBuiltinMaximum ||
reg->builtin_code == kTfLiteBuiltinMinimum) {
const TfLiteTensor& operand_tensor =
context->tensors[node->inputs->data[input_pos]];
if (operand_tensor.dims->size == 0) {
int tensor_index;
TF_LITE_ENSURE_EQ(context, operand_tensor.allocation_type,
kTfLiteMmapRo);
switch (operand_tensor.type) {
case kTfLiteFloat32:
TF_LITE_ENSURE_STATUS(builder.AddNewInputConstantTensor(
ANEURALNETWORKS_TENSOR_FLOAT32, operand_tensor.type, {1},
std::vector<float>(1, operand_tensor.data.f[0]),
operand_tensor.params, &tensor_index));
break;
case kTfLiteUInt8:
TF_LITE_ENSURE_STATUS(builder.AddNewInputConstantTensor(
ANEURALNETWORKS_TENSOR_QUANT8_ASYMM, operand_tensor.type, {1},
std::vector<uint8_t>(1, operand_tensor.data.uint8[0]),
operand_tensor.params, &tensor_index));
break;
case kTfLiteInt8:
TF_LITE_ENSURE_STATUS(builder.AddNewInputConstantTensor(
ANEURALNETWORKS_TENSOR_QUANT8_SYMM, operand_tensor.type, {1},
std::vector<int8_t>(1, operand_tensor.data.int8[0]),
operand_tensor.params, &tensor_index));
break;
case kTfLiteInt32:
TF_LITE_ENSURE_STATUS(builder.AddNewInputConstantTensor(
ANEURALNETWORKS_TENSOR_INT32, operand_tensor.type, {1},
std::vector<int32_t>(1, operand_tensor.data.i32[0]),
operand_tensor.params, &tensor_index));
break;
default:
return kTfLiteError;
}
} else {
TF_LITE_ENSURE_STATUS(builder.AddTensorInput(input_index, hybrid_op,
input_tensor_flags));
}
} else if ((reg->builtin_code == kTfLiteBuiltinReduceAny ||
reg->builtin_code == kTfLiteBuiltinReduceMax ||
reg->builtin_code == kTfLiteBuiltinReduceMin ||
reg->builtin_code == kTfLiteBuiltinReduceProd ||
reg->builtin_code == kTfLiteBuiltinSum) &&
(input_pos == 1)) {
// The axis needs, be converted to a tensor if specified as scalar
const TfLiteTensor& axis_tensor =
context->tensors[node->inputs->data[input_pos]];
if (axis_tensor.dims->size == 0) {
TF_LITE_ENSURE_STATUS(
builder.AddVectorInt32Operand(axis_tensor.data.i32, 1));
} else {
TF_LITE_ENSURE_STATUS(builder.AddTensorInput(input_index, hybrid_op,
input_tensor_flags));
}
} else {
TF_LITE_ENSURE_STATUS(
builder.AddTensorInput(input_index, hybrid_op, input_tensor_flags));
}
}
// If we have target accelerators the target SDK version might be
// different than the current android version.
int target_sdk_version = nnapi_->android_sdk_version;
if (!nnapi_devices_.empty()) {
TF_LITE_ENSURE_STATUS(GetTargetSdkVersion(
context, nnapi_, nnapi_devices_, &target_sdk_version, nnapi_errno));
}
// Get op type and operands
// Fails if the Validate function failed
int nn_op_type;
TF_LITE_ENSURE_STATUS(
Map(context, reg->builtin_code, reg->version, target_sdk_version,
{context, &builder, node, &model_state_outputs_,
&model_state_tfl_inputs_, &feedback_loops_, nnapi_errno},
&nn_op_type));
// Map outputs to NN API tensor indices.
int output_tensor_flags = 0;
if (need_int8_conversion) {
output_tensor_flags |= NN_TENSOR_FLAG_INT8_CONVERSION;
}
for (int output_pos = 0; output_pos < node->outputs->size; ++output_pos) {
const auto output_index = node->outputs->data[output_pos];
// Outputs for basic LSTM cell are set in the Map function since
if (reg->builtin_code == kTfLiteBuiltinLstm && isLstmBasicKernel(node)) {
continue;
}
TF_LITE_ENSURE_STATUS(
builder.AddTensorOutput(output_index, output_tensor_flags));
}
// Dequantize operators may have to be added in case inputs are to be
// floating-point.
AddDequantizeOperatorsWhereNeeded(context, reg->builtin_code, node,
&builder, nnapi_errno);
builder.FinalizeAddOperation(nn_op_type, node_index);
}
return kTfLiteOk;
}
TfLiteStatus NNAPIDelegateKernel::BuildGraph(
TfLiteContext* context,
const StatefulNnApiDelegate::Options& delegate_options,
const TfLiteIntArray* input_tensors, const TfLiteIntArray* output_tensors,
int* nnapi_errno) {
// Build the ops and tensors.
TF_LITE_ENSURE_STATUS(AddOpsAndTensors(context, nnapi_errno));
// Map input and output tensor indices to ANN
std::vector<uint32_t> inputs;
inputs.reserve(input_tensors->size);
std::vector<uint32_t> outputs;
outputs.reserve(output_tensors->size);
size_t total_input_byte_size = 0;
// Make the TensorFlow Lite inputs and outputs to ann_indices.
for (int i : TfLiteIntArrayView(input_tensors)) {
// Constant tensors are not NNAPI inputs.
if (i != kTfLiteOptionalTensor &&
context->tensors[i].allocation_type != kTfLiteMmapRo &&
// The delegate might not have mapped this input (this can
// happen if one tensor is split in several ones)
operand_mapping_.lite_index_to_ann(i) != -1) {
inputs.push_back(operand_mapping_.lite_index_to_ann(i));
if (context->tensors[i].buffer_handle != kTfLiteNullBufferHandle) {
continue;
}
const TfLiteType nn_type_conversion =
operand_mapping_.lite_index_to_ann_type_conversion(i);
int tensor_size = 0;
if (nn_type_conversion == kTfLiteNoType) {
tensor_size = context->tensors[i].bytes;
} else {
size_t type_size;
TF_LITE_ENSURE_OK(
context, GetSizeOfType(context, nn_type_conversion, &type_size));
tensor_size = NumElements(&context->tensors[i]) * type_size;
}
total_input_byte_size += tensor_size;
total_input_byte_size += getNumPaddingBytes(tensor_size);
}
}
size_t total_output_byte_size = 0;
for (int i : TfLiteIntArrayView(output_tensors)) {
const int output_tensor_ann_index = operand_mapping_.lite_index_to_ann(i);
// Unmapped outputs are not added
if (output_tensor_ann_index != -1) {
outputs.push_back(output_tensor_ann_index);
}
if (context->tensors[i].buffer_handle != kTfLiteNullBufferHandle) {
continue;
}
total_output_byte_size += context->tensors[i].bytes;
total_output_byte_size += getNumPaddingBytes(context->tensors[i].bytes);
}
// Add state output tensors as model outputs.
for (int i : model_state_outputs_) {
outputs.push_back(i);
}
// Tell ANN to declare inputs/outputs
RETURN_TFLITE_ERROR_IF_NN_ERROR(
context,
nnapi_->ANeuralNetworksModel_identifyInputsAndOutputs(
nn_model_.get(), inputs.size(), inputs.data(), outputs.size(),
outputs.data()),
"identifying model inputs and outputs", nnapi_errno);
auto allow_fp16 =
context->allow_fp32_relax_to_fp16 | delegate_options.allow_fp16;
if (nnapi_->android_sdk_version >= kMinSdkVersionForNNAPI11) {
RETURN_TFLITE_ERROR_IF_NN_ERROR(
context,
nnapi_->ANeuralNetworksModel_relaxComputationFloat32toFloat16(
nn_model_.get(), allow_fp16),
"set relaxed computation mode for fp32 if possible", nnapi_errno);
}
RETURN_TFLITE_ERROR_IF_NN_ERROR(
context, nnapi_->ANeuralNetworksModel_finish(nn_model_.get()),
"finalizing the model", nnapi_errno);
// Create shared memory pool for inputs and outputs.
nn_input_memory_.reset(
new NNMemory(nnapi_, "input_pool", total_input_byte_size));
nn_output_memory_.reset(
new NNMemory(nnapi_, "output_pool", total_output_byte_size));
return kTfLiteOk;
}
} // namespace nnapi
} // namespace delegate
using ::tflite::delegate::nnapi::NNAPIDelegateKernel;
StatefulNnApiDelegate::Data::~Data() {
std::for_each(std::begin(delegate_state_cache),
std::end(delegate_state_cache),
[](const std::pair<int, NNAPIDelegateKernel*>& entry) {
delete entry.second;
});
}
void StatefulNnApiDelegate::Data::CacheDelegateKernel(
const TfLiteDelegateParams* delegate_params,
NNAPIDelegateKernel* delegate_state) {
const int cache_key = delegate_params->nodes_to_replace->data[0];
delegate_state_cache.emplace(cache_key, delegate_state);
}
absl::optional<NNAPIDelegateKernel*>
StatefulNnApiDelegate::Data::GetCachedDelegateKernel(
const TfLiteDelegateParams* delegate_params) {
const int cache_key = delegate_params->nodes_to_replace->data[0];
const auto cached_state = delegate_state_cache.find(cache_key);
if (cached_state != std::end(delegate_state_cache)) {
auto result = absl::optional<NNAPIDelegateKernel*>(cached_state->second);
delegate_state_cache.erase(cached_state);
return result;
} else {
return absl::nullopt;
}
}
StatefulNnApiDelegate::StatefulNnApiDelegate(const NnApi* nnapi)
: StatefulNnApiDelegate(nnapi, Options()) {}
StatefulNnApiDelegate::StatefulNnApiDelegate(Options options)
: StatefulNnApiDelegate(NnApiImplementation(), options) {}
StatefulNnApiDelegate::StatefulNnApiDelegate(const NnApi* nnapi,
Options options)
: TfLiteDelegate(TfLiteDelegateCreate()),
delegate_data_(Data{.execution_preference = options.execution_preference,
.nnapi = nnapi}) {
if (options.accelerator_name) {
delegate_data_.accelerator_name = options.accelerator_name;
}
if (options.cache_dir) {
delegate_data_.cache_dir = options.cache_dir;
}
if (options.model_token) {
delegate_data_.model_token = options.model_token;
}
delegate_data_.disallow_nnapi_cpu = options.disallow_nnapi_cpu;
delegate_data_.max_number_delegated_partitions =
options.max_number_delegated_partitions;
delegate_data_.allow_fp16 = options.allow_fp16;
TFLITE_LOG_PROD_ONCE(tflite::TFLITE_LOG_INFO,
"Created TensorFlow Lite delegate for NNAPI.");
Prepare = DoPrepare;
CopyFromBufferHandle = DoCopyFromBufferHandle;
CopyToBufferHandle = DoCopyToBufferHandle;
FreeBufferHandle = DoFreeBufferHandle;
data_ = &delegate_data_;
}
StatefulNnApiDelegate::StatefulNnApiDelegate()
: StatefulNnApiDelegate(Options()) {}
const StatefulNnApiDelegate::Options StatefulNnApiDelegate::GetOptions(
TfLiteDelegate* delegate) {
auto delegate_data = reinterpret_cast<Data*>(delegate->data_);
StatefulNnApiDelegate::Options options;
options.execution_preference = delegate_data->execution_preference;
options.accelerator_name = delegate_data->accelerator_name.empty()
? nullptr
: delegate_data->accelerator_name.c_str();
options.cache_dir = delegate_data->cache_dir.empty()
? nullptr
: delegate_data->cache_dir.c_str();
options.model_token = delegate_data->model_token.empty()
? nullptr
: delegate_data->model_token.c_str();
options.disallow_nnapi_cpu = delegate_data->disallow_nnapi_cpu;
options.max_number_delegated_partitions =
delegate_data->max_number_delegated_partitions;
options.allow_fp16 = delegate_data->allow_fp16;
return options;
}
const std::vector<StatefulNnApiDelegate::MemoryRegistration>&
StatefulNnApiDelegate::GetTensorMemoryMap(TfLiteDelegate* delegate) {
auto delegate_data = reinterpret_cast<Data*>(delegate->data_);
return delegate_data->tensor_memory_map;
}
TfLiteBufferHandle StatefulNnApiDelegate::RegisterNnapiMemory(
ANeuralNetworksMemory* memory, CopyToHostTensorFnPtr callback,
void* callback_context) {
int map_size = delegate_data_.tensor_memory_map.size();
for (int i = 0; i < map_size; i++) {
if (delegate_data_.tensor_memory_map[i].memory == nullptr) {
delegate_data_.tensor_memory_map[i] = {memory, callback,
callback_context};
return i;
}
}
delegate_data_.tensor_memory_map.push_back(
{memory, callback, callback_context});
return map_size;
}
TfLiteStatus StatefulNnApiDelegate::DoCopyFromBufferHandle(
TfLiteContext* context, TfLiteDelegate* delegate,
TfLiteBufferHandle buffer_handle, TfLiteTensor* tensor) {
auto delegate_data = reinterpret_cast<Data*>(delegate->data_);
if (buffer_handle < 0 ||
buffer_handle >= delegate_data->tensor_memory_map.size()) {
return kTfLiteError;
}
auto memory = delegate_data->tensor_memory_map[buffer_handle].memory;
auto callback = delegate_data->tensor_memory_map[buffer_handle].callback;
auto callback_context =
delegate_data->tensor_memory_map[buffer_handle].callback_context;
if (!memory || !callback) {
return kTfLiteError;
}
return callback(tensor, memory, 0, tensor->bytes, callback_context);
}
TfLiteStatus StatefulNnApiDelegate::DoCopyToBufferHandle(
TfLiteContext* context, TfLiteDelegate* delegate,
TfLiteBufferHandle buffer_handle, TfLiteTensor* tensor) {
return kTfLiteError;
}
void StatefulNnApiDelegate::DoFreeBufferHandle(TfLiteContext* context,
TfLiteDelegate* delegate,
TfLiteBufferHandle* handle) {
auto delegate_data = reinterpret_cast<Data*>(delegate->data_);
if (*handle >= 0 && *handle < delegate_data->tensor_memory_map.size()) {
delegate_data->tensor_memory_map[*handle] = {nullptr, nullptr, nullptr};
*handle = kTfLiteNullBufferHandle;
}
}
int StatefulNnApiDelegate::GetNnApiErrno() const {
return delegate_data_.nnapi_errno;
}
using ::tflite::delegate::nnapi::kMinSdkVersionForNNAPI;
using ::tflite::delegate::nnapi::kMinSdkVersionForNNAPI12;
namespace {
std::unique_ptr<TfLiteIntArray, TfLiteIntArrayDeleter> BuildTfLiteIntArray(
const std::vector<int>& data) {
std::unique_ptr<TfLiteIntArray, TfLiteIntArrayDeleter> result(
TfLiteIntArrayCreate(data.size()));
std::copy(data.begin(), data.end(), result->data);
return result;
}
} // namespace
// static
TfLiteStatus StatefulNnApiDelegate::GetNodesSupportedByAccelerator(
TfLiteContext* context, TfLiteDelegate* delegate, const NnApi* nnapi,
const std::vector<int>& supported_nodes,
std::vector<int>* device_supported_nodes, int* num_partitions,
TfLiteDelegateParams** params_array, int* nnapi_errno) {
auto* delegate_data = static_cast<Data*>(delegate->data_);
// The first entry in the array is the element count
auto supported_nodes_int_array = BuildTfLiteIntArray(supported_nodes);
TF_LITE_ENSURE_STATUS(context->PreviewDelegatePartitioning(
context, supported_nodes_int_array.get(), params_array, num_partitions));
// For each partition check if which nodes are actually supported by the
// target accelerators.
delegate_data->delegate_state_cache.clear();
for (int idx = 0; idx < *num_partitions; idx++) {
const auto& partition_params = (*params_array)[idx];
auto kernel_state = absl::make_unique<NNAPIDelegateKernel>(nnapi);
TfLiteDelegateParams params_with_delegate = partition_params;
params_with_delegate.delegate = delegate;
TF_LITE_ENSURE_STATUS(
kernel_state->Init(context, ¶ms_with_delegate, nnapi_errno));
std::vector<int> supported_partition_nodes;
TF_LITE_ENSURE_STATUS(
kernel_state->GetOperationsSupportedByTargetNnApiDevices(
context, &supported_partition_nodes, nnapi_errno));
device_supported_nodes->insert(device_supported_nodes->end(),
supported_partition_nodes.begin(),
supported_partition_nodes.end());
bool model_fully_supported = (supported_partition_nodes.size() ==
partition_params.nodes_to_replace->size);
if (model_fully_supported) {
delegate_data->CacheDelegateKernel(&partition_params,
kernel_state.release());
}
}
if (device_supported_nodes->size() != supported_nodes.size()) {
// We changed the set of nodes to delegate this will create a different
// partitioning layout.
auto device_sup_nodes_int_array =
BuildTfLiteIntArray(*device_supported_nodes);
TF_LITE_ENSURE_STATUS(context->PreviewDelegatePartitioning(
context, device_sup_nodes_int_array.get(), params_array,
num_partitions));
}
return kTfLiteOk;
}
// static
TfLiteStatus StatefulNnApiDelegate::LimitDelegatedPartitions(
int max_partitions,
std::vector<TfLiteDelegateParams> partition_params_array,
std::vector<int>* nodes_to_delegate) {
int num_partitions = partition_params_array.size();
if (max_partitions <= 0 || num_partitions <= max_partitions) {
return kTfLiteOk;
}
int number_delegated_partitions = std::count_if(
partition_params_array.begin(), partition_params_array.end(),
[nodes_to_delegate](const TfLiteDelegateParams& partition_params) {
return std::find(nodes_to_delegate->begin(), nodes_to_delegate->end(),
partition_params.nodes_to_replace->data[0]) !=
nodes_to_delegate->end();
});
if (number_delegated_partitions > max_partitions) {
std::sort(partition_params_array.begin(), partition_params_array.end(),
[](const TfLiteDelegateParams& left,
const TfLiteDelegateParams& right) -> bool {
// Reverse sort
return left.nodes_to_replace->size >
right.nodes_to_replace->size;
});
nodes_to_delegate->clear();
for (int i = 0; i < max_partitions; i++) {
const TfLiteDelegateParams& partition_params = partition_params_array[i];
nodes_to_delegate->insert(nodes_to_delegate->end(),
partition_params.nodes_to_replace->data,
partition_params.nodes_to_replace->data +
partition_params.nodes_to_replace->size);
}
}
return kTfLiteOk;
}
TfLiteStatus StatefulNnApiDelegate::DoPrepare(TfLiteContext* context,
TfLiteDelegate* delegate) {
auto* delegate_data = static_cast<Data*>(delegate->data_);
int* nnapi_errno = &(delegate_data->nnapi_errno);
const NnApi* nnapi = delegate_data->nnapi;
// Resetting the error code when the delegate is initialized
// by TFLite. This causes the error to be reset if reusing the same
// StatefulNnApiDelegate after a failure
*nnapi_errno = 0;
// Do not check nodes_ if NN API is unavailable.
if (nnapi->android_sdk_version < kMinSdkVersionForNNAPI ||
!nnapi->nnapi_exists) {
return kTfLiteOk;
}
int target_sdk_version = nnapi->android_sdk_version;
const StatefulNnApiDelegate::Options delegate_options =
StatefulNnApiDelegate::GetOptions(delegate);
// For NNAPI 1.2+, check if there is any accelerator available.
// If not, don't delegate to NNAPI's CPU reference implementation unless
// it has been specified as target accelerator.
if (nnapi->android_sdk_version >= kMinSdkVersionForNNAPI12) {
if (ShouldUseTargetDevices(delegate_options)) {
std::vector<ANeuralNetworksDevice*> devices;
TF_LITE_ENSURE_STATUS(
GetTargetDevices(context, delegate, nnapi, nnapi_errno, &devices));
if (devices.empty()) {
if (delegate_options.accelerator_name) {
// There was a selected device and it is not available.
return kTfLiteError;
} else {
// Only nnapi-reference is available but was disabled by the delegate
// options
return kTfLiteOk;
}
}
TF_LITE_ENSURE_STATUS(GetTargetSdkVersion(
context, nnapi, devices, &target_sdk_version, nnapi_errno));
} else {
// If no accelerator is specified, only use NNAPI if an accelerator is
// available. Any available accelerator will make the device_count larger
// than 1. More sophisticated check and whitelisting can be added later.
uint32_t device_count = 0;
RETURN_TFLITE_ERROR_IF_NN_ERROR(
context, nnapi->ANeuralNetworks_getDeviceCount(&device_count),
"getting number of NNAPI devices", nnapi_errno);
if (device_count <= 1) {
return kTfLiteOk;
}
}
}
std::vector<int> supported_nodes;
// We don't care about all nodes_, we only care about ones in the
// current plan.
TfLiteIntArray* plan;
TF_LITE_ENSURE_STATUS(context->GetExecutionPlan(context, &plan));
// Check for every node if it is supported
const bool is_accelerator_specified = ShouldUseTargetDevices(
delegate_options, /*exclude_nnapi_reference=*/true);
for (int node_index : TfLiteIntArrayView(plan)) {
TfLiteNode* node;
TfLiteRegistration* registration;
TF_LITE_ENSURE_STATUS(context->GetNodeAndRegistration(
context, node_index, &node, ®istration));
if (NNAPIDelegateKernel::Validate(context, registration->builtin_code,
registration->version, target_sdk_version,
node, is_accelerator_specified)) {
supported_nodes.push_back(node_index);
}
}
// If there are no delegated nodes, short-circuit node replacement.
if (supported_nodes.empty()) {
return kTfLiteOk;
}
// NN API Delegate Registration (the pseudo kernel that will invoke NN
// API node sub sets)
static const TfLiteRegistration nnapi_delegate_kernel = {
.init = [](TfLiteContext* context, const char* buffer,
size_t length) -> void* {
const TfLiteDelegateParams* params =
reinterpret_cast<const TfLiteDelegateParams*>(buffer);
auto* delegate_data = static_cast<Data*>(params->delegate->data_);
int* nnapi_errno = &(delegate_data->nnapi_errno);
auto delegate_state_maybe =
delegate_data->GetCachedDelegateKernel(params);
NNAPIDelegateKernel* kernel_state;
if (delegate_state_maybe.has_value()) {
kernel_state = *delegate_state_maybe;
} else {
kernel_state = new NNAPIDelegateKernel(delegate_data->nnapi);
kernel_state->Init(context, params, nnapi_errno);
}
return kernel_state;
},
.free = [](TfLiteContext* context, void* buffer) -> void {
delete reinterpret_cast<NNAPIDelegateKernel*>(buffer);
},
.prepare = [](TfLiteContext* context, TfLiteNode* node) -> TfLiteStatus {
NNAPIDelegateKernel* state =
reinterpret_cast<NNAPIDelegateKernel*>(node->user_data);
int* nnapi_errno =
&(static_cast<Data*>(node->delegate->data_)->nnapi_errno);
return state->Prepare(context, node, nnapi_errno);
},
.invoke = [](TfLiteContext* context, TfLiteNode* node) -> TfLiteStatus {
NNAPIDelegateKernel* state =
reinterpret_cast<NNAPIDelegateKernel*>(node->user_data);
int* nnapi_errno =
&(static_cast<Data*>(node->delegate->data_)->nnapi_errno);
return state->Invoke(context, node, nnapi_errno);
},
.profiling_string = nullptr,
.builtin_code = kTfLiteBuiltinDelegate,
.custom_name = "TfLiteNnapiDelegate",
.version = 1,
};
std::vector<int> nodes_to_delegate;
int num_partitions;
TfLiteDelegateParams* params_array;
if (is_accelerator_specified &&
nnapi->android_sdk_version >= kMinSdkVersionForNNAPI12) {
// Filtering out nodes not supported by target accelerators.
// Cannot query supported operation before NNAPI 1.2
TF_LITE_ENSURE_STATUS(GetNodesSupportedByAccelerator(
context, delegate, nnapi, supported_nodes, &nodes_to_delegate,
&num_partitions, ¶ms_array, nnapi_errno));
} else {
nodes_to_delegate = supported_nodes;
auto supported_nodes_int_array = BuildTfLiteIntArray(supported_nodes);
TF_LITE_ENSURE_STATUS(context->PreviewDelegatePartitioning(
context, supported_nodes_int_array.get(), ¶ms_array,
&num_partitions));
}
TF_LITE_ENSURE_STATUS(
LimitDelegatedPartitions(delegate_options.max_number_delegated_partitions,
std::vector<TfLiteDelegateParams>(
params_array, params_array + num_partitions),
&nodes_to_delegate));
if (nodes_to_delegate.empty()) {
return kTfLiteOk;
} else {
// Request TFLite to partition the graph and make kernels
// for each independent node sub set a new nnapi_delegate_kernel.
auto nodes_to_delegate_int_array = BuildTfLiteIntArray(nodes_to_delegate);
return context->ReplaceNodeSubsetsWithDelegateKernels(
context, nnapi_delegate_kernel, nodes_to_delegate_int_array.get(),
delegate);
}
}
// Returns a singleton NNAPI Delegate that can check for support of ops.
TfLiteDelegate* NnApiDelegate() {
static StatefulNnApiDelegate* delegate = new StatefulNnApiDelegate();
return delegate;
}
} // namespace tflite
|
#include <boost/asio/write.hpp>
|
/**
* @file src/llvmir2hll/graphs/cg/cg_builder.cpp
* @brief Implementation of CGBuilder.
* @copyright (c) 2017 Avast Software, licensed under the MIT license
*/
#include "retdec/llvmir2hll/graphs/cg/cg_builder.h"
#include "retdec/llvmir2hll/ir/call_expr.h"
#include "retdec/llvmir2hll/ir/function.h"
#include "retdec/llvmir2hll/ir/module.h"
#include "retdec/llvmir2hll/ir/statement.h"
#include "retdec/llvmir2hll/ir/variable.h"
#include "retdec/llvmir2hll/support/debug.h"
#include "retdec/llvmir2hll/utils/ir.h"
namespace retdec {
namespace llvmir2hll {
/**
* @brief Constructs a new builder.
*/
CGBuilder::CGBuilder(ShPtr<Module> module):
OrderedAllVisitor(), cg(new CG(module)) {}
/**
* @brief Destructs the builder.
*/
CGBuilder::~CGBuilder() {}
/**
* @brief Returns a CG of the given @a module.
*
* @par Preconditions
* - @a module is non-null
*/
ShPtr<CG> CGBuilder::getCG(ShPtr<Module> module) {
PRECONDITION_NON_NULL(module);
// Build the CG.
ShPtr<CGBuilder> builder(new CGBuilder(module));
builder->computeCG();
return builder->cg;
}
/**
* @brief Computes the CG.
*/
void CGBuilder::computeCG() {
// For each function in the module...
for (auto i = cg->module->func_begin(), e = cg->module->func_end();
i != e; ++i) {
cg->callerCalleeMap[*i] = computeCGPartForFunction(*i);
}
}
/**
* @brief Computes a part of the call graph from the given function and returns
* it.
*
* @a func may be a definition or a declaration.
*/
ShPtr<CG::CalledFuncs> CGBuilder::computeCGPartForFunction(ShPtr<Function> func) {
calledFuncs = ShPtr<CG::CalledFuncs>(new CG::CalledFuncs(func));
if (func->isDeclaration()) {
// It is a declaration, so we're done.
return calledFuncs;
}
// It is a definition, so obtain all the called functions.
restart(true, true);
visitStmt(func->getBody());
return calledFuncs;
}
void CGBuilder::visit(ShPtr<CallExpr> expr) {
OrderedAllVisitor::visit(expr);
// Skip any casts, which are irrelevant when looking for called functions.
ShPtr<Expression> callExpr(skipCasts(expr->getCalledExpr()));
if (isCallByPointer(callExpr, cg->module)) {
// There is a call by a pointer.
calledFuncs->callsByPointer = true;
return;
}
// Since it is not a call by a pointer, it has to be a direct call.
ShPtr<Variable> calledFuncVar(cast<Variable>(callExpr));
ShPtr<Function> calledFunc(cg->module->getFuncByName(
calledFuncVar->getName()));
ASSERT_MSG(calledFunc, "isCallByPointer() probably didn't work correctly");
calledFuncs->callees.insert(calledFunc);
if (calledFunc->isDeclaration()) {
calledFuncs->callsOnlyDefinedFuncs = false;
}
}
} // namespace llvmir2hll
} // namespace retdec
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.