hexsha stringlengths 40 40 | size int64 19 11.4M | ext stringclasses 13
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 3 270 | max_stars_repo_name stringlengths 5 110 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count float64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 3 270 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 78 | max_issues_repo_licenses listlengths 1 9 | max_issues_count float64 1 67k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 3 270 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 78 | max_forks_repo_licenses listlengths 1 9 | max_forks_count float64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 19 11.4M | avg_line_length float64 1.93 229k | max_line_length int64 12 688k | alphanum_fraction float64 0.07 0.99 | matches listlengths 1 10 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
9cebaef221d0202e0896d0835fd19c401414bc97 | 1,046 | cpp | C++ | test/integration/executor/executor_fixture_param_provider.cpp | Insafin/iroha | 5e3c3252b2a62fa887274bdf25547dc264c10c26 | [
"Apache-2.0"
] | 1,467 | 2016-10-25T12:27:19.000Z | 2022-03-28T04:32:05.000Z | test/integration/executor/executor_fixture_param_provider.cpp | Insafin/iroha | 5e3c3252b2a62fa887274bdf25547dc264c10c26 | [
"Apache-2.0"
] | 2,366 | 2016-10-25T10:07:57.000Z | 2022-03-31T22:03:24.000Z | test/integration/executor/executor_fixture_param_provider.cpp | Insafin/iroha | 5e3c3252b2a62fa887274bdf25547dc264c10c26 | [
"Apache-2.0"
] | 662 | 2016-10-26T04:41:22.000Z | 2022-03-31T04:15:02.000Z | /**
* Copyright Soramitsu Co., Ltd. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0
*/
#include "integration/executor/executor_fixture_param_provider.hpp"
#include "integration/executor/executor_fixture_param.hpp"
#include "integration/executor/executor_fixture_param_postgres.hpp"
#include "integration/executor/executor_fixture_param_rocksdb.hpp"
namespace executor_testing {
std::vector<ExecutorTestParamProvider> getExecutorTestParamProvidersVector() {
return std::vector<ExecutorTestParamProvider>{&getExecutorTestParamPostgres,
&getExecutorTestParamRocksDB};
}
auto getExecutorTestParams()
-> decltype(::testing::ValuesIn(getExecutorTestParamProvidersVector())) {
static auto params =
::testing::ValuesIn(getExecutorTestParamProvidersVector());
return params;
}
std::string paramToString(
testing::TestParamInfo<ExecutorTestParamProvider> param) {
return param.param().get().toString();
}
} // namespace executor_testing
| 33.741935 | 80 | 0.739006 | [
"vector"
] |
9ceedaafd3bf3e3032a33017e935ef07357202a5 | 3,285 | cpp | C++ | RLSimion/Lib/utils.cpp | xcillero001/SimionZoo | b343b08f3356e1aa230d4132b0abb58aac4c5e98 | [
"MIT"
] | 1 | 2019-02-21T10:40:28.000Z | 2019-02-21T10:40:28.000Z | RLSimion/Lib/utils.cpp | JosuGom3z/SimionZoo | b343b08f3356e1aa230d4132b0abb58aac4c5e98 | [
"MIT"
] | null | null | null | RLSimion/Lib/utils.cpp | JosuGom3z/SimionZoo | b343b08f3356e1aa230d4132b0abb58aac4c5e98 | [
"MIT"
] | null | null | null | #include "utils.h"
#include "config.h"
#include <algorithm>
#include <fstream>
Table::Table()
{
}
Table::~Table()
{
}
unsigned int parseHeader(const char* pInputString, vector<double>& outVector, char delimChar= '\t')
{
unsigned int numParsedValues = 0;
if (!pInputString) return 0;
const char* pt = pInputString;
if (*pt == delimChar || *pt == '\n') ++pt; //skip initial space/line jump
while (*pt != 0)
{
outVector.push_back (atof(pt));
++numParsedValues;
while (*pt != 0 && *pt != delimChar && *pt != '\n') ++pt;
if (*pt == delimChar || *pt == '\n') ++pt;
}
return numParsedValues;
}
bool Table::readFromFile(string filename)
{
//Reads a matrix from a file. The format should be:
// 3 5 7 9
//9 1.2 3.2 -3 -3.4
//10 2.3 2.5 -3 -4.2
char line[1024];
ifstream inputFile(filename);
if (inputFile.is_open())
{
//read the column headers
inputFile.getline(line,1024);
int numColumns= parseHeader(line, m_columns, '\t');
int numRows = 0;
double value;
while (!inputFile.eof())
{
inputFile >> value;
m_rows.push_back(value);
for (int i = 0; i < numColumns; ++i)
{
inputFile >> value;
m_values.push_back(value);
}
++numRows;
}
inputFile.close();
if (numRows*numColumns == (int) m_values.size())
{
m_bSuccess = true;
return true;
}
}
m_bSuccess = false;
return false;
}
double Table::getInterpolatedValue(double columnValue, double rowValue) const
{
//check column and row values are within the defined ranges
columnValue = std::max(m_columns[0], std::min(m_columns[m_columns.size() - 1], columnValue));
rowValue = std::max(m_rows[0], std::min(m_rows[m_rows.size() - 1], rowValue));
//search for the columns/rows where the given values are in
int colIndex = 1, rowIndex = 1;
while (m_columns[colIndex] < columnValue) ++colIndex;
while (m_rows[rowIndex] < rowValue) ++rowIndex;
--colIndex;
--rowIndex;
//interpolation factors
double colU, rowU, colRange, rowRange;
colRange = m_columns[colIndex + 1] - m_columns[colIndex];
rowRange = m_rows[rowIndex + 1] - m_rows[rowIndex];
colU = (columnValue - m_columns[colIndex]) / colRange;
rowU = (rowValue - m_rows[rowIndex]) / rowRange;
double value= 0.0;
value += (1 - colU) * (1- rowU) * getValue(colIndex,rowIndex);
value += (1 - colU) * rowU * getValue(colIndex,rowIndex + 1);
value += colU * (1 - rowU) * getValue(colIndex + 1, rowIndex);
value += colU * rowU * getValue(colIndex + 1, rowIndex + 1);
return value;
}
double Table::getValue(size_t col, size_t row) const
{
col = std::max((size_t)0, std::min(col, m_columns.size() - 1));
row = std::max((size_t)0, std::min(row, m_rows.size() - 1));
return m_values[row*m_columns.size() + col];
}
double Table::getMinCol() const
{
if (!m_bSuccess) return 0.0;
return m_columns[0];
}
double Table::getMaxCol() const
{
if (!m_bSuccess) return 0.0;
return m_columns[m_columns.size() - 1];
}
double Table::getMinRow() const
{
if (!m_bSuccess) return 0.0;
return m_rows[0];
}
double Table::getMaxRow() const
{
if (!m_bSuccess) return 0.0;
return m_rows[m_rows.size() - 1];
}
double Table::getNumCols() const
{
if (!m_bSuccess) return (double) m_columns.size();
return 0;
}
double Table::getNumRows() const
{
if (!m_bSuccess) return (double) m_rows.size();
return 0;
} | 23.297872 | 99 | 0.660274 | [
"vector"
] |
9cef4528a84e90d15303bd7bcd182e43866a49d0 | 3,530 | cpp | C++ | Engine/src/renderer/geometry/ObjLoader.cpp | Owlinated/SkyHockey | 787a7fa6c4cd1773c5a5c7e15e014f675947a21e | [
"MIT"
] | null | null | null | Engine/src/renderer/geometry/ObjLoader.cpp | Owlinated/SkyHockey | 787a7fa6c4cd1773c5a5c7e15e014f675947a21e | [
"MIT"
] | null | null | null | Engine/src/renderer/geometry/ObjLoader.cpp | Owlinated/SkyHockey | 787a7fa6c4cd1773c5a5c7e15e014f675947a21e | [
"MIT"
] | null | null | null | #include <memory>
#include <vector>
#include <cstdio>
#include <string>
#include <map>
#include <tuple>
#include <cstring>
#include <glm/glm.hpp>
#include <stdexcept>
#include <iostream>
#include <tiny_obj_loader.h>
#include <src/support/Logger.h>
#include "ObjLoader.h"
/**
* Create a new loader to load shapes from an .obj file.
* @param path Path to .obj file.
*/
ObjLoader::ObjLoader(const std::string& path) {
std::string err;
bool ret = tinyobj::LoadObj(&attrib, &shapes, &materials, &err, ("res/" + path).c_str());
if (!ret) {
Logger::error("Could not parse obj file: " + err);
}
}
/**
* Load shape from .obj file with the specified name.
* @param name Name of shape to load.
* @return Loaded shape.
*/
std::shared_ptr<Shape> ObjLoader::loadShape(const std::string &name) {
for (auto &shape: shapes) {
if (shape.name == name) {
return loadShape(shape);
}
}
Logger::error("Could not find object with name: " + name);
return loadShape(shapes[0]);
}
/**
* Load a shape internally. Converts a tinyobj shape into useful arrays.
* @param shape Shape to load into memory.
* @return A shape containing the loaded arrays
*/
std::shared_ptr<Shape> ObjLoader::loadShape(const tinyobj::shape_t shape) {
std::vector<unsigned short> indices;
std::vector<glm::vec3> vertices;
std::vector<glm::vec2> textures;
std::vector<glm::vec3> normals;
auto index_offset = 0;
unsigned short next_index = 0;
std::map<std::tuple<int, int, int>, unsigned short> index_map;
for (auto face_vertices: shape.mesh.num_face_vertices) {
for (size_t v = 0; v < face_vertices; v++) {
auto index = shape.mesh.indices[index_offset + v];
std::tuple<int, int, int> index_map_key(index.vertex_index, index.normal_index, index.texcoord_index);
if (index_map.find(index_map_key) == index_map.end()) {
vertices.emplace_back(
attrib.vertices[3 * index.vertex_index + 0],
attrib.vertices[3 * index.vertex_index + 1],
attrib.vertices[3 * index.vertex_index + 2]);
normals.emplace_back(
attrib.normals[3 * index.normal_index + 0],
attrib.normals[3 * index.normal_index + 1],
attrib.normals[3 * index.normal_index + 2]);
textures.emplace_back(
attrib.texcoords[2 * index.texcoord_index + 0],
attrib.texcoords[2 * index.texcoord_index + 1]);
index_map[index_map_key] = next_index++;
}
indices.emplace_back(index_map[index_map_key]);
}
index_offset += face_vertices;
}
// return std::make_shared<Shape>(indices, vertices, normals, textures);
return std::make_shared<Shape>(indices, vertices, normals, textures);
}
/**
* Create a screen sizes quad.
* @return Shape containing the quad.
*/
std::shared_ptr<Shape> createQuad() {
std::vector<unsigned short> indices = {0, 1, 2, 2, 1, 3};
std::vector<glm::vec3> vertices = {glm::vec3(-1, -1, 0), glm::vec3(1, -1, 0), glm::vec3(-1, 1, 0), glm::vec3(1, 1, 0)};
std::vector<glm::vec2> textures = {glm::vec2(0, 0), glm::vec2(1, 0), glm::vec2(0, 1), glm::vec2(1, 1)};
std::vector<glm::vec3> normals = {glm::vec3(0, 0, 1), glm::vec3(0, 0, 1), glm::vec3(0, 0, 1), glm::vec3(0, 0, 1)};
return std::make_shared<Shape>(indices, vertices, normals, textures);
}
std::shared_ptr<Shape> ObjLoader::getQuad() {
static std::shared_ptr<Shape> quad = createQuad();
return quad;
}
| 33.942308 | 122 | 0.632861 | [
"mesh",
"object",
"shape",
"vector"
] |
9cf38918e4de64223ff5b04d1daa5a6a5b8d6912 | 8,316 | hpp | C++ | include/yaarc/Value.hpp | Cookieverse/yaarc | 3e61c1cdb80a766f821249fcf4d6d72b19e247d2 | [
"BSL-1.0"
] | null | null | null | include/yaarc/Value.hpp | Cookieverse/yaarc | 3e61c1cdb80a766f821249fcf4d6d72b19e247d2 | [
"BSL-1.0"
] | null | null | null | include/yaarc/Value.hpp | Cookieverse/yaarc | 3e61c1cdb80a766f821249fcf4d6d72b19e247d2 | [
"BSL-1.0"
] | null | null | null | #pragma clang diagnostic push
#pragma ide diagnostic ignored "google-explicit-constructor"
#pragma ide diagnostic ignored "cppcoreguidelines-pro-type-member-init"
#ifndef YAARC_VALUE_HPP
#define YAARC_VALUE_HPP
#include <new>
#include <string_view>
#include <vector>
#include <stdexcept>
#include <fmt/format.h>
#include "impl/StringToInt64.hpp"
namespace yaarc {
enum class ValueType {
Null,
String,
Error,
Integer,
Array
};
class Value {
ValueType m_type;
union {
int64_t m_int;
// strings are stored as uint8_t vectors and just cast when we require a string
std::vector<uint8_t> m_string;
std::vector<Value> m_array;
};
public:
Value() {
m_type = ValueType::Null;
}
// creating a string
Value(const char* c_string) : m_type(ValueType::String) {
auto data = reinterpret_cast<const uint8_t*>(c_string);
new(&m_string) std::vector<uint8_t>;
m_string.insert(m_string.begin(), data, data + strlen(c_string));
}
Value(const char* string, size_t len) : m_type(ValueType::String) {
auto data = reinterpret_cast<const uint8_t*>(string);
new(&m_string) std::vector<uint8_t>;
m_string.insert(m_string.begin(), data, data + len);
}
Value(const uint8_t* data, size_t len) : m_type(ValueType::String) {
new(&m_string) std::vector<uint8_t>;
m_string.insert(m_string.begin(), data, data + len);
}
Value(const std::string& string) : m_type(ValueType::String) {
auto data = reinterpret_cast<const uint8_t*>(string.data());
new(&m_string) std::vector<uint8_t>;
m_string.insert(m_string.begin(), data, data + string.length());
}
Value(const std::string_view& string) : m_type(ValueType::String) {
auto data = reinterpret_cast<const uint8_t*>(string.data());
new(&m_string) std::vector<uint8_t>;
m_string.insert(m_string.begin(), data, data + string.length());
}
// creating an integer
Value(int64_t integer) : m_type(ValueType::Integer), m_int(integer) {
}
// array
Value(std::vector<Value> values) : m_type(ValueType::Array) {
new(&m_array) std::vector<Value>;
m_array = std::move(values);
}
Value(std::initializer_list<Value> values) : m_type(ValueType::Array) {
new(&m_array) std::vector<Value>(values);
}
Value(ValueType type) : m_type(type) {
switch (type) {
case ValueType::String:
case ValueType::Error:
new(&m_string) std::vector<uint8_t>;
break;
case ValueType::Integer:
m_int = 0;
break;
case ValueType::Array:
new(&m_array) std::vector<Value>;
break;
case ValueType::Null:
break;
}
}
// copy
Value(const Value& other) : m_type(ValueType::Null) {
*this = other;
}
Value& operator=(const Value& other) {
// destroy any potential old things if there's a different type
bool needsInit = false;
if (m_type != other.m_type) {
needsInit = true;
this->~Value();
}
m_type = other.m_type;
switch (m_type) {
case ValueType::String:
case ValueType::Error:
if (needsInit) {
new(&m_string) std::vector<uint8_t>;
}
m_string = other.m_string;
break;
case ValueType::Integer:
m_int = other.m_int;
break;
case ValueType::Array:
if (needsInit) {
new(&m_array) std::vector<Value>;
}
m_array = other.m_array;
break;
case ValueType::Null:
break;
}
return *this;
}
// move
Value(Value&& other) noexcept {
m_type = other.m_type;
switch (m_type) {
case ValueType::String:
case ValueType::Error:
new(&m_string) std::vector<uint8_t>;
m_string.swap(other.m_string);
break;
case ValueType::Integer:
m_int = other.m_int;
break;
case ValueType::Array:
new(&m_array) std::vector<Value>;
m_array.swap(other.m_array);
break;
case ValueType::Null:
break;
}
}
~Value() {
switch (m_type) {
case ValueType::String:
case ValueType::Error:
m_string.~vector();
break;
case ValueType::Array:
m_array.~vector();
break;
case ValueType::Integer:
case ValueType::Null:
break;
}
m_type = ValueType::Null;
}
bool operator==(const Value& rhs) const {
if (m_type != rhs.m_type) {
return false;
}
switch (m_type) {
case ValueType::Null:
return true;
case ValueType::String:
case ValueType::Error:
return m_string == rhs.m_string;
case ValueType::Integer:
return AsInteger() == rhs.AsInteger();
case ValueType::Array:
if (m_array.size() != rhs.m_array.size()) {
return false;
}
for (size_t i = 0; i < m_array.size(); i++) {
if (m_array[i] != rhs.m_array[i]) {
return false;
}
}
return true;
}
throw std::runtime_error(fmt::format("Bad ValueType {}", m_type));
}
bool operator!=(const Value& rhs) const {
return !(rhs == *this);
}
[[nodiscard]] ValueType GetType() const {
return m_type;
}
[[nodiscard]] bool IsString() const {
return m_type == ValueType::String;
}
[[nodiscard]] std::string_view AsString() const {
if (m_type != ValueType::String && m_type != ValueType::Error) {
throw std::runtime_error(fmt::format("Cannot convert type {} to string", m_type));
}
return std::string_view(reinterpret_cast<const char*>(m_string.data()), m_string.size());
}
const std::vector<uint8_t> AsBytes() const {
if (m_type != ValueType::String && m_type != ValueType::Error) {
throw std::runtime_error(fmt::format("Cannot convert type {} to string", m_type));
}
return m_string;
}
[[nodiscard]] std::string AsStringCopy() const {
if (m_type != ValueType::String && m_type != ValueType::Error) {
throw std::runtime_error(fmt::format("Cannot convert type {} to string", m_type));
}
return std::string(reinterpret_cast<const char*>(m_string.data()), m_string.size());
}
[[nodiscard]] bool IsNull() const {
return m_type == ValueType::Null;
}
[[nodiscard]] bool IsInteger(bool checkConvertible = true) const {
if (m_type == ValueType::Integer) {
return true;
}
if (IsString()) {
auto data = reinterpret_cast<const char*>(m_string.data());
if (data != nullptr) {
bool isInteger;
impl::StringToInt64(data, data + m_string.size(), isInteger);
return isInteger;
}
}
return false;
}
[[nodiscard]] int64_t AsInteger() const {
if (m_type == ValueType::Integer) {
return m_int;
}
if (IsString()) {
auto data = reinterpret_cast<const char*>(m_string.data());
if (data != nullptr) {
bool isInteger;
int64_t res = impl::StringToInt64(data, data + m_string.size(), isInteger);
if (isInteger) {
return res;
}
}
throw std::runtime_error(
fmt::format("Could not convert string '{}' to an integer",
std::string_view(data, m_string.size())));
}
throw std::runtime_error(fmt::format("Cannot convert type {} to integer", m_type));
}
[[nodiscard]] bool IsArray() const {
return m_type == ValueType::Array;
}
[[nodiscard]] const std::vector<Value>& AsArray() const {
if (m_type != ValueType::Array) {
throw std::runtime_error(fmt::format("Cannot convert type {} to array", m_type));
}
return m_array;
}
[[nodiscard]] bool IsError() const {
return m_type == ValueType::Error;
}
[[nodiscard]] std::string_view AsError() const {
if (m_type != ValueType::Error) {
throw std::runtime_error(fmt::format("Cannot convert type {} to error", m_type));
}
return AsString();
}
template<typename T>
inline T As() const;
[[nodiscard]]
/// Errors are pretty much string types under the hood, so there can't be a constructor overload
static Value NewError(const void* data, size_t size) {
auto v = Value(static_cast<const uint8_t*>(data), size);
v.m_type = ValueType::Error;
return std::move(v);
}
};
template<>
inline std::string_view Value::As<std::string_view>() const {
return AsString();
};
template<>
inline std::string Value::As<std::string>() const {
return AsStringCopy();
};
template<>
inline int64_t Value::As<int64_t>() const {
return AsInteger();
};
template<>
inline std::vector<Value> Value::As<std::vector<Value>>() const {
return AsArray();
};
}
#endif //YAARC_VALUE_HPP
#pragma clang diagnostic pop | 25.509202 | 98 | 0.63961 | [
"vector"
] |
9cf6bee91e8338bf8b3b7f3abc8488b0d6e9fc34 | 28,935 | cc | C++ | src/storage.cc | caipengbo/kvrocks-annotated | a9b186bb8671304686747f2eedeb5b58dd2890bf | [
"BSD-3-Clause"
] | null | null | null | src/storage.cc | caipengbo/kvrocks-annotated | a9b186bb8671304686747f2eedeb5b58dd2890bf | [
"BSD-3-Clause"
] | null | null | null | src/storage.cc | caipengbo/kvrocks-annotated | a9b186bb8671304686747f2eedeb5b58dd2890bf | [
"BSD-3-Clause"
] | null | null | null | #include "storage.h"
#include <fcntl.h>
#include <sys/stat.h>
#include <iostream>
#include <memory>
#include <algorithm>
#include <event2/buffer.h>
#include <glog/logging.h>
#include <rocksdb/filter_policy.h>
#include <rocksdb/table.h>
#include <rocksdb/sst_file_manager.h>
#include <rocksdb/utilities/table_properties_collectors.h>
#include <rocksdb/rate_limiter.h>
#include <rocksdb/env.h>
#include "config.h"
#include "redis_db.h"
#include "rocksdb_crc32c.h"
#include "redis_metadata.h"
#include "redis_slot.h"
#include "event_listener.h"
#include "compact_filter.h"
#include "table_properties_collector.h"
namespace Engine {
// 定义的不同的CF的名字,用于存储不同的类别的内容,防止冲突
const char *kPubSubColumnFamilyName = "pubsub";
const char *kZSetScoreColumnFamilyName = "zset_score";
const char *kMetadataColumnFamilyName = "metadata";
const char *kSubkeyColumnFamilyName = "default";
const char *kSlotMetadataColumnFamilyName = "slot_metadata";
const char *kSlotColumnFamilyName = "slot";
const uint64_t kIORateLimitMaxMb = 1024000;
using rocksdb::Slice;
using Redis::WriteBatchExtractor;
Storage::Storage(Config *config)
: backup_env_(rocksdb::Env::Default()),
config_(config),
lock_mgr_(16) {
InitCRC32Table();
Metadata::InitVersionCounter();
}
Storage::~Storage() {
if (backup_ != nullptr) {
DestroyBackup();
}
CloseDB();
}
void Storage::CloseDB() {
db_->SyncWAL();
// prevent to destroy the cloumn family while the compact filter was using
db_mu_.lock();
db_closing_ = true;
while (db_refs_ != 0) {
db_mu_.unlock();
usleep(10000);
db_mu_.lock();
}
db_mu_.unlock();
for (auto handle : cf_handles_) db_->DestroyColumnFamilyHandle(handle);
delete db_;
}
void Storage::InitOptions(rocksdb::Options *options) {
options->create_if_missing = true;
options->create_missing_column_families = true;
// options.IncreaseParallelism(2);
// NOTE: the overhead of statistics is 5%-10%, so it should be configurable in prod env
// See: https://github.com/facebook/rocksdb/wiki/Statistics
options->statistics = rocksdb::CreateDBStatistics();
options->stats_dump_period_sec = 0;
options->OptimizeLevelStyleCompaction();
options->max_open_files = config_->RocksDB.max_open_files;
options->max_subcompactions = static_cast<uint32_t>(config_->RocksDB.max_sub_compactions);
options->max_background_flushes = config_->RocksDB.max_background_flushes;
options->max_background_compactions = config_->RocksDB.max_background_compactions;
options->max_write_buffer_number = config_->RocksDB.max_write_buffer_number;
options->write_buffer_size = config_->RocksDB.write_buffer_size * MiB;
options->compression = static_cast<rocksdb::CompressionType>(config_->RocksDB.compression);
options->enable_pipelined_write = config_->RocksDB.enable_pipelined_write;
options->target_file_size_base = config_->RocksDB.target_file_size_base * MiB;
options->max_manifest_file_size = 64 * MiB;
options->max_log_file_size = 256 * MiB;
options->keep_log_file_num = 12;
options->WAL_ttl_seconds = static_cast<uint64_t>(config_->RocksDB.WAL_ttl_seconds);
options->WAL_size_limit_MB = static_cast<uint64_t>(config_->RocksDB.WAL_size_limit_MB);
options->max_total_wal_size = static_cast<uint64_t>(config_->RocksDB.max_total_wal_size * MiB);
options->listeners.emplace_back(new EventListener(this));
options->dump_malloc_stats = true;
sst_file_manager_ = std::shared_ptr<rocksdb::SstFileManager>(rocksdb::NewSstFileManager(rocksdb::Env::Default()));
options->sst_file_manager = sst_file_manager_;
uint64_t max_io_mb = kIORateLimitMaxMb;
if (config_->max_io_mb > 0) max_io_mb = static_cast<uint64_t>(config_->max_io_mb);
rate_limiter_ = std::shared_ptr<rocksdb::RateLimiter>(rocksdb::NewGenericRateLimiter(max_io_mb * MiB));
options->rate_limiter = rate_limiter_;
options->delayed_write_rate = static_cast<uint64_t>(config_->RocksDB.delayed_write_rate);
options->compaction_readahead_size = static_cast<size_t>(config_->RocksDB.compaction_readahead_size);
options->level0_slowdown_writes_trigger = config_->RocksDB.level0_slowdown_writes_trigger;
options->level0_stop_writes_trigger = config_->RocksDB.level0_stop_writes_trigger;
}
Status Storage::SetColumnFamilyOption(const std::string &key, const std::string &value) {
for (auto &cf_handle : cf_handles_) {
auto s = db_->SetOptions(cf_handle, {{key, value}});
if (!s.ok()) return Status(Status::NotOK, s.ToString());
}
return Status::OK();
}
Status Storage::SetOption(const std::string &key, const std::string &value) {
auto s = db_->SetOptions({{key, value}});
if (!s.ok()) return Status(Status::NotOK, s.ToString());
return Status::OK();
}
Status Storage::SetDBOption(const std::string &key, const std::string &value) {
auto s = db_->SetDBOptions({{key, value}});
if (!s.ok()) return Status(Status::NotOK, s.ToString());
return Status::OK();
}
// 创建KVRocks需要的CF
Status Storage::CreateColumnFamilies(const rocksdb::Options &options) {
rocksdb::DB *tmp_db;
rocksdb::ColumnFamilyOptions cf_options(options);
rocksdb::Status s = rocksdb::DB::Open(options, config_->db_dir, &tmp_db);
if (s.ok()) {
std::vector<std::string> cf_names = {kMetadataColumnFamilyName,
kZSetScoreColumnFamilyName,
kPubSubColumnFamilyName};
if (config_->codis_enabled) {
cf_names.emplace_back(kSlotMetadataColumnFamilyName);
cf_names.emplace_back(kSlotColumnFamilyName);
}
std::vector<rocksdb::ColumnFamilyHandle *> cf_handles;
s = tmp_db->CreateColumnFamilies(cf_options, cf_names, &cf_handles);
if (!s.ok()) {
delete tmp_db;
return Status(Status::DBOpenErr, s.ToString());
}
for (auto handle : cf_handles) tmp_db->DestroyColumnFamilyHandle(handle);
tmp_db->Close();
delete tmp_db;
}
// Open db would be failed if the column families have already exists,
// so we return ok here.
return Status::OK();
}
Status Storage::Open(bool read_only) {
db_mu_.lock();
db_closing_ = false;
db_refs_ = 0;
db_mu_.unlock();
bool cache_index_and_filter_blocks = config_->RocksDB.cache_index_and_filter_blocks;
size_t block_size = static_cast<size_t>(config_->RocksDB.block_size);
size_t metadata_block_cache_size = config_->RocksDB.metadata_block_cache_size*MiB;
size_t subkey_block_cache_size = config_->RocksDB.subkey_block_cache_size*MiB;
rocksdb::Options options;
InitOptions(&options);
// 创建KVRocks需要的 CF
CreateColumnFamilies(options);
// 各个CF 的 Option
rocksdb::BlockBasedTableOptions metadata_table_opts;
metadata_table_opts.filter_policy.reset(rocksdb::NewBloomFilterPolicy(10, true));
metadata_table_opts.block_cache = rocksdb::NewLRUCache(metadata_block_cache_size, -1, false, 0.75);
metadata_table_opts.cache_index_and_filter_blocks = cache_index_and_filter_blocks;
metadata_table_opts.cache_index_and_filter_blocks_with_high_priority = true;
metadata_table_opts.block_size = block_size;
rocksdb::ColumnFamilyOptions metadata_opts(options);
metadata_opts.table_factory.reset(rocksdb::NewBlockBasedTableFactory(metadata_table_opts));
metadata_opts.compaction_filter_factory = std::make_shared<MetadataFilterFactory>();
metadata_opts.disable_auto_compactions = config_->RocksDB.disable_auto_compactions;
metadata_opts.table_properties_collector_factories.emplace_back(
NewCompactOnExpiredTableCollectorFactory(kMetadataColumnFamilyName, 0.3));
rocksdb::BlockBasedTableOptions subkey_table_opts;
subkey_table_opts.filter_policy.reset(rocksdb::NewBloomFilterPolicy(10, true));
subkey_table_opts.block_cache = rocksdb::NewLRUCache(subkey_block_cache_size, -1, false, 0.75);
subkey_table_opts.cache_index_and_filter_blocks = cache_index_and_filter_blocks;
subkey_table_opts.cache_index_and_filter_blocks_with_high_priority = true;
subkey_table_opts.block_size = block_size;
rocksdb::ColumnFamilyOptions subkey_opts(options);
subkey_opts.table_factory.reset(rocksdb::NewBlockBasedTableFactory(subkey_table_opts));
subkey_opts.compaction_filter_factory = std::make_shared<SubKeyFilterFactory>(this);
subkey_opts.disable_auto_compactions = config_->RocksDB.disable_auto_compactions;
subkey_opts.table_properties_collector_factories.emplace_back(
NewCompactOnExpiredTableCollectorFactory(kSubkeyColumnFamilyName, 0.3));
rocksdb::BlockBasedTableOptions pubsub_table_opts;
pubsub_table_opts.filter_policy.reset(rocksdb::NewBloomFilterPolicy(10, true));
pubsub_table_opts.block_size = block_size;
rocksdb::ColumnFamilyOptions pubsub_opts(options);
pubsub_opts.table_factory.reset(rocksdb::NewBlockBasedTableFactory(pubsub_table_opts));
pubsub_opts.compaction_filter_factory = std::make_shared<PubSubFilterFactory>();
pubsub_opts.disable_auto_compactions = config_->RocksDB.disable_auto_compactions;
std::vector<rocksdb::ColumnFamilyDescriptor> column_families;
// Caution: don't change the order of column family, or the handle will be mismatched
column_families.emplace_back(rocksdb::ColumnFamilyDescriptor(rocksdb::kDefaultColumnFamilyName, subkey_opts));
column_families.emplace_back(rocksdb::ColumnFamilyDescriptor(kMetadataColumnFamilyName, metadata_opts));
column_families.emplace_back(rocksdb::ColumnFamilyDescriptor(kZSetScoreColumnFamilyName, subkey_opts));
column_families.emplace_back(rocksdb::ColumnFamilyDescriptor(kPubSubColumnFamilyName, pubsub_opts));
std::vector<std::string> old_column_families;
auto s = rocksdb::DB::ListColumnFamilies(options, config_->db_dir, &old_column_families);
if (!s.ok()) return Status(Status::NotOK, s.ToString());
if (!config_->codis_enabled && column_families.size() != old_column_families.size()) {
// 打开失败
return Status(Status::NotOK, "the db enabled codis mode at first open, please set codis-enabled 'yes'");
}
if (config_->codis_enabled && column_families.size() == old_column_families.size()) {
return Status(Status::NotOK, "the db disabled codis mode at first open, please set codis-enabled 'no'");
}
if (config_->codis_enabled) {
rocksdb::BlockBasedTableOptions slot_metadata_table_opts;
slot_metadata_table_opts.filter_policy.reset(rocksdb::NewBloomFilterPolicy(10, true));
slot_metadata_table_opts.block_cache =
rocksdb::NewLRUCache(metadata_block_cache_size, -1, false, 0.75);
slot_metadata_table_opts.cache_index_and_filter_blocks = true;
slot_metadata_table_opts.cache_index_and_filter_blocks_with_high_priority = true;
rocksdb::ColumnFamilyOptions slot_metadata_opts(options);
slot_metadata_opts.table_factory.reset(rocksdb::NewBlockBasedTableFactory(slot_metadata_table_opts));
rocksdb::BlockBasedTableOptions slotkey_table_opts;
slotkey_table_opts.filter_policy.reset(rocksdb::NewBloomFilterPolicy(10, true));
slotkey_table_opts.block_cache =
rocksdb::NewLRUCache(subkey_block_cache_size, -1, false, 0.75);
slotkey_table_opts.cache_index_and_filter_blocks = true;
slotkey_table_opts.cache_index_and_filter_blocks_with_high_priority = true;
rocksdb::ColumnFamilyOptions slotkey_opts(options);
slotkey_opts.table_factory.reset(rocksdb::NewBlockBasedTableFactory(slotkey_table_opts));
slotkey_opts.compaction_filter_factory = std::make_shared<SlotKeyFilterFactory>(this);
slotkey_opts.disable_auto_compactions = config_->RocksDB.disable_auto_compactions;
column_families.emplace_back(rocksdb::ColumnFamilyDescriptor(kSlotMetadataColumnFamilyName, slot_metadata_opts));
column_families.emplace_back(rocksdb::ColumnFamilyDescriptor(kSlotColumnFamilyName, slotkey_opts));
}
// 统计存储引擎的时间
auto start = std::chrono::high_resolution_clock::now();
if (read_only) {
s = rocksdb::DB::OpenForReadOnly(options, config_->db_dir, column_families, &cf_handles_, &db_);
} else {
s = rocksdb::DB::Open(options, config_->db_dir, column_families, &cf_handles_, &db_);
}
auto end = std::chrono::high_resolution_clock::now();
int64_t duration = std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count();
if (!s.ok()) {
LOG(INFO) << "[storage] Failed to load the data from disk: " << duration << " ms";
return Status(Status::DBOpenErr, s.ToString());
}
LOG(INFO) << "[storage] Success to load the data from disk: " << duration << " ms";
//
if (!read_only) {
// open backup engine
rocksdb::BackupableDBOptions bk_option(config_->backup_dir);
s = rocksdb::BackupEngine::Open(db_->GetEnv(), bk_option, &backup_);
if (!s.ok()) return Status(Status::DBBackupErr, s.ToString());
}
return Status::OK();
}
Status Storage::Open() {
return Open(false);
}
Status Storage::OpenForReadOnly() {
return Open(true);
}
Status Storage::CreateBackup() {
LOG(INFO) << "[storage] Start to create new backup";
auto tm = std::time(nullptr);
char time_str[25];
if (!std::strftime(time_str, sizeof(time_str), "%c", std::localtime(&tm))) {
return Status(Status::DBBackupErr, "Fail to format local time_str");
}
backup_mu_.lock();
rocksdb::Env::Default()->CreateDirIfMissing(config_->backup_dir);
auto s = backup_->CreateNewBackupWithMetadata(db_, time_str);
backup_mu_.unlock();
if (!s.ok()) return Status(Status::DBBackupErr, s.ToString());
LOG(INFO) << "[storage] Success to create new backup";
return Status::OK();
}
Status Storage::DestroyBackup() {
backup_->StopBackup();
delete backup_;
return Status();
}
Status Storage::RestoreFromBackup() {
// TODO(@ruoshan): assert role to be slave
// We must reopen the backup engine every time, as the files is changed
rocksdb::BackupableDBOptions bk_option(config_->backup_dir);
auto s = rocksdb::BackupEngine::Open(db_->GetEnv(), bk_option, &backup_);
if (!s.ok()) return Status(Status::DBBackupErr, s.ToString());
CloseDB();
s = backup_->RestoreDBFromLatestBackup(config_->db_dir, config_->db_dir);
if (!s.ok()) {
LOG(ERROR) << "[storage] Failed to restore: " << s.ToString();
} else {
LOG(INFO) << "[storage] Restore from backup";
}
// Reopen DB (should always try to reopen db even if restore failed , replication sst file crc check may use it)
auto s2 = Open();
if (!s2.IsOK()) {
LOG(ERROR) << "[storage] Failed to reopen db: " << s2.Msg();
return Status(Status::DBOpenErr, s2.Msg());
}
return s.ok() ? Status::OK() : Status(Status::DBBackupErr, s.ToString());
}
void Storage::PurgeOldBackups(uint32_t num_backups_to_keep, uint32_t backup_max_keep_hours) {
time_t now = time(nullptr);
std::vector<rocksdb::BackupInfo> backup_infos;
backup_mu_.lock();
backup_->GetBackupInfo(&backup_infos);
if (backup_infos.size() > num_backups_to_keep) {
uint32_t num_backups_to_purge = static_cast<uint32_t>(backup_infos.size()) - num_backups_to_keep;
for (uint32_t i = 0; i < num_backups_to_purge; i++) {
// the backup should not be purged if it's not yet expired,
// while multi slaves may create more replications than the `num_backups_to_keep`
if (backup_max_keep_hours != 0 && backup_infos[i].timestamp + backup_max_keep_hours * 3600 >= now) {
num_backups_to_purge--;
break;
}
LOG(INFO) << "[storage] The old backup(id: "
<< backup_infos[i].backup_id << ") would be purged, "
<< " created at: " << backup_infos[i].timestamp
<< ", size: " << backup_infos[i].size
<< ", num files: " << backup_infos[i].number_files;
}
if (num_backups_to_purge > 0) {
LOG(INFO) << "[storage] Going to purge " << num_backups_to_purge << " old backups";
auto s = backup_->PurgeOldBackups(backup_infos.size() - num_backups_to_purge);
LOG(INFO) << "[storage] Purge old backups, result: " << s.ToString();
}
}
if (backup_max_keep_hours == 0) {
backup_mu_.unlock();
return;
}
backup_infos.clear();
backup_->GetBackupInfo(&backup_infos);
for (uint32_t i = 0; i < backup_infos.size(); i++) {
if (backup_infos[i].timestamp + backup_max_keep_hours*3600 >= now) break;
LOG(INFO) << "[storage] The old backup(id:"
<< backup_infos[i].backup_id << ") would be purged because expired"
<< ", created at: " << backup_infos[i].timestamp
<< ", size: " << backup_infos[i].size
<< ", num files: " << backup_infos[i].number_files;
backup_->DeleteBackup(backup_infos[i].backup_id);
}
backup_mu_.unlock();
}
Status Storage::GetWALIter(
rocksdb::SequenceNumber seq,
std::unique_ptr<rocksdb::TransactionLogIterator> *iter) {
auto s = db_->GetUpdatesSince(seq, iter);
if (!s.ok()) return Status(Status::DBGetWALErr, s.ToString());
if (!(*iter)->Valid()) return Status(Status::DBGetWALErr, "iterator not valid");
return Status::OK();
}
rocksdb::SequenceNumber Storage::LatestSeq() {
return db_->GetLatestSequenceNumber();
}
rocksdb::Status Storage::Write(const rocksdb::WriteOptions &options, rocksdb::WriteBatch *updates) {
if (reach_db_size_limit_) {
return rocksdb::Status::SpaceLimit();
}
if (config_->codis_enabled) {
WriteBatchExtractor write_batch_extractor;
auto s = updates->Iterate(&write_batch_extractor);
if (!s.ok()) return s;
Redis::Slot slot_db(this);
slot_db.UpdateKeys(*write_batch_extractor.GetPutKeys(), *write_batch_extractor.GetDeleteKeys(), updates);
}
auto s = db_->Write(options, updates);
if (!s.ok()) return s;
return s;
}
rocksdb::Status Storage::Delete(const rocksdb::WriteOptions &options,
rocksdb::ColumnFamilyHandle *cf_handle,
const rocksdb::Slice &key) {
rocksdb::WriteBatch batch;
batch.Delete(cf_handle, key);
// 删除操作仅删除 metadata
if (config_->codis_enabled && cf_handle == GetCFHandle("metadata")) {
std::vector<std::string> delete_keys;
std::string ns, user_key;
ExtractNamespaceKey(key, &ns, &user_key);
delete_keys.emplace_back(user_key);
Redis::Slot slot_db(this);
auto s = slot_db.UpdateKeys({}, delete_keys, &batch);
if (!s.ok()) return s;
}
return db_->Write(options, &batch);
}
rocksdb::Status Storage::DeleteRange(const std::string &first_key, const std::string &last_key) {
auto s = db_->DeleteRange(rocksdb::WriteOptions(), GetCFHandle("metadata"), first_key, last_key);
if (!s.ok()) {
return s;
}
s = Delete(rocksdb::WriteOptions(), GetCFHandle("metadata"), last_key);
if (!s.ok()) {
return s;
}
if (config_->codis_enabled) {
// currently only flushall and flushdb use deleterange , so we can delete all codis slot data
// please do not use Storage::DeleteRange in other scenario
Redis::Slot slot_db(this);
auto s = slot_db.DeleteAll();
if (!s.ok()) return s;
}
return rocksdb::Status::OK();
}
Status Storage::WriteBatch(std::string &&raw_batch) {
if (reach_db_size_limit_) {
return Status(Status::NotOK, "reach space limit");
}
auto bat = rocksdb::WriteBatch(std::move(raw_batch));
auto s = db_->Write(rocksdb::WriteOptions(), &bat);
if (!s.ok()) {
return Status(Status::NotOK, s.ToString());
}
return Status::OK();
}
rocksdb::ColumnFamilyHandle *Storage::GetCFHandle(const std::string &name) {
if (name == kMetadataColumnFamilyName) {
return cf_handles_[1];
} else if (name == kZSetScoreColumnFamilyName) {
return cf_handles_[2];
} else if (name == kPubSubColumnFamilyName) {
return cf_handles_[3];
} else if (name == kSlotMetadataColumnFamilyName) {
return cf_handles_[4];
} else if (name == kSlotColumnFamilyName) {
return cf_handles_[5];
}
return cf_handles_[0];
}
rocksdb::Status Storage::Compact(const Slice *begin, const Slice *end) {
rocksdb::CompactRangeOptions compact_opts;
compact_opts.change_level = true;
for (const auto &cf_handle : cf_handles_) {
rocksdb::Status s = db_->CompactRange(compact_opts, cf_handle, begin, end);
if (!s.ok()) return s;
}
return rocksdb::Status::OK();
}
uint64_t Storage::GetTotalSize(const std::string &ns) {
if (ns == kDefaultNamespace) {
return sst_file_manager_->GetTotalSize();
}
std::string prefix, begin_key, end_key;
ComposeNamespaceKey(ns, "", &prefix);
Redis::Database db(this, ns);
auto s = db.FindKeyRangeWithPrefix(prefix, &begin_key, &end_key);
if (!s.ok()) {
return 0;
}
uint64_t size, total_size = 0;
rocksdb::Range r(begin_key, end_key);
uint8_t include_both = rocksdb::DB::SizeApproximationFlags::INCLUDE_FILES |
rocksdb::DB::SizeApproximationFlags::INCLUDE_MEMTABLES;
for (auto cf_handle : cf_handles_) {
if (cf_handle == GetCFHandle(kPubSubColumnFamilyName)) continue;
db_->GetApproximateSizes(cf_handle, &r, 1, &size, include_both);
total_size += size;
}
return total_size;
}
Status Storage::CheckDBSizeLimit() {
bool reach_db_size_limit;
if (config_->max_db_size == 0) {
reach_db_size_limit = false;
} else {
reach_db_size_limit = GetTotalSize() >= config_->max_db_size * GiB;
}
if (reach_db_size_limit_ == reach_db_size_limit) {
return Status::OK();
}
reach_db_size_limit_ = reach_db_size_limit;
if (reach_db_size_limit_) {
LOG(WARNING) << "[storage] ENABLE db_size limit " << config_->max_db_size << " GB"
<< "set kvrocks to read-only mode";
} else {
LOG(WARNING) << "[storage] DISABLE db_size limit, set kvrocks to read-write mode ";
}
return Status::OK();
}
void Storage::SetIORateLimit(uint64_t max_io_mb) {
if (max_io_mb == 0) {
max_io_mb = kIORateLimitMaxMb;
}
rate_limiter_->SetBytesPerSecond(max_io_mb * MiB);
}
rocksdb::DB *Storage::GetDB() { return db_; }
Status Storage::IncrDBRefs() {
db_mu_.lock();
if (db_closing_) {
db_mu_.unlock();
return Status(Status::NotOK, "db is closing");
}
db_refs_++;
db_mu_.unlock();
return Status::OK();
}
Status Storage::DecrDBRefs() {
db_mu_.lock();
if (db_refs_ == 0) {
db_mu_.unlock();
return Status(Status::NotOK, "db refs was zero");
}
db_refs_--;
db_mu_.unlock();
return Status::OK();
}
Status Storage::BackupManager::OpenLatestMeta(Storage *storage,
int *fd,
rocksdb::BackupID *meta_id,
uint64_t *file_size) {
Status status = storage->CreateBackup();
if (!status.IsOK()) return status;
std::vector<rocksdb::BackupInfo> backup_infos;
storage->backup_->GetBackupInfo(&backup_infos);
auto latest_backup = backup_infos.back();
rocksdb::Status r_status = storage->backup_->VerifyBackup(latest_backup.backup_id);
if (!r_status.ok()) {
return Status(Status::NotOK, r_status.ToString());
}
*meta_id = latest_backup.backup_id;
std::string meta_file =
storage->config_->backup_dir + "/meta/" + std::to_string(*meta_id);
auto s = storage->backup_env_->FileExists(meta_file);
storage->backup_env_->GetFileSize(meta_file, file_size);
// NOTE: here we use the system's open instead of using rocksdb::Env to open
// a sequential file, because we want to use sendfile syscall.
*fd = open(meta_file.c_str(), O_RDONLY);
if (*fd < 0) {
return Status(Status::NotOK, strerror(errno));
}
return Status::OK();
}
int Storage::BackupManager::OpenDataFile(Storage *storage, const std::string &rel_path,
uint64_t *file_size) {
std::string abs_path = storage->config_->backup_dir + "/" + rel_path;
auto s = storage->backup_env_->FileExists(abs_path);
if (!s.ok()) {
LOG(ERROR) << "[storage] Data file [" << abs_path << "] not found";
return -1;
}
storage->backup_env_->GetFileSize(abs_path, file_size);
auto rv = open(abs_path.c_str(), O_RDONLY);
if (rv < 0) {
LOG(ERROR) << "[storage] Failed to open file: " << strerror(errno);
}
return rv;
}
Storage::BackupManager::MetaInfo Storage::BackupManager::ParseMetaAndSave(
Storage *storage, rocksdb::BackupID meta_id, evbuffer *evbuf) {
char *line;
size_t len;
Storage::BackupManager::MetaInfo meta;
auto meta_file = "meta/" + std::to_string(meta_id);
DLOG(INFO) << "[meta] id: " << meta_id;
// Save the meta to tmp file
auto wf = NewTmpFile(storage, meta_file);
auto data = evbuffer_pullup(evbuf, -1);
wf->Append(rocksdb::Slice(reinterpret_cast<char *>(data),
evbuffer_get_length(evbuf)));
wf->Close();
// timestamp;
line = evbuffer_readln(evbuf, &len, EVBUFFER_EOL_LF);
DLOG(INFO) << "[meta] timestamp: " << line;
meta.timestamp = std::strtoll(line, nullptr, 10);
free(line);
// sequence
line = evbuffer_readln(evbuf, &len, EVBUFFER_EOL_LF);
DLOG(INFO) << "[meta] seq:" << line;
meta.seq = std::strtoull(line, nullptr, 10);
free(line);
// optional metadata
line = evbuffer_readln(evbuf, &len, EVBUFFER_EOL_LF);
if (strncmp(line, "metadata", 8) == 0) {
DLOG(INFO) << "[meta] meta: " << line;
meta.meta_data = std::string(line, len);
free(line);
line = evbuffer_readln(evbuf, &len, EVBUFFER_EOL_LF);
}
DLOG(INFO) << "[meta] file count: " << line;
free(line);
// file list
while (true) {
line = evbuffer_readln(evbuf, &len, EVBUFFER_EOL_LF);
if (!line) {
break;
}
DLOG(INFO) << "[meta] file info: " << line;
auto cptr = line;
while (*(cptr++) != ' ') {}
auto filename = std::string(line, cptr - line - 1);
while (*(cptr++) != ' ') {}
auto crc32 = std::strtoul(cptr, nullptr, 10);
meta.files.emplace_back(filename, crc32);
free(line);
}
SwapTmpFile(storage, meta_file);
return meta;
}
Status MkdirRecursively(rocksdb::Env *env, const std::string &dir) {
if (env->CreateDirIfMissing(dir).ok()) return Status::OK();
std::string parent;
for (auto pos = dir.find('/', 1); pos != std::string::npos;
pos = dir.find('/', pos + 1)) {
parent = dir.substr(0, pos);
if (!env->CreateDirIfMissing(parent).ok()) {
LOG(ERROR) << "[storage] Failed to create directory recursively";
return Status(Status::NotOK);
}
}
if (env->CreateDirIfMissing(dir).ok()) return Status::OK();
return Status(Status::NotOK);
}
std::unique_ptr<rocksdb::WritableFile> Storage::BackupManager::NewTmpFile(
Storage *storage, const std::string &rel_path) {
std::string tmp_path = storage->config_->backup_dir + "/" + rel_path + ".tmp";
auto s = storage->backup_env_->FileExists(tmp_path);
if (s.ok()) {
LOG(ERROR) << "[storage] Data file exists, override";
storage->backup_env_->DeleteFile(tmp_path);
}
// Create directory if missing
auto abs_dir = tmp_path.substr(0, tmp_path.rfind('/'));
if (!MkdirRecursively(storage->backup_env_, abs_dir).IsOK()) {
return nullptr;
}
std::unique_ptr<rocksdb::WritableFile> wf;
s = storage->backup_env_->NewWritableFile(tmp_path, &wf, rocksdb::EnvOptions());
if (!s.ok()) {
LOG(ERROR) << "[storage] Failed to create data file: " << s.ToString();
return nullptr;
}
return wf;
}
Status Storage::BackupManager::SwapTmpFile(Storage *storage,
const std::string &rel_path) {
std::string tmp_path = storage->config_->backup_dir + "/" + rel_path + ".tmp";
std::string orig_path = storage->config_->backup_dir + "/" + rel_path;
if (!storage->backup_env_->RenameFile(tmp_path, orig_path).ok()) {
return Status(Status::NotOK, "unable to rename: "+tmp_path);
}
return Status::OK();
}
bool Storage::BackupManager::FileExists(Storage *storage, const std::string &rel_path, uint32_t crc) {
if (storage->IsClosing()) return false;
auto file_path = storage->config_->backup_dir + "/" + rel_path;
auto s = storage->backup_env_->FileExists(file_path);
if (!s.ok()) return false;
std::unique_ptr<rocksdb::SequentialFile> src_file;
const rocksdb::EnvOptions soptions;
s = storage->GetDB()->GetEnv()->NewSequentialFile(file_path, &src_file, soptions);
if (!s.ok()) return false;
uint64_t size;
s = storage->GetDB()->GetEnv()->GetFileSize(file_path, &size);
if (!s.ok()) return false;
std::unique_ptr<rocksdb::SequentialFileWrapper> src_reader;
src_reader.reset(new rocksdb::SequentialFileWrapper(src_file.get()));
char buffer[4096];
Slice slice;
uint32_t tmp_crc = 0;
while (size > 0) {
size_t bytes_to_read = std::min(sizeof(buffer), static_cast<size_t>(size));
s = src_reader->Read(bytes_to_read, &slice, buffer);
if (!s.ok()) return false;
if (slice.size() == 0) return false;
tmp_crc = rocksdb::crc32c::Extend(0, slice.ToString().c_str(), slice.size());
size -= slice.size();
}
return crc == tmp_crc;
}
void Storage::PurgeBackupIfNeed(uint32_t next_backup_id) {
std::vector<rocksdb::BackupInfo> backup_infos;
backup_->GetBackupInfo(&backup_infos);
size_t num_backup = backup_infos.size();
if (num_backup > 0 && backup_infos[num_backup-1].backup_id != next_backup_id-1) {
PurgeOldBackups(0, 0);
}
}
} // namespace Engine
| 39.313859 | 117 | 0.705754 | [
"vector"
] |
9cf748b9216862541150b0eaab3eded4f6cd88db | 6,698 | hpp | C++ | sprout/darkroom/renderers/whitted_style.hpp | osyo-manga/Sprout | 8885b115f739ef255530f772067475d3bc0dcef7 | [
"BSL-1.0"
] | 1 | 2020-02-04T05:16:01.000Z | 2020-02-04T05:16:01.000Z | sprout/darkroom/renderers/whitted_style.hpp | osyo-manga/Sprout | 8885b115f739ef255530f772067475d3bc0dcef7 | [
"BSL-1.0"
] | null | null | null | sprout/darkroom/renderers/whitted_style.hpp | osyo-manga/Sprout | 8885b115f739ef255530f772067475d3bc0dcef7 | [
"BSL-1.0"
] | null | null | null | #ifndef SPROUT_DARKROOM_RENDERERS_WHITTED_STYLE_HPP
#define SPROUT_DARKROOM_RENDERERS_WHITTED_STYLE_HPP
#include <cstddef>
#include <limits>
#include <type_traits>
#include <sprout/config.hpp>
#include <sprout/tuple/functions.hpp>
#include <sprout/darkroom/access/access.hpp>
#include <sprout/darkroom/colors/rgb.hpp>
#include <sprout/darkroom/coords/vector.hpp>
#include <sprout/darkroom/rays/ray.hpp>
#include <sprout/darkroom/materials/material.hpp>
#include <sprout/darkroom/intersects/intersection.hpp>
#include <sprout/darkroom/objects/intersect.hpp>
#include <sprout/darkroom/renderers/infinity.hpp>
namespace sprout {
namespace darkroom {
namespace renderers {
//
// whitted_mirror
//
class whitted_mirror {
private:
template<
typename Color,
typename Camera, typename Objects, typename Lights,
typename Ray, typename Intersection, typename Tracer,
typename Direction
>
SPROUT_CONSTEXPR Color
color_1(
Camera const& camera, Objects const& objs, Lights const& lights,
Ray const& ray, Intersection const& inter, Tracer const& tracer,
std::size_t depth_max,
Direction const& reflect_dir
) const
{
return tracer.template operator()<Color>(
camera, objs, lights,
sprout::tuples::remake<Ray>(
ray,
sprout::darkroom::coords::add(
sprout::darkroom::intersects::point_of_intersection(inter),
sprout::darkroom::coords::scale(
reflect_dir,
std::numeric_limits<typename sprout::darkroom::access::unit<Direction>::type>::epsilon() * 256
)
// ???
// sprout::darkroom::coords::scale(
// sprout::darkroom::intersects::normal(inter),
// std::numeric_limits<typename sprout::darkroom::access::unit<Direction>::type>::epsilon() * 256
// )
),
reflect_dir
),
depth_max - 1
);
}
public:
template<
typename Color,
typename Camera, typename Objects, typename Lights,
typename Ray, typename Intersection, typename Tracer
>
SPROUT_CONSTEXPR Color
operator()(
Camera const& camera, Objects const& objs, Lights const& lights,
Ray const& ray, Intersection const& inter, Tracer const& tracer,
std::size_t depth_max
) const
{
typedef typename std::decay<
decltype(sprout::darkroom::materials::reflection(sprout::darkroom::intersects::material(inter)))
>::type reflection_type;
return depth_max > 0
&& sprout::darkroom::intersects::does_intersect(inter)
&& sprout::darkroom::materials::reflection(sprout::darkroom::intersects::material(inter))
> std::numeric_limits<reflection_type>::epsilon()
? color_1<Color>(
camera, objs, lights,
ray, inter, tracer,
depth_max,
sprout::darkroom::coords::reflect(
sprout::darkroom::rays::direction(ray),
sprout::darkroom::intersects::normal(inter)
)
)
: sprout::tuples::make<Color>(0, 0, 0)
;
}
};
//
// whitted_style
//
template<typename InfinityColor = sprout::darkroom::renderers::direction_gradation>
class whitted_style {
public:
typedef InfinityColor infinity_color_type;
private:
infinity_color_type infinity_color_;
private:
template<typename Color, typename Ray, typename Intersection>
SPROUT_CONSTEXPR Color
color_3(
Ray const& ray, Intersection const& inter,
Color const& diffuse_color, Color const& mirror_color
) const
{
return sprout::darkroom::intersects::does_intersect(inter)
? sprout::darkroom::colors::add(
sprout::darkroom::colors::mul(
diffuse_color,
1 - sprout::darkroom::materials::reflection(sprout::darkroom::intersects::material(inter))
),
sprout::darkroom::colors::mul(
mirror_color,
sprout::darkroom::materials::reflection(sprout::darkroom::intersects::material(inter))
)
)
: infinity_color_.template operator()<Color>(sprout::darkroom::rays::direction(ray))
;
}
template<
typename Color,
typename Camera, typename Objects, typename Lights,
typename Ray, typename Intersection
>
SPROUT_CONSTEXPR Color
color_2(
Camera const& camera, Objects const& objs, Lights const& lights,
Ray const& ray, std::size_t depth_max, Intersection const& inter,
Color const& diffuse_color
) const
{
return color_3<Color>(
ray, inter,
diffuse_color,
sprout::darkroom::renderers::whitted_mirror().template operator()<Color>(
camera, objs, lights,
ray, inter, *this,
depth_max
)
);
}
template<
typename Color,
typename Camera, typename Objects, typename Lights,
typename Ray, typename Intersection
>
SPROUT_CONSTEXPR Color
color_1(
Camera const& camera, Objects const& objs, Lights const& lights,
Ray const& ray, std::size_t depth_max, Intersection const& inter
) const
{
return color_2<Color>(
camera, objs, lights,
ray, depth_max, inter,
lights.template operator()(inter, objs)
);
}
public:
SPROUT_CONSTEXPR whitted_style()
: infinity_color_()
{}
SPROUT_CONSTEXPR whitted_style(whitted_style const&) = default;
explicit SPROUT_CONSTEXPR whitted_style(infinity_color_type const& infinity_color)
: infinity_color_(infinity_color)
{}
template<typename Color, typename Camera, typename Objects, typename Lights, typename Ray>
SPROUT_CONSTEXPR Color
operator()(
Camera const& camera, Objects const& objs, Lights const& lights,
Ray const& ray, std::size_t depth_max
) const
{
return color_1<Color>(
camera, objs, lights,
ray, depth_max,
sprout::darkroom::objects::intersect_list(objs, ray)
);
}
};
//
// make_whitted_style
//
inline SPROUT_CONSTEXPR sprout::darkroom::renderers::whitted_style<>
make_whitted_style() {
return sprout::darkroom::renderers::whitted_style<>();
}
template<typename InfinityColor>
inline SPROUT_CONSTEXPR sprout::darkroom::renderers::whitted_style<InfinityColor>
make_whitted_style(InfinityColor const& infinity_color) {
return sprout::darkroom::renderers::whitted_style<InfinityColor>(infinity_color);
}
} // namespace renderers
} // namespace darkroom
} // namespace sprout
#endif // #ifndef SPROUT_DARKROOM_RENDERERS_WHITTED_STYLE_HPP
| 32.995074 | 106 | 0.652135 | [
"vector"
] |
9cf904072e9f2cf5e07dc4f1cefaf0eae7d8eda8 | 2,161 | hpp | C++ | src/mlpack/methods/lmnn/lmnn_impl.hpp | steva44/mlpack | a766ea292e968f0cf1783f8293f36f47510fc6ad | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 8 | 2021-08-10T01:10:46.000Z | 2022-01-09T06:54:11.000Z | src/mlpack/methods/lmnn/lmnn_impl.hpp | steva44/mlpack | a766ea292e968f0cf1783f8293f36f47510fc6ad | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 4 | 2020-06-21T17:36:46.000Z | 2020-08-07T07:16:01.000Z | src/mlpack/methods/lmnn/lmnn_impl.hpp | steva44/mlpack | a766ea292e968f0cf1783f8293f36f47510fc6ad | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 2 | 2020-06-05T13:27:26.000Z | 2020-06-23T09:44:31.000Z | /**
* @file methods/lmnn/lmnn_impl.hpp
* @author Manish Kumar
*
* Implementation of Large Margin Nearest Neighbor class.
*
* mlpack is free software; you may redistribute it and/or modify it under the
* terms of the 3-clause BSD license. You should have received a copy of the
* 3-clause BSD license along with mlpack. If not, see
* http://www.opensource.org/licenses/BSD-3-Clause for more information.
*/
#ifndef MLPACK_METHODS_LMNN_LMNN_IMPL_HPP
#define MLPACK_METHODS_LMNN_LMNN_IMPL_HPP
// In case it was not already included.
#include "lmnn.hpp"
namespace mlpack {
namespace lmnn {
/**
* Takes in a reference to the dataset. Copies the data, initializes
* all of the member variables and constraint object and generate constraints.
*/
template<typename MetricType, typename OptimizerType>
LMNN<MetricType, OptimizerType>::LMNN(const arma::mat& dataset,
const arma::Row<size_t>& labels,
const size_t k,
const MetricType metric) :
dataset(dataset),
labels(labels),
k(k),
regularization(0.5),
range(1),
metric(metric)
{ /* nothing to do */ }
template<typename MetricType, typename OptimizerType>
template<typename... CallbackTypes>
void LMNN<MetricType, OptimizerType>::LearnDistance(arma::mat& outputMatrix,
CallbackTypes&&... callbacks)
{
// LMNN objective function.
LMNNFunction<MetricType> objFunction(dataset, labels, k,
regularization, range);
// See if we were passed an initialized matrix. outputMatrix (L) must be
// having r x d dimensionality.
if ((outputMatrix.n_cols != dataset.n_rows) ||
(outputMatrix.n_rows > dataset.n_rows) ||
!(arma::is_finite(outputMatrix)))
{
Log::Info << "Initial learning point have invalid dimensionality. "
"Identity matrix will be used as initial learning point for "
"optimization." << std::endl;
outputMatrix.eye(dataset.n_rows, dataset.n_rows);
}
Timer::Start("lmnn_optimization");
optimizer.Optimize(objFunction, outputMatrix, callbacks...);
Timer::Stop("lmnn_optimization");
}
} // namespace lmnn
} // namespace mlpack
#endif
| 30.43662 | 78 | 0.698751 | [
"object"
] |
9cf9eb8d9711594efcd228e20009233052dca49e | 15,206 | cc | C++ | gearsBridge/lshw/src/core/usb.cc | SSEHUB/spassMeter | f5071105fec6f5afbbd7426b8149b7973c1a5e55 | [
"Apache-2.0"
] | 1 | 2015-08-06T08:48:12.000Z | 2015-08-06T08:48:12.000Z | gearsBridge/lshw/src/core/usb.cc | SSEHUB/spassMeter | f5071105fec6f5afbbd7426b8149b7973c1a5e55 | [
"Apache-2.0"
] | 1 | 2018-05-08T12:17:23.000Z | 2018-05-09T12:03:13.000Z | gearsBridge/lshw/src/core/usb.cc | SSEHUB/spassMeter | f5071105fec6f5afbbd7426b8149b7973c1a5e55 | [
"Apache-2.0"
] | 3 | 2015-09-26T22:19:40.000Z | 2018-08-27T05:36:34.000Z | /*
* usb.cc
*
*/
#ifndef _GNU_SOURCE
#define _GNU_SOURCE
#endif
#include "version.h"
#include "config.h"
#include "usb.h"
#include "osutils.h"
#include "heuristics.h"
#include "options.h"
#include <stdio.h>
#include <map>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/ioctl.h>
#include <errno.h>
#include <fcntl.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <dirent.h>
#define PROCBUSUSBDEVICES "/proc/bus/usb/devices"
#define SYSBUSUSBDEVICES "/sys/bus/usb/devices"
#define USBID_PATH "/usr/share/lshw/usb.ids:/usr/local/share/usb.ids:/usr/share/usb.ids:/etc/usb.ids:/usr/share/hwdata/usb.ids:/usr/share/misc/usb.ids"
#define USB_CLASS_PER_INTERFACE 0 /* for DeviceClass */
#define USB_CLASS_AUDIO 1
#define USB_CLASS_COMM 2
#define USB_CLASS_HID 3
#define USB_CLASS_IMAGING 6
#define USB_CLASS_PRINTER 7
#define USB_CLASS_MASS_STORAGE 8
#define USB_CLASS_HUB 9
#define USB_CLASS_DATA 0xa
#define USB_CLASS_SMARTCARD 0xb
#define USB_CLASS_VIDEO 0xe
#define USB_CLASS_WIRELESS 0xe0
#define USB_CLASS_VENDOR_SPEC 0xff
#define USB_SC_AUDIOCONTROL 1
#define USB_SC_AUDIOSTREAMING 2
#define USB_SC_AUDIOMIDISTREAMING 3
#define USB_SC_COMMMODEM 2
#define USB_SC_COMMETHERNET 6
#define USB_SC_COMMOBEX 0xb
#define USB_SC_HIDNONE 0
#define USB_SC_HIDBOOT 1
#define USB_PROT_HIDKBD 1
#define USB_PROT_HIDMOUSE 2
#define USB_SC_PRINTER 1
#define USB_PROT_PRINTERUNIDIR 1
#define USB_PROT_PRINTERBIDIR 2
#define USB_PROT_PRINTER1284 3
#define USB_SC_STORAGERBC 1
#define USB_SC_STORAGEATAPI 2
#define USB_SC_STORAGEFLOPPY 4
#define USB_SC_STORAGESCSI 6
#define USB_SC_WIRELESSRADIO 1
#define USB_PROT_BLUETOOTH 1
static map<u_int16_t,string> usbvendors;
static map<u_int32_t,string> usbproducts;
#define PRODID(x, y) ((x << 16) + y)
__ID("@(#) $Id: usb.cc 2151 2010-03-15 20:26:20Z lyonel $");
static string usbhost(unsigned bus)
{
char buffer[10];
snprintf(buffer, sizeof(buffer), "usb%u", bus);
return string(buffer);
}
static string usbhandle(unsigned bus, unsigned level, unsigned dev)
{
char buffer[10];
snprintf(buffer, sizeof(buffer), "USB:%u:%u", bus, dev);
return string(buffer);
}
static string usbbusinfo(unsigned bus, unsigned level, unsigned port)
{
char buffer[10];
if(level>0)
snprintf(buffer, sizeof(buffer), "usb@%u:%u", bus, port);
else
snprintf(buffer, sizeof(buffer), "usb@%u", bus);
return string(buffer);
}
static string usbspeed(float speed)
{
char buffer[15];
snprintf(buffer, sizeof(buffer), "%.fMbit/s", speed);
return string(buffer);
}
static bool addUSBChild(hwNode & n, hwNode & device, unsigned bus, unsigned lev, unsigned prnt)
{
hwNode * parent = NULL;
device.addHint("bus.icon", string("usb"));
if(prnt>0) parent = n.findChildByHandle(usbhandle(bus, lev-1, prnt));
if(parent)
{
if(parent->getBusInfo().find(":")==string::npos)
device.setBusInfo(parent->getBusInfo()+":"+device.getPhysId());
else
device.setBusInfo(parent->getBusInfo()+"."+device.getPhysId());
parent->addChild(device);
return true;
}
else
{
// USB host
{
string businfo = guessBusInfo(device.getSerial());
parent = n.findChildByBusInfo(businfo);
if(!parent) // still no luck
{
unsigned long long ioport = strtoll(device.getSerial().c_str(), NULL, 16);
parent = n.findChildByResource(hw::resource::ioport(ioport, ioport));
}
device.setSerial(""); // serial# has no meaning for USB hosts
}
if(parent)
{
parent->addChild(device);
return true;
}
else
n.addChild(device);
return false;
}
}
static bool setUSBClass(hwNode & device, unsigned cls, unsigned sub, unsigned prot)
{
if(device.getClass()!=hw::generic) return false;
switch(cls)
{
case USB_CLASS_AUDIO:
device.setClass(hw::multimedia);
device.setDescription(_("Audio device"));
switch(sub)
{
case USB_SC_AUDIOCONTROL:
device.addCapability("audio-control", _("Control device"));
break;
case USB_SC_AUDIOMIDISTREAMING:
device.addCapability("midi", _("MIDI"));
case USB_SC_AUDIOSTREAMING:
device.addCapability("audio-streaming", _("Audio streaming"));
break;
}
break;
case USB_CLASS_COMM:
device.setClass(hw::communication);
device.setDescription(_("Communication device"));
if(sub == USB_SC_COMMMODEM)
{
device.setDescription(_("Modem"));
if((prot>=1) && (prot<=6)) device.addCapability("atcommands", _("AT (Hayes) compatible"));
}
if(sub==USB_SC_COMMETHERNET) device.addCapability("ethernet", _("Ethernet networking"));
if(sub==USB_SC_COMMOBEX) device.addCapability("obex", _("OBEX networking"));
break;
case USB_CLASS_HID:
device.setClass(hw::input);
device.setDescription(_("Human interface device"));
if((sub==USB_SC_HIDNONE)||(sub==USB_SC_HIDBOOT))
{
switch(prot)
{
case USB_PROT_HIDKBD:
device.setDescription(_("Keyboard"));
break;
case USB_PROT_HIDMOUSE:
device.setDescription(_("Mouse"));
break;
}
}
break;
case USB_CLASS_PRINTER:
device.setClass(hw::printer);
device.setDescription(_("Printer"));
device.addHint("icon", string("printer"));
if(sub==USB_SC_PRINTER)
{
switch(prot)
{
case USB_PROT_PRINTERUNIDIR:
device.addCapability("unidirectional", _("Unidirectional"));
break;
case USB_PROT_PRINTERBIDIR:
device.addCapability("bidirectional", _("Bidirectional"));
break;
case USB_PROT_PRINTER1284:
device.addCapability("ieee1284.4", _("IEEE 1284.4 compatible bidirectional"));
break;
}
}
break;
case USB_CLASS_MASS_STORAGE:
device.setClass(hw::storage);
device.setDescription(_("Mass storage device"));
switch(sub)
{
case USB_SC_STORAGERBC:
device.addCapability("flash", _("RBC (typically Flash) mass storage"));
break;
case USB_SC_STORAGEATAPI:
device.addCapability("atapi", _("SFF-8020i, MMC-2 (ATAPI)"));
break;
case USB_SC_STORAGEFLOPPY:
device.addCapability("floppy", _("Floppy (UFI)"));
break;
case USB_SC_STORAGESCSI:
device.addCapability("scsi", _("SCSI"));
break;
}
break;
case USB_CLASS_HUB:
device.setClass(hw::bus);
device.setDescription(_("USB hub"));
break;
case USB_CLASS_DATA:
device.setClass(hw::generic);
break;
case USB_CLASS_SMARTCARD:
device.setClass(hw::generic);
device.setDescription(_("Smart card reader"));
break;
case USB_CLASS_VIDEO:
device.setClass(hw::multimedia);
device.setDescription(_("Video"));
break;
case USB_CLASS_WIRELESS:
device.setClass(hw::communication);
device.setDescription(_("Wireless interface"));
if((sub==USB_SC_WIRELESSRADIO) && (prot==USB_PROT_BLUETOOTH))
{
device.setDescription(_("Bluetooth wireless interface"));
device.addCapability("bluetooth", _("Bluetooth wireless radio"));
device.addHint("icon", string("bluetooth"));
}
break;
default:
device.setDescription(_("Generic USB device"));
return false;
}
return true;
}
static bool describeUSB(hwNode & device, unsigned vendor, unsigned prodid)
{
if(usbvendors.find(vendor)==usbvendors.end()) return false;
device.setVendor(usbvendors[vendor]+(enabled("output:numeric")?" ["+tohex(vendor)+"]":""));
device.addHint("usb.idVendor", vendor);
device.addHint("usb.idProduct", prodid);
if(usbproducts.find(PRODID(vendor, prodid))!=usbproducts.end())
device.setProduct(usbproducts[PRODID(vendor, prodid)]+(enabled("output:numeric")?" ["+tohex(vendor)+":"+tohex(prodid)+"]":""));
return true;
}
static bool load_usbids(const string & name)
{
FILE * usbids = NULL;
u_int16_t vendorid = 0;
usbids = fopen(name.c_str(), "r");
if(!usbids) return false;
while(!feof(usbids))
{
char * buffer = NULL;
size_t linelen;
unsigned t = 0;
char *description = NULL;
if(getline(&buffer, &linelen, usbids)>0)
{
if(buffer[linelen-1]<' ')
buffer[linelen-1] = '\0'; // chop \n
string line = string(buffer);
free(buffer);
description = NULL;
t = 0;
if(line.length()>0)
{
if(line[0] == '\t') // product id entry
{
line.erase(0, 1);
if(matches(line, "^[[:xdigit:]][[:xdigit:]][[:xdigit:]][[:xdigit:]]"))
t = strtol(line.c_str(), &description, 16);
if(description && (description != line.c_str()))
{
usbproducts[PRODID(vendorid,t)] = hw::strip(description);
}
}
else // vendor id entry
{
if(matches(line, "^[[:xdigit:]][[:xdigit:]][[:xdigit:]][[:xdigit:]]"))
t = strtol(line.c_str(), &description, 16);
if(description && (description != line.c_str()))
{
vendorid = t;
usbvendors[t] = hw::strip(description);
}
}
}
}
}
fclose(usbids);
return true;
}
bool scan_usb(hwNode & n)
{
hwNode device("device");
FILE * usbdevices = NULL;
bool defined = false;
unsigned int bus,lev,prnt,port,cnt,devnum,mxch;
float speed;
char ver[10+1];
unsigned int cls, sub, prot, mxps, numcfgs;
unsigned int vendor, prodid;
char rev[10+1];
unsigned numifs, cfgnum, atr;
char mxpwr[10+1];
unsigned ifnum, alt, numeps;
char driver[80+1];
if (!exists(PROCBUSUSBDEVICES))
return false;
vector < string > filenames;
splitlines(USBID_PATH, filenames, ':');
for (int i = filenames.size() - 1; i >= 0; i--)
{
load_usbids(filenames[i]);
}
filenames.clear();
usbdevices = fopen(PROCBUSUSBDEVICES, "r");
#if 0
if(!usbdevices)
usbdevices = fopen(SYSBUSUSBDEVICES, "r");
#endif
while(!feof(usbdevices))
{
char * buffer = NULL;
size_t linelen;
char strname[80+1];
char strval[80+1];
if(getline(&buffer, &linelen, usbdevices)>0)
{
string line = hw::strip(string(buffer));
free(buffer);
if(line.length()<=0)
{
if(defined)
addUSBChild(n, device, bus, lev, prnt);
device = hwNode("device");
defined = false;
}
else
{
if((line.length()>1) && (line[1] == ':'))
switch(line[0])
{
case 'T':
bus = lev = prnt = port = cnt = devnum = mxch = 0;
speed = 0.0;
strcpy(ver, "");
strcpy(rev, "");
cls = sub = prot = mxps = numcfgs = 0;
vendor = prodid = 0;
if(sscanf(line.c_str(), "T: Bus=%u Lev=%u Prnt=%u Port=%u Cnt=%u Dev#=%u Spd=%f MxCh=%u", &bus, &lev, &prnt, &port, &cnt, &devnum, &speed, &mxch)>0)
{
defined = true;
if(lev==0)
{
device = hwNode("usbhost", hw::bus);
device.claim();
device.setLogicalName(usbhost(bus));
}
else
device = hwNode("usb");
device.setHandle(usbhandle(bus, lev, devnum));
device.setBusInfo(usbbusinfo(bus, lev, port));
device.setPhysId(port+1);
device.setConfig("speed", usbspeed(speed));
if(mxch>0)
{
snprintf(strval, sizeof(strval), "%u", mxch);
device.setConfig("slots", strval);
}
}
break;
case 'D':
strcpy(ver, "");
cls = sub = prot = mxps = numcfgs = 0;
if(sscanf(line.c_str(), "D: Ver=%s Cls=%x(%*5c) Sub=%x Prot=%x MxPS=%u #Cfgs=%u", ver, &cls, &sub, &prot, &mxps, &numcfgs)>0)
{
setUSBClass(device, cls, sub, prot);
device.addCapability(string("usb-")+string(ver));
device.describeCapability("usb-1.00", "USB 1.0");
device.describeCapability("usb-1.10", "USB 1.1");
device.describeCapability("usb-2.00", "USB 2.0");
device.addHint("usb.bDeviceClass", cls);
device.addHint("usb.bDeviceSubClass", sub);
device.addHint("usb.bDeviceProtocol", prot);
}
break;
case 'P':
vendor = prodid = 0;
strcpy(rev, "");
if(sscanf(line.c_str(), "P: Vendor=%x ProdID=%x Rev=%10s", &vendor, &prodid, rev)>0)
{
describeUSB(device, vendor, prodid);
device.setVersion(hw::strip(rev));
}
break;
case 'S':
memset(strname, 0, sizeof(strname));
memset(strval, 0, sizeof(strval));
if(sscanf(line.c_str(), "S: %80[^=]=%80[ -z]", strname, strval)>0)
{
if(strcasecmp(strname, "Manufacturer")==0)
device.setVendor(hw::strip(strval)+(enabled("output:numeric")?" ["+tohex(vendor)+"]":""));
if(strcasecmp(strname, "Product")==0)
device.setProduct(hw::strip(strval)+(enabled("output:numeric")?" ["+tohex(vendor)+":"+tohex(prodid)+"]":""));
if(strcasecmp(strname, "SerialNumber")==0)
device.setSerial(hw::strip(strval));
}
break;
case 'C':
numifs = cfgnum = atr = 0;
strcpy(mxpwr, "");
if(sscanf(line.c_str(), "C:* #Ifs=%u Cfg#=%u Atr=%x MxPwr=%s", &numifs, &cfgnum, &atr, mxpwr)>0)
{
if(strcmp("0mA", mxpwr)!=0)
device.setConfig("maxpower", mxpwr);
}
break;
case 'I':
ifnum = alt = numeps = cls = sub = prot = 0;
memset(driver, 0, sizeof(driver));
if(((sscanf(line.c_str(), "I:* If#=%u Alt=%u #EPs=%u Cls=%x(%*5c) Sub=%x Prot=%x Driver=%80[ -z]", &ifnum, &alt, &numeps, &cls, &sub, &prot, driver)>0) && (cfgnum>0)) || ((sscanf(line.c_str(), "I: If#=%u Alt=%u #EPs=%u Cls=%x(%*5c) Sub=%x Prot=%x Driver=%80[ -z]", &ifnum, &alt, &numeps, &cls, &sub, &prot, driver)>0) && (cfgnum>0)))
{
setUSBClass(device, cls, sub, prot);
if((strlen(driver)!=0) && (strcasecmp("(none)", driver)!=0))
{
device.setConfig("driver", hw::strip(driver));
device.claim();
}
}
break;
}
}
}
}
if(defined)
addUSBChild(n, device, bus, lev, prnt);
if(usbdevices) fclose(usbdevices);
return true;
}
| 30.110891 | 345 | 0.566618 | [
"vector"
] |
9cf9efcdbc5c2c6dbe9198f5423be0f2adef3ec2 | 6,814 | cpp | C++ | src/VM/ByteCodeChunk.cpp | sunverwerth/strela | e2aa305bd695deaec3bc0f1e32394af033ee0fdf | [
"MIT"
] | 16 | 2019-03-22T14:20:14.000Z | 2022-02-06T03:22:08.000Z | src/VM/ByteCodeChunk.cpp | MadHed/strela | e2aa305bd695deaec3bc0f1e32394af033ee0fdf | [
"MIT"
] | 2 | 2018-04-15T10:59:17.000Z | 2018-09-28T12:30:31.000Z | src/VM/ByteCodeChunk.cpp | MadHed/strela | e2aa305bd695deaec3bc0f1e32394af033ee0fdf | [
"MIT"
] | 1 | 2021-01-02T18:00:36.000Z | 2021-01-02T18:00:36.000Z | // Copyright (c) 2018 Stephan Unverwerth
// This code is licensed under MIT license (See LICENSE for details)
#include "ByteCodeChunk.h"
#include "../exceptions.h"
#include "../Ast/FuncDecl.h"
#include "../Ast/FuncType.h"
#include <string.h>
namespace Strela {
int ByteCodeChunk::addConstant(VMValue c) {
for (int i = 0; i < constants.size(); ++i) {
if (
c.type == VMValue::Type::object
&& constants[i].type == VMValue::Type::object
&& !strcmp((const char*)c.value.object, (const char*)constants[i].value.object)
) {
return i;
}
else if (constants[i].equals(c)) {
return i;
}
}
constants.push_back(c);
return constants.size() - 1;
}
int ByteCodeChunk::addForeignFunction(FuncDecl& n) {
for (int i = 0; i < foreignFunctions.size(); ++i) {
if (
foreignFunctions[i].name == n.name &&
foreignFunctions[i].returnType == n.declType->returnType &&
foreignFunctions[i].argTypes == n.declType->paramTypes
) {
return i;
}
}
foreignFunctions.push_back(ForeignFunction(n.name, n.declType->returnType, n.declType->paramTypes));
return foreignFunctions.size() - 1;
}
int ByteCodeChunk::addOp(Opcode code) {
if (opcodeInfo[(unsigned char)code].argWidth > 0) throw Exception(std::string("Opcode ") + opcodeInfo[(unsigned char)code].name + " requires arguments.");
opcodes.push_back(code);
return opcodes.size() - 1;
}
int ByteCodeChunk::addOp(Opcode code, size_t argSize, const void* arg) {
auto opwidth = opcodeInfo[(unsigned char)code].argWidth;
if (opwidth != argSize) throw Exception(std::string("Opcode ") + opcodeInfo[(unsigned char)code].name + " has mismatching argument size. "
+ std::to_string(opwidth) + " expected but got " + std::to_string(argSize)
);
auto opAddr = opcodes.size();
opcodes.push_back(code);
opcodes.resize(opcodes.size() + argSize);
memcpy(&opcodes[opAddr + 1], arg, argSize);
return opAddr;
}
int ByteCodeChunk::addOp(Opcode code, size_t argSize1, const void* arg1, size_t argSize2, const void* arg2) {
auto opwidth = opcodeInfo[(unsigned char)code].argWidth;
if (opwidth != argSize1 + argSize2) throw Exception(std::string("Opcode ") + opcodeInfo[(unsigned char)code].name + " has mismatching argument size. "
+ std::to_string(opwidth) + " expected but got " + std::to_string(argSize1 + argSize2)
);
auto opAddr = opcodes.size();
opcodes.push_back(code);
opcodes.resize(opcodes.size() + argSize1 + argSize2);
memcpy(&opcodes[opAddr + 1], arg1, argSize1);
memcpy(&opcodes[opAddr + 1 + argSize1], arg2, argSize2);
return opAddr;
}
void ByteCodeChunk::addFunction(size_t address, const FunctionInfo& func) {
functions.insert(std::make_pair(address, func));
}
void ByteCodeChunk::writeArgument(size_t pos, uint64_t arg) {
auto numargs = opcodeInfo[(int)opcodes[pos++]].argWidth;
if (pos + numargs > opcodes.size()) {
opcodes.resize(pos + numargs);
}
memcpy(&opcodes[pos], &arg, numargs);
}
void ByteCodeChunk::write(size_t pos, void* data, size_t size) {
memcpy(&opcodes[pos], data, size);
}
std::ostream& operator<<(std::ostream& str, const ByteCodeChunk& chunk) {
str.write("STBC", 4);
uint32_t numFunctions = chunk.functions.size();
str.write((const char*)&numFunctions, 4);
for (auto&& function: chunk.functions) {
uint64_t offset = function.first;
uint64_t len = function.second.name.size();
const char* name = function.second.name.c_str();
str.write((const char*)&offset, 8);
str.write((const char*)&len, 8);
str.write((const char*)name, len);
}
uint32_t numConstants = chunk.constants.size();
str.write((const char*)&numConstants, 4);
for (auto&& constant: chunk.constants) {
str << constant;
}
uint64_t main = chunk.main;
str.write((const char*)&main, 8);
uint64_t numOpcodes = chunk.opcodes.size();
str.write((const char*)&numOpcodes, 8);
str.write((const char*)chunk.opcodes.data(), sizeof(char) * numOpcodes);
return str;
}
std::istream& operator>>(std::istream& str, ByteCodeChunk& chunk) {
chunk.constants.clear();
chunk.functions.clear();
chunk.opcodes.clear();
char magic[5]{0};
str.read((char*)&magic, 4);
if (strcmp(magic, "STBC")) {
throw std::runtime_error("Invalid bytecode format");
}
uint32_t numFunctions;
str.read((char*)&numFunctions, 4);
for (size_t i = 0; i < numFunctions; ++i) {
uint64_t offset;
str.read((char*)&offset, 8);
uint64_t len;
str.read((char*)&len, 8);
char* name = new char[len + 1];
name[len] = 0;
str.read((char*)name, len);
chunk.functions.insert(std::make_pair(offset, FunctionInfo{std::string(name)}));
delete[] name;
}
uint32_t numConstants;
str.read((char*)&numConstants, 4);
for (size_t i = 0; i < numConstants; ++i) {
VMValue constant;
str >> constant;
chunk.constants.push_back(constant);
}
uint64_t main;
str.read((char*)&main, 8);
chunk.main = main;
uint64_t numOpcodes;
str.read((char*)&numOpcodes, 8);
for (size_t i = 0; i < numOpcodes; ++i) {
Opcode op;
str.read((char*)&op, 1);
chunk.opcodes.push_back(op);
}
return str;
}
const SourceLine* ByteCodeChunk::getLine(size_t address) const {
for (int i = 0; i < lines.size(); ++i) {
if (lines[i].address > address) {
if (i == 0) return nullptr;
return &lines[i - 1];
}
}
return nullptr;
}
void ByteCodeChunk::setLine(const SourceFile* file, size_t line) {
for (size_t i = 0; i < files.size(); ++i) {
if (files[i] == file) {
if (!lines.empty() && lines.back().file == i && lines.back().line == line) {
return;
}
lines.push_back({ opcodes.size(), i, line });
return;
}
}
files.push_back(file);
lines.push_back({ opcodes.size(), files.size() - 1, line });
}
} | 35.675393 | 162 | 0.555768 | [
"object"
] |
9cfe677345d2c2447df6b61d4dd6352baa693632 | 10,683 | cpp | C++ | ColliderBit/src/models/SUSY_extras.cpp | GambitBSM/gambit_2.0 | a4742ac94a0352585a3b9dcb9b222048a5959b91 | [
"Unlicense"
] | 1 | 2021-09-17T22:53:26.000Z | 2021-09-17T22:53:26.000Z | ColliderBit/src/models/SUSY_extras.cpp | GambitBSM/gambit_2.0 | a4742ac94a0352585a3b9dcb9b222048a5959b91 | [
"Unlicense"
] | 3 | 2021-07-22T11:23:48.000Z | 2021-08-22T17:24:41.000Z | ColliderBit/src/models/SUSY_extras.cpp | GambitBSM/gambit_2.0 | a4742ac94a0352585a3b9dcb9b222048a5959b91 | [
"Unlicense"
] | 1 | 2021-08-14T10:31:41.000Z | 2021-08-14T10:31:41.000Z | // GAMBIT: Global and Modular BSM Inference Tool
// *********************************************
/// \file
///
/// SUSY-specific sources for ColliderBit.
///
/// *********************************************
///
/// Authors (add name and date if you modify):
///
/// \author Anders Kvellestad
/// (anders.kvellestad@fys.uio.no)
/// \date 2019 Dec
///
/// *********************************************
#include "gambit/ColliderBit/getPy8Collider.hpp"
#include "gambit/ColliderBit/generateEventPy8Collider.hpp"
namespace Gambit
{
namespace ColliderBit
{
// Get Monte Carlo event generator from SLHA file input
GET_SPECIFIC_PYTHIA_SLHA(getPythia_SLHA, Pythia_default, )
// Get next SLHA file path and content (for use with model ColliderBit_SLHA_file_model)
void getNextSLHAFileNameAndContent(pair_str_SLHAstruct& result)
{
using namespace Pipes::getNextSLHAFileNameAndContent;
static unsigned int counter = 0;
static bool first = true;
if (first)
{
if (!runOptions->hasKey("SLHA_filenames")) ColliderBit_error().raise(LOCAL_INFO,"Expected YAML file option 'SLHA_filenames' (a list of SLHA filenames) not found.");
first = false;
}
const static std::vector<str> filenames = runOptions->getValue<std::vector<str> >("SLHA_filenames");
if (counter >= filenames.size())
{
invalid_point().raise("No more SLHA files. My work is done.");
result = std::make_pair("", SLHAstruct());
}
else
{
const str& filename = filenames.at(counter);
result = std::make_pair(filename, read_SLHA(filename));
}
counter++;
}
// Read a single SLHA file and update some entries for each scan point
// (for use with model ColliderBit_SLHA_scan_model)
void getAndReplaceSLHAContent(pair_str_SLHAstruct& result)
{
using namespace Pipes::getAndReplaceSLHAContent;
static unsigned int counter = 0;
static str filename;
static SLHAstruct file_content;
static YAML::Node keysNode;
static Options keysOptions;
static std::map<str,str> SLHAkey_to_parname;
// Do the variable initialization only once
static bool first = true;
if (first)
{
if (!runOptions->hasKey("SLHA_filename")) ColliderBit_error().raise(LOCAL_INFO,"Expected YAML file option 'SLHA_filename' (a single SLHA filename) not found.");
if (!runOptions->hasKey("replace_SLHA_keys")) ColliderBit_error().raise(LOCAL_INFO,"Expected YAML file option 'replace_SLHA_keys' (a list of strings in the SLHAea key format, e.g. 'MASS;1000022;1') not found.");
// Get filename of base SLHA file
filename = runOptions->getValue<str>("SLHA_filename");
// Read the original SLHA file once
file_content = read_SLHA(filename);
// Get the YAML options under 'replace_SLHA_keys'
keysNode = runOptions->getValue<YAML::Node>("replace_SLHA_keys");
keysOptions = Options(keysNode);
// Construct a map from SLHA keys to scan model parameters
for (const str& parname : keysOptions.getNames())
{
std::vector<str> slhakeys = keysOptions.getValue<std::vector<str> >(parname);
for (const str& slhakey : slhakeys)
{
SLHAkey_to_parname[slhakey] = parname;
}
}
first = false;
}
// Generate new SLHA content by replacing SLHA elements with scan parameters
SLHAstruct new_content(file_content);
static int precision = 8;
for (const auto& key_param_pair : SLHAkey_to_parname)
{
new_content.field(key_param_pair.first) = SLHAea::to_string(*Param.at(key_param_pair.second), precision);
}
// Construct a dummy name for the SLHA "file" we pass around as a SLHAea object
std::stringstream filename_mod_ss;
filename_mod_ss << filename << ".point" << counter;
// Save result as a pair_str_SLHAstruct
result = std::make_pair(filename_mod_ss.str(), new_content);
/// @todo Add option to save the new SLHA content to file
counter++;
}
// Extract SLHA file elements (for use with model ColliderBit_SLHA_file_model)
void getSLHAFileElements(map_str_dbl& result)
{
using namespace Pipes::getSLHAFileElements;
// Split the required SLHAFileNameAndContent pair
const str& filename = Dep::SLHAFileNameAndContent->first;
const SLHAstruct& content = Dep::SLHAFileNameAndContent->second;
// Should missing elements be replaced by a default value?
const static bool use_missing_element_value = runOptions->hasKey("value_for_missing_elements");
static double missing_element_value;
static bool first = true;
if (first)
{
// Check that the required YAML option "SLHA_keys" is present
if (!runOptions->hasKey("SLHA_keys")) ColliderBit_error().raise(LOCAL_INFO,"Expected YAML file option 'SLHA_keys' (a list of strings in the SLHAea key format, e.g. 'MASS;1000022;1') not found.");
// Read default value for missing elements;
if (use_missing_element_value) missing_element_value = runOptions->getValue<double>("value_for_missing_elements");
first = false;
}
// Read the list of SLHA element keys
const static std::vector<str> slha_element_keys = runOptions->getValue<std::vector<str> >("SLHA_keys");
// Loop through the list of SLHA keys and grab the corresponding elements from the SLHA content
for(str key_str : slha_element_keys)
{
// Construct a SLHAea::Key from the key string
const SLHAea::Key key(key_str);
// Grab the correct entryand store in the results map
try
{
result[key_str] = SLHAea::to<double>( content.field(key) );
}
catch (const std::out_of_range& e)
{
std::stringstream errmsg_ss;
errmsg_ss << "Could not find SLHA element " << key_str << " in file " << filename;
if (use_missing_element_value)
{
logger() << errmsg_ss.str() << EOM;
result[key_str] = missing_element_value;
}
else
{
ColliderBit_error().raise(LOCAL_INFO, errmsg_ss.str());
}
}
}
}
// Extract an SLHAstruct with the specturm, either from the MSSM_spectrum
// capability (for MSSM models), or simply from the SLHAFileNameAndContent
// capability (for ColliderBit_SLHA_file_model, ColliderBit_SLHA_scan_model)
// @todo Should we perform some kind of SLHA1 vs SLHA2 check when used with the
// ColliderBit_SLHA_* models below? For these models we currently just trust
// the user to supply SLHA info in the appropriate format.
// @todo Should we unify these two functions into a single module function that just
// provides a std::function instance that can be called with an
// int argument = 1 or 2 and returns the appropriate SLHA1 or SLHA2 struct?
// SLHA1
void getSLHA1Spectrum(SLHAstruct& result)
{
using namespace Pipes::getSLHA1Spectrum;
static const bool write_summary_to_log = runOptions->getValueOrDef<bool>(false, "write_summary_to_log");
result.clear();
if( ModelInUse("MSSM63atQ") || ModelInUse("MSSM63atMGUT")
|| ModelInUse("MSSM63atQ_mA") || ModelInUse("MSSM63atMGUT_mA") )
{
result = Dep::MSSM_spectrum->getSLHAea(1);
}
else if (ModelInUse("ColliderBit_SLHA_file_model") || ModelInUse("ColliderBit_SLHA_scan_model"))
{
result = Dep::SLHAFileNameAndContent->second;
}
else
{
// This can only happen if the ALLOW_MODELS list in SUSY.hpp has been changed
// without also changing this function
std::stringstream errmsg_ss;
errmsg_ss << "Unknown model! And that makes it a bit hard to return an SLHA1 spectrum... "
<< "Please expand the function getSLHA1Spectrum if you want to use it with for new models.!";
ColliderBit_error().raise(LOCAL_INFO, errmsg_ss.str());
}
if(write_summary_to_log)
{
std::stringstream SLHA_log_output;
SLHA_log_output << "getSLHA1Spectrum:\n" << result.str() << "\n";
logger() << SLHA_log_output.str() << EOM;
}
}
// SLHA2
void getSLHA2Spectrum(SLHAstruct& result)
{
using namespace Pipes::getSLHA2Spectrum;
static const bool write_summary_to_log = runOptions->getValueOrDef<bool>(false, "write_summary_to_log");
result.clear();
if( ModelInUse("MSSM63atQ") || ModelInUse("MSSM63atMGUT")
|| ModelInUse("MSSM63atQ_mA") || ModelInUse("MSSM63atMGUT_mA") )
{
result = Dep::MSSM_spectrum->getSLHAea(2);
}
else if (ModelInUse("ColliderBit_SLHA_file_model") || ModelInUse("ColliderBit_SLHA_scan_model"))
{
result = Dep::SLHAFileNameAndContent->second;
}
else
{
// This can only happen if the ALLOW_MODELS list in SUSY.hpp has been changed
// without also changing this function
std::stringstream errmsg_ss;
errmsg_ss << "Unknown model! And that makes it a bit hard to return an SLHA1 spectrum... "
<< "Please expand the function getSLHA2Spectrum if you want to use it with for new models.!";
ColliderBit_error().raise(LOCAL_INFO, errmsg_ss.str());
}
if(write_summary_to_log)
{
std::stringstream SLHA_log_output;
SLHA_log_output << "getSLHA2Spectrum:\n" << result.str() << "\n";
logger() << SLHA_log_output.str() << EOM;
}
}
// Advanced mass-cuts to aid SUSY scans
void calc_susy_spectrum_scan_guide(double& result)
{
using namespace Pipes::calc_susy_spectrum_scan_guide;
bool discard_point = false;
result = 0.0;
// Get masses
mass_es_pseudonyms psn = *(Dep::SLHA_pseudonyms);
const Spectrum& spec = *Dep::MSSM_spectrum;
const double m_N1_signed = spec.get(Par::Pole_Mass,"~chi0_1");
const double m_N1 = abs(m_N1_signed);
// const double m_C1_signed = spec.get(Par::Pole_Mass,"~chi+_1");
// const double m_C1 = abs(m_C1_signed);
const double m_st1 = spec.get(Par::Pole_Mass, psn.ist1);
// Define cuts
if (m_N1 < 250. && m_st1 < 750.) discard_point = true;
if (m_N1 > 600.) discard_point = true;
if (m_st1 > 1100.) discard_point = true;
// Discard point?
if (discard_point) invalid_point().raise("Point discarded by susy_spectrum_scan_guide.");
}
}
}
| 35.374172 | 219 | 0.642048 | [
"object",
"vector",
"model"
] |
1402b9d7171c62a525673287bdefff7b4598eb25 | 10,911 | cpp | C++ | src/sv_simulator/SVsim.cpp | hsinnan75/Kart-SV | ddd092794fd7f751a436ede2f4d6211e02d2e4ce | [
"MIT"
] | 35 | 2019-09-27T14:29:22.000Z | 2022-03-27T20:02:08.000Z | src/sv_simulator/SVsim.cpp | hsinnan75/Kart-SV | ddd092794fd7f751a436ede2f4d6211e02d2e4ce | [
"MIT"
] | 71 | 2019-09-27T14:19:56.000Z | 2022-03-31T09:22:25.000Z | src/sv_simulator/SVsim.cpp | hsinnan75/Kart-SV | ddd092794fd7f751a436ede2f4d6211e02d2e4ce | [
"MIT"
] | 5 | 2018-09-04T11:51:35.000Z | 2020-01-07T05:26:45.000Z | #include <iostream>
#include <fstream>
#include <sstream>
#include <cstdlib>
#include <cstdio>
#include <ctype.h>
#include <cstring>
#include <cmath>
#include <ctime>
#include <map>
#include <vector>
#include <algorithm>
#define DOM 1000000
#define MutationBlock 3000
#define SNP_rate 3000 // SNPs # per 1M base
#define sIND_rate 200 // small indels # per 1M base (1~10bp)
#define lIND_rate 50 // large indels # per 1M base (11~50bp)
#define TraLoc_rate 1 // 2 translocation # per 1M base
#define Inv_rate 1 //1 // inversion # per 1M base
#define CNV_rate 1 //1 // CNV # per 1M base (1000bp)
using namespace std;
typedef struct
{
int gPos;
int mtype;
string ori_seq;
string mut_seq;
} SV_t;
FILE *vcf_fd, *mut_fd, *info_fd;
int iSNP, isIND, ilIND, iTraLoc, iInv, iCNV;
static const char ReverseMap[255] =
{
'\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', /* 0 - 9 */
'\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', /* 10 - 19 */
'\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', /* 20 - 29 */
'\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', /* 30 - 39 */
'\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', /* 40 - 49 */
'\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', /* 50 - 59 */
'\0', '\0', '\0', '\0', '\0', 'T', '\0', 'G', '\0', '\0', /* 60 - 69 */
'\0', 'C', '\0', '\0', '\0', '\0', '\0', '\0', 'N', '\0', /* 70 - 79 */
'\0', '\0', '\0', '\0', 'A', 'A', '\0', '\0', '\0', '\0', /* 80 - 89 */
'\0', '\0', '\0', '\0', '\0', '\0', '\0', 'T', '\0', 'G', /* 90 - 99 */
'\0', '\0', '\0', 'C', '\0', '\0', '\0', '\0', '\0', '\0', /* 100 - 109 */
'N', '\0', '\0', '\0', '\0', '\0', 'A', 'A', '\0', '\0', /* 110 - 119 */
'\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', /* 120 - 129 */
'\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', /* 130 - 139 */
'\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', /* 140 - 149 */
'\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', /* 150 - 159 */
'\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', /* 160 - 169 */
'\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', /* 170 - 179 */
'\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', /* 180 - 189 */
'\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', /* 190 - 199 */
'\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', /* 200 - 209 */
'\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', /* 210 - 219 */
'\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', /* 220 - 229 */
'\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', /* 230 - 239 */
'\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', /* 240 - 249 */
'\0', '\0', '\0', '\0', '\0' /* 250 - 254 */
};
int myrandom(int num)
{
if (num == 0 || num == 1)
return 0;
else
return (int)(rand() >> 1) % num;
}
bool CheckSeq(int gPos, int mLen, string& seq)
{
bool bRet = true;
for (int i = 0; i < mLen; gPos++, i++)
{
if (seq[gPos] == 'N')
{
bRet = false;
break;
}
}
return bRet;
}
void GetComplementarySeq(int len, string& seq, string& rseq)
{
int i, j;
for (j = len - 1, i = 0; i < j; i++, j--)
{
rseq[i] = ReverseMap[(int)seq[j]];
rseq[j] = ReverseMap[(int)seq[i]];
}
if (i == j) rseq[i] = ReverseMap[(int)seq[i]];
}
string GenRandomInsertion(int len)
{
string str;
for (int i = 0; i < len; i++)
{
switch (myrandom(4))
{
case 0: str.push_back('A'); break;
case 1: str.push_back('C'); break;
case 2: str.push_back('G'); break;
case 3: str.push_back('T'); break;
}
}
return str;
}
void OutputMutantSeq(string chr, string ref_seq, map<int64_t, SV_t>& StrVarMap)
{
string mut_seq;
int gPos1, gPos2, chrLen, mutLen;
map<int64_t, SV_t>::iterator StrVarMapIter;
gPos1 = gPos2 = 0; chrLen = (int)ref_seq.length();
for (StrVarMapIter = StrVarMap.begin(); StrVarMapIter != StrVarMap.end(); StrVarMapIter++)
{
gPos2 = StrVarMapIter->second.gPos;
if (gPos2 > gPos1)
{
if (StrVarMapIter->second.mtype == 0) fprintf(vcf_fd, "%s %d . %s %s 30 PASS SVTYPE=SUBSTITUTE\n", chr.c_str(), StrVarMapIter->second.gPos + 1, (char*)StrVarMapIter->second.ori_seq.c_str(), (char*)StrVarMapIter->second.mut_seq.c_str());
else if (StrVarMapIter->second.mtype == 1 || StrVarMapIter->second.mtype == 2) fprintf(vcf_fd, "%s %d . %s %s 30 PASS SVTYPE=%s\n", chr.c_str(), StrVarMapIter->second.gPos + 1, (char*)StrVarMapIter->second.ori_seq.c_str(), (char*)StrVarMapIter->second.mut_seq.c_str(), StrVarMapIter->second.ori_seq.length() < StrVarMapIter->second.mut_seq.length() ? "INSERT" : "DELETE");
else if (StrVarMapIter->second.mtype == 3) fprintf(vcf_fd, "%s %d . %c <TRANSLOCATION> 30 PASS SVTYPE=BND\n", chr.c_str(), StrVarMapIter->second.gPos + 1, StrVarMapIter->second.ori_seq[0], (int)StrVarMapIter->second.mut_seq.length());
else if (StrVarMapIter->second.mtype == 4) fprintf(vcf_fd, "%s %d . %c <INV> 30 PASS size=%d;SVTYPE=INVERSION\n", chr.c_str(), StrVarMapIter->second.gPos + 1, StrVarMapIter->second.ori_seq[0], (int)StrVarMapIter->second.mut_seq.length());
else if (StrVarMapIter->second.mtype == 5) fprintf(vcf_fd, "%s %d . %dx %dx 30 PASS SVTYPE=CNV\n", chr.c_str(), StrVarMapIter->second.gPos + 1, 1, (int)StrVarMapIter->second.mut_seq.length() / (int)StrVarMapIter->second.ori_seq.length());
mut_seq.append(ref_seq.substr(gPos1, gPos2 - gPos1));
mut_seq.append(StrVarMapIter->second.mut_seq);
gPos1 = (gPos2 + (int)StrVarMapIter->second.ori_seq.length());
}
else
{
if (StrVarMapIter->second.mtype == 0) iSNP--;
else if (StrVarMapIter->second.mtype == 1) isIND--;
else if (StrVarMapIter->second.mtype == 2) ilIND--;
else if (StrVarMapIter->second.mtype == 3) iTraLoc--;
else if (StrVarMapIter->second.mtype == 4) iInv--;
else if (StrVarMapIter->second.mtype == 5) iCNV--;
}
}
if (gPos1 < chrLen) mut_seq.append(ref_seq.substr(gPos1, chrLen - gPos1));
mutLen = (int)mut_seq.length();
fprintf(stderr, "\tMutatnt (%s): len = %d (ori = %d)\n", chr.c_str(), mutLen, chrLen);
fprintf(mut_fd, ">%s_mut\n", chr.c_str());
for (gPos1 = 0; gPos1 < mutLen; gPos1 += 70) fprintf(mut_fd, "%s\n", mut_seq.substr(gPos1, 70).c_str());
}
void GenMutantSeq(string chr, string& ref_seq)
{
SV_t sv;
map<int64_t, SV_t> StrVarMap;
int i, ref_len, gPos, mPos, mLen, mType, Dup;
fprintf(stderr, "Generate mutant sequence\n");
ref_len = (int)ref_seq.length();
for (gPos = 0; gPos < ref_len; gPos++)
{
if (gPos % 10000 == 0) fprintf(stderr, "\rScan %d / %d", gPos, ref_len);
if (ref_seq[gPos] == 'N') continue;
if (myrandom(DOM) < SNP_rate)
{
sv.mtype = 0; sv.gPos = gPos; sv.ori_seq = ref_seq.substr(gPos, 1);
switch (ref_seq[gPos])
{
case 'A': sv.mut_seq = "T"; break;
case 'C': sv.mut_seq = "G"; break;
case 'G': sv.mut_seq = "C"; break;
case 'T': sv.mut_seq = "A"; break;
}
iSNP++; StrVarMap.insert(make_pair(sv.gPos, sv)); gPos+=30;
}
else if (myrandom(DOM) < sIND_rate)
{
sv.mtype = 1; sv.gPos = gPos; mLen = 1; while (mLen < 10 && myrandom(10) == 0) mLen++;
if (myrandom(2)) // ins
{
sv.ori_seq = ref_seq.substr(gPos, 1);
sv.mut_seq = sv.ori_seq + GenRandomInsertion(mLen);
}
else // del
{
sv.mut_seq = ref_seq.substr(gPos, 1);
sv.ori_seq = ref_seq.substr(gPos, mLen + 1);
gPos += mLen;
}
isIND++; StrVarMap.insert(make_pair(sv.gPos, sv)); gPos+=30;
}
else if (myrandom(DOM) < lIND_rate)
{
sv.mtype = 2; sv.gPos = gPos; mLen = 11; while (mLen < 30 && myrandom(10) < 7) mLen++;
if (myrandom(2)) // ins
{
sv.ori_seq = ref_seq.substr(gPos, 1);
sv.mut_seq = sv.ori_seq + GenRandomInsertion(mLen);
}
else // del
{
sv.mut_seq = ref_seq.substr(gPos, 1);
sv.ori_seq = ref_seq.substr(gPos, mLen + 1);
gPos += mLen;
}
ilIND++; StrVarMap.insert(make_pair(sv.gPos, sv)); gPos+=30;
}
else if (myrandom(DOM) < Inv_rate)
{
sv.mtype = 4; sv.gPos = gPos; mLen = myrandom(1000) + 1000;
if (gPos + mLen < ref_len)
{
sv.ori_seq = ref_seq.substr(gPos, mLen);
sv.mut_seq.resize(mLen); GetComplementarySeq(mLen, sv.ori_seq, sv.mut_seq);
iInv++; StrVarMap.insert(make_pair(sv.gPos, sv));
gPos += mLen;
}
}
else if (myrandom(DOM) < TraLoc_rate && myrandom(2))
{
sv.mtype = 3; mLen = myrandom(1000) + 1000; mPos = gPos + myrandom(1000) + 10000;
if ((mPos + mLen) < ref_len)
{
sv.gPos = gPos;
sv.ori_seq = ref_seq.substr(gPos, mLen);
sv.mut_seq = ref_seq.substr(mPos, mLen);
StrVarMap.insert(make_pair(sv.gPos, sv));
sv.gPos = mPos;
sv.ori_seq = ref_seq.substr(mPos, mLen);
sv.mut_seq = ref_seq.substr(gPos, mLen);
StrVarMap.insert(make_pair(sv.gPos, sv));
iTraLoc += 2; gPos += mLen;
for (i = 0; i < mLen; i++, mPos++) ref_seq[mPos] = 'N';
}
}
else if (myrandom(DOM) < CNV_rate)
{
sv.mtype = 5; sv.gPos = gPos; mLen = myrandom(1000) + 300;
if (gPos + mLen < ref_len && CheckSeq(gPos, mLen, ref_seq))
{
Dup = myrandom(100) % 8 + 2;
sv.ori_seq = ref_seq.substr(gPos, mLen); sv.mut_seq = "";
for (; Dup > 0; Dup--) sv.mut_seq += sv.ori_seq;
iCNV++; StrVarMap.insert(make_pair(sv.gPos, sv));
gPos += mLen;
}
}
}
fprintf(stderr, "\rScan %d / %d\n", gPos, ref_len);
OutputMutantSeq(chr, ref_seq, StrVarMap);
}
int main(int argc, char* argv[])
{
fstream file;
string fname, chr, seq, str;
if (argc != 2)
{
fprintf(stderr, "Usage: %s ref_seq\n", argv[0]);
exit(0);
}
srand((unsigned int)time(NULL));
iSNP = isIND = ilIND = iTraLoc = iInv = iCNV = 0;
fname = ((string)argv[1]).substr(0, ((string)argv[1]).find_last_of('.')) + ".vcf";
vcf_fd = fopen((char*)fname.c_str(), "w");
fprintf(vcf_fd, "##maf version=1\n");
fname = ((string)argv[1]).substr(0, ((string)argv[1]).find_last_of('.')) + ".mut";
mut_fd = fopen((char*)fname.c_str(), "w");
fname = ((string)argv[1]).substr(0, ((string)argv[1]).find_last_of('.')) + ".info";
info_fd = fopen((char*)fname.c_str(), "w");
file.open(argv[1], ios_base::in);
while (!file.eof())
{
getline(file, str); if (str == "") break;
if (str[0] == '>')
{
if (seq != "") GenMutantSeq(chr, seq);
chr = str.substr(1); seq = "";
}
else seq.append(str);
}
if (seq != "") GenMutantSeq(chr, seq);
fprintf(stderr, "SNP=%d, sIND=%d, lIND=%d, Translocation=%d, Inversion=%d, CNV=%d\n", iSNP, isIND, ilIND, iTraLoc, iInv, iCNV);
fprintf(info_fd, "SNP=%d, sIND=%d, lIND=%d, Translocation=%d, Inversion=%d, CNV=%d\n", iSNP, isIND, ilIND, iTraLoc, iInv, iCNV);
fclose(info_fd); fclose(vcf_fd); fclose(mut_fd);
return 0;
}
| 35.891447 | 376 | 0.53469 | [
"vector"
] |
14039fb5a3ccf5835eb60282abb4401e585467b3 | 12,021 | cc | C++ | tensorflow/core/kernels/spacetobatch_op.cc | abhaikollara/tensorflow | 4f96df3659696990cb34d0ad07dc67843c4225a9 | [
"Apache-2.0"
] | 848 | 2019-12-03T00:16:17.000Z | 2022-03-31T22:53:17.000Z | tensorflow/core/kernels/spacetobatch_op.cc | sseung0703/tensorflow | be084bd7a4dd241eb781fc704f57bcacc5c9b6dd | [
"Apache-2.0"
] | 1,056 | 2019-12-15T01:20:31.000Z | 2022-02-10T02:06:28.000Z | tensorflow/core/kernels/spacetobatch_op.cc | sseung0703/tensorflow | be084bd7a4dd241eb781fc704f57bcacc5c9b6dd | [
"Apache-2.0"
] | 506 | 2019-12-03T00:46:26.000Z | 2022-03-30T10:34:56.000Z | /* Copyright 2016 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.
==============================================================================*/
// See docs in ../ops/array_ops.cc.
#define EIGEN_USE_THREADS
#include <memory>
#include <string>
#include <utility>
#include "tensorflow/core/kernels/spacetobatch_functor.h"
#include "third_party/eigen3/unsupported/Eigen/CXX11/Tensor"
#include "tensorflow/core/framework/op.h"
#include "tensorflow/core/framework/op_kernel.h"
#include "tensorflow/core/framework/register_types.h"
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/framework/tensor_shape.h"
#include "tensorflow/core/framework/tensor_types.h"
#include "tensorflow/core/framework/types.h"
#include "tensorflow/core/platform/logging.h"
#include "tensorflow/core/platform/types.h"
namespace tensorflow {
typedef Eigen::ThreadPoolDevice CPUDevice;
typedef Eigen::GpuDevice GPUDevice;
namespace {
template <typename Device, typename T>
Status SpaceToBatchOpCompute(OpKernelContext* context,
const Tensor& orig_input_tensor,
const Tensor& orig_block_shape,
const Tensor& orig_paddings) {
const int input_dims = orig_input_tensor.dims();
if (!TensorShapeUtils::IsVector(orig_block_shape.shape())) {
return errors::InvalidArgument("block_shape rank should be 1 instead of ",
orig_block_shape.dims());
}
const int block_dims = orig_block_shape.dim_size(0);
if (orig_input_tensor.dims() < 1 + block_dims) {
return errors::InvalidArgument("input rank should be >= ", 1 + block_dims,
" instead of ", orig_input_tensor.dims());
}
if (!(TensorShapeUtils::IsMatrix(orig_paddings.shape()) &&
block_dims == orig_paddings.dim_size(0) &&
2 == orig_paddings.dim_size(1))) {
return errors::InvalidArgument("paddings should have shape [", block_dims,
", 2] instead of ",
orig_paddings.shape().DebugString());
}
// To avoid out-of-bounds access in the case that the block_shape and/or
// paddings tensors are concurrently modified, we must copy the values.
gtl::InlinedVector<int64, 4> block_shape;
gtl::InlinedVector<int64, 8> paddings;
internal::spacetobatch::SubtleMustCopyFlat(orig_block_shape, &block_shape);
internal::spacetobatch::SubtleMustCopyFlat(orig_paddings, &paddings);
// Determine the length of the prefix of block dims that can be combined
// into the batch dimension due to having no padding and block_shape=1.
int removed_prefix_block_dims = 0;
for (; removed_prefix_block_dims < block_dims; ++removed_prefix_block_dims) {
const int dim = removed_prefix_block_dims;
if (paddings[2 * dim] != 0 || paddings[2 * dim + 1] != 0 ||
block_shape[dim] != 1) {
break;
}
}
// Determine the length of the suffix of block dims that can be combined
// into the depth dimension due to having no padding and block_shape=1.
int removed_suffix_block_dims = 0;
for (; removed_suffix_block_dims < block_dims - removed_prefix_block_dims;
++removed_suffix_block_dims) {
const int dim = block_dims - 1 - removed_suffix_block_dims;
if (paddings[dim * 2] != 0 || paddings[dim * 2 + 1] != 0 ||
block_shape[dim] != 1) {
break;
}
}
// Compute the product of the block_shape values.
int64 block_shape_product = 1;
for (int block_dim = 0; block_dim < block_dims; ++block_dim) {
block_shape_product *= block_shape[block_dim];
}
if (block_shape_product <= 0) {
return errors::InvalidArgument(
"Product of block sizes must be positive, got ", block_shape_product);
}
const int internal_block_dims =
block_dims - removed_prefix_block_dims - removed_suffix_block_dims;
if (internal_block_dims > kMaxSpaceToBatchBlockDims) {
return errors::InvalidArgument(
"Maximum number of non-combined block dimensions is ",
internal_block_dims, " but must not exceed ",
kMaxSpaceToBatchBlockDims);
}
if (internal_block_dims == 0) {
context->set_output(0, orig_input_tensor);
return Status::OK();
}
// For the purpose of computing the result, the input will be treated as
// having this shape, of rank 2 + internal_block_dims.
TensorShape internal_input_shape;
// For the purpose of computing the result, the output will be treated as
// having this shape, of rank 2 + internal_block_dims.
TensorShape internal_output_shape;
// The actual output shape exposed to callers.
TensorShape external_output_shape;
external_output_shape.AddDim(orig_input_tensor.dim_size(0) *
block_shape_product);
int64 input_batch_size = orig_input_tensor.dim_size(0);
for (int block_dim = 0; block_dim < removed_prefix_block_dims; ++block_dim) {
const int64 size = orig_input_tensor.dim_size(block_dim + 1);
input_batch_size *= size;
external_output_shape.AddDim(size);
}
internal_input_shape.AddDim(input_batch_size);
internal_output_shape.AddDim(input_batch_size * block_shape_product);
for (int block_dim = removed_prefix_block_dims;
block_dim < block_dims - removed_suffix_block_dims; ++block_dim) {
const int64 pad_start = paddings[2 * block_dim],
pad_end = paddings[2 * block_dim + 1];
if (pad_start < 0 || pad_end < 0) {
return errors::InvalidArgument("Paddings must be non-negative");
}
const int64 input_size = orig_input_tensor.dim_size(block_dim + 1);
const int64 block_shape_value = block_shape[block_dim];
const int64 padded_size = input_size + pad_start + pad_end;
if (padded_size % block_shape_value != 0) {
return errors::InvalidArgument("padded_shape[", block_dim,
"]=", padded_size,
" is not divisible by block_shape[",
block_dim, "]=", block_shape_value);
}
internal_input_shape.AddDim(input_size);
const int64 output_size = padded_size / block_shape_value;
internal_output_shape.AddDim(output_size);
external_output_shape.AddDim(output_size);
}
int64 depth = 1;
for (int dim = block_dims - removed_suffix_block_dims + 1; dim < input_dims;
++dim) {
const int64 size = orig_input_tensor.dim_size(dim);
external_output_shape.AddDim(size);
depth *= size;
}
internal_input_shape.AddDim(depth);
internal_output_shape.AddDim(depth);
// Allocate output tensor.
Tensor* output_tensor = nullptr;
TF_RETURN_IF_ERROR(
context->allocate_output(0, external_output_shape, &output_tensor));
const int64* internal_paddings = &paddings[2 * removed_prefix_block_dims];
const int64* internal_block_shape = &block_shape[removed_prefix_block_dims];
switch (internal_block_dims) {
#define TF_SPACETOBATCH_BLOCK_DIMS_CASE(NUM_BLOCK_DIMS) \
case NUM_BLOCK_DIMS: { \
TF_RETURN_IF_ERROR( \
functor::SpaceToBatchFunctor<Device, T, NUM_BLOCK_DIMS, false>()( \
context->eigen_device<Device>(), \
orig_input_tensor.shaped<T, NUM_BLOCK_DIMS + 2>( \
internal_input_shape.dim_sizes()), \
internal_block_shape, internal_paddings, \
output_tensor->shaped<T, NUM_BLOCK_DIMS + 2>( \
internal_output_shape.dim_sizes()))); \
} break; \
/**/
TF_SPACETOBATCH_FOR_EACH_NUM_BLOCK_DIMS(TF_SPACETOBATCH_BLOCK_DIMS_CASE)
#undef TF_SPACETOBATCH_BLOCK_DIMS_CASE
}
return Status::OK();
}
} // namespace
template <typename Device, typename T>
class SpaceToBatchNDOp : public OpKernel {
public:
explicit SpaceToBatchNDOp(OpKernelConstruction* context)
: OpKernel(context) {}
void Compute(OpKernelContext* context) override {
const Tensor& orig_input_tensor = context->input(0);
const Tensor& orig_block_shape = context->input(1);
const Tensor& orig_paddings = context->input(2);
OP_REQUIRES_OK(context, SpaceToBatchOpCompute<Device, T>(
context, orig_input_tensor, orig_block_shape,
orig_paddings));
}
};
template <typename Device, typename T>
class SpaceToBatchOp : public OpKernel {
public:
explicit SpaceToBatchOp(OpKernelConstruction* context) : OpKernel(context) {
OP_REQUIRES_OK(context, context->GetAttr("block_size", &block_size_));
OP_REQUIRES(
context, block_size_ > 1,
errors::InvalidArgument("Block size should be > 1: ", block_size_));
// We don't use context->allocate_persistent because the allocation must
// happen on the CPU regardless of Device.
block_shape_ = Tensor(tensorflow::DT_INT64, TensorShape({2}));
auto block_shape_vec = block_shape_.vec<int64>();
block_shape_vec(0) = block_size_;
block_shape_vec(1) = block_size_;
}
void Compute(OpKernelContext* context) override {
const Tensor& in0 = context->input(0);
const Tensor& in1 = context->input(1);
const int dims = in0.dims();
static const int kRequiredDims = 4;
OP_REQUIRES(context, kRequiredDims == dims,
errors::InvalidArgument("Input rank should be: ", kRequiredDims,
"instead of: ", dims));
OP_REQUIRES_OK(context, SpaceToBatchOpCompute<Device, T>(
context, in0, block_shape_, in1));
}
private:
int block_size_;
Tensor block_shape_;
};
#define REGISTER(T) \
REGISTER_KERNEL_BUILDER(Name("SpaceToBatchND") \
.Device(DEVICE_CPU) \
.TypeConstraint<T>("T") \
.HostMemory("block_shape") \
.HostMemory("paddings"), \
SpaceToBatchNDOp<CPUDevice, T>); \
REGISTER_KERNEL_BUILDER(Name("SpaceToBatch") \
.Device(DEVICE_CPU) \
.TypeConstraint<T>("T") \
.HostMemory("paddings"), \
SpaceToBatchOp<CPUDevice, T>);
TF_CALL_REAL_NUMBER_TYPES(REGISTER);
#undef REGISTER
#if GOOGLE_CUDA || TENSORFLOW_USE_ROCM
#define REGISTER(T) \
REGISTER_KERNEL_BUILDER(Name("SpaceToBatchND") \
.Device(DEVICE_GPU) \
.TypeConstraint<T>("T") \
.HostMemory("block_shape") \
.HostMemory("paddings"), \
SpaceToBatchNDOp<GPUDevice, T>); \
REGISTER_KERNEL_BUILDER(Name("SpaceToBatch") \
.Device(DEVICE_GPU) \
.TypeConstraint<T>("T") \
.HostMemory("paddings"), \
SpaceToBatchOp<GPUDevice, T>);
TF_CALL_GPU_NUMBER_TYPES(REGISTER);
#undef REGISTER
#endif // GOOGLE_CUDA || TENSORFLOW_USE_ROCM
} // end namespace tensorflow
| 41.167808 | 80 | 0.631894 | [
"shape"
] |
1406e736a8ea4a0e2f84ba63bfb0e93cb537bde5 | 4,952 | cpp | C++ | voxgraph/src/frontend/map_tracker/map_tracker.cpp | supernlogn/voxgraph | bd802b5aee54e68e28c94d71cc0fbd7bdda98bd6 | [
"BSD-2-Clause"
] | 361 | 2020-04-28T09:47:42.000Z | 2022-03-18T02:19:22.000Z | voxgraph/src/frontend/map_tracker/map_tracker.cpp | koide3/voxgraph | 61eccede46aacb3041451e715a3e6291620f213c | [
"BSD-2-Clause"
] | 35 | 2020-04-28T09:43:14.000Z | 2022-03-15T12:20:04.000Z | voxgraph/src/frontend/map_tracker/map_tracker.cpp | koide3/voxgraph | 61eccede46aacb3041451e715a3e6291620f213c | [
"BSD-2-Clause"
] | 56 | 2020-04-28T09:58:07.000Z | 2022-02-15T20:13:32.000Z | #include "voxgraph/frontend/map_tracker/map_tracker.h"
#include <limits>
#include <string>
#include <utility>
#include "voxgraph/tools/tf_helper.h"
namespace voxgraph {
MapTracker::MapTracker(VoxgraphSubmapCollection::ConstPtr submap_collection_ptr,
FrameNames frame_names, bool verbose)
: verbose_(verbose),
submap_collection_ptr_(submap_collection_ptr),
frame_names_(std::move(frame_names)),
tf_transformer_(),
odom_transformer_() {}
void MapTracker::subscribeToTopics(ros::NodeHandle nh,
const std::string& odometry_input_topic) {
if (!odometry_input_topic.empty()) {
ROS_INFO_STREAM("Using odometry from ROS topic: " << odometry_input_topic);
use_odom_from_tfs_ = false;
odom_transformer_.subscribeToTopic(nh, odometry_input_topic);
}
}
void MapTracker::advertiseTopics(ros::NodeHandle nh_private,
const std::string& odometry_output_topic) {}
bool MapTracker::updateToTime(const ros::Time& timestamp,
const std::string& sensor_frame_id) {
// Keep track of the timestamp that the MapTracker is currently at
current_timestamp_ = timestamp;
// Update the odometry
if (use_odom_from_tfs_) {
// Update the odometry estimate
if (!tf_transformer_.lookupTransform(frame_names_.input_odom_frame,
frame_names_.input_base_link_frame,
timestamp, &T_O_B_)) {
return false;
}
} else {
if (!odom_transformer_.lookupTransform(timestamp, &T_O_B_)) {
return false;
}
}
// Express the odometry pose in the frame of the current submap
T_S_B_ = initial_T_S_O_ * T_O_B_;
// Get the transformation from the pointcloud sensor to the robot's
// base link from TFs, unless it was already provided through ROS params
if (use_sensor_calibration_from_tfs_) {
// TODO(victorr): Implement option to provide a sensor_frame_id instead of
// taking the one from the message
// Strip leading slashes if needed to avoid TF errors
std::string tf_sensor_frame_id;
if (sensor_frame_id[0] == '/') {
tf_sensor_frame_id = sensor_frame_id.substr(1, sensor_frame_id.length());
} else {
tf_sensor_frame_id = sensor_frame_id;
}
// Lookup the transform
if (!tf_transformer_.lookupTransform(frame_names_.input_base_link_frame,
tf_sensor_frame_id, timestamp,
&T_B_C_)) {
return false;
}
}
// Signal that all transforms were successfully updated
return true;
}
void MapTracker::switchToNewSubmap(const Transformation& T_M_S_new) {
// Store the initial submap pose for visualization purposes
initial_T_M_S_ = T_M_S_new;
// Get the pose of the new submap in odom frame
Transformation T_O_S = VoxgraphSubmapCollection::gravityAlignPose(T_O_B_);
// Store the transform used to convert the odometry input into submap frame
initial_T_S_O_ = T_O_S.inverse();
// Update the current robot pose
// NOTE: This initial pose can differ from Identity, since the submap pose
// has zero pitch and roll whereas the robot pose is in 6DoF
T_S_B_ = initial_T_S_O_ * T_O_B_;
}
void MapTracker::publishTFs() {
TfHelper::publishTransform(submap_collection_ptr_->getActiveSubmapPose(),
frame_names_.output_mission_frame,
frame_names_.output_active_submap_frame, false,
current_timestamp_);
TfHelper::publishTransform(
initial_T_S_O_, frame_names_.output_active_submap_frame,
frame_names_.output_odom_frame, false, current_timestamp_);
if (frame_names_.input_odom_frame != frame_names_.output_odom_frame ||
frame_names_.input_base_link_frame !=
frame_names_.output_base_link_frame ||
!use_odom_from_tfs_) {
// Republish the odometry if the output frame names are different,
// or if the odom input is coming from a ROS topic
// (in which case it might not yet be in the TF tree)
TfHelper::publishTransform(T_O_B_, frame_names_.output_odom_frame,
frame_names_.output_base_link_frame, false,
current_timestamp_);
}
TfHelper::publishTransform(T_B_C_, frame_names_.output_base_link_frame,
frame_names_.output_sensor_frame, true,
current_timestamp_);
}
Transformation MapTracker::get_T_M_B() {
if (submap_collection_ptr_->empty()) {
// If no submap has been created yet, return the odometry pose
return T_O_B_;
} else {
return submap_collection_ptr_->getActiveSubmapPose() * T_S_B_;
}
}
void MapTracker::set_T_B_C(const Transformation& T_B_C) {
T_B_C_ = T_B_C;
use_sensor_calibration_from_tfs_ = false;
}
} // namespace voxgraph
| 37.233083 | 80 | 0.675283 | [
"transform"
] |
1406ed8a571794c39a48d24bc1e4748f3963f06e | 4,159 | cxx | C++ | sw/3rd_party/VTK-7.1.0/Common/DataModel/vtkPerlinNoise.cxx | esean/stl_voro_fill | c569a4019ff80afbf85482c7193711ea85a7cafb | [
"MIT"
] | 4 | 2019-05-30T01:52:12.000Z | 2021-09-29T21:12:13.000Z | sw/3rd_party/VTK-7.1.0/Common/DataModel/vtkPerlinNoise.cxx | esean/stl_voro_fill | c569a4019ff80afbf85482c7193711ea85a7cafb | [
"MIT"
] | null | null | null | sw/3rd_party/VTK-7.1.0/Common/DataModel/vtkPerlinNoise.cxx | esean/stl_voro_fill | c569a4019ff80afbf85482c7193711ea85a7cafb | [
"MIT"
] | 2 | 2019-08-30T23:36:13.000Z | 2019-11-08T16:52:01.000Z | /*=========================================================================
Program: Visualization Toolkit
Module: vtkPerlinNoise.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#include "vtkPerlinNoise.h"
#include "vtkObjectFactory.h"
#include <cmath>
#include <cassert>
vtkStandardNewMacro(vtkPerlinNoise);
// These functions are from Greg Ward's recursive implementation in
// Graphics Gems II. I've kept the names the same for instructional
// purposes, and only changed things where optimizations could be made
// or where correctness fixes were necessary.
static double hermite(double p0, double p1,
double r0, double r1, double t)
{
double tt = t*t;
return (p0*((2.0*t - 3.0)*tt + 1.0) +
p1*(-2.0*t + 3.0)*tt +
r0*((t-2.0)*t+1.0)*t +
r1*(t-1.0)*tt);
}
// assumes 32 bit ints, but so it seems does VTK
static double frand(unsigned int s)
{
s = (s<<13) ^ s;
s = (s*(s*s*15731 + 789221)+1376312589)&VTK_INT_MAX;
return 1.0 - double(s)/(VTK_INT_MAX/2 + 1);
}
static void rand3abcd(int x, int y, int z, double outv[4])
{
outv[0] = frand(67*x + 59*y + 71*z);
outv[1] = frand(73*x + 79*y + 83*z);
outv[2] = frand(89*x + 97*y + 101*z);
outv[3] = frand(103*x + 107*y + 109*z);
}
static void interpolate(double f[4], int i, int n,
int xlim[3][2], const double xarg[3])
{
double f0[4], f1[4];
if (n == 0)
{
rand3abcd(xlim[0][i&1], xlim[1][(i>>1) & 1], xlim[2][i>>2], f);
return;
}
n--;
assert((n>=0)&&(n<=2));
interpolate(f0, i, n, xlim, xarg);
interpolate(f1, i | (1<<n), n, xlim, xarg);
f[0] = (1.0 - xarg[n])*f0[0] + xarg[n]*f1[0];
f[1] = (1.0 - xarg[n])*f0[1] + xarg[n]*f1[1];
f[2] = (1.0 - xarg[n])*f0[2] + xarg[n]*f1[2];
f[3] = hermite(f0[3], f1[3], f0[n], f1[n], xarg[n]);
}
static void perlinNoise(double x[3], double noise[4])
{
double xarg[3];
int xlim[3][2];
xlim[0][0] = int(floor(x[0]));
xlim[1][0] = int(floor(x[1]));
xlim[2][0] = int(floor(x[2]));
xlim[0][1] = xlim[0][0] + 1;
xlim[1][1] = xlim[1][0] + 1;
xlim[2][1] = xlim[2][0] + 1;
xarg[0] = x[0] - xlim[0][0];
xarg[1] = x[1] - xlim[1][0];
xarg[2] = x[2] - xlim[2][0];
interpolate(noise, 0, 3, xlim, xarg);
}
vtkPerlinNoise::vtkPerlinNoise()
{
this->Frequency[0] = 1.0;
this->Frequency[1] = 1.0;
this->Frequency[2] = 1.0;
this->Phase[0] = 0.0;
this->Phase[1] = 0.0;
this->Phase[2] = 0.0;
this->Amplitude = 1.0;
}
double vtkPerlinNoise::EvaluateFunction(double x[3])
{
double xd[3];
double noise[4];
xd[0] = x[0]*this->Frequency[0] - this->Phase[0]*2.0;
xd[1] = x[1]*this->Frequency[1] - this->Phase[1]*2.0;
xd[2] = x[2]*this->Frequency[2] - this->Phase[2]*2.0;
perlinNoise(xd, noise);
return noise[3]*this->Amplitude;
}
// Evaluate PerlinNoise gradient.
void vtkPerlinNoise::EvaluateGradient(double* vtkNotUsed(x), // Was x[3]
double n[3])
{
// contrary to the paper, the vector computed as a byproduct of
// the Perlin Noise computation isn't a gradient; it's a tangent.
// Doing this right will take some work.
n[0] = 0.0;
n[1] = 0.0;
n[2] = 0.0;
}
void vtkPerlinNoise::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os,indent);
os << indent << "Amplitude: " << this->Amplitude << "\n";
os << indent << "Frequency: ("
<< this->Frequency[0] << ", "
<< this->Frequency[1] << ", "
<< this->Frequency[2] << ")\n";
os << indent << "Phase: ("
<< this->Phase[0] << ", "
<< this->Phase[1] << ", "
<< this->Phase[2] << ")\n";
}
| 27.912752 | 76 | 0.540995 | [
"vector"
] |
1407964579d67dc87f999d989a404aa0e34008ac | 2,520 | cpp | C++ | tests/test_eigen_serialization.cpp | UM-ARM-Lab/arc_utilities | e21bd5062983b25e61e33f832ec66b937540ba10 | [
"BSD-2-Clause"
] | 10 | 2017-01-09T14:37:14.000Z | 2022-03-16T08:02:08.000Z | tests/test_eigen_serialization.cpp | UM-ARM-Lab/arc_utilities | e21bd5062983b25e61e33f832ec66b937540ba10 | [
"BSD-2-Clause"
] | 62 | 2017-05-25T16:52:38.000Z | 2022-03-08T20:05:09.000Z | tests/test_eigen_serialization.cpp | UM-ARM-Lab/arc_utilities | e21bd5062983b25e61e33f832ec66b937540ba10 | [
"BSD-2-Clause"
] | 7 | 2017-08-04T13:06:17.000Z | 2022-03-16T08:02:11.000Z | #include <gtest/gtest.h>
#include "arc_utilities/serialization_eigen.hpp"
template <typename Scalar, int _Rows>
void testFloatVectors(const size_t num_tests, const ssize_t rows = -1) {
typedef Eigen::Matrix<Scalar, _Rows, 1> EigenType;
for (size_t idx = 0; idx < num_tests; ++idx) {
EigenType vec;
if (_Rows == Eigen::Dynamic) {
ASSERT_GT(rows, 0) << "Dynamically sized vector must have positive number of rows";
vec.resize(rows);
}
vec.setRandom();
// First, serialize
std::vector<uint8_t> buffer;
const size_t bytes_used = arc_utilities::SerializeEigen(vec, buffer);
// Then deserialze and compare
const auto deserialized = arc_utilities::DeserializeEigen<EigenType>(buffer, 0);
EXPECT_EQ(deserialized.second, bytes_used) << "Deserialized bytes does not match original bytes";
EXPECT_EQ(deserialized.first, vec) << "Deserialized value does not match original";
}
}
template <typename Scalar, int _Rows, int _Cols>
void testFloatMatrices(const size_t num_tests, const ssize_t rows = -1, const ssize_t cols = -1) {
typedef Eigen::Matrix<Scalar, _Rows, _Cols> EigenType;
for (size_t idx = 0; idx < num_tests; ++idx) {
EigenType matrix;
if (_Rows == Eigen::Dynamic || _Cols == Eigen::Dynamic) {
ASSERT_GT(rows, 0) << "Dynamically sized matrix must have positive number of rows";
matrix.resize(rows, cols);
}
matrix.setRandom();
// First, serialize
std::vector<uint8_t> buffer;
const size_t bytes_used = arc_utilities::SerializeEigen(matrix, buffer);
// Then deserialze and compare
const auto deserialized = arc_utilities::DeserializeEigen<EigenType>(buffer, 0);
EXPECT_EQ(deserialized.second, bytes_used) << "Deserialized bytes does not match original bytes";
EXPECT_EQ(deserialized.first, matrix) << "Deserialized value does not match original";
}
}
TEST(EigenSerialization, Vectors_have_same_value_after_serialize_and_deserialize) {
testFloatVectors<double, 3>(10);
testFloatVectors<double, 6>(10);
testFloatVectors<double, 7>(10);
testFloatVectors<double, Eigen::Dynamic>(10, 20);
}
TEST(EigenSerialization, Matrices_have_same_value_after_serialize_and_deserialize) {
testFloatMatrices<double, Eigen::Dynamic, Eigen::Dynamic>(10, 40, 50);
testFloatMatrices<double, 3, Eigen::Dynamic>(10, 3, 50);
testFloatMatrices<float, 3, Eigen::Dynamic>(10, 3, 50);
}
GTEST_API_ int main(int argc, char **argv) {
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
| 36 | 101 | 0.719048 | [
"vector"
] |
1409a29066ab46eb5635f818947a225e65c66ed3 | 1,280 | cpp | C++ | Codingame/CPP/SinglePlayer/Medium/Conway Sequence.cpp | MoonAntonio/codingame | 4efdd8176163eb4fc5e246a9662a8c42bc0e8647 | [
"Unlicense"
] | null | null | null | Codingame/CPP/SinglePlayer/Medium/Conway Sequence.cpp | MoonAntonio/codingame | 4efdd8176163eb4fc5e246a9662a8c42bc0e8647 | [
"Unlicense"
] | null | null | null | Codingame/CPP/SinglePlayer/Medium/Conway Sequence.cpp | MoonAntonio/codingame | 4efdd8176163eb4fc5e246a9662a8c42bc0e8647 | [
"Unlicense"
] | null | null | null | #include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <cassert>
using namespace std;
/**
* Auto-generated code below aims at helping you parse
* the standard input according to the problem statement.
**/
int main()
{
int R;
cin >> R; cin.ignore();
int L;
cin >> L; cin.ignore();
vector<vector<int>> lines(2, vector<int>(1, R));
for (int l = 2; l <= L; ++l)
{
assert(!lines[l-1].empty());
int last = numeric_limits<int>::max();
vector<pair<int, int>> count;
for (int i = 0; i < lines[l-1].size(); ++i)
{
if (lines[l-1][i] == last)
{
count.back().second++;
}
else
{
last = lines[l-1][i];
count.push_back({lines[l-1][i], 1});
}
}
lines.push_back({});
for (int i = 0; i < count.size(); ++i)
{
lines[l].push_back(count[i].second);
lines[l].push_back(count[i].first);
}
}
for (int i = 0; i < lines.back().size(); ++i)
{
if (i+1 == lines.back().size())
cout << lines.back()[i] << endl;
else
cout << lines.back()[i] << " ";
}
}
| 23.272727 | 57 | 0.451563 | [
"vector"
] |
140e4c63830204cf04746d9ed9a552044ee820b1 | 4,084 | cpp | C++ | src/qt/qtwebkit/Source/WebKit2/WebProcess/Geolocation/WebGeolocationManager.cpp | viewdy/phantomjs | eddb0db1d253fd0c546060a4555554c8ee08c13c | [
"BSD-3-Clause"
] | 1 | 2015-05-27T13:52:20.000Z | 2015-05-27T13:52:20.000Z | src/qt/qtwebkit/Source/WebKit2/WebProcess/Geolocation/WebGeolocationManager.cpp | mrampersad/phantomjs | dca6f77a36699eb4e1c46f7600cca618f01b0ac3 | [
"BSD-3-Clause"
] | null | null | null | src/qt/qtwebkit/Source/WebKit2/WebProcess/Geolocation/WebGeolocationManager.cpp | mrampersad/phantomjs | dca6f77a36699eb4e1c46f7600cca618f01b0ac3 | [
"BSD-3-Clause"
] | 1 | 2022-02-18T10:41:38.000Z | 2022-02-18T10:41:38.000Z | /*
* Copyright (C) 2011, 2012, 2013 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. AND ITS 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 APPLE INC. OR ITS 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 "config.h"
#include "WebGeolocationManager.h"
#include "WebGeolocationManagerMessages.h"
#include "WebGeolocationManagerProxyMessages.h"
#include "WebPage.h"
#include "WebProcess.h"
#include <WebCore/Geolocation.h>
#include <WebCore/GeolocationController.h>
#include <WebCore/GeolocationError.h>
#include <WebCore/GeolocationPosition.h>
#include <WebCore/Page.h>
using namespace WebCore;
namespace WebKit {
const char* WebGeolocationManager::supplementName()
{
return "WebGeolocationManager";
}
WebGeolocationManager::WebGeolocationManager(WebProcess* process)
: m_process(process)
{
m_process->addMessageReceiver(Messages::WebGeolocationManager::messageReceiverName(), this);
}
WebGeolocationManager::~WebGeolocationManager()
{
}
void WebGeolocationManager::registerWebPage(WebPage* page)
{
bool wasEmpty = m_pageSet.isEmpty();
m_pageSet.add(page);
if (wasEmpty)
m_process->parentProcessConnection()->send(Messages::WebGeolocationManagerProxy::StartUpdating(), 0);
}
void WebGeolocationManager::unregisterWebPage(WebPage* page)
{
m_pageSet.remove(page);
if (m_pageSet.isEmpty())
m_process->parentProcessConnection()->send(Messages::WebGeolocationManagerProxy::StopUpdating(), 0);
}
void WebGeolocationManager::didChangePosition(const WebGeolocationPosition::Data& data)
{
#if ENABLE(GEOLOCATION)
RefPtr<GeolocationPosition> position = GeolocationPosition::create(data.timestamp, data.latitude, data.longitude, data.accuracy, data.canProvideAltitude, data.altitude, data.canProvideAltitudeAccuracy, data.altitudeAccuracy, data.canProvideHeading, data.heading, data.canProvideSpeed, data.speed);
Vector<RefPtr<WebPage> > webPageCopy;
copyToVector(m_pageSet, webPageCopy);
for (size_t i = 0; i < webPageCopy.size(); ++i) {
WebPage* page = webPageCopy[i].get();
if (page->corePage())
GeolocationController::from(page->corePage())->positionChanged(position.get());
}
#else
UNUSED_PARAM(data);
#endif // ENABLE(GEOLOCATION)
}
void WebGeolocationManager::didFailToDeterminePosition(const String& errorMessage)
{
#if ENABLE(GEOLOCATION)
// FIXME: Add localized error string.
RefPtr<GeolocationError> error = GeolocationError::create(GeolocationError::PositionUnavailable, errorMessage);
Vector<RefPtr<WebPage> > webPageCopy;
copyToVector(m_pageSet, webPageCopy);
for (size_t i = 0; i < webPageCopy.size(); ++i) {
WebPage* page = webPageCopy[i].get();
if (page->corePage())
GeolocationController::from(page->corePage())->errorOccurred(error.get());
}
#else
UNUSED_PARAM(errorMessage);
#endif // ENABLE(GEOLOCATION)
}
} // namespace WebKit
| 36.464286 | 301 | 0.75 | [
"vector"
] |
140ea5a91472ec0c7e1e64b665339ff9df4207f8 | 11,261 | cc | C++ | tests/ut/cpp/dataset/c_api_dataset_places365_test.cc | mindspore-ai/mindspore | a9fbb25530a2874166ff0045ddcdfc73207bf5eb | [
"Apache-2.0"
] | 3,200 | 2020-02-17T12:45:41.000Z | 2022-03-31T20:21:16.000Z | tests/ut/cpp/dataset/c_api_dataset_places365_test.cc | mindspore-ai/mindspore | a9fbb25530a2874166ff0045ddcdfc73207bf5eb | [
"Apache-2.0"
] | 176 | 2020-02-12T02:52:11.000Z | 2022-03-28T22:15:55.000Z | tests/ut/cpp/dataset/c_api_dataset_places365_test.cc | mindspore-ai/mindspore | a9fbb25530a2874166ff0045ddcdfc73207bf5eb | [
"Apache-2.0"
] | 621 | 2020-03-09T01:31:41.000Z | 2022-03-30T03:43:19.000Z | /**
* Copyright 2021 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 "common/common.h"
#include "minddata/dataset/core/tensor.h"
#include "minddata/dataset/include/dataset/datasets.h"
using namespace mindspore::dataset;
using mindspore::dataset::DataType;
using mindspore::dataset::Tensor;
using mindspore::dataset::TensorShape;
class MindDataTestPipeline : public UT::DatasetOpTesting {
protected:
};
/// Feature: Places365TrainStandardDataset.
/// Description: test basic usage of Places365TrainStandardDataset.
/// Expectation: get correct number of data.
TEST_F(MindDataTestPipeline, TestPlaces365TrainStandardDataset) {
MS_LOG(INFO) << "Doing MindDataTestPipeline-TestPlaces365TrainStandardDataset.";
// Create a Places365 Train Dataset.
std::string folder_path = datasets_root_path_ + "/testPlaces365Data";
std::shared_ptr<Dataset> ds =
Places365(folder_path, "train-standard", true, true, std::make_shared<RandomSampler>(false, 4));
EXPECT_NE(ds, nullptr);
// Create an iterator over the result of the above dataset.
// This will trigger the creation of the Execution Tree and launch it.
std::shared_ptr<Iterator> iter = ds->CreateIterator();
EXPECT_NE(iter, nullptr);
// Iterate the dataset and get each row.
std::unordered_map<std::string, mindspore::MSTensor> row;
ASSERT_OK(iter->GetNextRow(&row));
EXPECT_NE(row.find("image"), row.end());
EXPECT_NE(row.find("label"), row.end());
uint64_t i = 0;
while (row.size() != 0) {
i++;
auto image = row["image"];
MS_LOG(INFO) << "Tensor image shape: " << image.Shape();
ASSERT_OK(iter->GetNextRow(&row));
}
EXPECT_EQ(i, 4);
// Manually terminate the pipeline.
iter->Stop();
}
/// Feature: Places365TrainChallengeDataset.
/// Description: test basic usage of Places365TrainChallengeDataset.
/// Expectation: get correct number of data.
TEST_F(MindDataTestPipeline, TestPlaces365TrainChallengeDataset) {
MS_LOG(INFO) << "Doing MindDataTestPipeline-TestPlaces365TrainChallengeDataset.";
// Create a Places365 Train Dataset.
std::string folder_path = datasets_root_path_ + "/testPlaces365Data";
std::shared_ptr<Dataset> ds =
Places365(folder_path, "train-challenge", false, true, std::make_shared<RandomSampler>(false, 4));
EXPECT_NE(ds, nullptr);
// Create an iterator over the result of the above dataset.
// This will trigger the creation of the Execution Tree and launch it.
std::shared_ptr<Iterator> iter = ds->CreateIterator();
EXPECT_NE(iter, nullptr);
// Iterate the dataset and get each row.
std::unordered_map<std::string, mindspore::MSTensor> row;
ASSERT_OK(iter->GetNextRow(&row));
EXPECT_NE(row.find("image"), row.end());
EXPECT_NE(row.find("label"), row.end());
uint64_t i = 0;
while (row.size() != 0) {
i++;
auto image = row["image"];
MS_LOG(INFO) << "Tensor image shape: " << image.Shape();
ASSERT_OK(iter->GetNextRow(&row));
}
EXPECT_EQ(i, 4);
// Manually terminate the pipeline.
iter->Stop();
}
/// Feature: Places365ValDataset.
/// Description: test basic usage of Places365ValDataset.
/// Expectation: get correct number of data.
TEST_F(MindDataTestPipeline, TestPlaces365ValDataset) {
MS_LOG(INFO) << "Doing MindDataTestPipeline-TestPlaces365ValDataset.";
// Create a Places365 Test Dataset.
std::string folder_path = datasets_root_path_ + "/testPlaces365Data";
std::shared_ptr<Dataset> ds = Places365(folder_path, "val", true, true, std::make_shared<RandomSampler>(false, 4));
EXPECT_NE(ds, nullptr);
// Create an iterator over the result of the above dataset.
// This will trigger the creation of the Execution Tree and launch it.
std::shared_ptr<Iterator> iter = ds->CreateIterator();
EXPECT_NE(iter, nullptr);
// Iterate the dataset and get each row.
std::unordered_map<std::string, mindspore::MSTensor> row;
ASSERT_OK(iter->GetNextRow(&row));
EXPECT_NE(row.find("image"), row.end());
EXPECT_NE(row.find("label"), row.end());
uint64_t i = 0;
while (row.size() != 0) {
i++;
auto image = row["image"];
MS_LOG(INFO) << "Tensor image shape: " << image.Shape();
ASSERT_OK(iter->GetNextRow(&row));
}
EXPECT_EQ(i, 4);
// Manually terminate the pipeline.
iter->Stop();
}
/// Feature: Places365TrainDatasetWithPipeline.
/// Description: test usage of Places365TrainDataset pith pipeline.
/// Expectation: get correct number of data.
TEST_F(MindDataTestPipeline, TestPlaces365TrainDatasetWithPipeline) {
MS_LOG(INFO) << "Doing MindDataTestPipeline-TestPlaces365TrainDatasetWithPipeline.";
// Create two Places365 Train Dataset.
std::string folder_path = datasets_root_path_ + "/testPlaces365Data";
std::shared_ptr<Dataset> ds1 =
Places365(folder_path, "train-standard", true, true, std::make_shared<RandomSampler>(false, 4));
std::shared_ptr<Dataset> ds2 =
Places365(folder_path, "train-standard", true, true, std::make_shared<RandomSampler>(false, 4));
EXPECT_NE(ds1, nullptr);
EXPECT_NE(ds2, nullptr);
// Create two Repeat operation on ds.
int32_t repeat_num = 2;
ds1 = ds1->Repeat(repeat_num);
EXPECT_NE(ds1, nullptr);
repeat_num = 2;
ds2 = ds2->Repeat(repeat_num);
EXPECT_NE(ds2, nullptr);
// Create two Project operation on ds.
std::vector<std::string> column_project = {"image", "label"};
ds1 = ds1->Project(column_project);
EXPECT_NE(ds1, nullptr);
ds2 = ds2->Project(column_project);
EXPECT_NE(ds2, nullptr);
// Create a Concat operation on the ds.
ds1 = ds1->Concat({ds2});
EXPECT_NE(ds1, nullptr);
// Create an iterator over the result of the above dataset.
// This will trigger the creation of the Execution Tree and launch it.
std::shared_ptr<Iterator> iter = ds1->CreateIterator();
EXPECT_NE(iter, nullptr);
// Iterate the dataset and get each row.
std::unordered_map<std::string, mindspore::MSTensor> row;
ASSERT_OK(iter->GetNextRow(&row));
EXPECT_NE(row.find("image"), row.end());
EXPECT_NE(row.find("label"), row.end());
uint64_t i = 0;
while (row.size() != 0) {
i++;
auto image = row["image"];
MS_LOG(INFO) << "Tensor image shape: " << image.Shape();
ASSERT_OK(iter->GetNextRow(&row));
}
EXPECT_EQ(i, 16);
// Manually terminate the pipeline.
iter->Stop();
}
/// Feature: Places365TrainDatasetSize.
/// Description: test usage of get the size of Places365TrainDataset.
/// Expectation: get correct number of data.
TEST_F(MindDataTestPipeline, TestGetPlaces365TrainDatasetSize) {
MS_LOG(INFO) << "Doing MindDataTestPipeline-TestGetPlaces365TrainDatasetSize.";
// Create a Places365 Train Dataset.
std::string folder_path = datasets_root_path_ + "/testPlaces365Data";
std::shared_ptr<Dataset> ds = Places365(folder_path, "train-standard", true, true);
EXPECT_NE(ds, nullptr);
EXPECT_EQ(ds->GetDatasetSize(), 4);
}
/// Feature: Places365TrainDatasetGetters.
/// Description: test usage of getters Places365TrainDataset.
/// Expectation: get correct number of data and correct tensor shape.
TEST_F(MindDataTestPipeline, TestPlaces365TrainDatasetGetters) {
MS_LOG(INFO) << "Doing MindDataTestPipeline-TestPlaces365TrainDatasetGetters.";
// Create a Places365 Train Dataset.
std::string folder_path = datasets_root_path_ + "/testPlaces365Data";
std::shared_ptr<Dataset> ds = Places365(folder_path, "train-standard", true, true);
EXPECT_NE(ds, nullptr);
EXPECT_EQ(ds->GetDatasetSize(), 4);
std::vector<DataType> types = ToDETypes(ds->GetOutputTypes());
std::vector<TensorShape> shapes = ToTensorShapeVec(ds->GetOutputShapes());
std::vector<std::string> column_names = {"image", "label"};
int64_t num_classes = ds->GetNumClasses();
EXPECT_EQ(types.size(), 2);
EXPECT_EQ(types[0].ToString(), "uint8");
EXPECT_EQ(types[1].ToString(), "uint32");
EXPECT_EQ(shapes.size(), 2);
EXPECT_EQ(shapes[0].ToString(), "<256,256,3>");
EXPECT_EQ(shapes[1].ToString(), "<>");
EXPECT_EQ(num_classes, -1);
EXPECT_EQ(ds->GetBatchSize(), 1);
EXPECT_EQ(ds->GetRepeatCount(), 1);
EXPECT_EQ(ds->GetDatasetSize(), 4);
EXPECT_EQ(ToDETypes(ds->GetOutputTypes()), types);
EXPECT_EQ(ToTensorShapeVec(ds->GetOutputShapes()), shapes);
EXPECT_EQ(ds->GetNumClasses(), -1);
EXPECT_EQ(ds->GetColumnNames(), column_names);
EXPECT_EQ(ds->GetDatasetSize(), 4);
EXPECT_EQ(ToDETypes(ds->GetOutputTypes()), types);
EXPECT_EQ(ToTensorShapeVec(ds->GetOutputShapes()), shapes);
EXPECT_EQ(ds->GetBatchSize(), 1);
EXPECT_EQ(ds->GetRepeatCount(), 1);
EXPECT_EQ(ds->GetNumClasses(), -1);
EXPECT_EQ(ds->GetDatasetSize(), 4);
}
/// Feature: Places365DatasetFail.
/// Description: test failure of Places365Dataset.
/// Expectation: get none piece of data.
TEST_F(MindDataTestPipeline, TestPlaces365DatasetFail) {
MS_LOG(INFO) << "Doing MindDataTestPipeline-TestPlaces365DatasetFail.";
// Create a Places365 Dataset.
std::shared_ptr<Dataset> ds = Places365("", "val", true, true, std::make_shared<RandomSampler>(false, 10));
EXPECT_NE(ds, nullptr);
// Create an iterator over the result of the above dataset.
std::shared_ptr<Iterator> iter = ds->CreateIterator();
// Expect failure: invalid Places365 input.
EXPECT_EQ(iter, nullptr);
}
/// Feature: Places365DatasetWithInvalidUsageFail.
/// Description: test failure of Places365Dataset with invalid usage.
/// Expectation: get none piece of data.
TEST_F(MindDataTestPipeline, TestPlaces365DatasetWithInvalidUsageFail) {
MS_LOG(INFO) << "Doing MindDataTestPipeline-TestPlaces365DatasetWithInvalidUsageFail.";
// Create a Places365 Dataset.
std::string folder_path = datasets_root_path_ + "/testPlaces365Data";
std::shared_ptr<Dataset> ds = Places365(folder_path, "validation", true, true);
EXPECT_NE(ds, nullptr);
// Create an iterator over the result of the above dataset.
std::shared_ptr<Iterator> iter = ds->CreateIterator();
// Expect failure: invalid Places365 input, validation is not a valid usage.
EXPECT_EQ(iter, nullptr);
}
/// Feature: Places365DatasetWithNullSamplerFail.
/// Description: test failure of Places365Dataset with null sampler.
/// Expectation: get none piece of data.
TEST_F(MindDataTestPipeline, TestPlaces365DatasetWithNullSamplerFail) {
MS_LOG(INFO) << "Doing MindDataTestPipeline-TestPlaces365DatasetWithNullSamplerFail.";
// Create a Places365 Dataset.
std::string folder_path = datasets_root_path_ + "/testPlaces365Data";
std::shared_ptr<Dataset> ds = Places365(folder_path, "train-standard", true, true, nullptr);
EXPECT_NE(ds, nullptr);
// Create an iterator over the result of the above dataset.
std::shared_ptr<Iterator> iter = ds->CreateIterator();
// Expect failure: invalid Places365 input, sampler cannot be nullptr.
EXPECT_EQ(iter, nullptr);
}
| 36.800654 | 117 | 0.726312 | [
"shape",
"vector"
] |
14119ddf93f87f84423c129620da8c9db201ec0e | 1,108 | cpp | C++ | geometry/polygon_width.cpp | ACM-CUBA/Team-Reference | 0ffa66be3ebed7a0c34dfffc19c9189d9435b182 | [
"Apache-2.0"
] | 3 | 2019-04-12T16:24:59.000Z | 2022-03-30T20:21:31.000Z | geometry/polygon_width.cpp | ACM-CUBA/TR | 0ffa66be3ebed7a0c34dfffc19c9189d9435b182 | [
"Apache-2.0"
] | 3 | 2018-04-01T22:41:51.000Z | 2018-04-02T21:20:42.000Z | geometry/polygon_width.cpp | ACM-CUBA/TR | 0ffa66be3ebed7a0c34dfffc19c9189d9435b182 | [
"Apache-2.0"
] | 2 | 2019-04-12T16:25:04.000Z | 2019-09-22T20:28:11.000Z | /*
Algorithm:
Compute the width of a convex polygon
Complexity:
O(n)
Tested:
https://icpcarchive.ecs.baylor.edu/index.php?option=onlinejudge&page=show_problem&problem=3139
*/
#include <geometry/basics.cpp>
const int oo = 1e9; // adjust
double check(int a, int b, int c, int d, const polygon &P)
{
for (int i = 0; i < 4 && a != c; ++i)
{
if (i == 1) swap(a, b);
else swap(c, d);
}
if (a == c) // a admits a support line parallel to bd
{
double A = abs(area2(P[a], P[b], P[d]));
// double of the triangle area
double base = abs(P[b] - P[d]);
// base of the triangle abd
return A / base;
}
return oo;
}
double polygon_width(const polygon &P)
{
if (P.size() < 3)
return 0;
auto pairs = antipodal(P);
double best = oo;
int n = pairs.size();
for (int i = 0; i < n; ++i)
{
double tmp = check(pairs[i].first, pairs[i].second,
pairs[NEXT(i)].first, pairs[NEXT(i)].second, P);
best = min(best, tmp);
}
return best;
}
| 21.307692 | 102 | 0.527076 | [
"geometry"
] |
1412f2abbe9c42d4913b7c1c34aff5baaf64d6c8 | 9,003 | cpp | C++ | src/gpu/d3d/GrD3DPipelineState.cpp | roylanceMichael/skia | 68a09699e94237b4b4d3376de620c3cc3c141177 | [
"BSD-3-Clause"
] | 1 | 2021-11-18T17:03:57.000Z | 2021-11-18T17:03:57.000Z | src/gpu/d3d/GrD3DPipelineState.cpp | roylanceMichael/skia | 68a09699e94237b4b4d3376de620c3cc3c141177 | [
"BSD-3-Clause"
] | null | null | null | src/gpu/d3d/GrD3DPipelineState.cpp | roylanceMichael/skia | 68a09699e94237b4b4d3376de620c3cc3c141177 | [
"BSD-3-Clause"
] | null | null | null | /*
* Copyright 2020 Google LLC
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "src/gpu/d3d/GrD3DPipelineState.h"
#include "include/private/SkTemplates.h"
#include "src/gpu/GrFragmentProcessor.h"
#include "src/gpu/GrGeometryProcessor.h"
#include "src/gpu/GrProgramInfo.h"
#include "src/gpu/GrStencilSettings.h"
#include "src/gpu/GrXferProcessor.h"
#include "src/gpu/d3d/GrD3DBuffer.h"
#include "src/gpu/d3d/GrD3DGpu.h"
#include "src/gpu/d3d/GrD3DPipeline.h"
#include "src/gpu/d3d/GrD3DRootSignature.h"
#include "src/gpu/d3d/GrD3DTexture.h"
#include "src/gpu/effects/GrTextureEffect.h"
GrD3DPipelineState::GrD3DPipelineState(
sk_sp<GrD3DPipeline> pipeline,
sk_sp<GrD3DRootSignature> rootSignature,
GrUniformDataManager::ProgramUniforms programUniforms,
const GrGLSLBuiltinUniformHandles& builtinUniformHandles,
const UniformInfoArray& uniforms,
uint32_t uniformSize,
uint32_t numSamplers,
std::unique_ptr<GrGeometryProcessor::ProgramImpl> gpImpl,
std::unique_ptr<GrXferProcessor::ProgramImpl> xpImpl,
std::vector<std::unique_ptr<GrFragmentProcessor::ProgramImpl>> fpImpls,
size_t vertexStride,
size_t instanceStride)
: fPipeline(std::move(pipeline))
, fRootSignature(std::move(rootSignature))
, fBuiltinUniformHandles(builtinUniformHandles)
, fGPImpl(std::move(gpImpl))
, fXPImpl(std::move(xpImpl))
, fFPImpls(std::move(fpImpls))
, fDataManager(std::move(programUniforms), uniforms, uniformSize)
, fNumSamplers(numSamplers)
, fVertexStride(vertexStride)
, fInstanceStride(instanceStride) {}
void GrD3DPipelineState::setAndBindConstants(GrD3DGpu* gpu,
const GrRenderTarget* renderTarget,
const GrProgramInfo& programInfo) {
fDataManager.setUniforms(programInfo);
this->setRenderTargetState(renderTarget, programInfo.origin());
fGPImpl->setData(fDataManager, *gpu->caps()->shaderCaps(), programInfo.geomProc());
for (int i = 0; i < programInfo.pipeline().numFragmentProcessors(); ++i) {
const auto& fp = programInfo.pipeline().getFragmentProcessor(i);
fp.visitWithImpls([&](const GrFragmentProcessor& fp,
GrFragmentProcessor::ProgramImpl& impl) {
impl.setData(fDataManager, fp);
}, *fFPImpls[i]);
}
programInfo.pipeline().setDstTextureUniforms(fDataManager, &fBuiltinUniformHandles);
fXPImpl->setData(fDataManager, programInfo.pipeline().getXferProcessor());
D3D12_GPU_VIRTUAL_ADDRESS constantsAddress = fDataManager.uploadConstants(gpu);
gpu->currentCommandList()->setGraphicsRootConstantBufferView(
(unsigned int)(GrD3DRootSignature::ParamIndex::kConstantBufferView),
constantsAddress);
}
void GrD3DPipelineState::setRenderTargetState(const GrRenderTarget* rt, GrSurfaceOrigin origin) {
// Set RT adjustment and RT flip
SkISize dimensions = rt->dimensions();
SkASSERT(fBuiltinUniformHandles.fRTAdjustmentUni.isValid());
if (fRenderTargetState.fRenderTargetOrigin != origin ||
fRenderTargetState.fRenderTargetSize != dimensions) {
fRenderTargetState.fRenderTargetSize = dimensions;
fRenderTargetState.fRenderTargetOrigin = origin;
// The client will mark a swap buffer as kTopLeft when making a SkSurface because
// D3D's framebuffer space has (0, 0) at the top left. This agrees with Skia's device
// coords. However, in NDC (-1, -1) is the bottom left. So we flip when origin is kTopLeft.
bool flip = (origin == kTopLeft_GrSurfaceOrigin);
std::array<float, 4> v = SkSL::Compiler::GetRTAdjustVector(dimensions, flip);
fDataManager.set4fv(fBuiltinUniformHandles.fRTAdjustmentUni, 1, v.data());
if (fBuiltinUniformHandles.fRTFlipUni.isValid()) {
// Note above that framebuffer space has origin top left. So we need !flip here.
std::array<float, 2> d = SkSL::Compiler::GetRTFlipVector(rt->height(), !flip);
fDataManager.set2fv(fBuiltinUniformHandles.fRTFlipUni, 1, d.data());
}
}
}
void GrD3DPipelineState::setAndBindTextures(GrD3DGpu* gpu,
const GrGeometryProcessor& geomProc,
const GrSurfaceProxy* const geomProcTextures[],
const GrPipeline& pipeline) {
SkASSERT(geomProcTextures || !geomProc.numTextureSamplers());
std::vector<D3D12_CPU_DESCRIPTOR_HANDLE> shaderResourceViews(fNumSamplers);
std::vector<D3D12_CPU_DESCRIPTOR_HANDLE> samplers(fNumSamplers);
unsigned int currTextureBinding = 0;
for (int i = 0; i < geomProc.numTextureSamplers(); ++i) {
SkASSERT(geomProcTextures[i]->asTextureProxy());
const auto& sampler = geomProc.textureSampler(i);
auto texture = static_cast<GrD3DTexture*>(geomProcTextures[i]->peekTexture());
shaderResourceViews[currTextureBinding] = texture->shaderResourceView();
samplers[currTextureBinding++] =
gpu->resourceProvider().findOrCreateCompatibleSampler(sampler.samplerState());
gpu->currentCommandList()->addSampledTextureRef(texture);
}
if (GrTexture* dstTexture = pipeline.peekDstTexture()) {
auto texture = static_cast<GrD3DTexture*>(dstTexture);
shaderResourceViews[currTextureBinding] = texture->shaderResourceView();
samplers[currTextureBinding++] = gpu->resourceProvider().findOrCreateCompatibleSampler(
GrSamplerState::Filter::kNearest);
gpu->currentCommandList()->addSampledTextureRef(texture);
}
pipeline.visitTextureEffects([&](const GrTextureEffect& te) {
GrSamplerState samplerState = te.samplerState();
auto* texture = static_cast<GrD3DTexture*>(te.texture());
shaderResourceViews[currTextureBinding] = texture->shaderResourceView();
samplers[currTextureBinding++] =
gpu->resourceProvider().findOrCreateCompatibleSampler(samplerState);
gpu->currentCommandList()->addSampledTextureRef(texture);
});
SkASSERT(fNumSamplers == currTextureBinding);
// fill in descriptor tables and bind to root signature
if (fNumSamplers > 0) {
// set up and bind shader resource view table
sk_sp<GrD3DDescriptorTable> srvTable =
gpu->resourceProvider().findOrCreateShaderViewTable(shaderResourceViews);
gpu->currentCommandList()->setGraphicsRootDescriptorTable(
(unsigned int)GrD3DRootSignature::ParamIndex::kShaderViewDescriptorTable,
srvTable->baseGpuDescriptor());
// set up and bind sampler table
sk_sp<GrD3DDescriptorTable> samplerTable =
gpu->resourceProvider().findOrCreateSamplerTable(samplers);
gpu->currentCommandList()->setGraphicsRootDescriptorTable(
(unsigned int)GrD3DRootSignature::ParamIndex::kSamplerDescriptorTable,
samplerTable->baseGpuDescriptor());
}
}
void GrD3DPipelineState::bindBuffers(GrD3DGpu* gpu, sk_sp<const GrBuffer> indexBuffer,
sk_sp<const GrBuffer> instanceBuffer,
sk_sp<const GrBuffer> vertexBuffer,
GrD3DDirectCommandList* commandList) {
// Here our vertex and instance inputs need to match the same 0-based bindings they were
// assigned in the PipelineState. That is, vertex first (if any) followed by instance.
if (vertexBuffer) {
auto* d3dVertexBuffer = static_cast<const GrD3DBuffer*>(vertexBuffer.get());
SkASSERT(!d3dVertexBuffer->isCpuBuffer());
SkASSERT(!d3dVertexBuffer->isMapped());
const_cast<GrD3DBuffer*>(d3dVertexBuffer)->setResourceState(
gpu, D3D12_RESOURCE_STATE_VERTEX_AND_CONSTANT_BUFFER);
}
if (instanceBuffer) {
auto* d3dInstanceBuffer = static_cast<const GrD3DBuffer*>(instanceBuffer.get());
SkASSERT(!d3dInstanceBuffer->isCpuBuffer());
SkASSERT(!d3dInstanceBuffer->isMapped());
const_cast<GrD3DBuffer*>(d3dInstanceBuffer)->setResourceState(
gpu, D3D12_RESOURCE_STATE_VERTEX_AND_CONSTANT_BUFFER);
}
commandList->setVertexBuffers(0, std::move(vertexBuffer), fVertexStride,
std::move(instanceBuffer), fInstanceStride);
if (auto* d3dIndexBuffer = static_cast<const GrD3DBuffer*>(indexBuffer.get())) {
SkASSERT(!d3dIndexBuffer->isCpuBuffer());
SkASSERT(!d3dIndexBuffer->isMapped());
const_cast<GrD3DBuffer*>(d3dIndexBuffer)->setResourceState(
gpu, D3D12_RESOURCE_STATE_INDEX_BUFFER);
commandList->setIndexBuffer(std::move(indexBuffer));
}
}
| 48.929348 | 99 | 0.679662 | [
"vector"
] |
141401122b685e03b5ee674b394ba3580d108d9c | 1,223 | cpp | C++ | c++/binary_tree_right_side_view.cpp | SongZhao/leetcode | 4a2b4f554e91f6a2167b336f8a69b80fa9f3f920 | [
"Apache-2.0"
] | null | null | null | c++/binary_tree_right_side_view.cpp | SongZhao/leetcode | 4a2b4f554e91f6a2167b336f8a69b80fa9f3f920 | [
"Apache-2.0"
] | null | null | null | c++/binary_tree_right_side_view.cpp | SongZhao/leetcode | 4a2b4f554e91f6a2167b336f8a69b80fa9f3f920 | [
"Apache-2.0"
] | null | null | null | /*
Given a binary tree, imagine yourself standing on the right side of it, return the values of the nodes you can see
ordered from top to bottom.
For example:
Given the following binary tree,
1 <---
/ \
2 3 <---
\ \
5 4 <---
You should return [1, 3, 4].
*/
/*
*
*/
#include "helper.h"
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<int> rightSideView(TreeNode* root) {
vector<int> res;
traversal(root, res, 1);
return res;
}
void traversal(TreeNode* root, vector<int> &res, int depth) {
if (!root) {
return;
}
if (res.size() < depth) {
res.push_back(root->val);
}
traversal(root->right, res, depth + 1);
traversal(root->left, res, depth + 1);
}
};
int main() {
Solution s;
vector<int> preorder({1, 2, 5, 3, 4}), inorder({2, 5, 1, 3, 4});
TreeNode *root = buildTree(preorder, inorder);
root->print();
cout << s.rightSideView(root) << endl;
return 0;
}
| 21.086207 | 114 | 0.535568 | [
"vector"
] |
1416cafa915c0438827756c1ffd3c558f44a20be | 5,332 | cpp | C++ | aws-cpp-sdk-iotsecuretunneling/source/model/Tunnel.cpp | grujicbr/aws-sdk-cpp | bdd43c178042f09c6739645e3f6cd17822a7c35c | [
"Apache-2.0"
] | 1 | 2020-03-11T05:36:20.000Z | 2020-03-11T05:36:20.000Z | aws-cpp-sdk-iotsecuretunneling/source/model/Tunnel.cpp | novaquark/aws-sdk-cpp | a0969508545bec9ae2864c9e1e2bb9aff109f90c | [
"Apache-2.0"
] | null | null | null | aws-cpp-sdk-iotsecuretunneling/source/model/Tunnel.cpp | novaquark/aws-sdk-cpp | a0969508545bec9ae2864c9e1e2bb9aff109f90c | [
"Apache-2.0"
] | null | null | null | /*
* Copyright 2010-2017 Amazon.com, Inc. or its affiliates. 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.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 <aws/iotsecuretunneling/model/Tunnel.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <utility>
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
namespace Aws
{
namespace IoTSecureTunneling
{
namespace Model
{
Tunnel::Tunnel() :
m_tunnelIdHasBeenSet(false),
m_tunnelArnHasBeenSet(false),
m_status(TunnelStatus::NOT_SET),
m_statusHasBeenSet(false),
m_sourceConnectionStateHasBeenSet(false),
m_destinationConnectionStateHasBeenSet(false),
m_descriptionHasBeenSet(false),
m_destinationConfigHasBeenSet(false),
m_timeoutConfigHasBeenSet(false),
m_tagsHasBeenSet(false),
m_createdAtHasBeenSet(false),
m_lastUpdatedAtHasBeenSet(false)
{
}
Tunnel::Tunnel(JsonView jsonValue) :
m_tunnelIdHasBeenSet(false),
m_tunnelArnHasBeenSet(false),
m_status(TunnelStatus::NOT_SET),
m_statusHasBeenSet(false),
m_sourceConnectionStateHasBeenSet(false),
m_destinationConnectionStateHasBeenSet(false),
m_descriptionHasBeenSet(false),
m_destinationConfigHasBeenSet(false),
m_timeoutConfigHasBeenSet(false),
m_tagsHasBeenSet(false),
m_createdAtHasBeenSet(false),
m_lastUpdatedAtHasBeenSet(false)
{
*this = jsonValue;
}
Tunnel& Tunnel::operator =(JsonView jsonValue)
{
if(jsonValue.ValueExists("tunnelId"))
{
m_tunnelId = jsonValue.GetString("tunnelId");
m_tunnelIdHasBeenSet = true;
}
if(jsonValue.ValueExists("tunnelArn"))
{
m_tunnelArn = jsonValue.GetString("tunnelArn");
m_tunnelArnHasBeenSet = true;
}
if(jsonValue.ValueExists("status"))
{
m_status = TunnelStatusMapper::GetTunnelStatusForName(jsonValue.GetString("status"));
m_statusHasBeenSet = true;
}
if(jsonValue.ValueExists("sourceConnectionState"))
{
m_sourceConnectionState = jsonValue.GetObject("sourceConnectionState");
m_sourceConnectionStateHasBeenSet = true;
}
if(jsonValue.ValueExists("destinationConnectionState"))
{
m_destinationConnectionState = jsonValue.GetObject("destinationConnectionState");
m_destinationConnectionStateHasBeenSet = true;
}
if(jsonValue.ValueExists("description"))
{
m_description = jsonValue.GetString("description");
m_descriptionHasBeenSet = true;
}
if(jsonValue.ValueExists("destinationConfig"))
{
m_destinationConfig = jsonValue.GetObject("destinationConfig");
m_destinationConfigHasBeenSet = true;
}
if(jsonValue.ValueExists("timeoutConfig"))
{
m_timeoutConfig = jsonValue.GetObject("timeoutConfig");
m_timeoutConfigHasBeenSet = true;
}
if(jsonValue.ValueExists("tags"))
{
Array<JsonView> tagsJsonList = jsonValue.GetArray("tags");
for(unsigned tagsIndex = 0; tagsIndex < tagsJsonList.GetLength(); ++tagsIndex)
{
m_tags.push_back(tagsJsonList[tagsIndex].AsObject());
}
m_tagsHasBeenSet = true;
}
if(jsonValue.ValueExists("createdAt"))
{
m_createdAt = jsonValue.GetDouble("createdAt");
m_createdAtHasBeenSet = true;
}
if(jsonValue.ValueExists("lastUpdatedAt"))
{
m_lastUpdatedAt = jsonValue.GetDouble("lastUpdatedAt");
m_lastUpdatedAtHasBeenSet = true;
}
return *this;
}
JsonValue Tunnel::Jsonize() const
{
JsonValue payload;
if(m_tunnelIdHasBeenSet)
{
payload.WithString("tunnelId", m_tunnelId);
}
if(m_tunnelArnHasBeenSet)
{
payload.WithString("tunnelArn", m_tunnelArn);
}
if(m_statusHasBeenSet)
{
payload.WithString("status", TunnelStatusMapper::GetNameForTunnelStatus(m_status));
}
if(m_sourceConnectionStateHasBeenSet)
{
payload.WithObject("sourceConnectionState", m_sourceConnectionState.Jsonize());
}
if(m_destinationConnectionStateHasBeenSet)
{
payload.WithObject("destinationConnectionState", m_destinationConnectionState.Jsonize());
}
if(m_descriptionHasBeenSet)
{
payload.WithString("description", m_description);
}
if(m_destinationConfigHasBeenSet)
{
payload.WithObject("destinationConfig", m_destinationConfig.Jsonize());
}
if(m_timeoutConfigHasBeenSet)
{
payload.WithObject("timeoutConfig", m_timeoutConfig.Jsonize());
}
if(m_tagsHasBeenSet)
{
Array<JsonValue> tagsJsonList(m_tags.size());
for(unsigned tagsIndex = 0; tagsIndex < tagsJsonList.GetLength(); ++tagsIndex)
{
tagsJsonList[tagsIndex].AsObject(m_tags[tagsIndex].Jsonize());
}
payload.WithArray("tags", std::move(tagsJsonList));
}
if(m_createdAtHasBeenSet)
{
payload.WithDouble("createdAt", m_createdAt.SecondsWithMSPrecision());
}
if(m_lastUpdatedAtHasBeenSet)
{
payload.WithDouble("lastUpdatedAt", m_lastUpdatedAt.SecondsWithMSPrecision());
}
return payload;
}
} // namespace Model
} // namespace IoTSecureTunneling
} // namespace Aws
| 23.488987 | 92 | 0.736497 | [
"model"
] |
1418ee748a9885affe143a0e8d9d41d4104376c4 | 524 | cpp | C++ | src/sdk/model/transaction/address_alias_transaction.cpp | proximax-storage/cpp-xpx-chain-sdk | ff562e8a089849eb0b7f8edc83ad61c7a2728f34 | [
"Apache-2.0"
] | 1 | 2019-12-06T06:55:37.000Z | 2019-12-06T06:55:37.000Z | src/sdk/model/transaction/address_alias_transaction.cpp | proximax-storage/cpp-xpx-chain-sdk | ff562e8a089849eb0b7f8edc83ad61c7a2728f34 | [
"Apache-2.0"
] | null | null | null | src/sdk/model/transaction/address_alias_transaction.cpp | proximax-storage/cpp-xpx-chain-sdk | ff562e8a089849eb0b7f8edc83ad61c7a2728f34 | [
"Apache-2.0"
] | null | null | null | /**
*** Copyright 2019 ProximaX Limited. All rights reserved.
*** Use of this source code is governed by the Apache 2.0
*** license that can be found in the LICENSE file.
**/
#include <xpxchaincpp/model/transaction/address_alias_transaction.h>
namespace xpx_chain_sdk {
template<typename TBase>
const Address& TAddressAliasTransaction<TBase>::aliasedAddress() const
{
return aliasedAddress_;
}
template class TAddressAliasTransaction<Transaction>;
template class TAddressAliasTransaction<EmbeddedTransaction>;
}
| 27.578947 | 71 | 0.78626 | [
"model"
] |
141a6161669a7caa59f374776a77a0859c869dbf | 1,299 | cc | C++ | RecoTracker/TkHitPairs/src/CosmicHitPairGenerator.cc | nistefan/cmssw | ea13af97f7f2117a4f590a5e654e06ecd9825a5b | [
"Apache-2.0"
] | 3 | 2018-08-24T19:10:26.000Z | 2019-02-19T11:45:32.000Z | RecoTracker/TkHitPairs/src/CosmicHitPairGenerator.cc | nistefan/cmssw | ea13af97f7f2117a4f590a5e654e06ecd9825a5b | [
"Apache-2.0"
] | 3 | 2018-08-23T13:40:24.000Z | 2019-12-05T21:16:03.000Z | RecoTracker/TkHitPairs/src/CosmicHitPairGenerator.cc | nistefan/cmssw | ea13af97f7f2117a4f590a5e654e06ecd9825a5b | [
"Apache-2.0"
] | 5 | 2018-08-21T16:37:52.000Z | 2020-01-09T13:33:17.000Z | //#include "RecoTracker/TkHitPairs/interface/LayerWithHits.h"
#include "RecoTracker/TkHitPairs/interface/CosmicHitPairGenerator.h"
#include "RecoTracker/TkHitPairs/interface/SeedLayerPairs.h"
#include "RecoTracker/TkHitPairs/interface/CosmicHitPairGeneratorFromLayerPair.h"
#include "FWCore/MessageLogger/interface/MessageLogger.h"
using namespace std;
CosmicHitPairGenerator::CosmicHitPairGenerator(SeedLayerPairs& layers,
const edm::EventSetup& iSetup)
{
vector<SeedLayerPairs::LayerPair> layerPairs = layers();
vector<SeedLayerPairs::LayerPair>::const_iterator it;
for (it = layerPairs.begin(); it != layerPairs.end(); it++) {
add( (*it).first, (*it).second,iSetup);
}
}
CosmicHitPairGenerator::~CosmicHitPairGenerator()
{
}
void CosmicHitPairGenerator::add(
const LayerWithHits *inner, const LayerWithHits *outer,
const edm::EventSetup& iSetup)
{
theGenerators.push_back(std::make_unique<CosmicHitPairGeneratorFromLayerPair>( inner, outer, iSetup));
}
void CosmicHitPairGenerator::hitPairs(
const TrackingRegion& region,
OrderedHitPairs & pairs,
const edm::EventSetup& iSetup)
{
Container::const_iterator i;
for (i=theGenerators.begin(); i!=theGenerators.end(); i++) {
(**i).hitPairs( region, pairs, iSetup);
}
}
| 25.98 | 104 | 0.742109 | [
"vector"
] |
141d436117c3670f90f8ab4288d3709a2e356324 | 3,019 | hpp | C++ | src/Illusion/Graphics/Swapchain.hpp | Simmesimme/illusion-3d | 48520d87ea0677bb8852b20bb6fbfbe1a49402d2 | [
"MIT"
] | 8 | 2019-12-05T15:57:23.000Z | 2022-01-19T19:37:23.000Z | src/Illusion/Graphics/Swapchain.hpp | Schneegans/illusion | 48520d87ea0677bb8852b20bb6fbfbe1a49402d2 | [
"MIT"
] | null | null | null | src/Illusion/Graphics/Swapchain.hpp | Schneegans/illusion | 48520d87ea0677bb8852b20bb6fbfbe1a49402d2 | [
"MIT"
] | 1 | 2019-01-15T10:35:13.000Z | 2019-01-15T10:35:13.000Z | ////////////////////////////////////////////////////////////////////////////////////////////////////
// //
// _) | | _) This code may be used and modified under the terms //
// | | | | | (_-< | _ \ \ of the MIT license. See the LICENSE file for details. //
// _| _| _| \_,_| ___/ _| \___/ _| _| Copyright (c) 2018-2019 Simon Schneegans //
// //
////////////////////////////////////////////////////////////////////////////////////////////////////
#ifndef ILLUSION_GRAPHICS_SWAPCHAIN_HPP
#define ILLUSION_GRAPHICS_SWAPCHAIN_HPP
#include "RenderPass.hpp"
#include <functional>
namespace Illusion::Graphics {
////////////////////////////////////////////////////////////////////////////////////////////////////
// This class is primarily as member of the Window class. It manages presentation of images on //
// the window's surface. The image given to the present() method will be blitted to the current //
// swapchain image. //
////////////////////////////////////////////////////////////////////////////////////////////////////
class Swapchain : public Core::StaticCreate<Swapchain>, public Core::NamedObject {
public:
// This is called by the Window.
Swapchain(std::string const& name, DeviceConstPtr device, vk::SurfaceKHRPtr surface);
virtual ~Swapchain();
// For now, vk::PresentModeKHR::eFifo is used for v-sync, for no v-sync either
// vk::PresentModeKHR::eImmediate (if supported) or preferably vk::PresentModeKHR::eMailbox (if
// supported) are used.
void setEnableVsync(bool enable);
// This will trigger a re-creation of the SwapChain. This is called by the Window on size changes.
void markDirty();
// Get the current size of the swapchain images.
glm::uvec2 const& getExtent() const;
// Blits the given image to one of the swapchain images. The operation will wait for the given
// semaphore and will signal the given fence once it finishes.
void present(BackedImagePtr const& image, vk::SemaphorePtr const& renderFinishedSemaphore,
vk::FencePtr const& signalFence);
private:
void recreate();
DeviceConstPtr mDevice;
vk::SurfaceKHRPtr mSurface;
glm::uvec2 mExtent{};
vk::SurfaceFormatKHR mFormat{};
vk::SwapchainKHRPtr mSwapchain;
std::vector<vk::Image> mImages;
uint32_t mCurrentImageIndex = 0;
std::vector<vk::SemaphorePtr> mImageAvailableSemaphores;
std::vector<vk::SemaphorePtr> mCopyFinishedSemaphores;
std::vector<CommandBufferPtr> mPresentCommandBuffers;
uint32_t mCurrentPresentIndex = 0;
bool mEnableVsync = true;
bool mDirty = true;
};
} // namespace Illusion::Graphics
#endif // ILLUSION_GRAPHICS_SWAPCHAIN_HPP
| 43.128571 | 100 | 0.533952 | [
"vector"
] |
141f0ad57622bcd718601cc01c63c5380c61490b | 38,589 | cpp | C++ | visa/BinaryEncodingIGA.cpp | scott-snyder/intel-graphics-compiler | 0977554d5aecf93b4a777f38e6c2e73e4dea313e | [
"MIT"
] | null | null | null | visa/BinaryEncodingIGA.cpp | scott-snyder/intel-graphics-compiler | 0977554d5aecf93b4a777f38e6c2e73e4dea313e | [
"MIT"
] | null | null | null | visa/BinaryEncodingIGA.cpp | scott-snyder/intel-graphics-compiler | 0977554d5aecf93b4a777f38e6c2e73e4dea313e | [
"MIT"
] | null | null | null | /*===================== begin_copyright_notice ==================================
Copyright (c) 2017 Intel Corporation
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
======================= end_copyright_notice ==================================*/
#include "BinaryEncodingIGA.h"
#include "GTGPU_RT_ASM_Interface.h"
#include "iga/IGALibrary/api/igaEncoderWrapper.hpp"
#include "Timer.h"
#include "BuildIR.h"
using namespace iga;
using namespace vISA;
Platform BinaryEncodingIGA::getIGAInternalPlatform(TARGET_PLATFORM genxPlatform)
{
Platform platform = Platform::INVALID;
switch (genxPlatform)
{
case GENX_BDW:
platform = Platform::GEN8;
break;
case GENX_CHV:
platform = Platform::GEN8;
break;
case GENX_SKL:
case GENX_BXT:
platform = Platform::GEN9;
break;
case GENX_ICLLP:
platform = Platform::GEN11;
break;
case GENX_TGLLP:
platform = Platform::GEN12P1;
break;
default:
break;
}
return platform;
}
BinaryEncodingIGA::BinaryEncodingIGA(vISA::Mem_Manager &m, vISA::G4_Kernel& k, std::string fname) :
mem(m), kernel(k), fileName(fname), m_kernelBuffer(nullptr), m_kernelBufferSize(0)
{
platformModel = iga::Model::LookupModel(getIGAInternalPlatform(getGenxPlatform()));
IGAKernel = new iga::Kernel(*platformModel);
}
iga::InstOptSet BinaryEncodingIGA::getIGAInstOptSet(G4_INST* inst) const
{
iga::InstOptSet options;
if (inst->isAccWrCtrlInst() && kernel.fg.builder->encodeAccWrEn())
{
options.add(iga::InstOpt::ACCWREN);
}
if (inst->isAtomicInst())
{
options.add(iga::InstOpt::ATOMIC);
}
if (inst->isBreakPointInst())
{
options.add(iga::InstOpt::BREAKPOINT);
}
if (inst->isNoDDChkInst())
{
options.add(iga::InstOpt::NODDCHK);
}
if (inst->isNoDDClrInst())
{
options.add(iga::InstOpt::NODDCLR);
}
if (inst->isNoPreemptInst())
{
options.add(iga::InstOpt::NOPREEMPT);
}
if (inst->isYieldInst())
{
options.add(iga::InstOpt::SWITCH);
}
if (inst->isSend())
{
if (inst->isEOT())
{
options.add(iga::InstOpt::EOT);
}
if (inst->isNoSrcDepSet())
{
options.add(iga::InstOpt::NOSRCDEPSET);
}
if (inst->asSendInst()->isSerializedInst())
{
options.add(iga::InstOpt::SERIALIZE);
}
}
if (inst->isNoCompactedInst())
{
options.add(iga::InstOpt::NOCOMPACT);
}
return options;
}
void BinaryEncodingIGA::FixInst()
{
for (auto bb : kernel.fg)
{
for (auto iter = bb->begin(); iter != bb->end();)
{
G4_INST* inst = *iter;
if (inst->isIntrinsic())
{
// WA for simulation: remove any intrinsics that should be lowered before binary encoding
MUST_BE_TRUE(inst->asIntrinsicInst()->getLoweredByPhase() == Phase::BinaryEncoding,
"Unexpected intrinsics in binary encoding");
iter = bb->erase(iter);
}
else
{
++iter;
}
}
}
}
iga::Op BinaryEncodingIGA::getIGAOpFromSFIDForSend(G4_opcode op, const G4_INST *inst)
{
ASSERT_USER(inst->isSend(), "Only send has SFID");
iga::Op igaOp = iga::Op::INVALID;
G4_SendMsgDescriptor *msgDesc = inst->getMsgDesc();
auto funcID = msgDesc->getFuncId();
switch (funcID)
{
case vISA::SFID::NULL_SFID:
igaOp = (op == G4_send) ? iga::Op::SEND_NULL : iga::Op::SENDC_NULL;
break;
case vISA::SFID::SAMPLER:
igaOp = (op == G4_send) ? iga::Op::SEND_SMPL : iga::Op::SENDC_SMPL;
break;
case vISA::SFID::GATEWAY:
igaOp = (op == G4_send) ? iga::Op::SEND_GTWY : iga::Op::SENDC_GTWY;
break;
case vISA::SFID::DP_DC2:
igaOp = (op == G4_send) ? iga::Op::SEND_DC2 : iga::Op::SENDC_DC2;
break;
case vISA::SFID::DP_WRITE:
igaOp = (op == G4_send) ? iga::Op::SEND_RC : iga::Op::SENDC_RC;
break;
case vISA::SFID::URB:
igaOp = (op == G4_send) ? iga::Op::SEND_URB : iga::Op::SENDC_URB;
break;
case vISA::SFID::SPAWNER:
igaOp = (op == G4_send) ? iga::Op::SEND_TS : iga::Op::SENDC_TS;
break;
case vISA::SFID::VME:
igaOp = (op == G4_send) ? iga::Op::SEND_VME : iga::Op::SENDC_VME;
break;
case vISA::SFID::DP_CC:
igaOp = (op == G4_send) ? iga::Op::SEND_DCRO : iga::Op::SENDC_DCRO;
break;
case vISA::SFID::DP_DC:
igaOp = (op == G4_send) ? iga::Op::SEND_DC0 : iga::Op::SENDC_DC0;
break;
case vISA::SFID::DP_PI:
igaOp = (op == G4_send) ? iga::Op::SEND_PIXI : iga::Op::SENDC_PIXI;
break;
case vISA::SFID::DP_DC1:
igaOp = (op == G4_send) ? iga::Op::SEND_DC1 : iga::Op::SENDC_DC1;
break;
case vISA::SFID::CRE:
igaOp = (op == G4_send) ? iga::Op::SEND_CRE : iga::Op::SENDC_CRE;
break;
default:
ASSERT_USER(false, "Unknow SFID generated from vISA");
break;
}
return igaOp;
}
iga::Op BinaryEncodingIGA::getIGAOp(G4_opcode op, const G4_INST *inst, Platform iga_platform)
{
iga::Op igaOp = iga::Op::INVALID;
switch (op)
{
case G4_illegal:
igaOp = iga::Op::ILLEGAL;
break;
case G4_mov:
igaOp = iga::Op::MOV;
break;
case G4_sel:
igaOp = iga::Op::SEL;
break;
case G4_movi:
igaOp = iga::Op::MOVI;
break;
case G4_not:
igaOp = iga::Op::NOT;
break;
case G4_and:
igaOp = iga::Op::AND;
break;
case G4_or:
igaOp = iga::Op::OR;
break;
case G4_xor:
igaOp = iga::Op::XOR;
break;
case G4_shr:
igaOp = iga::Op::SHR;
break;
case G4_shl:
igaOp = iga::Op::SHL;
break;
case G4_smov:
igaOp = iga::Op::SMOV;
break;
case G4_asr:
igaOp = iga::Op::ASR;
break;
case G4_ror:
igaOp = iga::Op::ROR;
break;
case G4_rol:
igaOp = iga::Op::ROL;
break;
case G4_cmp:
igaOp = iga::Op::CMP;
break;
case G4_cmpn:
igaOp = iga::Op::CMPN;
break;
case G4_csel:
igaOp = iga::Op::CSEL;
break;
case G4_bfrev:
igaOp = iga::Op::BFREV;
break;
case G4_bfe:
igaOp = iga::Op::BFE;
break;
case G4_bfi1:
igaOp = iga::Op::BFI1;
break;
case G4_bfi2:
igaOp = iga::Op::BFI2;
break;
case G4_jmpi:
igaOp = iga::Op::JMPI;
break;
case G4_brd:
igaOp = iga::Op::BRD;
break;
case G4_if:
igaOp = iga::Op::IF;
break;
case G4_brc:
igaOp = iga::Op::BRC;
break;
case G4_else:
igaOp = iga::Op::ELSE;
break;
case G4_endif:
igaOp = iga::Op::ENDIF;
break;
case G4_while:
igaOp = iga::Op::WHILE;
break;
case G4_break:
igaOp = iga::Op::BREAK;
break;
case G4_cont:
igaOp = iga::Op::CONT;
break;
case G4_halt:
igaOp = iga::Op::HALT;
break;
case G4_call:
igaOp = iga::Op::CALL;
break;
case G4_return:
igaOp = iga::Op::RET;
break;
case G4_goto:
igaOp = iga::Op::GOTO;
break;
case G4_join:
igaOp = iga::Op::JOIN;
break;
case G4_wait:
if (iga_platform >= iga::Platform::GEN12P1)
{
igaOp = iga::Op::SYNC_BAR;
}
else
{
igaOp = iga::Op::WAIT;
}
break;
case G4_send:
if (iga_platform >= iga::Platform::GEN12P1)
{
igaOp = getIGAOpFromSFIDForSend(op, inst);
}
else
{
igaOp = iga::Op::SEND;
}
break;
case G4_sendc:
if (iga_platform >= iga::Platform::GEN12P1)
{
igaOp = getIGAOpFromSFIDForSend(op, inst);
}
else
{
igaOp = iga::Op::SENDC;
}
break;
case G4_sends:
if (iga_platform >= iga::Platform::GEN12P1)
{
igaOp = getIGAOpFromSFIDForSend(G4_send, inst);
}
else
{
igaOp = iga::Op::SENDS;
}
break;
case G4_sendsc:
if (iga_platform >= iga::Platform::GEN12P1)
{
igaOp = getIGAOpFromSFIDForSend(G4_sendc, inst);
}
else
{
igaOp = iga::Op::SENDSC;
}
break;
case G4_math:
igaOp = getIGAMathOp(inst);
break;
case G4_add:
igaOp = iga::Op::ADD;
break;
case G4_mul:
igaOp = iga::Op::MUL;
break;
case G4_avg:
igaOp = iga::Op::AVG;
break;
case G4_frc:
igaOp = iga::Op::FRC;
break;
case G4_rndu:
igaOp = iga::Op::RNDU;
break;
case G4_rndd:
igaOp = iga::Op::RNDD;
break;
case G4_rnde:
igaOp = iga::Op::RNDE;
break;
case G4_rndz:
igaOp = iga::Op::RNDZ;
break;
case G4_mac:
igaOp = iga::Op::MAC;
break;
case G4_mach:
igaOp = iga::Op::MACH;
break;
case G4_lzd:
igaOp = iga::Op::LZD;
break;
case G4_fbh:
igaOp = iga::Op::FBH;
break;
case G4_fbl:
igaOp = iga::Op::FBL;
break;
case G4_cbit:
igaOp = iga::Op::CBIT;
break;
case G4_addc:
igaOp = iga::Op::ADDC;
break;
case G4_subb:
igaOp = iga::Op::SUBB;
break;
case G4_sad2:
igaOp = iga::Op::SAD2;
break;
case G4_sada2:
igaOp = iga::Op::SADA2;
break;
case G4_dp4:
igaOp = iga::Op::DP4;
break;
case G4_dph:
igaOp = iga::Op::DPH;
break;
case G4_dp3:
igaOp = iga::Op::DP3;
break;
case G4_dp2:
igaOp = iga::Op::DP2;
break;
case G4_dp4a:
igaOp = iga::Op::DP4A;
break;
case G4_line:
igaOp = iga::Op::LINE;
break;
case G4_pln:
igaOp = iga::Op::PLN;
break;
case G4_mad:
igaOp = iga::Op::MAD;
break;
case G4_lrp:
igaOp = iga::Op::LRP;
break;
case G4_madm:
igaOp = iga::Op::MADM;
break;
case G4_nop:
igaOp = iga::Op::NOP;
break;
case G4_label:
break;
case G4_pseudo_mad:
igaOp = iga::Op::MAD;
break;
case G4_do:
ASSERT_USER(false, "G4_do is not GEN ISA OPCODE.");
break;
case G4_mulh:
ASSERT_USER(false, "G4_mulh is not GEN ISA OPCODE.");
break;
case G4_pseudo_and:
igaOp = iga::Op::AND;
break;
case G4_pseudo_or:
igaOp = iga::Op::OR;
break;
case G4_pseudo_xor:
igaOp = iga::Op::XOR;
break;
case G4_pseudo_not:
igaOp = iga::Op::NOT;
break;
case G4_pseudo_fcall:
igaOp = iga::Op::CALL;
break;
case G4_pseudo_fret:
igaOp = iga::Op::RET;
break;
case G4_pseudo_sada2:
igaOp = iga::Op::SADA2;
break;
case G4_pseudo_exit:
ASSERT_USER(false, "G4_pseudo_exit not GEN ISA OPCODE.");
break;
case G4_pseudo_fc_call:
igaOp = iga::Op::CALL;
break;
case G4_pseudo_fc_ret:
igaOp = iga::Op::RET;
break;
case G4_intrinsic:
ASSERT_USER(false, "G4_intrinsic not GEN ISA OPCODE.");
break;
case G4_sync_nop:
igaOp = iga::Op::SYNC_NOP;
break;
case G4_sync_allrd:
igaOp = iga::Op::SYNC_ALLRD;
break;
case G4_sync_allwr:
igaOp = iga::Op::SYNC_ALLWR;
break;
case G4_NUM_OPCODE:
ASSERT_USER(false, "G4_NUM_OPCODE not GEN ISA OPCODE.");
break;
default:
ASSERT_USER(false, "INVALID opcode.");
break;
}
return igaOp;
}
void BinaryEncodingIGA::SetSWSB(G4_INST *inst, iga::SWSB &sw)
{
// Set token, e.g. $0
if (inst->tokenHonourInstruction() && (inst->getToken() != (unsigned short)-1))
{
sw.tokenType = SWSB::TokenType::SET;
sw.sbid = inst->getToken();
}
if ((unsigned)inst->getDistance())
{
{
// there is only one pipe on single-dist-pipe platform,
// must be REG_DIST
sw.distType = SWSB::DistType::REG_DIST;
}
sw.minDist = (uint32_t)inst->getDistance();
}
// Set token dependency, e.g. $1.src
if (inst->getDepTokenNum())
{
assert(sw.tokenType != SWSB::TokenType::SET &&
"unexpect SWSB dependence type");
assert(inst->getDepTokenNum() == 1 &&
"More than one token dependence in one instruction");
using SWSBTokenType = vISA::G4_INST::SWSBTokenType;
for (int i = 0; i < (int)inst->getDepTokenNum(); i++)
{
SWSBTokenType type = SWSBTokenType::TOKEN_NONE;
uint8_t token = (uint8_t)inst->getDepToken(i, type);
if (type == SWSBTokenType::AFTER_READ)
{
sw.tokenType = SWSB::TokenType::SRC;
}
else if (type == SWSBTokenType::AFTER_WRITE)
{
sw.tokenType = SWSB::TokenType::DST;
}
sw.sbid = token;
}
}
return;
}
void BinaryEncodingIGA::getIGAFlagInfo(
G4_INST* inst, const OpSpec* opSpec, Predication& pred, FlagModifier& condMod, RegRef& flagReg)
{
G4_Predicate* predG4 = inst->getPredicate();
G4_CondMod* condModG4 = inst->getCondMod();
iga::RegRef predFlag;
bool hasPredFlag = false;
if (opSpec->supportsPredication() && predG4 != nullptr)
{
pred = getIGAPredication(predG4);
predFlag = getIGAFlagReg(predG4->getBase());
flagReg = predFlag;
hasPredFlag = true;
}
if ((opSpec->supportsFlagModifier() || opSpec->hasImplicitFlagModifier()) &&
condModG4 != nullptr)
{
condMod = getIGAFlagModifier(condModG4);
// in case for min/max sel instruction, it could have CondMod but has no flag registers
if (condModG4->getBase() != nullptr) {
flagReg = getIGAFlagReg(condModG4->getBase());
// pred and condMod Flags must be the same
assert(!hasPredFlag || predFlag == flagReg);
}
}
}
void BinaryEncodingIGA::DoAll()
{
FixInst();
Block* currBB = nullptr;
auto isFirstInstLabel = [this]()
{
for (auto bb : kernel.fg)
{
for (auto inst : *bb)
{
return inst->isLabel();
}
}
return false;
};
auto platform = kernel.fg.builder->getPlatform();
// Make the size of the first BB be multiple of 4 instructions, and do not compact
// any instructions in it, so that the size of the first BB is multiple of 64 bytes
if (kernel.fg.builder->getHasPerThreadProlog() ||
kernel.fg.builder->getHasComputeFFIDProlog())
{
G4_BB* first_bb = *kernel.fg.begin();
size_t num_inst = first_bb->getInstList().size();
assert(num_inst != 0 && "the first BB must not be empty");
// label instructions don't count. Only the first instruction could be a label
if (first_bb->getInstList().front()->isLabel())
--num_inst;
if (num_inst % 4 != 0) {
size_t num_nop = 4 - (num_inst % 4);
for (size_t i = 0; i < num_nop; ++i)
first_bb->getInstList().push_back(
kernel.fg.builder->createNop(InstOpt_NoCompact));
}
// set all instruction to be NoCompact
for (auto inst : *first_bb)
{
inst->setOptionOn(InstOpt_NoCompact);
}
}
if (!isFirstInstLabel())
{
// create a new BB if kernel does not start with label
currBB = IGAKernel->createBlock();
IGAKernel->appendBlock(currBB);
}
std::list<std::pair<Instruction*, G4_INST*>> encodedInsts;
iga::Block *bbNew = nullptr;
for (auto bb : this->kernel.fg)
{
for (auto inst : *bb)
{
bbNew = nullptr;
if (inst->isLabel())
{
// note that we create a new IGA BB per label instead of directly mapping vISA BB to IGA BB,
// as some vISA BBs can have multiple labels (e.g., multiple endifs)
G4_Label* label = inst->getLabel();
currBB = lookupIGABlock(label, *IGAKernel);
IGAKernel->appendBlock(currBB);
continue;
}
Instruction *igaInst = nullptr;
auto igaOpcode = getIGAOp(inst->opcode(), inst, platformModel->platform);
// common fields: op, predicate, flag reg, exec size, exec mask offset, mask ctrl, conditional modifier
const OpSpec* opSpec = &platformModel->lookupOpSpec(igaOpcode);
if (opSpec->op == Op::INVALID)
{
std::cerr << "INVALID opcode " << G4_Inst_Table[inst->opcode()].str << "\n";
ASSERT_USER(false, "INVALID OPCODE.");
continue;
}
Predication pred;
RegRef flagReg {0, 0};
ExecSize execSize = getIGAExecSize(inst->getExecSize());
ChannelOffset chOff = getIGAChannelOffset(inst->getMaskOffset());
MaskCtrl maskCtrl = getIGAMaskCtrl(inst->opcode() == G4_jmpi || inst->isWriteEnableInst());
FlagModifier condModifier = FlagModifier::NONE;
getIGAFlagInfo(inst, opSpec, pred, condModifier, flagReg);
if (opSpec->isBranching())
{
BranchCntrl brnchCtrl = getIGABranchCntrl(inst->asCFInst()->isBackward());
igaInst = IGAKernel->createBranchInstruction(
*opSpec,
pred,
flagReg,
execSize,
chOff,
maskCtrl,
brnchCtrl);
}
else if (opSpec->isSendOrSendsFamily())
{
SendDesc desc = getIGASendDesc(inst);
InstOptSet extraOpts; // empty set
int xlen = -1;
SendDesc exDesc = getIGASendExDesc(inst, xlen, extraOpts);
igaInst =
IGAKernel->createSendInstruction(
*opSpec,
pred,
flagReg,
execSize,
chOff,
maskCtrl,
exDesc,
desc);
igaInst->setSrc1Length(xlen);
igaInst->addInstOpts(extraOpts);
}
else if (opSpec->op == Op::NOP)
{
igaInst = IGAKernel->createNopInstruction();
}
else if (opSpec->op == Op::ILLEGAL)
{
igaInst = IGAKernel->createIllegalInstruction();
}
else
{
igaInst =
IGAKernel->createBasicInstruction(
*opSpec,
pred,
flagReg,
execSize,
chOff,
maskCtrl,
condModifier);
}
if (igaInst == nullptr)
{
ASSERT_USER(false, "Instruction is NULL");
continue;
}
igaInst->setID(IGAInstId++);
igaInst->setLoc(inst->getCISAOff()); // make IGA src off track CISA id
if (opSpec->supportsDestination())
{
assert(inst->getDst() && "dst must not be null");
G4_DstRegRegion* dst = inst->getDst();
DstModifier dstModifier = getIGADstModifier(inst->getSaturate());
Region::Horz hstride = getIGAHorz(dst->getHorzStride());
Type type = getIGAType(dst->getType());
// workaround for SKL bug
// not all bits are copied from immediate descriptor
if (inst->isSend() &&
platform >= GENX_SKL &&
platform < GENX_ICLLP)
{
G4_SendMsgDescriptor* msgDesc = inst->getMsgDesc();
G4_Operand* descOpnd = inst->isSplitSend() ? inst->getSrc(2) : inst->getSrc(1);
if (!descOpnd->isImm() && msgDesc->is16BitReturn())
{
type = Type::HF;
}
}
if (igaInst->isMacro())
{
RegRef regRef = getIGARegRef(dst);
Region::Horz hstride = getIGAHorz(dst->getHorzStride());
igaInst->setMacroDestination(
dstModifier,
getIGARegName(dst),
regRef,
getIGAImplAcc(dst->getAccRegSel()),
hstride,
type);
}
else if (dst->getRegAccess() == Direct)
{
igaInst->setDirectDestination(
dstModifier,
getIGARegName(dst),
getIGARegRef(dst),
hstride,
type);
}
else
{ // Operand::Kind::INDIRECT
RegRef regRef {0, 0};
bool valid;
regRef.subRegNum = (uint8_t) dst->ExIndSubRegNum(valid);
igaInst->setInidirectDestination(
dstModifier,
regRef,
dst->getAddrImm(),
hstride,
type);
}
} // end setting destinations
if (opSpec->isBranching() &&
igaOpcode != iga::Op::JMPI &&
igaOpcode != iga::Op::RET &&
igaOpcode != iga::Op::CALL &&
igaOpcode != iga::Op::BRC &&
igaOpcode != iga::Op::BRD)
{
if (inst->asCFInst()->getJip())
{
// encode jip/uip for branch inst
// note that it does not apply to jmpi/call/ret/brc/brd, which may have register sources. Their label
// appears directly as source operand instead.
G4_Operand* uip = inst->asCFInst()->getUip();
G4_Operand* jip = inst->asCFInst()->getJip();
//iga will take care off
if (uip)
{
igaInst->setLabelSource(SourceIndex::SRC1, lookupIGABlock(uip->asLabel(), *IGAKernel), iga::Type::UD);
}
igaInst->setLabelSource(SourceIndex::SRC0, lookupIGABlock(jip->asLabel(), *IGAKernel), iga::Type::UD);
}
else
{
//Creating a fall through block
bbNew = IGAKernel->createBlock();
igaInst->setLabelSource(SourceIndex::SRC0, bbNew, iga::Type::UD);
IGAKernel->appendBlock(bbNew);
}
}
else
{
// set source operands
int numSrcToEncode = inst->getNumSrc();
if (inst->isSend())
{
// skip desc/exdesc as they are handled separately
numSrcToEncode = inst->isSplitSend() ? 2 : 1;
if (numSrcToEncode == 1 && platformModel->platform >= Platform::GEN12P1)
{
RegRef regTemp;
regTemp.regNum = 0;
regTemp.subRegNum = 0;
Region rgnTemp;
rgnTemp.set(Region::Vert::VT_0, Region::Width::WI_1, Region::Horz::HZ_0);
igaInst->setDirectSource(
SourceIndex::SRC1,
SrcModifier::NONE,
RegName::ARF_NULL,
regTemp,
rgnTemp,
Type::INVALID);
}
}
if (platform >= GENX_ICLLP
&& inst->opcode() == G4_movi && numSrcToEncode == 1)
{
// From ICL, 'movi' becomes a binary instruction with an
// optional immediate operand, which needs encoding as null
// or imm32. So far, within vISA jitter, 'movi' is still
// modeled as unary instruction, setting src1 to null for
// platforms >= CNL.
RegRef regTemp;
regTemp.regNum = 0;
regTemp.subRegNum = 0;
Region rgnTemp;
rgnTemp.set(Region::Vert::VT_1, Region::Width::WI_1,
Region::Horz::HZ_0);
igaInst->setDirectSource(SourceIndex::SRC1,
SrcModifier::NONE,
RegName::ARF_NULL,
regTemp, rgnTemp,
Type::UB);
}
for (int i = 0; i < numSrcToEncode; i++)
{
SourceIndex opIx = (SourceIndex)((int)SourceIndex::SRC0 + i);
G4_Operand* src = inst->getSrc(i);
if (src->isSrcRegRegion())
{
G4_SrcRegRegion* srcRegion = src->asSrcRegRegion();
SrcModifier srcMod = getIGASrcModifier(srcRegion->getModifier());
Region region = getIGARegion(srcRegion, i);
Type type = Type::INVALID;
//let IGA take care of types for send/s instructions
if (!opSpec->isSendOrSendsFamily())
{
type = getIGAType(src->getType());
}
else if (i == 0 &&
platform >= GENX_SKL &&
platform < GENX_ICLLP)
{
//work around for SKL bug
//not all bits are copied from immediate descriptor
G4_SendMsgDescriptor* msgDesc = inst->getMsgDesc();
G4_Operand* descOpnd = inst->isSplitSend() ? inst->getSrc(2) : inst->getSrc(1);
if (!descOpnd->isImm() && msgDesc->is16BitInput())
{
type = Type::HF;
}
}
if (igaInst->isMacro())
{
auto accRegSel = srcRegion->isNullReg() ? NOACC : srcRegion->getAccRegSel();
RegRef regRef = getIGARegRef(srcRegion);
igaInst->setMacroSource(
opIx,
srcMod,
getIGARegName(srcRegion),
regRef,
getIGAImplAcc(accRegSel),
region,
type);
}
else if (srcRegion->getRegAccess() == Direct)
{
igaInst->setDirectSource(
opIx,
srcMod,
getIGARegName(srcRegion),
getIGARegRef(srcRegion),
region,
type);
}
else
{
RegRef regRef {0, 0};
bool valid;
regRef.subRegNum = (uint8_t)srcRegion->ExIndSubRegNum(valid);
igaInst->setInidirectSource(
opIx,
srcMod,
regRef,
srcRegion->getAddrImm(),
region,
type);
}
}
else if (src->isLabel())
{
igaInst->setLabelSource(opIx, lookupIGABlock(src->asLabel(), *IGAKernel), iga::Type::UD);
}
else if (src->isImm())
{
Type type = getIGAType(src->getType());
ImmVal val;
val = src->asImm()->getImm();
val.kind = getIGAImmType(src->getType());
igaInst->setImmediateSource(opIx, val, type);
}
else
{
IGA_ASSERT_FALSE("unexpected src kind");
}
} // for
}
igaInst->addInstOpts(getIGAInstOptSet(inst));
if (getPlatformGeneration(platform) >= PlatformGen::GEN12) {
iga::SWSB sw;
SetSWSB(inst, sw);
SWSB::InstType inst_ty = SWSB::InstType::UNKNOWN;
if (inst->isMath())
inst_ty = SWSB::InstType::MATH;
else if (inst->isSend())
inst_ty = SWSB::InstType::SEND;
else
inst_ty = SWSB::InstType::OTHERS;
// Verify if swsb is in encode-able dist and token combination
if(!sw.verify(getIGASWSBEncodeMode(*kernel.fg.builder), inst_ty))
IGA_ASSERT_FALSE("Invalid swsb dist and token combination");
igaInst->setSWSB(sw);
}
#if _DEBUG
igaInst->validate();
#endif
currBB->appendInstruction(igaInst);
if (bbNew)
{
// Fall through block is created.
// So the new block needs to become current block
// so that jump offsets can be calculated correctly
currBB = bbNew;
}
// If, in future, we generate multiple binary inst
// for a single G4_INST, then it should be safe to
// make pair between the G4_INST and first encoded
// binary inst.
encodedInsts.push_back(std::make_pair(igaInst, inst));
}
}
kernel.setAsmCount(IGAInstId);
if (m_kernelBuffer)
{
m_kernelBufferSize = 0;
delete static_cast<uint8_t*>(m_kernelBuffer);
m_kernelBuffer = nullptr;
}
//Will compact only if Compaction flag is present
startTimer(TIMER_IGA_ENCODER);
bool autoCompact = true;
if (kernel.getOption(vISA_Compaction) == false)
{
autoCompact = false;
}
KernelEncoder encoder(IGAKernel, autoCompact);
encoder.setSWSBEncodingMode(getIGASWSBEncodeMode(*kernel.fg.builder));
if (kernel.getOption(vISA_EnableIGASWSB))
{
encoder.enableIGAAutoDeps();
}
encoder.encode();
stopTimer(TIMER_IGA_ENCODER);
m_kernelBufferSize = encoder.getBinarySize();
m_kernelBuffer = allocCodeBlock(m_kernelBufferSize);
memcpy_s(m_kernelBuffer, m_kernelBufferSize, encoder.getBinary(), m_kernelBufferSize);
// encodedPC is available after encoding
for (auto&& inst : encodedInsts)
{
inst.second->setGenOffset(inst.first->getPC());
}
if (kernel.fg.builder->getHasPerThreadProlog())
{
// per thread data load is in the first BB
assert(kernel.fg.getNumBB() > 1 && "expect at least one prolog BB");
auto secondBB = *(std::next(kernel.fg.begin()));
auto iter = std::find_if(secondBB->begin(), secondBB->end(), [](G4_INST* inst) { return !inst->isLabel();});
assert(iter != secondBB->end() && "execpt at least one non-label inst in second BB");
kernel.fg.builder->getJitInfo()->offsetToSkipPerThreadDataLoad = (uint32_t)(*iter)->getGenOffset();
}
if (kernel.fg.builder->getHasComputeFFIDProlog())
{
// something weird will happen if both HasPerThreadProlog and HasComputeFFIDProlog
assert(!kernel.fg.builder->getHasPerThreadProlog());
// set offsetToSkipSetFFIDGP to the second entry's offset
// the first instruction in the second BB is the start of the sencond entry
assert(kernel.fg.getNumBB() > 1 && "expect at least one prolog BB");
auto secondBB = *(std::next(kernel.fg.begin()));
assert(!secondBB->empty() && !secondBB->front()->isLabel());
kernel.fg.builder->getJitInfo()->offsetToSkipSetFFIDGP = (uint32_t)secondBB->front()->getGenOffset();
}
}
SWSB_ENCODE_MODE BinaryEncodingIGA::getIGASWSBEncodeMode(const IR_Builder& builder) {
if (getPlatformGeneration(builder.getPlatform()) < PlatformGen::GEN12)
return SWSB_ENCODE_MODE::SWSBInvalidMode;
return SWSB_ENCODE_MODE::SingleDistPipe;
}
SendDesc BinaryEncodingIGA::getIGASendDesc(G4_INST* sendInst) const
{
SendDesc desc;
assert(sendInst->isSend() && "expect send inst");
G4_Operand* msgDesc = sendInst->isSplitSend() ? sendInst->getSrc(2) : sendInst->getSrc(1);
if (msgDesc->isImm())
{
desc.type = SendDesc::Kind::IMM;
desc.imm = (uint32_t)msgDesc->asImm()->getImm();
}
else
{
desc.type = SendDesc::Kind::REG32A;
desc.reg.regNum = 0; // must be a0
bool valid = false;
desc.reg.subRegNum = (uint8_t) msgDesc->asSrcRegRegion()->ExSubRegNum(valid);
assert(valid && "invalid subreg");
}
return desc;
}
SendDesc BinaryEncodingIGA::getIGASendExDesc(
G4_INST* sendInst, int& xlen, iga::InstOptSet& extraOpts) const
{
SendDesc exDescArg;
if (sendInst->isEOT())
extraOpts.add(InstOpt::EOT);
xlen = -1;
assert(sendInst->isSend() && "expect send inst");
if (sendInst->isSplitSend())
{
G4_Operand* exDesc = sendInst->getSrc(3);
if (exDesc->isImm())
{
G4_SendMsgDescriptor* g4SendMsg = sendInst->getMsgDesc();
xlen = (int)g4SendMsg->extMessageLength();
//
exDescArg.type = SendDesc::Kind::IMM;
uint32_t tVal = (uint32_t)exDesc->asImm()->getImm();
//We must clear the funcID in the extended message for Gen12+
//It's because the explicit encoding is applied, no mapping anymore.
//ditto for the EOT bit which is moved out of extDesc
//The extended message format
//struct ExtendedMsgDescLayout {
// uint32_t funcID : 4; // bit 0:3 << not part of ExDesc
// uint32_t unnamed1 : 1; // bit 4
// uint32_t eot : 1; // bit 5 << not part of ExDesc
// uint32_t extMsgLength : 5; // bit 6:10
// uint32_t unnamed2 : 5; // bit 11:15
// uint32_t extFuncCtrl : 16; // bit 16:31
//};
if (getPlatformGeneration(sendInst->getPlatform()) >= PlatformGen::GEN12)
{
tVal &= 0xFFFFFFC0;
}
exDescArg.imm = tVal;
}
else
{
exDescArg.type = SendDesc::Kind::REG32A;
exDescArg.reg.regNum = 0; // must be a0
bool valid = false;
exDescArg.reg.subRegNum =
(uint8_t)exDesc->asSrcRegRegion()->ExSubRegNum(valid);
assert(valid && "invalid subreg");
}
}
else // old unary packed send
{
// exDesc is stored in SendMsgDesc and must be IMM
G4_SendMsgDescriptor* sendDesc = sendInst->getMsgDesc();
assert(sendDesc != nullptr && "null msg desc");
exDescArg.type = SendDesc::Kind::IMM;
uint32_t tVal = sendDesc->getExtendedDesc();
// We must clear the funcID in the extended message
if (getPlatformGeneration(sendInst->getPlatform()) >= PlatformGen::GEN12)
{
tVal = tVal & 0xFFFFFFF0;
}
exDescArg.imm = tVal;
// non-split send implies Src1.Length == 0
xlen = 0;
}
return exDescArg;
}
void *BinaryEncodingIGA::EmitBinary(uint32_t& binarySize)
{
binarySize = m_kernelBufferSize;
if (kernel.getOption(vISA_GenerateBinary))
{
std::string binFileName = fileName + ".dat";
std::string errStr;
ofstream os(binFileName.c_str(), ios::binary);
if (!os)
{
errStr = "Can't open " + binFileName + ".\n";
MUST_BE_TRUE(0, errStr);
return nullptr;
}
os.write((const char*) m_kernelBuffer, binarySize);
}
return m_kernelBuffer;
}
| 32.400504 | 126 | 0.503278 | [
"model"
] |
1422982b6dfbe615bd87f2962b7e429b7353a738 | 364,704 | cpp | C++ | fem/fe.cpp | shahzebsiddiqui/mfem | 08b339303b11b98a1aa3db5e04369a6405d4ca5a | [
"BSD-3-Clause"
] | null | null | null | fem/fe.cpp | shahzebsiddiqui/mfem | 08b339303b11b98a1aa3db5e04369a6405d4ca5a | [
"BSD-3-Clause"
] | null | null | null | fem/fe.cpp | shahzebsiddiqui/mfem | 08b339303b11b98a1aa3db5e04369a6405d4ca5a | [
"BSD-3-Clause"
] | null | null | null | // Copyright (c) 2010-2020, Lawrence Livermore National Security, LLC. Produced
// at the Lawrence Livermore National Laboratory. All Rights reserved. See files
// LICENSE and NOTICE for details. LLNL-CODE-806117.
//
// This file is part of the MFEM library. For more information and source code
// availability visit https://mfem.org.
//
// MFEM is free software; you can redistribute it and/or modify it under the
// terms of the BSD-3 license. We welcome feedback and contributions, see file
// CONTRIBUTING.md for details.
// Finite Element classes
#include "fe.hpp"
#include "fe_coll.hpp"
#include "../mesh/nurbs.hpp"
#include "bilininteg.hpp"
#include <cmath>
namespace mfem
{
using namespace std;
FiniteElement::FiniteElement(int D, Geometry::Type G, int Do, int O, int F)
: Nodes(Do)
{
dim = D ; geom_type = G ; dof = Do ; order = O ; func_space = F;
range_type = SCALAR;
map_type = VALUE;
deriv_type = NONE;
deriv_range_type = SCALAR;
deriv_map_type = VALUE;
for (int i = 0; i < Geometry::MaxDim; i++) { orders[i] = -1; }
#ifndef MFEM_THREAD_SAFE
vshape.SetSize(dof, dim);
#endif
}
void FiniteElement::CalcVShape (
const IntegrationPoint &ip, DenseMatrix &shape) const
{
mfem_error ("FiniteElement::CalcVShape (ip, ...)\n"
" is not implemented for this class!");
}
void FiniteElement::CalcVShape (
ElementTransformation &Trans, DenseMatrix &shape) const
{
mfem_error ("FiniteElement::CalcVShape (trans, ...)\n"
" is not implemented for this class!");
}
void FiniteElement::CalcDivShape (
const IntegrationPoint &ip, Vector &divshape) const
{
mfem_error ("FiniteElement::CalcDivShape (ip, ...)\n"
" is not implemented for this class!");
}
void FiniteElement::CalcPhysDivShape(
ElementTransformation &Trans, Vector &div_shape) const
{
CalcDivShape(Trans.GetIntPoint(), div_shape);
div_shape *= (1.0 / Trans.Weight());
}
void FiniteElement::CalcCurlShape(const IntegrationPoint &ip,
DenseMatrix &curl_shape) const
{
mfem_error ("FiniteElement::CalcCurlShape (ip, ...)\n"
" is not implemented for this class!");
}
void FiniteElement::CalcPhysCurlShape(ElementTransformation &Trans,
DenseMatrix &curl_shape) const
{
switch (dim)
{
case 3:
{
#ifdef MFEM_THREAD_SAFE
DenseMatrix vshape(dof, dim);
#endif
CalcCurlShape(Trans.GetIntPoint(), vshape);
MultABt(vshape, Trans.Jacobian(), curl_shape);
curl_shape *= (1.0 / Trans.Weight());
break;
}
case 2:
// This is valid for both 2x2 and 3x2 Jacobians
CalcCurlShape(Trans.GetIntPoint(), curl_shape);
curl_shape *= (1.0 / Trans.Weight());
break;
default:
MFEM_ABORT("Invalid dimension, Dim = " << dim);
}
}
void FiniteElement::GetFaceDofs(int face, int **dofs, int *ndofs) const
{
mfem_error ("FiniteElement::GetFaceDofs (...)");
}
void FiniteElement::CalcHessian (const IntegrationPoint &ip,
DenseMatrix &h) const
{
mfem_error ("FiniteElement::CalcHessian (...) is not overloaded !");
}
void FiniteElement::GetLocalInterpolation (ElementTransformation &Trans,
DenseMatrix &I) const
{
mfem_error ("GetLocalInterpolation (...) is not overloaded !");
}
void FiniteElement::GetLocalRestriction(ElementTransformation &,
DenseMatrix &) const
{
mfem_error("FiniteElement::GetLocalRestriction() is not overloaded !");
}
void FiniteElement::GetTransferMatrix(const FiniteElement &fe,
ElementTransformation &Trans,
DenseMatrix &I) const
{
MFEM_ABORT("method is not overloaded !");
}
void FiniteElement::Project (
Coefficient &coeff, ElementTransformation &Trans, Vector &dofs) const
{
mfem_error ("FiniteElement::Project (...) is not overloaded !");
}
void FiniteElement::Project (
VectorCoefficient &vc, ElementTransformation &Trans, Vector &dofs) const
{
mfem_error ("FiniteElement::Project (...) (vector) is not overloaded !");
}
void FiniteElement::ProjectFromNodes(Vector &vc, ElementTransformation &Trans,
Vector &dofs) const
{
mfem_error ("FiniteElement::ProjectFromNodes() (vector) is not overloaded!");
}
void FiniteElement::ProjectMatrixCoefficient(
MatrixCoefficient &mc, ElementTransformation &T, Vector &dofs) const
{
mfem_error("FiniteElement::ProjectMatrixCoefficient() is not overloaded !");
}
void FiniteElement::ProjectDelta(int vertex, Vector &dofs) const
{
mfem_error("FiniteElement::ProjectDelta(...) is not implemented for "
"this element!");
}
void FiniteElement::Project(
const FiniteElement &fe, ElementTransformation &Trans, DenseMatrix &I) const
{
mfem_error("FiniteElement::Project(...) (fe version) is not implemented "
"for this element!");
}
void FiniteElement::ProjectGrad(
const FiniteElement &fe, ElementTransformation &Trans,
DenseMatrix &grad) const
{
mfem_error("FiniteElement::ProjectGrad(...) is not implemented for "
"this element!");
}
void FiniteElement::ProjectCurl(
const FiniteElement &fe, ElementTransformation &Trans,
DenseMatrix &curl) const
{
mfem_error("FiniteElement::ProjectCurl(...) is not implemented for "
"this element!");
}
void FiniteElement::ProjectDiv(
const FiniteElement &fe, ElementTransformation &Trans,
DenseMatrix &div) const
{
mfem_error("FiniteElement::ProjectDiv(...) is not implemented for "
"this element!");
}
void FiniteElement::CalcPhysShape(ElementTransformation &Trans,
Vector &shape) const
{
CalcShape(Trans.GetIntPoint(), shape);
if (map_type == INTEGRAL)
{
shape /= Trans.Weight();
}
}
void FiniteElement::CalcPhysDShape(ElementTransformation &Trans,
DenseMatrix &dshape) const
{
MFEM_ASSERT(map_type == VALUE, "");
#ifdef MFEM_THREAD_SAFE
DenseMatrix vshape(dof, dim);
#endif
CalcDShape(Trans.GetIntPoint(), vshape);
Mult(vshape, Trans.InverseJacobian(), dshape);
}
void FiniteElement::CalcPhysLaplacian(ElementTransformation &Trans,
Vector &Laplacian) const
{
MFEM_ASSERT(map_type == VALUE, "");
// Simpler routine if mapping is affine
if (Trans.Hessian().FNorm2() < 1e-20)
{
CalcPhysLinLaplacian(Trans, Laplacian);
return;
}
// Compute full Hessian first if non-affine
int size = (dim*(dim+1))/2;
DenseMatrix hess(dof, size);
CalcPhysHessian(Trans,hess);
if (dim == 3)
{
for (int nd = 0; nd < dof; nd++)
{
Laplacian[nd] = hess(nd,0) + hess(nd,4) + hess(nd,5);
}
}
else if (dim == 2)
{
for (int nd = 0; nd < dof; nd++)
{
Laplacian[nd] = hess(nd,0) + hess(nd,2);
}
}
else
{
for (int nd = 0; nd < dof; nd++)
{
Laplacian[nd] = hess(nd,0);
}
}
}
// Assume a linear mapping
void FiniteElement::CalcPhysLinLaplacian(ElementTransformation &Trans,
Vector &Laplacian) const
{
MFEM_ASSERT(map_type == VALUE, "");
int size = (dim*(dim+1))/2;
DenseMatrix hess(dof, size);
DenseMatrix Gij(dim,dim);
Vector scale(size);
CalcHessian (Trans.GetIntPoint(), hess);
MultAAt(Trans.InverseJacobian(), Gij);
if (dim == 3)
{
scale[0] = Gij(0,0);
scale[1] = 2*Gij(0,1);
scale[2] = 2*Gij(0,2);
scale[3] = 2*Gij(1,2);
scale[4] = Gij(2,2);
scale[5] = Gij(1,1);
}
else if (dim == 2)
{
scale[0] = Gij(0,0);
scale[1] = 2*Gij(0,1);
scale[2] = Gij(1,1);
}
else
{
scale[0] = Gij(0,0);
}
for (int nd = 0; nd < dof; nd++)
{
Laplacian[nd] = 0.0;
for (int ii = 0; ii < size; ii++)
{
Laplacian[nd] += hess(nd,ii)*scale[ii];
}
}
}
void FiniteElement::CalcPhysHessian(ElementTransformation &Trans,
DenseMatrix& Hessian) const
{
MFEM_ASSERT(map_type == VALUE, "");
// Roll 2-Tensors in vectors and 4-Tensor in Matrix, exploiting symmetry
Array<int> map(dim*dim);
if (dim == 3)
{
map[0] = 0;
map[1] = 1;
map[2] = 2;
map[3] = 1;
map[4] = 5;
map[5] = 3;
map[6] = 2;
map[7] = 3;
map[8] = 4;
}
else if (dim == 2)
{
map[0] = 0;
map[1] = 1;
map[2] = 1;
map[3] = 2;
}
else
{
map[0] = 0;
}
// Hessian in ref coords
int size = (dim*(dim+1))/2;
DenseMatrix hess(dof, size);
CalcHessian(Trans.GetIntPoint(), hess);
// Gradient in physical coords
if (Trans.Hessian().FNorm2() > 1e-10)
{
DenseMatrix grad(dof, dim);
CalcPhysDShape(Trans, grad);
DenseMatrix gmap(dof, size);
Mult(grad,Trans.Hessian(),gmap);
hess -= gmap;
}
// LHM
DenseMatrix lhm(size,size);
DenseMatrix invJ = Trans.Jacobian();
lhm = 0.0;
for (int i = 0; i < dim; i++)
{
for (int j = 0; j < dim; j++)
{
for (int k = 0; k < dim; k++)
{
for (int l = 0; l < dim; l++)
{
lhm(map[i*dim+j],map[k*dim+l]) += invJ(i,k)*invJ(j,l);
}
}
}
}
// Correct multiplicity
Vector mult(size);
mult = 0.0;
for (int i = 0; i < dim*dim; i++) { mult[map[i]]++; }
lhm.InvRightScaling(mult);
// Hessian in physical coords
lhm.Invert();
Mult( hess, lhm, Hessian);
}
const DofToQuad &FiniteElement::GetDofToQuad(const IntegrationRule &,
DofToQuad::Mode) const
{
mfem_error("FiniteElement::GetDofToQuad(...) is not implemented for "
"this element!");
return *dof2quad_array[0]; // suppress a warning
}
FiniteElement::~FiniteElement()
{
for (int i = 0; i < dof2quad_array.Size(); i++)
{
delete dof2quad_array[i];
}
}
void ScalarFiniteElement::NodalLocalInterpolation (
ElementTransformation &Trans, DenseMatrix &I,
const ScalarFiniteElement &fine_fe) const
{
double v[Geometry::MaxDim];
Vector vv (v, dim);
IntegrationPoint f_ip;
#ifdef MFEM_THREAD_SAFE
Vector c_shape(dof);
#endif
MFEM_ASSERT(map_type == fine_fe.GetMapType(), "");
I.SetSize(fine_fe.dof, dof);
for (int i = 0; i < fine_fe.dof; i++)
{
Trans.Transform(fine_fe.Nodes.IntPoint(i), vv);
f_ip.Set(v, dim);
CalcShape(f_ip, c_shape);
for (int j = 0; j < dof; j++)
if (fabs(I(i,j) = c_shape(j)) < 1.0e-12)
{
I(i,j) = 0.0;
}
}
if (map_type == INTEGRAL)
{
// assuming Trans is linear; this should be ok for all refinement types
Trans.SetIntPoint(&Geometries.GetCenter(geom_type));
I *= Trans.Weight();
}
}
void ScalarFiniteElement::ScalarLocalInterpolation(
ElementTransformation &Trans, DenseMatrix &I,
const ScalarFiniteElement &fine_fe) const
{
// General "interpolation", defined by L2 projection
double v[Geometry::MaxDim];
Vector vv (v, dim);
IntegrationPoint f_ip;
const int fs = fine_fe.GetDof(), cs = this->GetDof();
I.SetSize(fs, cs);
Vector fine_shape(fs), coarse_shape(cs);
DenseMatrix fine_mass(fs), fine_coarse_mass(fs, cs); // initialized with 0
const int ir_order = GetOrder() + fine_fe.GetOrder();
const IntegrationRule &ir = IntRules.Get(fine_fe.GetGeomType(), ir_order);
for (int i = 0; i < ir.GetNPoints(); i++)
{
const IntegrationPoint &ip = ir.IntPoint(i);
fine_fe.CalcShape(ip, fine_shape);
Trans.Transform(ip, vv);
f_ip.Set(v, dim);
this->CalcShape(f_ip, coarse_shape);
AddMult_a_VVt(ip.weight, fine_shape, fine_mass);
AddMult_a_VWt(ip.weight, fine_shape, coarse_shape, fine_coarse_mass);
}
DenseMatrixInverse fine_mass_inv(fine_mass);
fine_mass_inv.Mult(fine_coarse_mass, I);
if (map_type == INTEGRAL)
{
// assuming Trans is linear; this should be ok for all refinement types
Trans.SetIntPoint(&Geometries.GetCenter(geom_type));
I *= Trans.Weight();
}
}
void ScalarFiniteElement::ScalarLocalRestriction(
ElementTransformation &Trans, DenseMatrix &R,
const ScalarFiniteElement &coarse_fe) const
{
// General "restriction", defined by L2 projection
double v[Geometry::MaxDim];
Vector vv (v, dim);
IntegrationPoint f_ip;
const int cs = coarse_fe.GetDof(), fs = this->GetDof();
R.SetSize(cs, fs);
Vector fine_shape(fs), coarse_shape(cs);
DenseMatrix coarse_mass(cs), coarse_fine_mass(cs, fs); // initialized with 0
const int ir_order = GetOrder() + coarse_fe.GetOrder();
const IntegrationRule &ir = IntRules.Get(coarse_fe.GetGeomType(), ir_order);
for (int i = 0; i < ir.GetNPoints(); i++)
{
const IntegrationPoint &ip = ir.IntPoint(i);
this->CalcShape(ip, fine_shape);
Trans.Transform(ip, vv);
f_ip.Set(v, dim);
coarse_fe.CalcShape(f_ip, coarse_shape);
AddMult_a_VVt(ip.weight, coarse_shape, coarse_mass);
AddMult_a_VWt(ip.weight, coarse_shape, fine_shape, coarse_fine_mass);
}
DenseMatrixInverse coarse_mass_inv(coarse_mass);
coarse_mass_inv.Mult(coarse_fine_mass, R);
if (map_type == INTEGRAL)
{
// assuming Trans is linear; this should be ok for all refinement types
Trans.SetIntPoint(&Geometries.GetCenter(geom_type));
R *= 1.0 / Trans.Weight();
}
}
const DofToQuad &ScalarFiniteElement::GetDofToQuad(const IntegrationRule &ir,
DofToQuad::Mode mode) const
{
MFEM_VERIFY(mode == DofToQuad::FULL, "invalid mode requested");
for (int i = 0; i < dof2quad_array.Size(); i++)
{
const DofToQuad &d2q = *dof2quad_array[i];
if (d2q.IntRule == &ir && d2q.mode == mode) { return d2q; }
}
DofToQuad *d2q = new DofToQuad;
const int nqpt = ir.GetNPoints();
d2q->FE = this;
d2q->IntRule = &ir;
d2q->mode = mode;
d2q->ndof = dof;
d2q->nqpt = nqpt;
d2q->B.SetSize(nqpt*dof);
d2q->Bt.SetSize(dof*nqpt);
d2q->G.SetSize(nqpt*dim*dof);
d2q->Gt.SetSize(dof*nqpt*dim);
#ifdef MFEM_THREAD_SAFE
Vector c_shape(dof);
DenseMatrix vshape(dof, dim);
#endif
for (int i = 0; i < nqpt; i++)
{
const IntegrationPoint &ip = ir.IntPoint(i);
CalcShape(ip, c_shape);
for (int j = 0; j < dof; j++)
{
d2q->B[i+nqpt*j] = d2q->Bt[j+dof*i] = c_shape(j);
}
CalcDShape(ip, vshape);
for (int d = 0; d < dim; d++)
{
for (int j = 0; j < dof; j++)
{
d2q->G[i+nqpt*(d+dim*j)] = d2q->Gt[j+dof*(i+nqpt*d)] = vshape(j,d);
}
}
}
dof2quad_array.Append(d2q);
return *d2q;
}
// protected method
const DofToQuad &ScalarFiniteElement::GetTensorDofToQuad(
const TensorBasisElement &tb,
const IntegrationRule &ir, DofToQuad::Mode mode) const
{
MFEM_VERIFY(mode == DofToQuad::TENSOR, "invalid mode requested");
for (int i = 0; i < dof2quad_array.Size(); i++)
{
const DofToQuad &d2q = *dof2quad_array[i];
if (d2q.IntRule == &ir && d2q.mode == mode) { return d2q; }
}
DofToQuad *d2q = new DofToQuad;
const Poly_1D::Basis &basis_1d = tb.GetBasis1D();
const int ndof = order + 1;
const int nqpt = (int)floor(pow(ir.GetNPoints(), 1.0/dim) + 0.5);
d2q->FE = this;
d2q->IntRule = &ir;
d2q->mode = mode;
d2q->ndof = ndof;
d2q->nqpt = nqpt;
d2q->B.SetSize(nqpt*ndof);
d2q->Bt.SetSize(ndof*nqpt);
d2q->G.SetSize(nqpt*ndof);
d2q->Gt.SetSize(ndof*nqpt);
Vector val(ndof), grad(ndof);
for (int i = 0; i < nqpt; i++)
{
// The first 'nqpt' points in 'ir' have the same x-coordinates as those
// of the 1D rule.
basis_1d.Eval(ir.IntPoint(i).x, val, grad);
for (int j = 0; j < ndof; j++)
{
d2q->B[i+nqpt*j] = d2q->Bt[j+ndof*i] = val(j);
d2q->G[i+nqpt*j] = d2q->Gt[j+ndof*i] = grad(j);
}
}
dof2quad_array.Append(d2q);
return *d2q;
}
void NodalFiniteElement::ProjectCurl_2D(
const FiniteElement &fe, ElementTransformation &Trans,
DenseMatrix &curl) const
{
DenseMatrix curl_shape(fe.GetDof(), 1);
curl.SetSize(dof, fe.GetDof());
for (int i = 0; i < dof; i++)
{
fe.CalcCurlShape(Nodes.IntPoint(i), curl_shape);
double w = 1.0;
if (GetMapType() == FiniteElement::VALUE)
{
Trans.SetIntPoint(&Nodes.IntPoint(i));
w /= Trans.Weight();
}
for (int j = 0; j < fe.GetDof(); j++)
{
curl(i,j) = w * curl_shape(j,0);
}
}
}
void InvertLinearTrans(ElementTransformation &trans,
const IntegrationPoint &pt, Vector &x)
{
// invert a linear transform with one Newton step
IntegrationPoint p0;
p0.Set3(0, 0, 0);
trans.Transform(p0, x);
double store[3];
Vector v(store, x.Size());
pt.Get(v, x.Size());
v -= x;
trans.InverseJacobian().Mult(v, x);
}
void NodalFiniteElement::GetLocalRestriction(ElementTransformation &Trans,
DenseMatrix &R) const
{
IntegrationPoint ipt;
Vector pt(&ipt.x, dim);
#ifdef MFEM_THREAD_SAFE
Vector c_shape(dof);
#endif
Trans.SetIntPoint(&Nodes[0]);
for (int j = 0; j < dof; j++)
{
InvertLinearTrans(Trans, Nodes[j], pt);
if (Geometries.CheckPoint(geom_type, ipt)) // do we need an epsilon here?
{
CalcShape(ipt, c_shape);
R.SetRow(j, c_shape);
}
else
{
// Set the whole row to avoid valgrind warnings in R.Threshold().
R.SetRow(j, infinity());
}
}
R.Threshold(1e-12);
}
void NodalFiniteElement::Project (
Coefficient &coeff, ElementTransformation &Trans, Vector &dofs) const
{
for (int i = 0; i < dof; i++)
{
const IntegrationPoint &ip = Nodes.IntPoint(i);
// some coefficients expect that Trans.IntPoint is the same
// as the second argument of Eval
Trans.SetIntPoint(&ip);
dofs(i) = coeff.Eval (Trans, ip);
if (map_type == INTEGRAL)
{
dofs(i) *= Trans.Weight();
}
}
}
void NodalFiniteElement::Project (
VectorCoefficient &vc, ElementTransformation &Trans, Vector &dofs) const
{
MFEM_ASSERT(dofs.Size() == vc.GetVDim()*dof, "");
Vector x(vc.GetVDim());
for (int i = 0; i < dof; i++)
{
const IntegrationPoint &ip = Nodes.IntPoint(i);
Trans.SetIntPoint(&ip);
vc.Eval (x, Trans, ip);
if (map_type == INTEGRAL)
{
x *= Trans.Weight();
}
for (int j = 0; j < x.Size(); j++)
{
dofs(dof*j+i) = x(j);
}
}
}
void NodalFiniteElement::ProjectMatrixCoefficient(
MatrixCoefficient &mc, ElementTransformation &T, Vector &dofs) const
{
// (mc.height x mc.width) @ DOFs -> (dof x mc.width x mc.height) in dofs
MFEM_ASSERT(dofs.Size() == mc.GetHeight()*mc.GetWidth()*dof, "");
DenseMatrix MQ(mc.GetHeight(), mc.GetWidth());
for (int k = 0; k < dof; k++)
{
T.SetIntPoint(&Nodes.IntPoint(k));
mc.Eval(MQ, T, Nodes.IntPoint(k));
if (map_type == INTEGRAL) { MQ *= T.Weight(); }
for (int r = 0; r < MQ.Height(); r++)
{
for (int d = 0; d < MQ.Width(); d++)
{
dofs(k+dof*(d+MQ.Width()*r)) = MQ(r,d);
}
}
}
}
void NodalFiniteElement::Project(
const FiniteElement &fe, ElementTransformation &Trans, DenseMatrix &I) const
{
if (fe.GetRangeType() == SCALAR)
{
Vector shape(fe.GetDof());
I.SetSize(dof, fe.GetDof());
if (map_type == fe.GetMapType())
{
for (int k = 0; k < dof; k++)
{
fe.CalcShape(Nodes.IntPoint(k), shape);
for (int j = 0; j < shape.Size(); j++)
{
I(k,j) = (fabs(shape(j)) < 1e-12) ? 0.0 : shape(j);
}
}
}
else
{
for (int k = 0; k < dof; k++)
{
Trans.SetIntPoint(&Nodes.IntPoint(k));
fe.CalcPhysShape(Trans, shape);
if (map_type == INTEGRAL)
{
shape *= Trans.Weight();
}
for (int j = 0; j < shape.Size(); j++)
{
I(k,j) = (fabs(shape(j)) < 1e-12) ? 0.0 : shape(j);
}
}
}
}
else
{
DenseMatrix vshape(fe.GetDof(), Trans.GetSpaceDim());
I.SetSize(vshape.Width()*dof, fe.GetDof());
for (int k = 0; k < dof; k++)
{
Trans.SetIntPoint(&Nodes.IntPoint(k));
fe.CalcVShape(Trans, vshape);
if (map_type == INTEGRAL)
{
vshape *= Trans.Weight();
}
for (int j = 0; j < vshape.Height(); j++)
for (int d = 0; d < vshape.Width(); d++)
{
I(k+d*dof,j) = vshape(j,d);
}
}
}
}
void NodalFiniteElement::ProjectGrad(
const FiniteElement &fe, ElementTransformation &Trans,
DenseMatrix &grad) const
{
MFEM_ASSERT(fe.GetMapType() == VALUE, "");
MFEM_ASSERT(Trans.GetSpaceDim() == dim, "")
DenseMatrix dshape(fe.GetDof(), dim), grad_k(fe.GetDof(), dim), Jinv(dim);
grad.SetSize(dim*dof, fe.GetDof());
for (int k = 0; k < dof; k++)
{
const IntegrationPoint &ip = Nodes.IntPoint(k);
fe.CalcDShape(ip, dshape);
Trans.SetIntPoint(&ip);
CalcInverse(Trans.Jacobian(), Jinv);
Mult(dshape, Jinv, grad_k);
if (map_type == INTEGRAL)
{
grad_k *= Trans.Weight();
}
for (int j = 0; j < grad_k.Height(); j++)
for (int d = 0; d < dim; d++)
{
grad(k+d*dof,j) = grad_k(j,d);
}
}
}
void NodalFiniteElement::ProjectDiv(
const FiniteElement &fe, ElementTransformation &Trans,
DenseMatrix &div) const
{
double detJ;
Vector div_shape(fe.GetDof());
div.SetSize(dof, fe.GetDof());
for (int k = 0; k < dof; k++)
{
const IntegrationPoint &ip = Nodes.IntPoint(k);
fe.CalcDivShape(ip, div_shape);
if (map_type == VALUE)
{
Trans.SetIntPoint(&ip);
detJ = Trans.Weight();
for (int j = 0; j < div_shape.Size(); j++)
{
div(k,j) = (fabs(div_shape(j)) < 1e-12) ? 0.0 : div_shape(j)/detJ;
}
}
else
{
for (int j = 0; j < div_shape.Size(); j++)
{
div(k,j) = (fabs(div_shape(j)) < 1e-12) ? 0.0 : div_shape(j);
}
}
}
}
void PositiveFiniteElement::Project(
Coefficient &coeff, ElementTransformation &Trans, Vector &dofs) const
{
for (int i = 0; i < dof; i++)
{
const IntegrationPoint &ip = Nodes.IntPoint(i);
Trans.SetIntPoint(&ip);
dofs(i) = coeff.Eval(Trans, ip);
}
}
void PositiveFiniteElement::Project(
VectorCoefficient &vc, ElementTransformation &Trans, Vector &dofs) const
{
MFEM_ASSERT(dofs.Size() == vc.GetVDim()*dof, "");
Vector x(vc.GetVDim());
for (int i = 0; i < dof; i++)
{
const IntegrationPoint &ip = Nodes.IntPoint(i);
Trans.SetIntPoint(&ip);
vc.Eval (x, Trans, ip);
for (int j = 0; j < x.Size(); j++)
{
dofs(dof*j+i) = x(j);
}
}
}
void PositiveFiniteElement::Project(
const FiniteElement &fe, ElementTransformation &Trans, DenseMatrix &I) const
{
const NodalFiniteElement *nfe =
dynamic_cast<const NodalFiniteElement *>(&fe);
if (nfe && dof == nfe->GetDof())
{
nfe->Project(*this, Trans, I);
I.Invert();
}
else
{
// local L2 projection
DenseMatrix pos_mass, mixed_mass;
MassIntegrator mass_integ;
mass_integ.AssembleElementMatrix(*this, Trans, pos_mass);
mass_integ.AssembleElementMatrix2(fe, *this, Trans, mixed_mass);
DenseMatrixInverse pos_mass_inv(pos_mass);
I.SetSize(dof, fe.GetDof());
pos_mass_inv.Mult(mixed_mass, I);
}
}
void VectorFiniteElement::CalcShape (
const IntegrationPoint &ip, Vector &shape ) const
{
mfem_error ("Error: Cannot use scalar CalcShape(...) function with\n"
" VectorFiniteElements!");
}
void VectorFiniteElement::CalcDShape (
const IntegrationPoint &ip, DenseMatrix &dshape ) const
{
mfem_error ("Error: Cannot use scalar CalcDShape(...) function with\n"
" VectorFiniteElements!");
}
void VectorFiniteElement::SetDerivMembers()
{
switch (map_type)
{
case H_DIV:
deriv_type = DIV;
deriv_range_type = SCALAR;
deriv_map_type = INTEGRAL;
break;
case H_CURL:
switch (dim)
{
case 3: // curl: 3D H_CURL -> 3D H_DIV
deriv_type = CURL;
deriv_range_type = VECTOR;
deriv_map_type = H_DIV;
break;
case 2:
// curl: 2D H_CURL -> INTEGRAL
deriv_type = CURL;
deriv_range_type = SCALAR;
deriv_map_type = INTEGRAL;
break;
case 1:
deriv_type = NONE;
deriv_range_type = SCALAR;
deriv_map_type = INTEGRAL;
break;
default:
MFEM_ABORT("Invalid dimension, Dim = " << dim);
}
break;
default:
MFEM_ABORT("Invalid MapType = " << map_type);
}
}
void VectorFiniteElement::CalcVShape_RT (
ElementTransformation &Trans, DenseMatrix &shape) const
{
MFEM_ASSERT(map_type == H_DIV, "");
#ifdef MFEM_THREAD_SAFE
DenseMatrix vshape(dof, dim);
#endif
CalcVShape(Trans.GetIntPoint(), vshape);
MultABt(vshape, Trans.Jacobian(), shape);
shape *= (1.0 / Trans.Weight());
}
void VectorFiniteElement::CalcVShape_ND (
ElementTransformation &Trans, DenseMatrix &shape) const
{
MFEM_ASSERT(map_type == H_CURL, "");
#ifdef MFEM_THREAD_SAFE
DenseMatrix vshape(dof, dim);
#endif
CalcVShape(Trans.GetIntPoint(), vshape);
Mult(vshape, Trans.InverseJacobian(), shape);
}
void VectorFiniteElement::Project_RT(
const double *nk, const Array<int> &d2n,
VectorCoefficient &vc, ElementTransformation &Trans, Vector &dofs) const
{
double vk[Geometry::MaxDim];
const int sdim = Trans.GetSpaceDim();
MFEM_ASSERT(vc.GetVDim() == sdim, "");
Vector xk(vk, sdim);
const bool square_J = (dim == sdim);
for (int k = 0; k < dof; k++)
{
Trans.SetIntPoint(&Nodes.IntPoint(k));
vc.Eval(xk, Trans, Nodes.IntPoint(k));
// dof_k = nk^t adj(J) xk
dofs(k) = Trans.AdjugateJacobian().InnerProduct(vk, nk + d2n[k]*dim);
if (!square_J) { dofs(k) /= Trans.Weight(); }
}
}
void VectorFiniteElement::Project_RT(
const double *nk, const Array<int> &d2n,
Vector &vc, ElementTransformation &Trans, Vector &dofs) const
{
const int sdim = Trans.GetSpaceDim();
const bool square_J = (dim == sdim);
for (int k = 0; k < dof; k++)
{
Trans.SetIntPoint(&Nodes.IntPoint(k));
// dof_k = nk^t adj(J) xk
Vector vk(vc.GetData()+k*sdim, sdim);
dofs(k) = Trans.AdjugateJacobian().InnerProduct(vk, nk + d2n[k]*dim);
if (!square_J) { dofs(k) /= Trans.Weight(); }
}
}
void VectorFiniteElement::ProjectMatrixCoefficient_RT(
const double *nk, const Array<int> &d2n,
MatrixCoefficient &mc, ElementTransformation &T, Vector &dofs) const
{
// project the rows of the matrix coefficient in an RT space
const int sdim = T.GetSpaceDim();
MFEM_ASSERT(mc.GetWidth() == sdim, "");
const bool square_J = (dim == sdim);
DenseMatrix MQ(mc.GetHeight(), mc.GetWidth());
Vector nk_phys(sdim), dofs_k(MQ.Height());
MFEM_ASSERT(dofs.Size() == dof*MQ.Height(), "");
for (int k = 0; k < dof; k++)
{
T.SetIntPoint(&Nodes.IntPoint(k));
mc.Eval(MQ, T, Nodes.IntPoint(k));
// nk_phys = adj(J)^t nk
T.AdjugateJacobian().MultTranspose(nk + d2n[k]*dim, nk_phys);
if (!square_J) { nk_phys /= T.Weight(); }
MQ.Mult(nk_phys, dofs_k);
for (int r = 0; r < MQ.Height(); r++)
{
dofs(k+dof*r) = dofs_k(r);
}
}
}
void VectorFiniteElement::Project_RT(
const double *nk, const Array<int> &d2n, const FiniteElement &fe,
ElementTransformation &Trans, DenseMatrix &I) const
{
if (fe.GetRangeType() == SCALAR)
{
double vk[Geometry::MaxDim];
Vector shape(fe.GetDof());
int sdim = Trans.GetSpaceDim();
I.SetSize(dof, sdim*fe.GetDof());
for (int k = 0; k < dof; k++)
{
const IntegrationPoint &ip = Nodes.IntPoint(k);
fe.CalcShape(ip, shape);
Trans.SetIntPoint(&ip);
// Transform RT face normals from reference to physical space
// vk = adj(J)^T nk
Trans.AdjugateJacobian().MultTranspose(nk + d2n[k]*dim, vk);
if (fe.GetMapType() == INTEGRAL)
{
double w = 1.0/Trans.Weight();
for (int d = 0; d < dim; d++)
{
vk[d] *= w;
}
}
for (int j = 0; j < shape.Size(); j++)
{
double s = shape(j);
if (fabs(s) < 1e-12)
{
s = 0.0;
}
// Project scalar basis function multiplied by each coordinate
// direction onto the transformed face normals
for (int d = 0; d < sdim; d++)
{
I(k,j+d*shape.Size()) = s*vk[d];
}
}
}
}
else
{
int sdim = Trans.GetSpaceDim();
double vk[Geometry::MaxDim];
DenseMatrix vshape(fe.GetDof(), sdim);
Vector vshapenk(fe.GetDof());
const bool square_J = (dim == sdim);
I.SetSize(dof, fe.GetDof());
for (int k = 0; k < dof; k++)
{
const IntegrationPoint &ip = Nodes.IntPoint(k);
Trans.SetIntPoint(&ip);
// Transform RT face normals from reference to physical space
// vk = adj(J)^T nk
Trans.AdjugateJacobian().MultTranspose(nk + d2n[k]*dim, vk);
// Compute fe basis functions in physical space
fe.CalcVShape(Trans, vshape);
// Project fe basis functions onto transformed face normals
vshape.Mult(vk, vshapenk);
if (!square_J) { vshapenk /= Trans.Weight(); }
for (int j=0; j<vshapenk.Size(); j++)
{
I(k,j) = vshapenk(j);
}
}
}
}
void VectorFiniteElement::ProjectGrad_RT(
const double *nk, const Array<int> &d2n, const FiniteElement &fe,
ElementTransformation &Trans, DenseMatrix &grad) const
{
if (dim != 2)
{
mfem_error("VectorFiniteElement::ProjectGrad_RT works only in 2D!");
}
DenseMatrix dshape(fe.GetDof(), fe.GetDim());
Vector grad_k(fe.GetDof());
double tk[2];
grad.SetSize(dof, fe.GetDof());
for (int k = 0; k < dof; k++)
{
fe.CalcDShape(Nodes.IntPoint(k), dshape);
tk[0] = nk[d2n[k]*dim+1];
tk[1] = -nk[d2n[k]*dim];
dshape.Mult(tk, grad_k);
for (int j = 0; j < grad_k.Size(); j++)
{
grad(k,j) = (fabs(grad_k(j)) < 1e-12) ? 0.0 : grad_k(j);
}
}
}
void VectorFiniteElement::ProjectCurl_ND(
const double *tk, const Array<int> &d2t, const FiniteElement &fe,
ElementTransformation &Trans, DenseMatrix &curl) const
{
#ifdef MFEM_THREAD_SAFE
DenseMatrix curlshape(fe.GetDof(), dim);
DenseMatrix curlshape_J(fe.GetDof(), dim);
DenseMatrix J(dim, dim);
#else
curlshape.SetSize(fe.GetDof(), dim);
curlshape_J.SetSize(fe.GetDof(), dim);
J.SetSize(dim, dim);
#endif
Vector curl_k(fe.GetDof());
curl.SetSize(dof, fe.GetDof());
for (int k = 0; k < dof; k++)
{
const IntegrationPoint &ip = Nodes.IntPoint(k);
// calculate J^t * J / |J|
Trans.SetIntPoint(&ip);
MultAtB(Trans.Jacobian(), Trans.Jacobian(), J);
J *= 1.0 / Trans.Weight();
// transform curl of shapes (rows) by J^t * J / |J|
fe.CalcCurlShape(ip, curlshape);
Mult(curlshape, J, curlshape_J);
curlshape_J.Mult(tk + d2t[k]*dim, curl_k);
for (int j = 0; j < curl_k.Size(); j++)
{
curl(k,j) = (fabs(curl_k(j)) < 1e-12) ? 0.0 : curl_k(j);
}
}
}
void VectorFiniteElement::ProjectCurl_RT(
const double *nk, const Array<int> &d2n, const FiniteElement &fe,
ElementTransformation &Trans, DenseMatrix &curl) const
{
DenseMatrix curl_shape(fe.GetDof(), dim);
Vector curl_k(fe.GetDof());
curl.SetSize(dof, fe.GetDof());
for (int k = 0; k < dof; k++)
{
fe.CalcCurlShape(Nodes.IntPoint(k), curl_shape);
curl_shape.Mult(nk + d2n[k]*dim, curl_k);
for (int j = 0; j < curl_k.Size(); j++)
{
curl(k,j) = (fabs(curl_k(j)) < 1e-12) ? 0.0 : curl_k(j);
}
}
}
void VectorFiniteElement::Project_ND(
const double *tk, const Array<int> &d2t,
VectorCoefficient &vc, ElementTransformation &Trans, Vector &dofs) const
{
double vk[Geometry::MaxDim];
Vector xk(vk, vc.GetVDim());
for (int k = 0; k < dof; k++)
{
Trans.SetIntPoint(&Nodes.IntPoint(k));
vc.Eval(xk, Trans, Nodes.IntPoint(k));
// dof_k = xk^t J tk
dofs(k) = Trans.Jacobian().InnerProduct(tk + d2t[k]*dim, vk);
}
}
void VectorFiniteElement::Project_ND(
const double *tk, const Array<int> &d2t,
Vector &vc, ElementTransformation &Trans, Vector &dofs) const
{
for (int k = 0; k < dof; k++)
{
Trans.SetIntPoint(&Nodes.IntPoint(k));
Vector vk(vc.GetData()+k*dim, dim);
// dof_k = xk^t J tk
dofs(k) = Trans.Jacobian().InnerProduct(tk + d2t[k]*dim, vk);
}
}
void VectorFiniteElement::ProjectMatrixCoefficient_ND(
const double *tk, const Array<int> &d2t,
MatrixCoefficient &mc, ElementTransformation &T, Vector &dofs) const
{
// project the rows of the matrix coefficient in an ND space
const int sdim = T.GetSpaceDim();
MFEM_ASSERT(mc.GetWidth() == sdim, "");
DenseMatrix MQ(mc.GetHeight(), mc.GetWidth());
Vector tk_phys(sdim), dofs_k(MQ.Height());
MFEM_ASSERT(dofs.Size() == dof*MQ.Height(), "");
for (int k = 0; k < dof; k++)
{
T.SetIntPoint(&Nodes.IntPoint(k));
mc.Eval(MQ, T, Nodes.IntPoint(k));
// tk_phys = J tk
T.Jacobian().Mult(tk + d2t[k]*dim, tk_phys);
MQ.Mult(tk_phys, dofs_k);
for (int r = 0; r < MQ.Height(); r++)
{
dofs(k+dof*r) = dofs_k(r);
}
}
}
void VectorFiniteElement::Project_ND(
const double *tk, const Array<int> &d2t, const FiniteElement &fe,
ElementTransformation &Trans, DenseMatrix &I) const
{
if (fe.GetRangeType() == SCALAR)
{
int sdim = Trans.GetSpaceDim();
double vk[Geometry::MaxDim];
Vector shape(fe.GetDof());
I.SetSize(dof, sdim*fe.GetDof());
for (int k = 0; k < dof; k++)
{
const IntegrationPoint &ip = Nodes.IntPoint(k);
fe.CalcShape(ip, shape);
Trans.SetIntPoint(&ip);
// Transform ND edge tengents from reference to physical space
// vk = J tk
Trans.Jacobian().Mult(tk + d2t[k]*dim, vk);
if (fe.GetMapType() == INTEGRAL)
{
double w = 1.0/Trans.Weight();
for (int d = 0; d < sdim; d++)
{
vk[d] *= w;
}
}
for (int j = 0; j < shape.Size(); j++)
{
double s = shape(j);
if (fabs(s) < 1e-12)
{
s = 0.0;
}
// Project scalar basis function multiplied by each coordinate
// direction onto the transformed edge tangents
for (int d = 0; d < sdim; d++)
{
I(k, j + d*shape.Size()) = s*vk[d];
}
}
}
}
else
{
int sdim = Trans.GetSpaceDim();
double vk[Geometry::MaxDim];
DenseMatrix vshape(fe.GetDof(), sdim);
Vector vshapetk(fe.GetDof());
I.SetSize(dof, fe.GetDof());
for (int k = 0; k < dof; k++)
{
const IntegrationPoint &ip = Nodes.IntPoint(k);
Trans.SetIntPoint(&ip);
// Transform ND edge tangents from reference to physical space
// vk = J tk
Trans.Jacobian().Mult(tk + d2t[k]*dim, vk);
// Compute fe basis functions in physical space
fe.CalcVShape(Trans, vshape);
// Project fe basis functions onto transformed edge tangents
vshape.Mult(vk, vshapetk);
for (int j=0; j<vshapetk.Size(); j++)
{
I(k, j) = vshapetk(j);
}
}
}
}
void VectorFiniteElement::ProjectGrad_ND(
const double *tk, const Array<int> &d2t, const FiniteElement &fe,
ElementTransformation &Trans, DenseMatrix &grad) const
{
MFEM_ASSERT(fe.GetMapType() == VALUE, "");
DenseMatrix dshape(fe.GetDof(), fe.GetDim());
Vector grad_k(fe.GetDof());
grad.SetSize(dof, fe.GetDof());
for (int k = 0; k < dof; k++)
{
fe.CalcDShape(Nodes.IntPoint(k), dshape);
dshape.Mult(tk + d2t[k]*dim, grad_k);
for (int j = 0; j < grad_k.Size(); j++)
{
grad(k,j) = (fabs(grad_k(j)) < 1e-12) ? 0.0 : grad_k(j);
}
}
}
void VectorFiniteElement::LocalInterpolation_RT(
const VectorFiniteElement &cfe, const double *nk, const Array<int> &d2n,
ElementTransformation &Trans, DenseMatrix &I) const
{
MFEM_ASSERT(map_type == cfe.GetMapType(), "");
double vk[Geometry::MaxDim];
Vector xk(vk, dim);
IntegrationPoint ip;
#ifdef MFEM_THREAD_SAFE
DenseMatrix vshape(cfe.GetDof(), cfe.GetDim());
#else
DenseMatrix vshape(cfe.vshape.Data(), cfe.GetDof(), cfe.GetDim());
#endif
I.SetSize(dof, vshape.Height());
// assuming Trans is linear; this should be ok for all refinement types
Trans.SetIntPoint(&Geometries.GetCenter(geom_type));
const DenseMatrix &adjJ = Trans.AdjugateJacobian();
for (int k = 0; k < dof; k++)
{
Trans.Transform(Nodes.IntPoint(k), xk);
ip.Set3(vk);
cfe.CalcVShape(ip, vshape);
// xk = |J| J^{-t} n_k
adjJ.MultTranspose(nk + d2n[k]*dim, vk);
// I_k = vshape_k.adj(J)^t.n_k, k=1,...,dof
for (int j = 0; j < vshape.Height(); j++)
{
double Ikj = 0.;
for (int i = 0; i < dim; i++)
{
Ikj += vshape(j, i) * vk[i];
}
I(k, j) = (fabs(Ikj) < 1e-12) ? 0.0 : Ikj;
}
}
}
void VectorFiniteElement::LocalInterpolation_ND(
const VectorFiniteElement &cfe, const double *tk, const Array<int> &d2t,
ElementTransformation &Trans, DenseMatrix &I) const
{
double vk[Geometry::MaxDim];
Vector xk(vk, dim);
IntegrationPoint ip;
#ifdef MFEM_THREAD_SAFE
DenseMatrix vshape(cfe.GetDof(), cfe.GetDim());
#else
DenseMatrix vshape(cfe.vshape.Data(), cfe.GetDof(), cfe.GetDim());
#endif
I.SetSize(dof, vshape.Height());
// assuming Trans is linear; this should be ok for all refinement types
Trans.SetIntPoint(&Geometries.GetCenter(geom_type));
const DenseMatrix &J = Trans.Jacobian();
for (int k = 0; k < dof; k++)
{
Trans.Transform(Nodes.IntPoint(k), xk);
ip.Set3(vk);
cfe.CalcVShape(ip, vshape);
// xk = J t_k
J.Mult(tk + d2t[k]*dim, vk);
// I_k = vshape_k.J.t_k, k=1,...,Dof
for (int j = 0; j < vshape.Height(); j++)
{
double Ikj = 0.;
for (int i = 0; i < dim; i++)
{
Ikj += vshape(j, i) * vk[i];
}
I(k, j) = (fabs(Ikj) < 1e-12) ? 0.0 : Ikj;
}
}
}
void VectorFiniteElement::LocalRestriction_RT(
const double *nk, const Array<int> &d2n, ElementTransformation &Trans,
DenseMatrix &R) const
{
double pt_data[Geometry::MaxDim];
IntegrationPoint ip;
Vector pt(pt_data, dim);
#ifdef MFEM_THREAD_SAFE
DenseMatrix vshape(dof, dim);
#endif
Trans.SetIntPoint(&Geometries.GetCenter(geom_type));
const DenseMatrix &J = Trans.Jacobian();
const double weight = Trans.Weight();
for (int j = 0; j < dof; j++)
{
InvertLinearTrans(Trans, Nodes.IntPoint(j), pt);
ip.Set(pt_data, dim);
if (Geometries.CheckPoint(geom_type, ip)) // do we need an epsilon here?
{
CalcVShape(ip, vshape);
J.MultTranspose(nk+dim*d2n[j], pt_data);
pt /= weight;
for (int k = 0; k < dof; k++)
{
double R_jk = 0.0;
for (int d = 0; d < dim; d++)
{
R_jk += vshape(k,d)*pt_data[d];
}
R(j,k) = R_jk;
}
}
else
{
// Set the whole row to avoid valgrind warnings in R.Threshold().
R.SetRow(j, infinity());
}
}
R.Threshold(1e-12);
}
void VectorFiniteElement::LocalRestriction_ND(
const double *tk, const Array<int> &d2t, ElementTransformation &Trans,
DenseMatrix &R) const
{
double pt_data[Geometry::MaxDim];
IntegrationPoint ip;
Vector pt(pt_data, dim);
#ifdef MFEM_THREAD_SAFE
DenseMatrix vshape(dof, dim);
#endif
Trans.SetIntPoint(&Geometries.GetCenter(geom_type));
const DenseMatrix &Jinv = Trans.InverseJacobian();
for (int j = 0; j < dof; j++)
{
InvertLinearTrans(Trans, Nodes.IntPoint(j), pt);
ip.Set(pt_data, dim);
if (Geometries.CheckPoint(geom_type, ip)) // do we need an epsilon here?
{
CalcVShape(ip, vshape);
Jinv.Mult(tk+dim*d2t[j], pt_data);
for (int k = 0; k < dof; k++)
{
double R_jk = 0.0;
for (int d = 0; d < dim; d++)
{
R_jk += vshape(k,d)*pt_data[d];
}
R(j,k) = R_jk;
}
}
else
{
// Set the whole row to avoid valgrind warnings in R.Threshold().
R.SetRow(j, infinity());
}
}
R.Threshold(1e-12);
}
PointFiniteElement::PointFiniteElement()
: NodalFiniteElement(0, Geometry::POINT, 1, 0)
{
Nodes.IntPoint(0).x = 0.0;
}
void PointFiniteElement::CalcShape(const IntegrationPoint &ip,
Vector &shape) const
{
shape(0) = 1.;
}
void PointFiniteElement::CalcDShape(const IntegrationPoint &ip,
DenseMatrix &dshape) const
{
// dshape is (1 x 0) - nothing to compute
}
Linear1DFiniteElement::Linear1DFiniteElement()
: NodalFiniteElement(1, Geometry::SEGMENT, 2, 1)
{
Nodes.IntPoint(0).x = 0.0;
Nodes.IntPoint(1).x = 1.0;
}
void Linear1DFiniteElement::CalcShape(const IntegrationPoint &ip,
Vector &shape) const
{
shape(0) = 1. - ip.x;
shape(1) = ip.x;
}
void Linear1DFiniteElement::CalcDShape(const IntegrationPoint &ip,
DenseMatrix &dshape) const
{
dshape(0,0) = -1.;
dshape(1,0) = 1.;
}
Linear2DFiniteElement::Linear2DFiniteElement()
: NodalFiniteElement(2, Geometry::TRIANGLE, 3, 1)
{
Nodes.IntPoint(0).x = 0.0;
Nodes.IntPoint(0).y = 0.0;
Nodes.IntPoint(1).x = 1.0;
Nodes.IntPoint(1).y = 0.0;
Nodes.IntPoint(2).x = 0.0;
Nodes.IntPoint(2).y = 1.0;
}
void Linear2DFiniteElement::CalcShape(const IntegrationPoint &ip,
Vector &shape) const
{
shape(0) = 1. - ip.x - ip.y;
shape(1) = ip.x;
shape(2) = ip.y;
}
void Linear2DFiniteElement::CalcDShape(const IntegrationPoint &ip,
DenseMatrix &dshape) const
{
dshape(0,0) = -1.; dshape(0,1) = -1.;
dshape(1,0) = 1.; dshape(1,1) = 0.;
dshape(2,0) = 0.; dshape(2,1) = 1.;
}
BiLinear2DFiniteElement::BiLinear2DFiniteElement()
: NodalFiniteElement(2, Geometry::SQUARE, 4, 1, FunctionSpace::Qk)
{
Nodes.IntPoint(0).x = 0.0;
Nodes.IntPoint(0).y = 0.0;
Nodes.IntPoint(1).x = 1.0;
Nodes.IntPoint(1).y = 0.0;
Nodes.IntPoint(2).x = 1.0;
Nodes.IntPoint(2).y = 1.0;
Nodes.IntPoint(3).x = 0.0;
Nodes.IntPoint(3).y = 1.0;
}
void BiLinear2DFiniteElement::CalcShape(const IntegrationPoint &ip,
Vector &shape) const
{
shape(0) = (1. - ip.x) * (1. - ip.y) ;
shape(1) = ip.x * (1. - ip.y) ;
shape(2) = ip.x * ip.y ;
shape(3) = (1. - ip.x) * ip.y ;
}
void BiLinear2DFiniteElement::CalcDShape(const IntegrationPoint &ip,
DenseMatrix &dshape) const
{
dshape(0,0) = -1. + ip.y; dshape(0,1) = -1. + ip.x ;
dshape(1,0) = 1. - ip.y; dshape(1,1) = -ip.x ;
dshape(2,0) = ip.y ; dshape(2,1) = ip.x ;
dshape(3,0) = -ip.y ; dshape(3,1) = 1. - ip.x ;
}
void BiLinear2DFiniteElement::CalcHessian(
const IntegrationPoint &ip, DenseMatrix &h) const
{
h(0,0) = 0.; h(0,1) = 1.; h(0,2) = 0.;
h(1,0) = 0.; h(1,1) = -1.; h(1,2) = 0.;
h(2,0) = 0.; h(2,1) = 1.; h(2,2) = 0.;
h(3,0) = 0.; h(3,1) = -1.; h(3,2) = 0.;
}
GaussLinear2DFiniteElement::GaussLinear2DFiniteElement()
: NodalFiniteElement(2, Geometry::TRIANGLE, 3, 1, FunctionSpace::Pk)
{
Nodes.IntPoint(0).x = 1./6.;
Nodes.IntPoint(0).y = 1./6.;
Nodes.IntPoint(1).x = 2./3.;
Nodes.IntPoint(1).y = 1./6.;
Nodes.IntPoint(2).x = 1./6.;
Nodes.IntPoint(2).y = 2./3.;
}
void GaussLinear2DFiniteElement::CalcShape(const IntegrationPoint &ip,
Vector &shape) const
{
const double x = ip.x, y = ip.y;
shape(0) = 5./3. - 2. * (x + y);
shape(1) = 2. * (x - 1./6.);
shape(2) = 2. * (y - 1./6.);
}
void GaussLinear2DFiniteElement::CalcDShape(const IntegrationPoint &ip,
DenseMatrix &dshape) const
{
dshape(0,0) = -2.; dshape(0,1) = -2.;
dshape(1,0) = 2.; dshape(1,1) = 0.;
dshape(2,0) = 0.; dshape(2,1) = 2.;
}
void GaussLinear2DFiniteElement::ProjectDelta(int vertex, Vector &dofs) const
{
dofs(vertex) = 2./3.;
dofs((vertex+1)%3) = 1./6.;
dofs((vertex+2)%3) = 1./6.;
}
// 0.5-0.5/sqrt(3) and 0.5+0.5/sqrt(3)
const double GaussBiLinear2DFiniteElement::p[] =
{ 0.2113248654051871177454256, 0.7886751345948128822545744 };
GaussBiLinear2DFiniteElement::GaussBiLinear2DFiniteElement()
: NodalFiniteElement(2, Geometry::SQUARE, 4, 1, FunctionSpace::Qk)
{
Nodes.IntPoint(0).x = p[0];
Nodes.IntPoint(0).y = p[0];
Nodes.IntPoint(1).x = p[1];
Nodes.IntPoint(1).y = p[0];
Nodes.IntPoint(2).x = p[1];
Nodes.IntPoint(2).y = p[1];
Nodes.IntPoint(3).x = p[0];
Nodes.IntPoint(3).y = p[1];
}
void GaussBiLinear2DFiniteElement::CalcShape(const IntegrationPoint &ip,
Vector &shape) const
{
const double x = ip.x, y = ip.y;
shape(0) = 3. * (p[1] - x) * (p[1] - y);
shape(1) = 3. * (x - p[0]) * (p[1] - y);
shape(2) = 3. * (x - p[0]) * (y - p[0]);
shape(3) = 3. * (p[1] - x) * (y - p[0]);
}
void GaussBiLinear2DFiniteElement::CalcDShape(const IntegrationPoint &ip,
DenseMatrix &dshape) const
{
const double x = ip.x, y = ip.y;
dshape(0,0) = 3. * (y - p[1]); dshape(0,1) = 3. * (x - p[1]);
dshape(1,0) = 3. * (p[1] - y); dshape(1,1) = 3. * (p[0] - x);
dshape(2,0) = 3. * (y - p[0]); dshape(2,1) = 3. * (x - p[0]);
dshape(3,0) = 3. * (p[0] - y); dshape(3,1) = 3. * (p[1] - x);
}
void GaussBiLinear2DFiniteElement::ProjectDelta(int vertex, Vector &dofs) const
{
#if 1
dofs(vertex) = p[1]*p[1];
dofs((vertex+1)%4) = p[0]*p[1];
dofs((vertex+2)%4) = p[0]*p[0];
dofs((vertex+3)%4) = p[0]*p[1];
#else
dofs = 1.0;
#endif
}
P1OnQuadFiniteElement::P1OnQuadFiniteElement()
: NodalFiniteElement(2, Geometry::SQUARE, 3, 1, FunctionSpace::Qk)
{
Nodes.IntPoint(0).x = 0.0;
Nodes.IntPoint(0).y = 0.0;
Nodes.IntPoint(1).x = 1.0;
Nodes.IntPoint(1).y = 0.0;
Nodes.IntPoint(2).x = 0.0;
Nodes.IntPoint(2).y = 1.0;
}
void P1OnQuadFiniteElement::CalcShape(const IntegrationPoint &ip,
Vector &shape) const
{
shape(0) = 1. - ip.x - ip.y;
shape(1) = ip.x;
shape(2) = ip.y;
}
void P1OnQuadFiniteElement::CalcDShape(const IntegrationPoint &ip,
DenseMatrix &dshape) const
{
dshape(0,0) = -1.; dshape(0,1) = -1.;
dshape(1,0) = 1.; dshape(1,1) = 0.;
dshape(2,0) = 0.; dshape(2,1) = 1.;
}
Quad1DFiniteElement::Quad1DFiniteElement()
: NodalFiniteElement(1, Geometry::SEGMENT, 3, 2)
{
Nodes.IntPoint(0).x = 0.0;
Nodes.IntPoint(1).x = 1.0;
Nodes.IntPoint(2).x = 0.5;
}
void Quad1DFiniteElement::CalcShape(const IntegrationPoint &ip,
Vector &shape) const
{
double x = ip.x;
double l1 = 1.0 - x, l2 = x, l3 = 2. * x - 1.;
shape(0) = l1 * (-l3);
shape(1) = l2 * l3;
shape(2) = 4. * l1 * l2;
}
void Quad1DFiniteElement::CalcDShape(const IntegrationPoint &ip,
DenseMatrix &dshape) const
{
double x = ip.x;
dshape(0,0) = 4. * x - 3.;
dshape(1,0) = 4. * x - 1.;
dshape(2,0) = 4. - 8. * x;
}
QuadPos1DFiniteElement::QuadPos1DFiniteElement()
: PositiveFiniteElement(1, Geometry::SEGMENT, 3, 2)
{
Nodes.IntPoint(0).x = 0.0;
Nodes.IntPoint(1).x = 1.0;
Nodes.IntPoint(2).x = 0.5;
}
void QuadPos1DFiniteElement::CalcShape(const IntegrationPoint &ip,
Vector &shape) const
{
const double x = ip.x, x1 = 1. - x;
shape(0) = x1 * x1;
shape(1) = x * x;
shape(2) = 2. * x * x1;
}
void QuadPos1DFiniteElement::CalcDShape(const IntegrationPoint &ip,
DenseMatrix &dshape) const
{
const double x = ip.x;
dshape(0,0) = 2. * x - 2.;
dshape(1,0) = 2. * x;
dshape(2,0) = 2. - 4. * x;
}
Quad2DFiniteElement::Quad2DFiniteElement()
: NodalFiniteElement(2, Geometry::TRIANGLE, 6, 2)
{
Nodes.IntPoint(0).x = 0.0;
Nodes.IntPoint(0).y = 0.0;
Nodes.IntPoint(1).x = 1.0;
Nodes.IntPoint(1).y = 0.0;
Nodes.IntPoint(2).x = 0.0;
Nodes.IntPoint(2).y = 1.0;
Nodes.IntPoint(3).x = 0.5;
Nodes.IntPoint(3).y = 0.0;
Nodes.IntPoint(4).x = 0.5;
Nodes.IntPoint(4).y = 0.5;
Nodes.IntPoint(5).x = 0.0;
Nodes.IntPoint(5).y = 0.5;
}
void Quad2DFiniteElement::CalcShape(const IntegrationPoint &ip,
Vector &shape) const
{
double x = ip.x, y = ip.y;
double l1 = 1.-x-y, l2 = x, l3 = y;
shape(0) = l1 * (2. * l1 - 1.);
shape(1) = l2 * (2. * l2 - 1.);
shape(2) = l3 * (2. * l3 - 1.);
shape(3) = 4. * l1 * l2;
shape(4) = 4. * l2 * l3;
shape(5) = 4. * l3 * l1;
}
void Quad2DFiniteElement::CalcDShape(const IntegrationPoint &ip,
DenseMatrix &dshape) const
{
double x = ip.x, y = ip.y;
dshape(0,0) =
dshape(0,1) = 4. * (x + y) - 3.;
dshape(1,0) = 4. * x - 1.;
dshape(1,1) = 0.;
dshape(2,0) = 0.;
dshape(2,1) = 4. * y - 1.;
dshape(3,0) = -4. * (2. * x + y - 1.);
dshape(3,1) = -4. * x;
dshape(4,0) = 4. * y;
dshape(4,1) = 4. * x;
dshape(5,0) = -4. * y;
dshape(5,1) = -4. * (x + 2. * y - 1.);
}
void Quad2DFiniteElement::CalcHessian (const IntegrationPoint &ip,
DenseMatrix &h) const
{
h(0,0) = 4.;
h(0,1) = 4.;
h(0,2) = 4.;
h(1,0) = 4.;
h(1,1) = 0.;
h(1,2) = 0.;
h(2,0) = 0.;
h(2,1) = 0.;
h(2,2) = 4.;
h(3,0) = -8.;
h(3,1) = -4.;
h(3,2) = 0.;
h(4,0) = 0.;
h(4,1) = 4.;
h(4,2) = 0.;
h(5,0) = 0.;
h(5,1) = -4.;
h(5,2) = -8.;
}
void Quad2DFiniteElement::ProjectDelta(int vertex, Vector &dofs) const
{
#if 0
dofs = 1.;
#else
dofs = 0.;
dofs(vertex) = 1.;
switch (vertex)
{
case 0: dofs(3) = 0.25; dofs(5) = 0.25; break;
case 1: dofs(3) = 0.25; dofs(4) = 0.25; break;
case 2: dofs(4) = 0.25; dofs(5) = 0.25; break;
}
#endif
}
const double GaussQuad2DFiniteElement::p[] =
{ 0.0915762135097707434595714634022015, 0.445948490915964886318329253883051 };
GaussQuad2DFiniteElement::GaussQuad2DFiniteElement()
: NodalFiniteElement(2, Geometry::TRIANGLE, 6, 2), A(6), D(6,2), pol(6)
{
Nodes.IntPoint(0).x = p[0];
Nodes.IntPoint(0).y = p[0];
Nodes.IntPoint(1).x = 1. - 2. * p[0];
Nodes.IntPoint(1).y = p[0];
Nodes.IntPoint(2).x = p[0];
Nodes.IntPoint(2).y = 1. - 2. * p[0];
Nodes.IntPoint(3).x = p[1];
Nodes.IntPoint(3).y = p[1];
Nodes.IntPoint(4).x = 1. - 2. * p[1];
Nodes.IntPoint(4).y = p[1];
Nodes.IntPoint(5).x = p[1];
Nodes.IntPoint(5).y = 1. - 2. * p[1];
for (int i = 0; i < 6; i++)
{
const double x = Nodes.IntPoint(i).x, y = Nodes.IntPoint(i).y;
A(0,i) = 1.;
A(1,i) = x;
A(2,i) = y;
A(3,i) = x * x;
A(4,i) = x * y;
A(5,i) = y * y;
}
A.Invert();
}
void GaussQuad2DFiniteElement::CalcShape(const IntegrationPoint &ip,
Vector &shape) const
{
const double x = ip.x, y = ip.y;
pol(0) = 1.;
pol(1) = x;
pol(2) = y;
pol(3) = x * x;
pol(4) = x * y;
pol(5) = y * y;
A.Mult(pol, shape);
}
void GaussQuad2DFiniteElement::CalcDShape(const IntegrationPoint &ip,
DenseMatrix &dshape) const
{
const double x = ip.x, y = ip.y;
D(0,0) = 0.; D(0,1) = 0.;
D(1,0) = 1.; D(1,1) = 0.;
D(2,0) = 0.; D(2,1) = 1.;
D(3,0) = 2. * x; D(3,1) = 0.;
D(4,0) = y; D(4,1) = x;
D(5,0) = 0.; D(5,1) = 2. * y;
Mult(A, D, dshape);
}
BiQuad2DFiniteElement::BiQuad2DFiniteElement()
: NodalFiniteElement(2, Geometry::SQUARE, 9, 2, FunctionSpace::Qk)
{
Nodes.IntPoint(0).x = 0.0;
Nodes.IntPoint(0).y = 0.0;
Nodes.IntPoint(1).x = 1.0;
Nodes.IntPoint(1).y = 0.0;
Nodes.IntPoint(2).x = 1.0;
Nodes.IntPoint(2).y = 1.0;
Nodes.IntPoint(3).x = 0.0;
Nodes.IntPoint(3).y = 1.0;
Nodes.IntPoint(4).x = 0.5;
Nodes.IntPoint(4).y = 0.0;
Nodes.IntPoint(5).x = 1.0;
Nodes.IntPoint(5).y = 0.5;
Nodes.IntPoint(6).x = 0.5;
Nodes.IntPoint(6).y = 1.0;
Nodes.IntPoint(7).x = 0.0;
Nodes.IntPoint(7).y = 0.5;
Nodes.IntPoint(8).x = 0.5;
Nodes.IntPoint(8).y = 0.5;
}
void BiQuad2DFiniteElement::CalcShape(const IntegrationPoint &ip,
Vector &shape) const
{
double x = ip.x, y = ip.y;
double l1x, l2x, l3x, l1y, l2y, l3y;
l1x = (x - 1.) * (2. * x - 1);
l2x = 4. * x * (1. - x);
l3x = x * (2. * x - 1.);
l1y = (y - 1.) * (2. * y - 1);
l2y = 4. * y * (1. - y);
l3y = y * (2. * y - 1.);
shape(0) = l1x * l1y;
shape(4) = l2x * l1y;
shape(1) = l3x * l1y;
shape(7) = l1x * l2y;
shape(8) = l2x * l2y;
shape(5) = l3x * l2y;
shape(3) = l1x * l3y;
shape(6) = l2x * l3y;
shape(2) = l3x * l3y;
}
void BiQuad2DFiniteElement::CalcDShape(const IntegrationPoint &ip,
DenseMatrix &dshape) const
{
double x = ip.x, y = ip.y;
double l1x, l2x, l3x, l1y, l2y, l3y;
double d1x, d2x, d3x, d1y, d2y, d3y;
l1x = (x - 1.) * (2. * x - 1);
l2x = 4. * x * (1. - x);
l3x = x * (2. * x - 1.);
l1y = (y - 1.) * (2. * y - 1);
l2y = 4. * y * (1. - y);
l3y = y * (2. * y - 1.);
d1x = 4. * x - 3.;
d2x = 4. - 8. * x;
d3x = 4. * x - 1.;
d1y = 4. * y - 3.;
d2y = 4. - 8. * y;
d3y = 4. * y - 1.;
dshape(0,0) = d1x * l1y;
dshape(0,1) = l1x * d1y;
dshape(4,0) = d2x * l1y;
dshape(4,1) = l2x * d1y;
dshape(1,0) = d3x * l1y;
dshape(1,1) = l3x * d1y;
dshape(7,0) = d1x * l2y;
dshape(7,1) = l1x * d2y;
dshape(8,0) = d2x * l2y;
dshape(8,1) = l2x * d2y;
dshape(5,0) = d3x * l2y;
dshape(5,1) = l3x * d2y;
dshape(3,0) = d1x * l3y;
dshape(3,1) = l1x * d3y;
dshape(6,0) = d2x * l3y;
dshape(6,1) = l2x * d3y;
dshape(2,0) = d3x * l3y;
dshape(2,1) = l3x * d3y;
}
void BiQuad2DFiniteElement::ProjectDelta(int vertex, Vector &dofs) const
{
#if 0
dofs = 1.;
#else
dofs = 0.;
dofs(vertex) = 1.;
switch (vertex)
{
case 0: dofs(4) = 0.25; dofs(7) = 0.25; break;
case 1: dofs(4) = 0.25; dofs(5) = 0.25; break;
case 2: dofs(5) = 0.25; dofs(6) = 0.25; break;
case 3: dofs(6) = 0.25; dofs(7) = 0.25; break;
}
dofs(8) = 1./16.;
#endif
}
H1Ser_QuadrilateralElement::H1Ser_QuadrilateralElement(const int p)
: ScalarFiniteElement(2, Geometry::SQUARE, (p*p + 3*p +6) / 2, p,
FunctionSpace::Qk)
{
// Store the dof_map of the associated TensorBasisElement, which will be used
// to create the serendipity dof map. Its size is larger than the size of
// the serendipity element.
TensorBasisElement tbeTemp =
TensorBasisElement(2, p, BasisType::GaussLobatto,
TensorBasisElement::DofMapType::Sr_DOF_MAP);
const Array<int> tp_dof_map = tbeTemp.GetDofMap();
const double *cp = poly1d.ClosedPoints(p, BasisType::GaussLobatto);
// Fixing the Nodes is exactly the same as the H1_QuadrilateralElement
// constructor except we only use those values of the associated tensor
// product dof_map that are <= the number of serendipity Dofs e.g. only DoFs
// 0-7 out of the 9 tensor product dofs (at quadratic order)
int o = 0;
for (int j = 0; j <= p; j++)
{
for (int i = 0; i <= p; i++)
{
if (tp_dof_map[o] < Nodes.Size())
{
Nodes.IntPoint(tp_dof_map[o]).x = cp[i];
Nodes.IntPoint(tp_dof_map[o]).y = cp[j];
}
o++;
}
}
}
void H1Ser_QuadrilateralElement::CalcShape(const IntegrationPoint &ip,
Vector &shape) const
{
int p = (this)->GetOrder();
double x = ip.x, y = ip.y;
Poly_1D::Basis edgeNodalBasis(poly1d.GetBasis(p, BasisType::GaussLobatto));
Vector nodalX(p+1);
Vector nodalY(p+1);
edgeNodalBasis.Eval(x, nodalX);
edgeNodalBasis.Eval(y, nodalY);
// First, fix edge-based shape functions. Use a nodal interpolant for edge
// points, weighted by the linear function that vanishes on opposite edge.
for (int i = 0; i < p-1; i++)
{
shape(4 + 0*(p-1) + i) = (nodalX(i+1))*(1.-y); // south edge 0->1
shape(4 + 1*(p-1) + i) = (nodalY(i+1))*x; // east edge 1->2
shape(4 + 3*(p-1) - i - 1) = (nodalX(i+1)) * y; // north edge 3->2
shape(4 + 4*(p-1) - i - 1) = (nodalY(i+1)) * (1. - x); // west edge 0->3
}
BiLinear2DFiniteElement bilinear = BiLinear2DFiniteElement();
Vector bilinearsAtIP(4);
bilinear.CalcShape(ip, bilinearsAtIP);
const double *edgePts(poly1d.ClosedPoints(p, BasisType::GaussLobatto));
// Next, set the shape function associated with vertex V, evaluated at (x,y)
// to be: bilinear function associated to V, evaluated at (x,y) - sum (shape
// function at edge point P, weighted by bilinear function for V evaluated at
// P) where the sum is taken only for points P on edges incident to V.
double vtx0fix =0;
double vtx1fix =0;
double vtx2fix =0;
double vtx3fix =0;
for (int i = 0; i<p-1; i++)
{
vtx0fix += (1-edgePts[i+1])*(shape(4 + i) +
shape(4 + 4*(p-1) - i - 1)); // bot+left edge
vtx1fix += (1-edgePts[i+1])*(shape(4 + 1*(p-1) + i) +
shape(4 + (p-2)-i)); // right+bot edge
vtx2fix += (1-edgePts[i+1])*(shape(4 + 2*(p-1) + i) +
shape(1 + 2*p-i)); // top+right edge
vtx3fix += (1-edgePts[i+1])*(shape(4 + 3*(p-1) + i) +
shape(3*p - i)); // left+top edge
}
shape(0) = bilinearsAtIP(0) - vtx0fix;
shape(1) = bilinearsAtIP(1) - vtx1fix;
shape(2) = bilinearsAtIP(2) - vtx2fix;
shape(3) = bilinearsAtIP(3) - vtx3fix;
// Interior basis functions appear starting at order p=4. These are non-nodal
// bubble functions.
if (p > 3)
{
double *legX = new double[p-1];
double *legY = new double[p-1];
Poly_1D *storeLegendre = new Poly_1D();
storeLegendre->CalcLegendre(p-2, x, legX);
storeLegendre->CalcLegendre(p-2, y, legY);
int interior_total = 0;
for (int j = 4; j < p + 1; j++)
{
for (int k = 0; k < j-3; k++)
{
shape(4 + 4*(p-1) + interior_total)
= legX[k] * legY[j-4-k] * x * (1. - x) * y * (1. - y);
interior_total++;
}
}
delete[] legX;
delete[] legY;
delete storeLegendre;
}
}
void H1Ser_QuadrilateralElement::CalcDShape(const IntegrationPoint &ip,
DenseMatrix &dshape) const
{
int p = (this)->GetOrder();
double x = ip.x, y = ip.y;
Poly_1D::Basis edgeNodalBasis(poly1d.GetBasis(p, BasisType::GaussLobatto));
Vector nodalX(p+1);
Vector DnodalX(p+1);
Vector nodalY(p+1);
Vector DnodalY(p+1);
edgeNodalBasis.Eval(x, nodalX, DnodalX);
edgeNodalBasis.Eval(y, nodalY, DnodalY);
for (int i = 0; i < p-1; i++)
{
dshape(4 + 0*(p-1) + i,0) = DnodalX(i+1) * (1.-y);
dshape(4 + 0*(p-1) + i,1) = -nodalX(i+1);
dshape(4 + 1*(p-1) + i,0) = nodalY(i+1);
dshape(4 + 1*(p-1) + i,1) = DnodalY(i+1)*x;
dshape(4 + 3*(p-1) - i - 1,0) = DnodalX(i+1)*y;
dshape(4 + 3*(p-1) - i - 1,1) = nodalX(i+1);
dshape(4 + 4*(p-1) - i - 1,0) = -nodalY(i+1);
dshape(4 + 4*(p-1) - i - 1,1) = DnodalY(i+1) * (1.-x);
}
BiLinear2DFiniteElement bilinear = BiLinear2DFiniteElement();
DenseMatrix DbilinearsAtIP(4);
bilinear.CalcDShape(ip, DbilinearsAtIP);
const double *edgePts(poly1d.ClosedPoints(p, BasisType::GaussLobatto));
dshape(0,0) = DbilinearsAtIP(0,0);
dshape(0,1) = DbilinearsAtIP(0,1);
dshape(1,0) = DbilinearsAtIP(1,0);
dshape(1,1) = DbilinearsAtIP(1,1);
dshape(2,0) = DbilinearsAtIP(2,0);
dshape(2,1) = DbilinearsAtIP(2,1);
dshape(3,0) = DbilinearsAtIP(3,0);
dshape(3,1) = DbilinearsAtIP(3,1);
for (int i = 0; i<p-1; i++)
{
dshape(0,0) -= (1-edgePts[i+1])*(dshape(4 + 0*(p-1) + i, 0) +
dshape(4 + 4*(p-1) - i - 1,0));
dshape(0,1) -= (1-edgePts[i+1])*(dshape(4 + 0*(p-1) + i, 1) +
dshape(4 + 4*(p-1) - i - 1,1));
dshape(1,0) -= (1-edgePts[i+1])*(dshape(4 + 1*(p-1) + i, 0) +
dshape(4 + (p-2)-i, 0));
dshape(1,1) -= (1-edgePts[i+1])*(dshape(4 + 1*(p-1) + i, 1) +
dshape(4 + (p-2)-i, 1));
dshape(2,0) -= (1-edgePts[i+1])*(dshape(4 + 2*(p-1) + i, 0) +
dshape(1 + 2*p-i, 0));
dshape(2,1) -= (1-edgePts[i+1])*(dshape(4 + 2*(p-1) + i, 1) +
dshape(1 + 2*p-i, 1));
dshape(3,0) -= (1-edgePts[i+1])*(dshape(4 + 3*(p-1) + i, 0) +
dshape(3*p - i, 0));
dshape(3,1) -= (1-edgePts[i+1])*(dshape(4 + 3*(p-1) + i, 1) +
dshape(3*p - i, 1));
}
if (p > 3)
{
double *legX = new double[p-1];
double *legY = new double[p-1];
double *DlegX = new double[p-1];
double *DlegY = new double[p-1];
Poly_1D *storeLegendre = new Poly_1D();
storeLegendre->CalcLegendre(p-2, x, legX, DlegX);
storeLegendre->CalcLegendre(p-2, y, legY, DlegY);
int interior_total = 0;
for (int j = 4; j < p + 1; j++)
{
for (int k = 0; k < j-3; k++)
{
dshape(4 + 4*(p-1) + interior_total, 0) =
legY[j-4-k]*y*(1-y) * (DlegX[k]*x*(1-x) + legX[k]*(1-2*x));
dshape(4 + 4*(p-1) + interior_total, 1) =
legX[k]*x*(1-x) * (DlegY[j-4-k]*y*(1-y) + legY[j-4-k]*(1-2*y));
interior_total++;
}
}
delete[] legX;
delete[] legY;
delete[] DlegX;
delete[] DlegY;
delete storeLegendre;
}
}
void H1Ser_QuadrilateralElement::GetLocalInterpolation(ElementTransformation
&Trans,
DenseMatrix &I) const
{
// For p<=4, the basis is nodal; for p>4, the quad-interior functions are
// non-nodal.
if (order <= 4)
{
NodalLocalInterpolation(Trans, I, *this);
}
else
{
ScalarLocalInterpolation(Trans, I, *this);
}
}
BiQuadPos2DFiniteElement::BiQuadPos2DFiniteElement()
: PositiveFiniteElement(2, Geometry::SQUARE, 9, 2, FunctionSpace::Qk)
{
Nodes.IntPoint(0).x = 0.0;
Nodes.IntPoint(0).y = 0.0;
Nodes.IntPoint(1).x = 1.0;
Nodes.IntPoint(1).y = 0.0;
Nodes.IntPoint(2).x = 1.0;
Nodes.IntPoint(2).y = 1.0;
Nodes.IntPoint(3).x = 0.0;
Nodes.IntPoint(3).y = 1.0;
Nodes.IntPoint(4).x = 0.5;
Nodes.IntPoint(4).y = 0.0;
Nodes.IntPoint(5).x = 1.0;
Nodes.IntPoint(5).y = 0.5;
Nodes.IntPoint(6).x = 0.5;
Nodes.IntPoint(6).y = 1.0;
Nodes.IntPoint(7).x = 0.0;
Nodes.IntPoint(7).y = 0.5;
Nodes.IntPoint(8).x = 0.5;
Nodes.IntPoint(8).y = 0.5;
}
void BiQuadPos2DFiniteElement::CalcShape(const IntegrationPoint &ip,
Vector &shape) const
{
double x = ip.x, y = ip.y;
double l1x, l2x, l3x, l1y, l2y, l3y;
l1x = (1. - x) * (1. - x);
l2x = 2. * x * (1. - x);
l3x = x * x;
l1y = (1. - y) * (1. - y);
l2y = 2. * y * (1. - y);
l3y = y * y;
shape(0) = l1x * l1y;
shape(4) = l2x * l1y;
shape(1) = l3x * l1y;
shape(7) = l1x * l2y;
shape(8) = l2x * l2y;
shape(5) = l3x * l2y;
shape(3) = l1x * l3y;
shape(6) = l2x * l3y;
shape(2) = l3x * l3y;
}
void BiQuadPos2DFiniteElement::CalcDShape(const IntegrationPoint &ip,
DenseMatrix &dshape) const
{
double x = ip.x, y = ip.y;
double l1x, l2x, l3x, l1y, l2y, l3y;
double d1x, d2x, d3x, d1y, d2y, d3y;
l1x = (1. - x) * (1. - x);
l2x = 2. * x * (1. - x);
l3x = x * x;
l1y = (1. - y) * (1. - y);
l2y = 2. * y * (1. - y);
l3y = y * y;
d1x = 2. * x - 2.;
d2x = 2. - 4. * x;
d3x = 2. * x;
d1y = 2. * y - 2.;
d2y = 2. - 4. * y;
d3y = 2. * y;
dshape(0,0) = d1x * l1y;
dshape(0,1) = l1x * d1y;
dshape(4,0) = d2x * l1y;
dshape(4,1) = l2x * d1y;
dshape(1,0) = d3x * l1y;
dshape(1,1) = l3x * d1y;
dshape(7,0) = d1x * l2y;
dshape(7,1) = l1x * d2y;
dshape(8,0) = d2x * l2y;
dshape(8,1) = l2x * d2y;
dshape(5,0) = d3x * l2y;
dshape(5,1) = l3x * d2y;
dshape(3,0) = d1x * l3y;
dshape(3,1) = l1x * d3y;
dshape(6,0) = d2x * l3y;
dshape(6,1) = l2x * d3y;
dshape(2,0) = d3x * l3y;
dshape(2,1) = l3x * d3y;
}
void BiQuadPos2DFiniteElement::GetLocalInterpolation(
ElementTransformation &Trans, DenseMatrix &I) const
{
double s[9];
IntegrationPoint tr_ip;
Vector xx(&tr_ip.x, 2), shape(s, 9);
for (int i = 0; i < 9; i++)
{
Trans.Transform(Nodes.IntPoint(i), xx);
CalcShape(tr_ip, shape);
for (int j = 0; j < 9; j++)
if (fabs(I(i,j) = s[j]) < 1.0e-12)
{
I(i,j) = 0.0;
}
}
for (int i = 0; i < 9; i++)
{
double *d = &I(0,i);
d[4] = 2. * d[4] - 0.5 * (d[0] + d[1]);
d[5] = 2. * d[5] - 0.5 * (d[1] + d[2]);
d[6] = 2. * d[6] - 0.5 * (d[2] + d[3]);
d[7] = 2. * d[7] - 0.5 * (d[3] + d[0]);
d[8] = 4. * d[8] - 0.5 * (d[4] + d[5] + d[6] + d[7]) -
0.25 * (d[0] + d[1] + d[2] + d[3]);
}
}
void BiQuadPos2DFiniteElement::Project(
Coefficient &coeff, ElementTransformation &Trans, Vector &dofs) const
{
double *d = dofs;
for (int i = 0; i < 9; i++)
{
const IntegrationPoint &ip = Nodes.IntPoint(i);
Trans.SetIntPoint(&ip);
d[i] = coeff.Eval(Trans, ip);
}
d[4] = 2. * d[4] - 0.5 * (d[0] + d[1]);
d[5] = 2. * d[5] - 0.5 * (d[1] + d[2]);
d[6] = 2. * d[6] - 0.5 * (d[2] + d[3]);
d[7] = 2. * d[7] - 0.5 * (d[3] + d[0]);
d[8] = 4. * d[8] - 0.5 * (d[4] + d[5] + d[6] + d[7]) -
0.25 * (d[0] + d[1] + d[2] + d[3]);
}
void BiQuadPos2DFiniteElement::Project (
VectorCoefficient &vc, ElementTransformation &Trans,
Vector &dofs) const
{
double v[3];
Vector x (v, vc.GetVDim());
for (int i = 0; i < 9; i++)
{
const IntegrationPoint &ip = Nodes.IntPoint(i);
Trans.SetIntPoint(&ip);
vc.Eval (x, Trans, ip);
for (int j = 0; j < x.Size(); j++)
{
dofs(9*j+i) = v[j];
}
}
for (int j = 0; j < x.Size(); j++)
{
double *d = &dofs(9*j);
d[4] = 2. * d[4] - 0.5 * (d[0] + d[1]);
d[5] = 2. * d[5] - 0.5 * (d[1] + d[2]);
d[6] = 2. * d[6] - 0.5 * (d[2] + d[3]);
d[7] = 2. * d[7] - 0.5 * (d[3] + d[0]);
d[8] = 4. * d[8] - 0.5 * (d[4] + d[5] + d[6] + d[7]) -
0.25 * (d[0] + d[1] + d[2] + d[3]);
}
}
GaussBiQuad2DFiniteElement::GaussBiQuad2DFiniteElement()
: NodalFiniteElement(2, Geometry::SQUARE, 9, 2, FunctionSpace::Qk)
{
const double p1 = 0.5*(1.-sqrt(3./5.));
Nodes.IntPoint(0).x = p1;
Nodes.IntPoint(0).y = p1;
Nodes.IntPoint(4).x = 0.5;
Nodes.IntPoint(4).y = p1;
Nodes.IntPoint(1).x = 1.-p1;
Nodes.IntPoint(1).y = p1;
Nodes.IntPoint(7).x = p1;
Nodes.IntPoint(7).y = 0.5;
Nodes.IntPoint(8).x = 0.5;
Nodes.IntPoint(8).y = 0.5;
Nodes.IntPoint(5).x = 1.-p1;
Nodes.IntPoint(5).y = 0.5;
Nodes.IntPoint(3).x = p1;
Nodes.IntPoint(3).y = 1.-p1;
Nodes.IntPoint(6).x = 0.5;
Nodes.IntPoint(6).y = 1.-p1;
Nodes.IntPoint(2).x = 1.-p1;
Nodes.IntPoint(2).y = 1.-p1;
}
void GaussBiQuad2DFiniteElement::CalcShape(const IntegrationPoint &ip,
Vector &shape) const
{
const double a = sqrt(5./3.);
const double p1 = 0.5*(1.-sqrt(3./5.));
double x = a*(ip.x-p1), y = a*(ip.y-p1);
double l1x, l2x, l3x, l1y, l2y, l3y;
l1x = (x - 1.) * (2. * x - 1);
l2x = 4. * x * (1. - x);
l3x = x * (2. * x - 1.);
l1y = (y - 1.) * (2. * y - 1);
l2y = 4. * y * (1. - y);
l3y = y * (2. * y - 1.);
shape(0) = l1x * l1y;
shape(4) = l2x * l1y;
shape(1) = l3x * l1y;
shape(7) = l1x * l2y;
shape(8) = l2x * l2y;
shape(5) = l3x * l2y;
shape(3) = l1x * l3y;
shape(6) = l2x * l3y;
shape(2) = l3x * l3y;
}
void GaussBiQuad2DFiniteElement::CalcDShape(const IntegrationPoint &ip,
DenseMatrix &dshape) const
{
const double a = sqrt(5./3.);
const double p1 = 0.5*(1.-sqrt(3./5.));
double x = a*(ip.x-p1), y = a*(ip.y-p1);
double l1x, l2x, l3x, l1y, l2y, l3y;
double d1x, d2x, d3x, d1y, d2y, d3y;
l1x = (x - 1.) * (2. * x - 1);
l2x = 4. * x * (1. - x);
l3x = x * (2. * x - 1.);
l1y = (y - 1.) * (2. * y - 1);
l2y = 4. * y * (1. - y);
l3y = y * (2. * y - 1.);
d1x = a * (4. * x - 3.);
d2x = a * (4. - 8. * x);
d3x = a * (4. * x - 1.);
d1y = a * (4. * y - 3.);
d2y = a * (4. - 8. * y);
d3y = a * (4. * y - 1.);
dshape(0,0) = d1x * l1y;
dshape(0,1) = l1x * d1y;
dshape(4,0) = d2x * l1y;
dshape(4,1) = l2x * d1y;
dshape(1,0) = d3x * l1y;
dshape(1,1) = l3x * d1y;
dshape(7,0) = d1x * l2y;
dshape(7,1) = l1x * d2y;
dshape(8,0) = d2x * l2y;
dshape(8,1) = l2x * d2y;
dshape(5,0) = d3x * l2y;
dshape(5,1) = l3x * d2y;
dshape(3,0) = d1x * l3y;
dshape(3,1) = l1x * d3y;
dshape(6,0) = d2x * l3y;
dshape(6,1) = l2x * d3y;
dshape(2,0) = d3x * l3y;
dshape(2,1) = l3x * d3y;
}
BiCubic2DFiniteElement::BiCubic2DFiniteElement()
: NodalFiniteElement (2, Geometry::SQUARE, 16, 3, FunctionSpace::Qk)
{
Nodes.IntPoint(0).x = 0.;
Nodes.IntPoint(0).y = 0.;
Nodes.IntPoint(1).x = 1.;
Nodes.IntPoint(1).y = 0.;
Nodes.IntPoint(2).x = 1.;
Nodes.IntPoint(2).y = 1.;
Nodes.IntPoint(3).x = 0.;
Nodes.IntPoint(3).y = 1.;
Nodes.IntPoint(4).x = 1./3.;
Nodes.IntPoint(4).y = 0.;
Nodes.IntPoint(5).x = 2./3.;
Nodes.IntPoint(5).y = 0.;
Nodes.IntPoint(6).x = 1.;
Nodes.IntPoint(6).y = 1./3.;
Nodes.IntPoint(7).x = 1.;
Nodes.IntPoint(7).y = 2./3.;
Nodes.IntPoint(8).x = 2./3.;
Nodes.IntPoint(8).y = 1.;
Nodes.IntPoint(9).x = 1./3.;
Nodes.IntPoint(9).y = 1.;
Nodes.IntPoint(10).x = 0.;
Nodes.IntPoint(10).y = 2./3.;
Nodes.IntPoint(11).x = 0.;
Nodes.IntPoint(11).y = 1./3.;
Nodes.IntPoint(12).x = 1./3.;
Nodes.IntPoint(12).y = 1./3.;
Nodes.IntPoint(13).x = 2./3.;
Nodes.IntPoint(13).y = 1./3.;
Nodes.IntPoint(14).x = 1./3.;
Nodes.IntPoint(14).y = 2./3.;
Nodes.IntPoint(15).x = 2./3.;
Nodes.IntPoint(15).y = 2./3.;
}
void BiCubic2DFiniteElement::CalcShape(
const IntegrationPoint &ip, Vector &shape) const
{
double x = ip.x, y = ip.y;
double w1x, w2x, w3x, w1y, w2y, w3y;
double l0x, l1x, l2x, l3x, l0y, l1y, l2y, l3y;
w1x = x - 1./3.; w2x = x - 2./3.; w3x = x - 1.;
w1y = y - 1./3.; w2y = y - 2./3.; w3y = y - 1.;
l0x = (- 4.5) * w1x * w2x * w3x;
l1x = ( 13.5) * x * w2x * w3x;
l2x = (-13.5) * x * w1x * w3x;
l3x = ( 4.5) * x * w1x * w2x;
l0y = (- 4.5) * w1y * w2y * w3y;
l1y = ( 13.5) * y * w2y * w3y;
l2y = (-13.5) * y * w1y * w3y;
l3y = ( 4.5) * y * w1y * w2y;
shape(0) = l0x * l0y;
shape(1) = l3x * l0y;
shape(2) = l3x * l3y;
shape(3) = l0x * l3y;
shape(4) = l1x * l0y;
shape(5) = l2x * l0y;
shape(6) = l3x * l1y;
shape(7) = l3x * l2y;
shape(8) = l2x * l3y;
shape(9) = l1x * l3y;
shape(10) = l0x * l2y;
shape(11) = l0x * l1y;
shape(12) = l1x * l1y;
shape(13) = l2x * l1y;
shape(14) = l1x * l2y;
shape(15) = l2x * l2y;
}
void BiCubic2DFiniteElement::CalcDShape(
const IntegrationPoint &ip, DenseMatrix &dshape) const
{
double x = ip.x, y = ip.y;
double w1x, w2x, w3x, w1y, w2y, w3y;
double l0x, l1x, l2x, l3x, l0y, l1y, l2y, l3y;
double d0x, d1x, d2x, d3x, d0y, d1y, d2y, d3y;
w1x = x - 1./3.; w2x = x - 2./3.; w3x = x - 1.;
w1y = y - 1./3.; w2y = y - 2./3.; w3y = y - 1.;
l0x = (- 4.5) * w1x * w2x * w3x;
l1x = ( 13.5) * x * w2x * w3x;
l2x = (-13.5) * x * w1x * w3x;
l3x = ( 4.5) * x * w1x * w2x;
l0y = (- 4.5) * w1y * w2y * w3y;
l1y = ( 13.5) * y * w2y * w3y;
l2y = (-13.5) * y * w1y * w3y;
l3y = ( 4.5) * y * w1y * w2y;
d0x = -5.5 + ( 18. - 13.5 * x) * x;
d1x = 9. + (-45. + 40.5 * x) * x;
d2x = -4.5 + ( 36. - 40.5 * x) * x;
d3x = 1. + (- 9. + 13.5 * x) * x;
d0y = -5.5 + ( 18. - 13.5 * y) * y;
d1y = 9. + (-45. + 40.5 * y) * y;
d2y = -4.5 + ( 36. - 40.5 * y) * y;
d3y = 1. + (- 9. + 13.5 * y) * y;
dshape( 0,0) = d0x * l0y; dshape( 0,1) = l0x * d0y;
dshape( 1,0) = d3x * l0y; dshape( 1,1) = l3x * d0y;
dshape( 2,0) = d3x * l3y; dshape( 2,1) = l3x * d3y;
dshape( 3,0) = d0x * l3y; dshape( 3,1) = l0x * d3y;
dshape( 4,0) = d1x * l0y; dshape( 4,1) = l1x * d0y;
dshape( 5,0) = d2x * l0y; dshape( 5,1) = l2x * d0y;
dshape( 6,0) = d3x * l1y; dshape( 6,1) = l3x * d1y;
dshape( 7,0) = d3x * l2y; dshape( 7,1) = l3x * d2y;
dshape( 8,0) = d2x * l3y; dshape( 8,1) = l2x * d3y;
dshape( 9,0) = d1x * l3y; dshape( 9,1) = l1x * d3y;
dshape(10,0) = d0x * l2y; dshape(10,1) = l0x * d2y;
dshape(11,0) = d0x * l1y; dshape(11,1) = l0x * d1y;
dshape(12,0) = d1x * l1y; dshape(12,1) = l1x * d1y;
dshape(13,0) = d2x * l1y; dshape(13,1) = l2x * d1y;
dshape(14,0) = d1x * l2y; dshape(14,1) = l1x * d2y;
dshape(15,0) = d2x * l2y; dshape(15,1) = l2x * d2y;
}
void BiCubic2DFiniteElement::CalcHessian(
const IntegrationPoint &ip, DenseMatrix &h) const
{
double x = ip.x, y = ip.y;
double w1x, w2x, w3x, w1y, w2y, w3y;
double l0x, l1x, l2x, l3x, l0y, l1y, l2y, l3y;
double d0x, d1x, d2x, d3x, d0y, d1y, d2y, d3y;
double h0x, h1x, h2x, h3x, h0y, h1y, h2y, h3y;
w1x = x - 1./3.; w2x = x - 2./3.; w3x = x - 1.;
w1y = y - 1./3.; w2y = y - 2./3.; w3y = y - 1.;
l0x = (- 4.5) * w1x * w2x * w3x;
l1x = ( 13.5) * x * w2x * w3x;
l2x = (-13.5) * x * w1x * w3x;
l3x = ( 4.5) * x * w1x * w2x;
l0y = (- 4.5) * w1y * w2y * w3y;
l1y = ( 13.5) * y * w2y * w3y;
l2y = (-13.5) * y * w1y * w3y;
l3y = ( 4.5) * y * w1y * w2y;
d0x = -5.5 + ( 18. - 13.5 * x) * x;
d1x = 9. + (-45. + 40.5 * x) * x;
d2x = -4.5 + ( 36. - 40.5 * x) * x;
d3x = 1. + (- 9. + 13.5 * x) * x;
d0y = -5.5 + ( 18. - 13.5 * y) * y;
d1y = 9. + (-45. + 40.5 * y) * y;
d2y = -4.5 + ( 36. - 40.5 * y) * y;
d3y = 1. + (- 9. + 13.5 * y) * y;
h0x = -27. * x + 18.;
h1x = 81. * x - 45.;
h2x = -81. * x + 36.;
h3x = 27. * x - 9.;
h0y = -27. * y + 18.;
h1y = 81. * y - 45.;
h2y = -81. * y + 36.;
h3y = 27. * y - 9.;
h( 0,0) = h0x * l0y; h( 0,1) = d0x * d0y; h( 0,2) = l0x * h0y;
h( 1,0) = h3x * l0y; h( 1,1) = d3x * d0y; h( 1,2) = l3x * h0y;
h( 2,0) = h3x * l3y; h( 2,1) = d3x * d3y; h( 2,2) = l3x * h3y;
h( 3,0) = h0x * l3y; h( 3,1) = d0x * d3y; h( 3,2) = l0x * h3y;
h( 4,0) = h1x * l0y; h( 4,1) = d1x * d0y; h( 4,2) = l1x * h0y;
h( 5,0) = h2x * l0y; h( 5,1) = d2x * d0y; h( 5,2) = l2x * h0y;
h( 6,0) = h3x * l1y; h( 6,1) = d3x * d1y; h( 6,2) = l3x * h1y;
h( 7,0) = h3x * l2y; h( 7,1) = d3x * d2y; h( 7,2) = l3x * h2y;
h( 8,0) = h2x * l3y; h( 8,1) = d2x * d3y; h( 8,2) = l2x * h3y;
h( 9,0) = h1x * l3y; h( 9,1) = d1x * d3y; h( 9,2) = l1x * h3y;
h(10,0) = h0x * l2y; h(10,1) = d0x * d2y; h(10,2) = l0x * h2y;
h(11,0) = h0x * l1y; h(11,1) = d0x * d1y; h(11,2) = l0x * h1y;
h(12,0) = h1x * l1y; h(12,1) = d1x * d1y; h(12,2) = l1x * h1y;
h(13,0) = h2x * l1y; h(13,1) = d2x * d1y; h(13,2) = l2x * h1y;
h(14,0) = h1x * l2y; h(14,1) = d1x * d2y; h(14,2) = l1x * h2y;
h(15,0) = h2x * l2y; h(15,1) = d2x * d2y; h(15,2) = l2x * h2y;
}
Cubic1DFiniteElement::Cubic1DFiniteElement()
: NodalFiniteElement(1, Geometry::SEGMENT, 4, 3)
{
Nodes.IntPoint(0).x = 0.0;
Nodes.IntPoint(1).x = 1.0;
Nodes.IntPoint(2).x = 0.33333333333333333333;
Nodes.IntPoint(3).x = 0.66666666666666666667;
}
void Cubic1DFiniteElement::CalcShape(const IntegrationPoint &ip,
Vector &shape) const
{
double x = ip.x;
double l1 = x,
l2 = (1.0-x),
l3 = (0.33333333333333333333-x),
l4 = (0.66666666666666666667-x);
shape(0) = 4.5 * l2 * l3 * l4;
shape(1) = 4.5 * l1 * l3 * l4;
shape(2) = 13.5 * l1 * l2 * l4;
shape(3) = -13.5 * l1 * l2 * l3;
}
void Cubic1DFiniteElement::CalcDShape(const IntegrationPoint &ip,
DenseMatrix &dshape) const
{
double x = ip.x;
dshape(0,0) = -5.5 + x * (18. - 13.5 * x);
dshape(1,0) = 1. - x * (9. - 13.5 * x);
dshape(2,0) = 9. - x * (45. - 40.5 * x);
dshape(3,0) = -4.5 + x * (36. - 40.5 * x);
}
Cubic2DFiniteElement::Cubic2DFiniteElement()
: NodalFiniteElement(2, Geometry::TRIANGLE, 10, 3)
{
Nodes.IntPoint(0).x = 0.0;
Nodes.IntPoint(0).y = 0.0;
Nodes.IntPoint(1).x = 1.0;
Nodes.IntPoint(1).y = 0.0;
Nodes.IntPoint(2).x = 0.0;
Nodes.IntPoint(2).y = 1.0;
Nodes.IntPoint(3).x = 0.33333333333333333333;
Nodes.IntPoint(3).y = 0.0;
Nodes.IntPoint(4).x = 0.66666666666666666667;
Nodes.IntPoint(4).y = 0.0;
Nodes.IntPoint(5).x = 0.66666666666666666667;
Nodes.IntPoint(5).y = 0.33333333333333333333;
Nodes.IntPoint(6).x = 0.33333333333333333333;
Nodes.IntPoint(6).y = 0.66666666666666666667;
Nodes.IntPoint(7).x = 0.0;
Nodes.IntPoint(7).y = 0.66666666666666666667;
Nodes.IntPoint(8).x = 0.0;
Nodes.IntPoint(8).y = 0.33333333333333333333;
Nodes.IntPoint(9).x = 0.33333333333333333333;
Nodes.IntPoint(9).y = 0.33333333333333333333;
}
void Cubic2DFiniteElement::CalcShape(const IntegrationPoint &ip,
Vector &shape) const
{
double x = ip.x, y = ip.y;
double l1 = (-1. + x + y),
lx = (-1. + 3.*x),
ly = (-1. + 3.*y);
shape(0) = -0.5*l1*(3.*l1 + 1.)*(3.*l1 + 2.);
shape(1) = 0.5*x*(lx - 1.)*lx;
shape(2) = 0.5*y*(-1. + ly)*ly;
shape(3) = 4.5*x*l1*(3.*l1 + 1.);
shape(4) = -4.5*x*lx*l1;
shape(5) = 4.5*x*lx*y;
shape(6) = 4.5*x*y*ly;
shape(7) = -4.5*y*l1*ly;
shape(8) = 4.5*y*l1*(1. + 3.*l1);
shape(9) = -27.*x*y*l1;
}
void Cubic2DFiniteElement::CalcDShape(const IntegrationPoint &ip,
DenseMatrix &dshape) const
{
double x = ip.x, y = ip.y;
dshape(0,0) = 0.5*(-11. + 36.*y - 9.*(x*(-4. + 3.*x) + 6.*x*y + 3.*y*y));
dshape(1,0) = 1. + 4.5*x*(-2. + 3.*x);
dshape(2,0) = 0.;
dshape(3,0) = 4.5*(2. + 9.*x*x - 5.*y + 3.*y*y + 2.*x*(-5. + 6.*y));
dshape(4,0) = -4.5*(1. - 1.*y + x*(-8. + 9.*x + 6.*y));
dshape(5,0) = 4.5*(-1. + 6.*x)*y;
dshape(6,0) = 4.5*y*(-1. + 3.*y);
dshape(7,0) = 4.5*(1. - 3.*y)*y;
dshape(8,0) = 4.5*y*(-5. + 6.*x + 6.*y);
dshape(9,0) = -27.*y*(-1. + 2.*x + y);
dshape(0,1) = 0.5*(-11. + 36.*y - 9.*(x*(-4. + 3.*x) + 6.*x*y + 3.*y*y));
dshape(1,1) = 0.;
dshape(2,1) = 1. + 4.5*y*(-2. + 3.*y);
dshape(3,1) = 4.5*x*(-5. + 6.*x + 6.*y);
dshape(4,1) = 4.5*(1. - 3.*x)*x;
dshape(5,1) = 4.5*x*(-1. + 3.*x);
dshape(6,1) = 4.5*x*(-1. + 6.*y);
dshape(7,1) = -4.5*(1. + x*(-1. + 6.*y) + y*(-8. + 9.*y));
dshape(8,1) = 4.5*(2. + 3.*x*x + y*(-10. + 9.*y) + x*(-5. + 12.*y));
dshape(9,1) = -27.*x*(-1. + x + 2.*y);
}
void Cubic2DFiniteElement::CalcHessian (const IntegrationPoint &ip,
DenseMatrix &h) const
{
double x = ip.x, y = ip.y;
h(0,0) = 18.-27.*(x+y);
h(0,1) = 18.-27.*(x+y);
h(0,2) = 18.-27.*(x+y);
h(1,0) = -9.+27.*x;
h(1,1) = 0.;
h(1,2) = 0.;
h(2,0) = 0.;
h(2,1) = 0.;
h(2,2) = -9.+27.*y;
h(3,0) = -45.+81.*x+54.*y;
h(3,1) = -22.5+54.*x+27.*y;
h(3,2) = 27.*x;
h(4,0) = 36.-81.*x-27.*y;
h(4,1) = 4.5-27.*x;
h(4,2) = 0.;
h(5,0) = 27.*y;
h(5,1) = -4.5+27.*x;
h(5,2) = 0.;
h(6,0) = 0.;
h(6,1) = -4.5+27.*y;
h(6,2) = 27.*x;
h(7,0) = 0.;
h(7,1) = 4.5-27.*y;
h(7,2) = 36.-27.*x-81.*y;
h(8,0) = 27.*y;
h(8,1) = -22.5+27.*x+54.*y;
h(8,2) = -45.+54.*x+81.*y;
h(9,0) = -54.*y;
h(9,1) = 27.-54.*(x+y);
h(9,2) = -54.*x;
}
Cubic3DFiniteElement::Cubic3DFiniteElement()
: NodalFiniteElement(3, Geometry::TETRAHEDRON, 20, 3)
{
Nodes.IntPoint(0).x = 0;
Nodes.IntPoint(0).y = 0;
Nodes.IntPoint(0).z = 0;
Nodes.IntPoint(1).x = 1.;
Nodes.IntPoint(1).y = 0;
Nodes.IntPoint(1).z = 0;
Nodes.IntPoint(2).x = 0;
Nodes.IntPoint(2).y = 1.;
Nodes.IntPoint(2).z = 0;
Nodes.IntPoint(3).x = 0;
Nodes.IntPoint(3).y = 0;
Nodes.IntPoint(3).z = 1.;
Nodes.IntPoint(4).x = 0.3333333333333333333333333333;
Nodes.IntPoint(4).y = 0;
Nodes.IntPoint(4).z = 0;
Nodes.IntPoint(5).x = 0.6666666666666666666666666667;
Nodes.IntPoint(5).y = 0;
Nodes.IntPoint(5).z = 0;
Nodes.IntPoint(6).x = 0;
Nodes.IntPoint(6).y = 0.3333333333333333333333333333;
Nodes.IntPoint(6).z = 0;
Nodes.IntPoint(7).x = 0;
Nodes.IntPoint(7).y = 0.6666666666666666666666666667;
Nodes.IntPoint(7).z = 0;
Nodes.IntPoint(8).x = 0;
Nodes.IntPoint(8).y = 0;
Nodes.IntPoint(8).z = 0.3333333333333333333333333333;
Nodes.IntPoint(9).x = 0;
Nodes.IntPoint(9).y = 0;
Nodes.IntPoint(9).z = 0.6666666666666666666666666667;
Nodes.IntPoint(10).x = 0.6666666666666666666666666667;
Nodes.IntPoint(10).y = 0.3333333333333333333333333333;
Nodes.IntPoint(10).z = 0;
Nodes.IntPoint(11).x = 0.3333333333333333333333333333;
Nodes.IntPoint(11).y = 0.6666666666666666666666666667;
Nodes.IntPoint(11).z = 0;
Nodes.IntPoint(12).x = 0.6666666666666666666666666667;
Nodes.IntPoint(12).y = 0;
Nodes.IntPoint(12).z = 0.3333333333333333333333333333;
Nodes.IntPoint(13).x = 0.3333333333333333333333333333;
Nodes.IntPoint(13).y = 0;
Nodes.IntPoint(13).z = 0.6666666666666666666666666667;
Nodes.IntPoint(14).x = 0;
Nodes.IntPoint(14).y = 0.6666666666666666666666666667;
Nodes.IntPoint(14).z = 0.3333333333333333333333333333;
Nodes.IntPoint(15).x = 0;
Nodes.IntPoint(15).y = 0.3333333333333333333333333333;
Nodes.IntPoint(15).z = 0.6666666666666666666666666667;
Nodes.IntPoint(16).x = 0.3333333333333333333333333333;
Nodes.IntPoint(16).y = 0.3333333333333333333333333333;
Nodes.IntPoint(16).z = 0.3333333333333333333333333333;
Nodes.IntPoint(17).x = 0;
Nodes.IntPoint(17).y = 0.3333333333333333333333333333;
Nodes.IntPoint(17).z = 0.3333333333333333333333333333;
Nodes.IntPoint(18).x = 0.3333333333333333333333333333;
Nodes.IntPoint(18).y = 0;
Nodes.IntPoint(18).z = 0.3333333333333333333333333333;
Nodes.IntPoint(19).x = 0.3333333333333333333333333333;
Nodes.IntPoint(19).y = 0.3333333333333333333333333333;
Nodes.IntPoint(19).z = 0;
}
void Cubic3DFiniteElement::CalcShape(const IntegrationPoint &ip,
Vector &shape) const
{
double x = ip.x, y = ip.y, z = ip.z;
shape(0) = -((-1 + x + y + z)*(-2 + 3*x + 3*y + 3*z)*
(-1 + 3*x + 3*y + 3*z))/2.;
shape(4) = (9*x*(-1 + x + y + z)*(-2 + 3*x + 3*y + 3*z))/2.;
shape(5) = (-9*x*(-1 + 3*x)*(-1 + x + y + z))/2.;
shape(1) = (x*(2 + 9*(-1 + x)*x))/2.;
shape(6) = (9*y*(-1 + x + y + z)*(-2 + 3*x + 3*y + 3*z))/2.;
shape(19) = -27*x*y*(-1 + x + y + z);
shape(10) = (9*x*(-1 + 3*x)*y)/2.;
shape(7) = (-9*y*(-1 + 3*y)*(-1 + x + y + z))/2.;
shape(11) = (9*x*y*(-1 + 3*y))/2.;
shape(2) = (y*(2 + 9*(-1 + y)*y))/2.;
shape(8) = (9*z*(-1 + x + y + z)*(-2 + 3*x + 3*y + 3*z))/2.;
shape(18) = -27*x*z*(-1 + x + y + z);
shape(12) = (9*x*(-1 + 3*x)*z)/2.;
shape(17) = -27*y*z*(-1 + x + y + z);
shape(16) = 27*x*y*z;
shape(14) = (9*y*(-1 + 3*y)*z)/2.;
shape(9) = (-9*z*(-1 + x + y + z)*(-1 + 3*z))/2.;
shape(13) = (9*x*z*(-1 + 3*z))/2.;
shape(15) = (9*y*z*(-1 + 3*z))/2.;
shape(3) = (z*(2 + 9*(-1 + z)*z))/2.;
}
void Cubic3DFiniteElement::CalcDShape(const IntegrationPoint &ip,
DenseMatrix &dshape) const
{
double x = ip.x, y = ip.y, z = ip.z;
dshape(0,0) = (-11 + 36*y + 36*z - 9*(3*pow(x,2) + 3*pow(y + z,2) +
x*(-4 + 6*y + 6*z)))/2.;
dshape(0,1) = (-11 + 36*y + 36*z - 9*(3*pow(x,2) + 3*pow(y + z,2) +
x*(-4 + 6*y + 6*z)))/2.;
dshape(0,2) = (-11 + 36*y + 36*z - 9*(3*pow(x,2) + 3*pow(y + z,2) +
x*(-4 + 6*y + 6*z)))/2.;
dshape(4,0) = (9*(9*pow(x,2) + (-1 + y + z)*(-2 + 3*y + 3*z) +
2*x*(-5 + 6*y + 6*z)))/2.;
dshape(4,1) = (9*x*(-5 + 6*x + 6*y + 6*z))/2.;
dshape(4,2) = (9*x*(-5 + 6*x + 6*y + 6*z))/2.;
dshape(5,0) = (-9*(1 - y - z + x*(-8 + 9*x + 6*y + 6*z)))/2.;
dshape(5,1) = (9*(1 - 3*x)*x)/2.;
dshape(5,2) = (9*(1 - 3*x)*x)/2.;
dshape(1,0) = 1 + (9*x*(-2 + 3*x))/2.;
dshape(1,1) = 0;
dshape(1,2) = 0;
dshape(6,0) = (9*y*(-5 + 6*x + 6*y + 6*z))/2.;
dshape(6,1) = (9*(2 + 3*pow(x,2) - 10*y - 5*z + 3*(y + z)*(3*y + z) +
x*(-5 + 12*y + 6*z)))/2.;
dshape(6,2) = (9*y*(-5 + 6*x + 6*y + 6*z))/2.;
dshape(19,0) = -27*y*(-1 + 2*x + y + z);
dshape(19,1) = -27*x*(-1 + x + 2*y + z);
dshape(19,2) = -27*x*y;
dshape(10,0) = (9*(-1 + 6*x)*y)/2.;
dshape(10,1) = (9*x*(-1 + 3*x))/2.;
dshape(10,2) = 0;
dshape(7,0) = (9*(1 - 3*y)*y)/2.;
dshape(7,1) = (-9*(1 + x*(-1 + 6*y) - z + y*(-8 + 9*y + 6*z)))/2.;
dshape(7,2) = (9*(1 - 3*y)*y)/2.;
dshape(11,0) = (9*y*(-1 + 3*y))/2.;
dshape(11,1) = (9*x*(-1 + 6*y))/2.;
dshape(11,2) = 0;
dshape(2,0) = 0;
dshape(2,1) = 1 + (9*y*(-2 + 3*y))/2.;
dshape(2,2) = 0;
dshape(8,0) = (9*z*(-5 + 6*x + 6*y + 6*z))/2.;
dshape(8,1) = (9*z*(-5 + 6*x + 6*y + 6*z))/2.;
dshape(8,2) = (9*(2 + 3*pow(x,2) - 5*y - 10*z + 3*(y + z)*(y + 3*z) +
x*(-5 + 6*y + 12*z)))/2.;
dshape(18,0) = -27*z*(-1 + 2*x + y + z);
dshape(18,1) = -27*x*z;
dshape(18,2) = -27*x*(-1 + x + y + 2*z);
dshape(12,0) = (9*(-1 + 6*x)*z)/2.;
dshape(12,1) = 0;
dshape(12,2) = (9*x*(-1 + 3*x))/2.;
dshape(17,0) = -27*y*z;
dshape(17,1) = -27*z*(-1 + x + 2*y + z);
dshape(17,2) = -27*y*(-1 + x + y + 2*z);
dshape(16,0) = 27*y*z;
dshape(16,1) = 27*x*z;
dshape(16,2) = 27*x*y;
dshape(14,0) = 0;
dshape(14,1) = (9*(-1 + 6*y)*z)/2.;
dshape(14,2) = (9*y*(-1 + 3*y))/2.;
dshape(9,0) = (9*(1 - 3*z)*z)/2.;
dshape(9,1) = (9*(1 - 3*z)*z)/2.;
dshape(9,2) = (9*(-1 + x + y + 8*z - 6*(x + y)*z - 9*pow(z,2)))/2.;
dshape(13,0) = (9*z*(-1 + 3*z))/2.;
dshape(13,1) = 0;
dshape(13,2) = (9*x*(-1 + 6*z))/2.;
dshape(15,0) = 0;
dshape(15,1) = (9*z*(-1 + 3*z))/2.;
dshape(15,2) = (9*y*(-1 + 6*z))/2.;
dshape(3,0) = 0;
dshape(3,1) = 0;
dshape(3,2) = 1 + (9*z*(-2 + 3*z))/2.;
}
P0TriangleFiniteElement::P0TriangleFiniteElement()
: NodalFiniteElement(2, Geometry::TRIANGLE, 1, 0)
{
Nodes.IntPoint(0).x = 0.333333333333333333;
Nodes.IntPoint(0).y = 0.333333333333333333;
}
void P0TriangleFiniteElement::CalcShape(const IntegrationPoint &ip,
Vector &shape) const
{
shape(0) = 1.0;
}
void P0TriangleFiniteElement::CalcDShape(const IntegrationPoint &ip,
DenseMatrix &dshape) const
{
dshape(0,0) = 0.0;
dshape(0,1) = 0.0;
}
P0QuadFiniteElement::P0QuadFiniteElement()
: NodalFiniteElement(2, Geometry::SQUARE, 1, 0, FunctionSpace::Qk)
{
Nodes.IntPoint(0).x = 0.5;
Nodes.IntPoint(0).y = 0.5;
}
void P0QuadFiniteElement::CalcShape(const IntegrationPoint &ip,
Vector &shape) const
{
shape(0) = 1.0;
}
void P0QuadFiniteElement::CalcDShape(const IntegrationPoint &ip,
DenseMatrix &dshape) const
{
dshape(0,0) = 0.0;
dshape(0,1) = 0.0;
}
Linear3DFiniteElement::Linear3DFiniteElement()
: NodalFiniteElement(3, Geometry::TETRAHEDRON, 4, 1)
{
Nodes.IntPoint(0).x = 0.0;
Nodes.IntPoint(0).y = 0.0;
Nodes.IntPoint(0).z = 0.0;
Nodes.IntPoint(1).x = 1.0;
Nodes.IntPoint(1).y = 0.0;
Nodes.IntPoint(1).z = 0.0;
Nodes.IntPoint(2).x = 0.0;
Nodes.IntPoint(2).y = 1.0;
Nodes.IntPoint(2).z = 0.0;
Nodes.IntPoint(3).x = 0.0;
Nodes.IntPoint(3).y = 0.0;
Nodes.IntPoint(3).z = 1.0;
}
void Linear3DFiniteElement::CalcShape(const IntegrationPoint &ip,
Vector &shape) const
{
shape(0) = 1. - ip.x - ip.y - ip.z;
shape(1) = ip.x;
shape(2) = ip.y;
shape(3) = ip.z;
}
void Linear3DFiniteElement::CalcDShape(const IntegrationPoint &ip,
DenseMatrix &dshape) const
{
if (dshape.Height() == 4)
{
double *A = &dshape(0,0);
A[0] = -1.; A[4] = -1.; A[8] = -1.;
A[1] = 1.; A[5] = 0.; A[9] = 0.;
A[2] = 0.; A[6] = 1.; A[10] = 0.;
A[3] = 0.; A[7] = 0.; A[11] = 1.;
}
else
{
dshape(0,0) = -1.; dshape(0,1) = -1.; dshape(0,2) = -1.;
dshape(1,0) = 1.; dshape(1,1) = 0.; dshape(1,2) = 0.;
dshape(2,0) = 0.; dshape(2,1) = 1.; dshape(2,2) = 0.;
dshape(3,0) = 0.; dshape(3,1) = 0.; dshape(3,2) = 1.;
}
}
void Linear3DFiniteElement::GetFaceDofs (int face, int **dofs, int *ndofs)
const
{
static int face_dofs[4][3] = {{1, 2, 3}, {0, 2, 3}, {0, 1, 3}, {0, 1, 2}};
*ndofs = 3;
*dofs = face_dofs[face];
}
Quadratic3DFiniteElement::Quadratic3DFiniteElement()
: NodalFiniteElement(3, Geometry::TETRAHEDRON, 10, 2)
{
Nodes.IntPoint(0).x = 0.0;
Nodes.IntPoint(0).y = 0.0;
Nodes.IntPoint(0).z = 0.0;
Nodes.IntPoint(1).x = 1.0;
Nodes.IntPoint(1).y = 0.0;
Nodes.IntPoint(1).z = 0.0;
Nodes.IntPoint(2).x = 0.0;
Nodes.IntPoint(2).y = 1.0;
Nodes.IntPoint(2).z = 0.0;
Nodes.IntPoint(3).x = 0.0;
Nodes.IntPoint(3).y = 0.0;
Nodes.IntPoint(3).z = 1.0;
Nodes.IntPoint(4).x = 0.5;
Nodes.IntPoint(4).y = 0.0;
Nodes.IntPoint(4).z = 0.0;
Nodes.IntPoint(5).x = 0.0;
Nodes.IntPoint(5).y = 0.5;
Nodes.IntPoint(5).z = 0.0;
Nodes.IntPoint(6).x = 0.0;
Nodes.IntPoint(6).y = 0.0;
Nodes.IntPoint(6).z = 0.5;
Nodes.IntPoint(7).x = 0.5;
Nodes.IntPoint(7).y = 0.5;
Nodes.IntPoint(7).z = 0.0;
Nodes.IntPoint(8).x = 0.5;
Nodes.IntPoint(8).y = 0.0;
Nodes.IntPoint(8).z = 0.5;
Nodes.IntPoint(9).x = 0.0;
Nodes.IntPoint(9).y = 0.5;
Nodes.IntPoint(9).z = 0.5;
}
void Quadratic3DFiniteElement::CalcShape(const IntegrationPoint &ip,
Vector &shape) const
{
double L0, L1, L2, L3;
L0 = 1. - ip.x - ip.y - ip.z;
L1 = ip.x;
L2 = ip.y;
L3 = ip.z;
shape(0) = L0 * ( 2.0 * L0 - 1.0 );
shape(1) = L1 * ( 2.0 * L1 - 1.0 );
shape(2) = L2 * ( 2.0 * L2 - 1.0 );
shape(3) = L3 * ( 2.0 * L3 - 1.0 );
shape(4) = 4.0 * L0 * L1;
shape(5) = 4.0 * L0 * L2;
shape(6) = 4.0 * L0 * L3;
shape(7) = 4.0 * L1 * L2;
shape(8) = 4.0 * L1 * L3;
shape(9) = 4.0 * L2 * L3;
}
void Quadratic3DFiniteElement::CalcDShape(const IntegrationPoint &ip,
DenseMatrix &dshape) const
{
double x, y, z, L0;
x = ip.x;
y = ip.y;
z = ip.z;
L0 = 1.0 - x - y - z;
dshape(0,0) = dshape(0,1) = dshape(0,2) = 1.0 - 4.0 * L0;
dshape(1,0) = -1.0 + 4.0 * x; dshape(1,1) = 0.0; dshape(1,2) = 0.0;
dshape(2,0) = 0.0; dshape(2,1) = -1.0 + 4.0 * y; dshape(2,2) = 0.0;
dshape(3,0) = dshape(3,1) = 0.0; dshape(3,2) = -1.0 + 4.0 * z;
dshape(4,0) = 4.0 * (L0 - x); dshape(4,1) = dshape(4,2) = -4.0 * x;
dshape(5,0) = dshape(5,2) = -4.0 * y; dshape(5,1) = 4.0 * (L0 - y);
dshape(6,0) = dshape(6,1) = -4.0 * z; dshape(6,2) = 4.0 * (L0 - z);
dshape(7,0) = 4.0 * y; dshape(7,1) = 4.0 * x; dshape(7,2) = 0.0;
dshape(8,0) = 4.0 * z; dshape(8,1) = 0.0; dshape(8,2) = 4.0 * x;
dshape(9,0) = 0.0; dshape(9,1) = 4.0 * z; dshape(9,2) = 4.0 * y;
}
TriLinear3DFiniteElement::TriLinear3DFiniteElement()
: NodalFiniteElement(3, Geometry::CUBE, 8, 1, FunctionSpace::Qk)
{
Nodes.IntPoint(0).x = 0.0;
Nodes.IntPoint(0).y = 0.0;
Nodes.IntPoint(0).z = 0.0;
Nodes.IntPoint(1).x = 1.0;
Nodes.IntPoint(1).y = 0.0;
Nodes.IntPoint(1).z = 0.0;
Nodes.IntPoint(2).x = 1.0;
Nodes.IntPoint(2).y = 1.0;
Nodes.IntPoint(2).z = 0.0;
Nodes.IntPoint(3).x = 0.0;
Nodes.IntPoint(3).y = 1.0;
Nodes.IntPoint(3).z = 0.0;
Nodes.IntPoint(4).x = 0.0;
Nodes.IntPoint(4).y = 0.0;
Nodes.IntPoint(4).z = 1.0;
Nodes.IntPoint(5).x = 1.0;
Nodes.IntPoint(5).y = 0.0;
Nodes.IntPoint(5).z = 1.0;
Nodes.IntPoint(6).x = 1.0;
Nodes.IntPoint(6).y = 1.0;
Nodes.IntPoint(6).z = 1.0;
Nodes.IntPoint(7).x = 0.0;
Nodes.IntPoint(7).y = 1.0;
Nodes.IntPoint(7).z = 1.0;
}
void TriLinear3DFiniteElement::CalcShape(const IntegrationPoint &ip,
Vector &shape) const
{
double x = ip.x, y = ip.y, z = ip.z;
double ox = 1.-x, oy = 1.-y, oz = 1.-z;
shape(0) = ox * oy * oz;
shape(1) = x * oy * oz;
shape(2) = x * y * oz;
shape(3) = ox * y * oz;
shape(4) = ox * oy * z;
shape(5) = x * oy * z;
shape(6) = x * y * z;
shape(7) = ox * y * z;
}
void TriLinear3DFiniteElement::CalcDShape(const IntegrationPoint &ip,
DenseMatrix &dshape) const
{
double x = ip.x, y = ip.y, z = ip.z;
double ox = 1.-x, oy = 1.-y, oz = 1.-z;
dshape(0,0) = - oy * oz;
dshape(0,1) = - ox * oz;
dshape(0,2) = - ox * oy;
dshape(1,0) = oy * oz;
dshape(1,1) = - x * oz;
dshape(1,2) = - x * oy;
dshape(2,0) = y * oz;
dshape(2,1) = x * oz;
dshape(2,2) = - x * y;
dshape(3,0) = - y * oz;
dshape(3,1) = ox * oz;
dshape(3,2) = - ox * y;
dshape(4,0) = - oy * z;
dshape(4,1) = - ox * z;
dshape(4,2) = ox * oy;
dshape(5,0) = oy * z;
dshape(5,1) = - x * z;
dshape(5,2) = x * oy;
dshape(6,0) = y * z;
dshape(6,1) = x * z;
dshape(6,2) = x * y;
dshape(7,0) = - y * z;
dshape(7,1) = ox * z;
dshape(7,2) = ox * y;
}
P0SegmentFiniteElement::P0SegmentFiniteElement(int Ord)
: NodalFiniteElement(1, Geometry::SEGMENT, 1, Ord) // default Ord = 0
{
Nodes.IntPoint(0).x = 0.5;
}
void P0SegmentFiniteElement::CalcShape(const IntegrationPoint &ip,
Vector &shape) const
{
shape(0) = 1.0;
}
void P0SegmentFiniteElement::CalcDShape(const IntegrationPoint &ip,
DenseMatrix &dshape) const
{
dshape(0,0) = 0.0;
}
CrouzeixRaviartFiniteElement::CrouzeixRaviartFiniteElement()
: NodalFiniteElement(2, Geometry::TRIANGLE, 3, 1)
{
Nodes.IntPoint(0).x = 0.5;
Nodes.IntPoint(0).y = 0.0;
Nodes.IntPoint(1).x = 0.5;
Nodes.IntPoint(1).y = 0.5;
Nodes.IntPoint(2).x = 0.0;
Nodes.IntPoint(2).y = 0.5;
}
void CrouzeixRaviartFiniteElement::CalcShape(const IntegrationPoint &ip,
Vector &shape) const
{
shape(0) = 1.0 - 2.0 * ip.y;
shape(1) = -1.0 + 2.0 * ( ip.x + ip.y );
shape(2) = 1.0 - 2.0 * ip.x;
}
void CrouzeixRaviartFiniteElement::CalcDShape(const IntegrationPoint &ip,
DenseMatrix &dshape) const
{
dshape(0,0) = 0.0; dshape(0,1) = -2.0;
dshape(1,0) = 2.0; dshape(1,1) = 2.0;
dshape(2,0) = -2.0; dshape(2,1) = 0.0;
}
CrouzeixRaviartQuadFiniteElement::CrouzeixRaviartQuadFiniteElement()
// the FunctionSpace should be rotated (45 degrees) Q_1
// i.e. the span of { 1, x, y, x^2 - y^2 }
: NodalFiniteElement(2, Geometry::SQUARE, 4, 2, FunctionSpace::Qk)
{
Nodes.IntPoint(0).x = 0.5;
Nodes.IntPoint(0).y = 0.0;
Nodes.IntPoint(1).x = 1.0;
Nodes.IntPoint(1).y = 0.5;
Nodes.IntPoint(2).x = 0.5;
Nodes.IntPoint(2).y = 1.0;
Nodes.IntPoint(3).x = 0.0;
Nodes.IntPoint(3).y = 0.5;
}
void CrouzeixRaviartQuadFiniteElement::CalcShape(const IntegrationPoint &ip,
Vector &shape) const
{
const double l1 = ip.x+ip.y-0.5, l2 = 1.-l1, l3 = ip.x-ip.y+0.5, l4 = 1.-l3;
shape(0) = l2 * l3;
shape(1) = l1 * l3;
shape(2) = l1 * l4;
shape(3) = l2 * l4;
}
void CrouzeixRaviartQuadFiniteElement::CalcDShape(const IntegrationPoint &ip,
DenseMatrix &dshape) const
{
const double x2 = 2.*ip.x, y2 = 2.*ip.y;
dshape(0,0) = 1. - x2; dshape(0,1) = -2. + y2;
dshape(1,0) = x2; dshape(1,1) = 1. - y2;
dshape(2,0) = 1. - x2; dshape(2,1) = y2;
dshape(3,0) = -2. + x2; dshape(3,1) = 1. - y2;
}
RT0TriangleFiniteElement::RT0TriangleFiniteElement()
: VectorFiniteElement(2, Geometry::TRIANGLE, 3, 1, H_DIV)
{
Nodes.IntPoint(0).x = 0.5;
Nodes.IntPoint(0).y = 0.0;
Nodes.IntPoint(1).x = 0.5;
Nodes.IntPoint(1).y = 0.5;
Nodes.IntPoint(2).x = 0.0;
Nodes.IntPoint(2).y = 0.5;
}
void RT0TriangleFiniteElement::CalcVShape(const IntegrationPoint &ip,
DenseMatrix &shape) const
{
double x = ip.x, y = ip.y;
shape(0,0) = x;
shape(0,1) = y - 1.;
shape(1,0) = x;
shape(1,1) = y;
shape(2,0) = x - 1.;
shape(2,1) = y;
}
void RT0TriangleFiniteElement::CalcDivShape(const IntegrationPoint &ip,
Vector &divshape) const
{
divshape(0) = 2.;
divshape(1) = 2.;
divshape(2) = 2.;
}
const double RT0TriangleFiniteElement::nk[3][2] =
{ {0, -1}, {1, 1}, {-1, 0} };
void RT0TriangleFiniteElement::GetLocalInterpolation (
ElementTransformation &Trans, DenseMatrix &I) const
{
int k, j;
#ifdef MFEM_THREAD_SAFE
DenseMatrix vshape(dof, dim);
DenseMatrix Jinv(dim);
#endif
#ifdef MFEM_DEBUG
for (k = 0; k < 3; k++)
{
CalcVShape (Nodes.IntPoint(k), vshape);
for (j = 0; j < 3; j++)
{
double d = vshape(j,0)*nk[k][0]+vshape(j,1)*nk[k][1];
if (j == k) { d -= 1.0; }
if (fabs(d) > 1.0e-12)
{
mfem::err << "RT0TriangleFiniteElement::GetLocalInterpolation (...)\n"
" k = " << k << ", j = " << j << ", d = " << d << endl;
mfem_error();
}
}
}
#endif
IntegrationPoint ip;
ip.x = ip.y = 0.0;
Trans.SetIntPoint (&ip);
// Trans must be linear
// set Jinv = |J| J^{-t} = adj(J)^t
CalcAdjugateTranspose (Trans.Jacobian(), Jinv);
double vk[2];
Vector xk (vk, 2);
for (k = 0; k < 3; k++)
{
Trans.Transform (Nodes.IntPoint (k), xk);
ip.x = vk[0]; ip.y = vk[1];
CalcVShape (ip, vshape);
// vk = |J| J^{-t} nk
vk[0] = Jinv(0,0)*nk[k][0]+Jinv(0,1)*nk[k][1];
vk[1] = Jinv(1,0)*nk[k][0]+Jinv(1,1)*nk[k][1];
for (j = 0; j < 3; j++)
if (fabs (I(k,j) = vshape(j,0)*vk[0]+vshape(j,1)*vk[1]) < 1.0e-12)
{
I(k,j) = 0.0;
}
}
}
void RT0TriangleFiniteElement::Project (
VectorCoefficient &vc, ElementTransformation &Trans,
Vector &dofs) const
{
double vk[2];
Vector xk (vk, 2);
#ifdef MFEM_THREAD_SAFE
DenseMatrix Jinv(dim);
#endif
for (int k = 0; k < 3; k++)
{
Trans.SetIntPoint (&Nodes.IntPoint (k));
// set Jinv = |J| J^{-t} = adj(J)^t
CalcAdjugateTranspose (Trans.Jacobian(), Jinv);
vc.Eval (xk, Trans, Nodes.IntPoint (k));
// xk^t |J| J^{-t} nk
dofs(k) = (vk[0] * ( Jinv(0,0)*nk[k][0]+Jinv(0,1)*nk[k][1] ) +
vk[1] * ( Jinv(1,0)*nk[k][0]+Jinv(1,1)*nk[k][1] ));
}
}
RT0QuadFiniteElement::RT0QuadFiniteElement()
: VectorFiniteElement(2, Geometry::SQUARE, 4, 1, H_DIV, FunctionSpace::Qk)
{
Nodes.IntPoint(0).x = 0.5;
Nodes.IntPoint(0).y = 0.0;
Nodes.IntPoint(1).x = 1.0;
Nodes.IntPoint(1).y = 0.5;
Nodes.IntPoint(2).x = 0.5;
Nodes.IntPoint(2).y = 1.0;
Nodes.IntPoint(3).x = 0.0;
Nodes.IntPoint(3).y = 0.5;
}
void RT0QuadFiniteElement::CalcVShape(const IntegrationPoint &ip,
DenseMatrix &shape) const
{
double x = ip.x, y = ip.y;
shape(0,0) = 0;
shape(0,1) = y - 1.;
shape(1,0) = x;
shape(1,1) = 0;
shape(2,0) = 0;
shape(2,1) = y;
shape(3,0) = x - 1.;
shape(3,1) = 0;
}
void RT0QuadFiniteElement::CalcDivShape(const IntegrationPoint &ip,
Vector &divshape) const
{
divshape(0) = 1.;
divshape(1) = 1.;
divshape(2) = 1.;
divshape(3) = 1.;
}
const double RT0QuadFiniteElement::nk[4][2] =
{ {0, -1}, {1, 0}, {0, 1}, {-1, 0} };
void RT0QuadFiniteElement::GetLocalInterpolation (
ElementTransformation &Trans, DenseMatrix &I) const
{
int k, j;
#ifdef MFEM_THREAD_SAFE
DenseMatrix vshape(dof, dim);
DenseMatrix Jinv(dim);
#endif
#ifdef MFEM_DEBUG
for (k = 0; k < 4; k++)
{
CalcVShape (Nodes.IntPoint(k), vshape);
for (j = 0; j < 4; j++)
{
double d = vshape(j,0)*nk[k][0]+vshape(j,1)*nk[k][1];
if (j == k) { d -= 1.0; }
if (fabs(d) > 1.0e-12)
{
mfem::err << "RT0QuadFiniteElement::GetLocalInterpolation (...)\n"
" k = " << k << ", j = " << j << ", d = " << d << endl;
mfem_error();
}
}
}
#endif
IntegrationPoint ip;
ip.x = ip.y = 0.0;
Trans.SetIntPoint (&ip);
// Trans must be linear (more to have embedding?)
// set Jinv = |J| J^{-t} = adj(J)^t
CalcAdjugateTranspose (Trans.Jacobian(), Jinv);
double vk[2];
Vector xk (vk, 2);
for (k = 0; k < 4; k++)
{
Trans.Transform (Nodes.IntPoint (k), xk);
ip.x = vk[0]; ip.y = vk[1];
CalcVShape (ip, vshape);
// vk = |J| J^{-t} nk
vk[0] = Jinv(0,0)*nk[k][0]+Jinv(0,1)*nk[k][1];
vk[1] = Jinv(1,0)*nk[k][0]+Jinv(1,1)*nk[k][1];
for (j = 0; j < 4; j++)
if (fabs (I(k,j) = vshape(j,0)*vk[0]+vshape(j,1)*vk[1]) < 1.0e-12)
{
I(k,j) = 0.0;
}
}
}
void RT0QuadFiniteElement::Project (
VectorCoefficient &vc, ElementTransformation &Trans,
Vector &dofs) const
{
double vk[2];
Vector xk (vk, 2);
#ifdef MFEM_THREAD_SAFE
DenseMatrix Jinv(dim);
#endif
for (int k = 0; k < 4; k++)
{
Trans.SetIntPoint (&Nodes.IntPoint (k));
// set Jinv = |J| J^{-t} = adj(J)^t
CalcAdjugateTranspose (Trans.Jacobian(), Jinv);
vc.Eval (xk, Trans, Nodes.IntPoint (k));
// xk^t |J| J^{-t} nk
dofs(k) = (vk[0] * ( Jinv(0,0)*nk[k][0]+Jinv(0,1)*nk[k][1] ) +
vk[1] * ( Jinv(1,0)*nk[k][0]+Jinv(1,1)*nk[k][1] ));
}
}
RT1TriangleFiniteElement::RT1TriangleFiniteElement()
: VectorFiniteElement(2, Geometry::TRIANGLE, 8, 2, H_DIV)
{
Nodes.IntPoint(0).x = 0.33333333333333333333;
Nodes.IntPoint(0).y = 0.0;
Nodes.IntPoint(1).x = 0.66666666666666666667;
Nodes.IntPoint(1).y = 0.0;
Nodes.IntPoint(2).x = 0.66666666666666666667;
Nodes.IntPoint(2).y = 0.33333333333333333333;
Nodes.IntPoint(3).x = 0.33333333333333333333;
Nodes.IntPoint(3).y = 0.66666666666666666667;
Nodes.IntPoint(4).x = 0.0;
Nodes.IntPoint(4).y = 0.66666666666666666667;
Nodes.IntPoint(5).x = 0.0;
Nodes.IntPoint(5).y = 0.33333333333333333333;
Nodes.IntPoint(6).x = 0.33333333333333333333;
Nodes.IntPoint(6).y = 0.33333333333333333333;
Nodes.IntPoint(7).x = 0.33333333333333333333;
Nodes.IntPoint(7).y = 0.33333333333333333333;
}
void RT1TriangleFiniteElement::CalcVShape(const IntegrationPoint &ip,
DenseMatrix &shape) const
{
double x = ip.x, y = ip.y;
shape(0,0) = -2 * x * (-1 + x + 2 * y);
shape(0,1) = -2 * (-1 + y) * (-1 + x + 2 * y);
shape(1,0) = 2 * x * (x - y);
shape(1,1) = 2 * (x - y) * (-1 + y);
shape(2,0) = 2 * x * (-1 + 2 * x + y);
shape(2,1) = 2 * y * (-1 + 2 * x + y);
shape(3,0) = 2 * x * (-1 + x + 2 * y);
shape(3,1) = 2 * y * (-1 + x + 2 * y);
shape(4,0) = -2 * (-1 + x) * (x - y);
shape(4,1) = 2 * y * (-x + y);
shape(5,0) = -2 * (-1 + x) * (-1 + 2 * x + y);
shape(5,1) = -2 * y * (-1 + 2 * x + y);
shape(6,0) = -3 * x * (-2 + 2 * x + y);
shape(6,1) = -3 * y * (-1 + 2 * x + y);
shape(7,0) = -3 * x * (-1 + x + 2 * y);
shape(7,1) = -3 * y * (-2 + x + 2 * y);
}
void RT1TriangleFiniteElement::CalcDivShape(const IntegrationPoint &ip,
Vector &divshape) const
{
double x = ip.x, y = ip.y;
divshape(0) = -2 * (-4 + 3 * x + 6 * y);
divshape(1) = 2 + 6 * x - 6 * y;
divshape(2) = -4 + 12 * x + 6 * y;
divshape(3) = -4 + 6 * x + 12 * y;
divshape(4) = 2 - 6 * x + 6 * y;
divshape(5) = -2 * (-4 + 6 * x + 3 * y);
divshape(6) = -9 * (-1 + 2 * x + y);
divshape(7) = -9 * (-1 + x + 2 * y);
}
const double RT1TriangleFiniteElement::nk[8][2] =
{
{ 0,-1}, { 0,-1},
{ 1, 1}, { 1, 1},
{-1, 0}, {-1, 0},
{ 1, 0}, { 0, 1}
};
void RT1TriangleFiniteElement::GetLocalInterpolation (
ElementTransformation &Trans, DenseMatrix &I) const
{
int k, j;
#ifdef MFEM_THREAD_SAFE
DenseMatrix vshape(dof, dim);
DenseMatrix Jinv(dim);
#endif
#ifdef MFEM_DEBUG
for (k = 0; k < 8; k++)
{
CalcVShape (Nodes.IntPoint(k), vshape);
for (j = 0; j < 8; j++)
{
double d = vshape(j,0)*nk[k][0]+vshape(j,1)*nk[k][1];
if (j == k) { d -= 1.0; }
if (fabs(d) > 1.0e-12)
{
mfem::err << "RT1QuadFiniteElement::GetLocalInterpolation (...)\n"
" k = " << k << ", j = " << j << ", d = " << d << endl;
mfem_error();
}
}
}
#endif
IntegrationPoint ip;
ip.x = ip.y = 0.0;
Trans.SetIntPoint (&ip);
// Trans must be linear (more to have embedding?)
// set Jinv = |J| J^{-t} = adj(J)^t
CalcAdjugateTranspose (Trans.Jacobian(), Jinv);
double vk[2];
Vector xk (vk, 2);
for (k = 0; k < 8; k++)
{
Trans.Transform (Nodes.IntPoint (k), xk);
ip.x = vk[0]; ip.y = vk[1];
CalcVShape (ip, vshape);
// vk = |J| J^{-t} nk
vk[0] = Jinv(0,0)*nk[k][0]+Jinv(0,1)*nk[k][1];
vk[1] = Jinv(1,0)*nk[k][0]+Jinv(1,1)*nk[k][1];
for (j = 0; j < 8; j++)
if (fabs (I(k,j) = vshape(j,0)*vk[0]+vshape(j,1)*vk[1]) < 1.0e-12)
{
I(k,j) = 0.0;
}
}
}
void RT1TriangleFiniteElement::Project (
VectorCoefficient &vc, ElementTransformation &Trans, Vector &dofs) const
{
double vk[2];
Vector xk (vk, 2);
#ifdef MFEM_THREAD_SAFE
DenseMatrix Jinv(dim);
#endif
for (int k = 0; k < 8; k++)
{
Trans.SetIntPoint (&Nodes.IntPoint (k));
// set Jinv = |J| J^{-t} = adj(J)^t
CalcAdjugateTranspose (Trans.Jacobian(), Jinv);
vc.Eval (xk, Trans, Nodes.IntPoint (k));
// xk^t |J| J^{-t} nk
dofs(k) = (vk[0] * ( Jinv(0,0)*nk[k][0]+Jinv(0,1)*nk[k][1] ) +
vk[1] * ( Jinv(1,0)*nk[k][0]+Jinv(1,1)*nk[k][1] ));
dofs(k) *= 0.5;
}
}
RT1QuadFiniteElement::RT1QuadFiniteElement()
: VectorFiniteElement(2, Geometry::SQUARE, 12, 2, H_DIV, FunctionSpace::Qk)
{
// y = 0
Nodes.IntPoint(0).x = 1./3.;
Nodes.IntPoint(0).y = 0.0;
Nodes.IntPoint(1).x = 2./3.;
Nodes.IntPoint(1).y = 0.0;
// x = 1
Nodes.IntPoint(2).x = 1.0;
Nodes.IntPoint(2).y = 1./3.;
Nodes.IntPoint(3).x = 1.0;
Nodes.IntPoint(3).y = 2./3.;
// y = 1
Nodes.IntPoint(4).x = 2./3.;
Nodes.IntPoint(4).y = 1.0;
Nodes.IntPoint(5).x = 1./3.;
Nodes.IntPoint(5).y = 1.0;
// x = 0
Nodes.IntPoint(6).x = 0.0;
Nodes.IntPoint(6).y = 2./3.;
Nodes.IntPoint(7).x = 0.0;
Nodes.IntPoint(7).y = 1./3.;
// x = 0.5 (interior)
Nodes.IntPoint(8).x = 0.5;
Nodes.IntPoint(8).y = 1./3.;
Nodes.IntPoint(9).x = 0.5;
Nodes.IntPoint(9).y = 2./3.;
// y = 0.5 (interior)
Nodes.IntPoint(10).x = 1./3.;
Nodes.IntPoint(10).y = 0.5;
Nodes.IntPoint(11).x = 2./3.;
Nodes.IntPoint(11).y = 0.5;
}
void RT1QuadFiniteElement::CalcVShape(const IntegrationPoint &ip,
DenseMatrix &shape) const
{
double x = ip.x, y = ip.y;
// y = 0
shape(0,0) = 0;
shape(0,1) = -( 1. - 3.*y + 2.*y*y)*( 2. - 3.*x);
shape(1,0) = 0;
shape(1,1) = -( 1. - 3.*y + 2.*y*y)*(-1. + 3.*x);
// x = 1
shape(2,0) = (-x + 2.*x*x)*( 2. - 3.*y);
shape(2,1) = 0;
shape(3,0) = (-x + 2.*x*x)*(-1. + 3.*y);
shape(3,1) = 0;
// y = 1
shape(4,0) = 0;
shape(4,1) = (-y + 2.*y*y)*(-1. + 3.*x);
shape(5,0) = 0;
shape(5,1) = (-y + 2.*y*y)*( 2. - 3.*x);
// x = 0
shape(6,0) = -(1. - 3.*x + 2.*x*x)*(-1. + 3.*y);
shape(6,1) = 0;
shape(7,0) = -(1. - 3.*x + 2.*x*x)*( 2. - 3.*y);
shape(7,1) = 0;
// x = 0.5 (interior)
shape(8,0) = (4.*x - 4.*x*x)*( 2. - 3.*y);
shape(8,1) = 0;
shape(9,0) = (4.*x - 4.*x*x)*(-1. + 3.*y);
shape(9,1) = 0;
// y = 0.5 (interior)
shape(10,0) = 0;
shape(10,1) = (4.*y - 4.*y*y)*( 2. - 3.*x);
shape(11,0) = 0;
shape(11,1) = (4.*y - 4.*y*y)*(-1. + 3.*x);
}
void RT1QuadFiniteElement::CalcDivShape(const IntegrationPoint &ip,
Vector &divshape) const
{
double x = ip.x, y = ip.y;
divshape(0) = -(-3. + 4.*y)*( 2. - 3.*x);
divshape(1) = -(-3. + 4.*y)*(-1. + 3.*x);
divshape(2) = (-1. + 4.*x)*( 2. - 3.*y);
divshape(3) = (-1. + 4.*x)*(-1. + 3.*y);
divshape(4) = (-1. + 4.*y)*(-1. + 3.*x);
divshape(5) = (-1. + 4.*y)*( 2. - 3.*x);
divshape(6) = -(-3. + 4.*x)*(-1. + 3.*y);
divshape(7) = -(-3. + 4.*x)*( 2. - 3.*y);
divshape(8) = ( 4. - 8.*x)*( 2. - 3.*y);
divshape(9) = ( 4. - 8.*x)*(-1. + 3.*y);
divshape(10) = ( 4. - 8.*y)*( 2. - 3.*x);
divshape(11) = ( 4. - 8.*y)*(-1. + 3.*x);
}
const double RT1QuadFiniteElement::nk[12][2] =
{
// y = 0
{0,-1}, {0,-1},
// X = 1
{1, 0}, {1, 0},
// y = 1
{0, 1}, {0, 1},
// x = 0
{-1,0}, {-1,0},
// x = 0.5 (interior)
{1, 0}, {1, 0},
// y = 0.5 (interior)
{0, 1}, {0, 1}
};
void RT1QuadFiniteElement::GetLocalInterpolation (
ElementTransformation &Trans, DenseMatrix &I) const
{
int k, j;
#ifdef MFEM_THREAD_SAFE
DenseMatrix vshape(dof, dim);
DenseMatrix Jinv(dim);
#endif
#ifdef MFEM_DEBUG
for (k = 0; k < 12; k++)
{
CalcVShape (Nodes.IntPoint(k), vshape);
for (j = 0; j < 12; j++)
{
double d = vshape(j,0)*nk[k][0]+vshape(j,1)*nk[k][1];
if (j == k) { d -= 1.0; }
if (fabs(d) > 1.0e-12)
{
mfem::err << "RT1QuadFiniteElement::GetLocalInterpolation (...)\n"
" k = " << k << ", j = " << j << ", d = " << d << endl;
mfem_error();
}
}
}
#endif
IntegrationPoint ip;
ip.x = ip.y = 0.0;
Trans.SetIntPoint (&ip);
// Trans must be linear (more to have embedding?)
// set Jinv = |J| J^{-t} = adj(J)^t
CalcAdjugateTranspose (Trans.Jacobian(), Jinv);
double vk[2];
Vector xk (vk, 2);
for (k = 0; k < 12; k++)
{
Trans.Transform (Nodes.IntPoint (k), xk);
ip.x = vk[0]; ip.y = vk[1];
CalcVShape (ip, vshape);
// vk = |J| J^{-t} nk
vk[0] = Jinv(0,0)*nk[k][0]+Jinv(0,1)*nk[k][1];
vk[1] = Jinv(1,0)*nk[k][0]+Jinv(1,1)*nk[k][1];
for (j = 0; j < 12; j++)
if (fabs (I(k,j) = vshape(j,0)*vk[0]+vshape(j,1)*vk[1]) < 1.0e-12)
{
I(k,j) = 0.0;
}
}
}
void RT1QuadFiniteElement::Project (
VectorCoefficient &vc, ElementTransformation &Trans, Vector &dofs) const
{
double vk[2];
Vector xk (vk, 2);
#ifdef MFEM_THREAD_SAFE
DenseMatrix Jinv(dim);
#endif
for (int k = 0; k < 12; k++)
{
Trans.SetIntPoint (&Nodes.IntPoint (k));
// set Jinv = |J| J^{-t} = adj(J)^t
CalcAdjugateTranspose (Trans.Jacobian(), Jinv);
vc.Eval (xk, Trans, Nodes.IntPoint (k));
// xk^t |J| J^{-t} nk
dofs(k) = (vk[0] * ( Jinv(0,0)*nk[k][0]+Jinv(0,1)*nk[k][1] ) +
vk[1] * ( Jinv(1,0)*nk[k][0]+Jinv(1,1)*nk[k][1] ));
}
}
const double RT2TriangleFiniteElement::M[15][15] =
{
{
0, -5.3237900077244501311, 5.3237900077244501311, 16.647580015448900262,
0, 24.442740046346700787, -16.647580015448900262, -12.,
-19.118950038622250656, -47.237900077244501311, 0, -34.414110069520051180,
12., 30.590320061795601049, 15.295160030897800524
},
{
0, 1.5, -1.5, -15., 0, 2.625, 15., 15., -4.125, 30., 0, -14.625, -15.,
-15., 10.5
},
{
0, -0.67620999227554986889, 0.67620999227554986889, 7.3524199845510997378,
0, -3.4427400463467007866, -7.3524199845510997378, -12.,
4.1189500386222506555, -0.76209992275549868892, 0, 7.4141100695200511800,
12., -6.5903200617956010489, -3.2951600308978005244
},
{
0, 0, 1.5, 0, 0, 1.5, -11.471370023173350393, 0, 2.4713700231733503933,
-11.471370023173350393, 0, 2.4713700231733503933, 15.295160030897800524,
0, -3.2951600308978005244
},
{
0, 0, 4.875, 0, 0, 4.875, -16.875, 0, -16.875, -16.875, 0, -16.875, 10.5,
36., 10.5
},
{
0, 0, 1.5, 0, 0, 1.5, 2.4713700231733503933, 0, -11.471370023173350393,
2.4713700231733503933, 0, -11.471370023173350393, -3.2951600308978005244,
0, 15.295160030897800524
},
{
-0.67620999227554986889, 0, -3.4427400463467007866, 0,
7.3524199845510997378, 0.67620999227554986889, 7.4141100695200511800, 0,
-0.76209992275549868892, 4.1189500386222506555, -12.,
-7.3524199845510997378, -3.2951600308978005244, -6.5903200617956010489,
12.
},
{
1.5, 0, 2.625, 0, -15., -1.5, -14.625, 0, 30., -4.125, 15., 15., 10.5,
-15., -15.
},
{
-5.3237900077244501311, 0, 24.442740046346700787, 0, 16.647580015448900262,
5.3237900077244501311, -34.414110069520051180, 0, -47.237900077244501311,
-19.118950038622250656, -12., -16.647580015448900262, 15.295160030897800524,
30.590320061795601049, 12.
},
{ 0, 0, 18., 0, 0, 6., -42., 0, -30., -26., 0, -14., 24., 32., 8.},
{ 0, 0, 6., 0, 0, 18., -14., 0, -26., -30., 0, -42., 8., 32., 24.},
{ 0, 0, -6., 0, 0, -4., 30., 0, 4., 22., 0, 4., -24., -16., 0},
{ 0, 0, -4., 0, 0, -8., 20., 0, 8., 36., 0, 8., -16., -32., 0},
{ 0, 0, -8., 0, 0, -4., 8., 0, 36., 8., 0, 20., 0, -32., -16.},
{ 0, 0, -4., 0, 0, -6., 4., 0, 22., 4., 0, 30., 0, -16., -24.}
};
RT2TriangleFiniteElement::RT2TriangleFiniteElement()
: VectorFiniteElement(2, Geometry::TRIANGLE, 15, 3, H_DIV)
{
const double p = 0.11270166537925831148;
Nodes.IntPoint(0).x = p;
Nodes.IntPoint(0).y = 0.0;
Nodes.IntPoint(1).x = 0.5;
Nodes.IntPoint(1).y = 0.0;
Nodes.IntPoint(2).x = 1.-p;
Nodes.IntPoint(2).y = 0.0;
Nodes.IntPoint(3).x = 1.-p;
Nodes.IntPoint(3).y = p;
Nodes.IntPoint(4).x = 0.5;
Nodes.IntPoint(4).y = 0.5;
Nodes.IntPoint(5).x = p;
Nodes.IntPoint(5).y = 1.-p;
Nodes.IntPoint(6).x = 0.0;
Nodes.IntPoint(6).y = 1.-p;
Nodes.IntPoint(7).x = 0.0;
Nodes.IntPoint(7).y = 0.5;
Nodes.IntPoint(8).x = 0.0;
Nodes.IntPoint(8).y = p;
Nodes.IntPoint(9).x = 0.25;
Nodes.IntPoint(9).y = 0.25;
Nodes.IntPoint(10).x = 0.25;
Nodes.IntPoint(10).y = 0.25;
Nodes.IntPoint(11).x = 0.5;
Nodes.IntPoint(11).y = 0.25;
Nodes.IntPoint(12).x = 0.5;
Nodes.IntPoint(12).y = 0.25;
Nodes.IntPoint(13).x = 0.25;
Nodes.IntPoint(13).y = 0.5;
Nodes.IntPoint(14).x = 0.25;
Nodes.IntPoint(14).y = 0.5;
}
void RT2TriangleFiniteElement::CalcVShape(const IntegrationPoint &ip,
DenseMatrix &shape) const
{
double x = ip.x, y = ip.y;
double Bx[15] = {1., 0., x, 0., y, 0., x*x, 0., x*y, 0., y*y, 0., x*x*x,
x*x*y, x*y*y
};
double By[15] = {0., 1., 0., x, 0., y, 0., x*x, 0., x*y, 0., y*y,
x*x*y, x*y*y, y*y*y
};
for (int i = 0; i < 15; i++)
{
double cx = 0.0, cy = 0.0;
for (int j = 0; j < 15; j++)
{
cx += M[i][j] * Bx[j];
cy += M[i][j] * By[j];
}
shape(i,0) = cx;
shape(i,1) = cy;
}
}
void RT2TriangleFiniteElement::CalcDivShape(const IntegrationPoint &ip,
Vector &divshape) const
{
double x = ip.x, y = ip.y;
double DivB[15] = {0., 0., 1., 0., 0., 1., 2.*x, 0., y, x, 0., 2.*y,
4.*x*x, 4.*x*y, 4.*y*y
};
for (int i = 0; i < 15; i++)
{
double div = 0.0;
for (int j = 0; j < 15; j++)
{
div += M[i][j] * DivB[j];
}
divshape(i) = div;
}
}
const double RT2QuadFiniteElement::pt[4] = {0.,1./3.,2./3.,1.};
const double RT2QuadFiniteElement::dpt[3] = {0.25,0.5,0.75};
RT2QuadFiniteElement::RT2QuadFiniteElement()
: VectorFiniteElement(2, Geometry::SQUARE, 24, 3, H_DIV, FunctionSpace::Qk)
{
// y = 0 (pt[0])
Nodes.IntPoint(0).x = dpt[0]; Nodes.IntPoint(0).y = pt[0];
Nodes.IntPoint(1).x = dpt[1]; Nodes.IntPoint(1).y = pt[0];
Nodes.IntPoint(2).x = dpt[2]; Nodes.IntPoint(2).y = pt[0];
// x = 1 (pt[3])
Nodes.IntPoint(3).x = pt[3]; Nodes.IntPoint(3).y = dpt[0];
Nodes.IntPoint(4).x = pt[3]; Nodes.IntPoint(4).y = dpt[1];
Nodes.IntPoint(5).x = pt[3]; Nodes.IntPoint(5).y = dpt[2];
// y = 1 (pt[3])
Nodes.IntPoint(6).x = dpt[2]; Nodes.IntPoint(6).y = pt[3];
Nodes.IntPoint(7).x = dpt[1]; Nodes.IntPoint(7).y = pt[3];
Nodes.IntPoint(8).x = dpt[0]; Nodes.IntPoint(8).y = pt[3];
// x = 0 (pt[0])
Nodes.IntPoint(9).x = pt[0]; Nodes.IntPoint(9).y = dpt[2];
Nodes.IntPoint(10).x = pt[0]; Nodes.IntPoint(10).y = dpt[1];
Nodes.IntPoint(11).x = pt[0]; Nodes.IntPoint(11).y = dpt[0];
// x = pt[1] (interior)
Nodes.IntPoint(12).x = pt[1]; Nodes.IntPoint(12).y = dpt[0];
Nodes.IntPoint(13).x = pt[1]; Nodes.IntPoint(13).y = dpt[1];
Nodes.IntPoint(14).x = pt[1]; Nodes.IntPoint(14).y = dpt[2];
// x = pt[2] (interior)
Nodes.IntPoint(15).x = pt[2]; Nodes.IntPoint(15).y = dpt[0];
Nodes.IntPoint(16).x = pt[2]; Nodes.IntPoint(16).y = dpt[1];
Nodes.IntPoint(17).x = pt[2]; Nodes.IntPoint(17).y = dpt[2];
// y = pt[1] (interior)
Nodes.IntPoint(18).x = dpt[0]; Nodes.IntPoint(18).y = pt[1];
Nodes.IntPoint(19).x = dpt[1]; Nodes.IntPoint(19).y = pt[1];
Nodes.IntPoint(20).x = dpt[2]; Nodes.IntPoint(20).y = pt[1];
// y = pt[2] (interior)
Nodes.IntPoint(21).x = dpt[0]; Nodes.IntPoint(21).y = pt[2];
Nodes.IntPoint(22).x = dpt[1]; Nodes.IntPoint(22).y = pt[2];
Nodes.IntPoint(23).x = dpt[2]; Nodes.IntPoint(23).y = pt[2];
}
void RT2QuadFiniteElement::CalcVShape(const IntegrationPoint &ip,
DenseMatrix &shape) const
{
double x = ip.x, y = ip.y;
double ax0 = pt[0] - x;
double ax1 = pt[1] - x;
double ax2 = pt[2] - x;
double ax3 = pt[3] - x;
double by0 = dpt[0] - y;
double by1 = dpt[1] - y;
double by2 = dpt[2] - y;
double ay0 = pt[0] - y;
double ay1 = pt[1] - y;
double ay2 = pt[2] - y;
double ay3 = pt[3] - y;
double bx0 = dpt[0] - x;
double bx1 = dpt[1] - x;
double bx2 = dpt[2] - x;
double A01 = pt[0] - pt[1];
double A02 = pt[0] - pt[2];
double A12 = pt[1] - pt[2];
double A03 = pt[0] - pt[3];
double A13 = pt[1] - pt[3];
double A23 = pt[2] - pt[3];
double B01 = dpt[0] - dpt[1];
double B02 = dpt[0] - dpt[2];
double B12 = dpt[1] - dpt[2];
double tx0 = (bx1*bx2)/(B01*B02);
double tx1 = -(bx0*bx2)/(B01*B12);
double tx2 = (bx0*bx1)/(B02*B12);
double ty0 = (by1*by2)/(B01*B02);
double ty1 = -(by0*by2)/(B01*B12);
double ty2 = (by0*by1)/(B02*B12);
// y = 0 (p[0])
shape(0, 0) = 0;
shape(0, 1) = (ay1*ay2*ay3)/(A01*A02*A03)*tx0;
shape(1, 0) = 0;
shape(1, 1) = (ay1*ay2*ay3)/(A01*A02*A03)*tx1;
shape(2, 0) = 0;
shape(2, 1) = (ay1*ay2*ay3)/(A01*A02*A03)*tx2;
// x = 1 (p[3])
shape(3, 0) = (ax0*ax1*ax2)/(A03*A13*A23)*ty0;
shape(3, 1) = 0;
shape(4, 0) = (ax0*ax1*ax2)/(A03*A13*A23)*ty1;
shape(4, 1) = 0;
shape(5, 0) = (ax0*ax1*ax2)/(A03*A13*A23)*ty2;
shape(5, 1) = 0;
// y = 1 (p[3])
shape(6, 0) = 0;
shape(6, 1) = (ay0*ay1*ay2)/(A03*A13*A23)*tx2;
shape(7, 0) = 0;
shape(7, 1) = (ay0*ay1*ay2)/(A03*A13*A23)*tx1;
shape(8, 0) = 0;
shape(8, 1) = (ay0*ay1*ay2)/(A03*A13*A23)*tx0;
// x = 0 (p[0])
shape(9, 0) = (ax1*ax2*ax3)/(A01*A02*A03)*ty2;
shape(9, 1) = 0;
shape(10, 0) = (ax1*ax2*ax3)/(A01*A02*A03)*ty1;
shape(10, 1) = 0;
shape(11, 0) = (ax1*ax2*ax3)/(A01*A02*A03)*ty0;
shape(11, 1) = 0;
// x = p[1] (interior)
shape(12, 0) = (ax0*ax2*ax3)/(A01*A12*A13)*ty0;
shape(12, 1) = 0;
shape(13, 0) = (ax0*ax2*ax3)/(A01*A12*A13)*ty1;
shape(13, 1) = 0;
shape(14, 0) = (ax0*ax2*ax3)/(A01*A12*A13)*ty2;
shape(14, 1) = 0;
// x = p[2] (interior)
shape(15, 0) = -(ax0*ax1*ax3)/(A02*A12*A23)*ty0;
shape(15, 1) = 0;
shape(16, 0) = -(ax0*ax1*ax3)/(A02*A12*A23)*ty1;
shape(16, 1) = 0;
shape(17, 0) = -(ax0*ax1*ax3)/(A02*A12*A23)*ty2;
shape(17, 1) = 0;
// y = p[1] (interior)
shape(18, 0) = 0;
shape(18, 1) = (ay0*ay2*ay3)/(A01*A12*A13)*tx0;
shape(19, 0) = 0;
shape(19, 1) = (ay0*ay2*ay3)/(A01*A12*A13)*tx1;
shape(20, 0) = 0;
shape(20, 1) = (ay0*ay2*ay3)/(A01*A12*A13)*tx2;
// y = p[2] (interior)
shape(21, 0) = 0;
shape(21, 1) = -(ay0*ay1*ay3)/(A02*A12*A23)*tx0;
shape(22, 0) = 0;
shape(22, 1) = -(ay0*ay1*ay3)/(A02*A12*A23)*tx1;
shape(23, 0) = 0;
shape(23, 1) = -(ay0*ay1*ay3)/(A02*A12*A23)*tx2;
}
void RT2QuadFiniteElement::CalcDivShape(const IntegrationPoint &ip,
Vector &divshape) const
{
double x = ip.x, y = ip.y;
double a01 = pt[0]*pt[1];
double a02 = pt[0]*pt[2];
double a12 = pt[1]*pt[2];
double a03 = pt[0]*pt[3];
double a13 = pt[1]*pt[3];
double a23 = pt[2]*pt[3];
double bx0 = dpt[0] - x;
double bx1 = dpt[1] - x;
double bx2 = dpt[2] - x;
double by0 = dpt[0] - y;
double by1 = dpt[1] - y;
double by2 = dpt[2] - y;
double A01 = pt[0] - pt[1];
double A02 = pt[0] - pt[2];
double A12 = pt[1] - pt[2];
double A03 = pt[0] - pt[3];
double A13 = pt[1] - pt[3];
double A23 = pt[2] - pt[3];
double A012 = pt[0] + pt[1] + pt[2];
double A013 = pt[0] + pt[1] + pt[3];
double A023 = pt[0] + pt[2] + pt[3];
double A123 = pt[1] + pt[2] + pt[3];
double B01 = dpt[0] - dpt[1];
double B02 = dpt[0] - dpt[2];
double B12 = dpt[1] - dpt[2];
double tx0 = (bx1*bx2)/(B01*B02);
double tx1 = -(bx0*bx2)/(B01*B12);
double tx2 = (bx0*bx1)/(B02*B12);
double ty0 = (by1*by2)/(B01*B02);
double ty1 = -(by0*by2)/(B01*B12);
double ty2 = (by0*by1)/(B02*B12);
// y = 0 (p[0])
divshape(0) = -(a12 + a13 + a23 - 2.*A123*y + 3.*y*y)/(A01*A02*A03)*tx0;
divshape(1) = -(a12 + a13 + a23 - 2.*A123*y + 3.*y*y)/(A01*A02*A03)*tx1;
divshape(2) = -(a12 + a13 + a23 - 2.*A123*y + 3.*y*y)/(A01*A02*A03)*tx2;
// x = 1 (p[3])
divshape(3) = -(a01 + a02 + a12 - 2.*A012*x + 3.*x*x)/(A03*A13*A23)*ty0;
divshape(4) = -(a01 + a02 + a12 - 2.*A012*x + 3.*x*x)/(A03*A13*A23)*ty1;
divshape(5) = -(a01 + a02 + a12 - 2.*A012*x + 3.*x*x)/(A03*A13*A23)*ty2;
// y = 1 (p[3])
divshape(6) = -(a01 + a02 + a12 - 2.*A012*y + 3.*y*y)/(A03*A13*A23)*tx2;
divshape(7) = -(a01 + a02 + a12 - 2.*A012*y + 3.*y*y)/(A03*A13*A23)*tx1;
divshape(8) = -(a01 + a02 + a12 - 2.*A012*y + 3.*y*y)/(A03*A13*A23)*tx0;
// x = 0 (p[0])
divshape(9) = -(a12 + a13 + a23 - 2.*A123*x + 3.*x*x)/(A01*A02*A03)*ty2;
divshape(10) = -(a12 + a13 + a23 - 2.*A123*x + 3.*x*x)/(A01*A02*A03)*ty1;
divshape(11) = -(a12 + a13 + a23 - 2.*A123*x + 3.*x*x)/(A01*A02*A03)*ty0;
// x = p[1] (interior)
divshape(12) = -(a02 + a03 + a23 - 2.*A023*x + 3.*x*x)/(A01*A12*A13)*ty0;
divshape(13) = -(a02 + a03 + a23 - 2.*A023*x + 3.*x*x)/(A01*A12*A13)*ty1;
divshape(14) = -(a02 + a03 + a23 - 2.*A023*x + 3.*x*x)/(A01*A12*A13)*ty2;
// x = p[2] (interior)
divshape(15) = (a01 + a03 + a13 - 2.*A013*x + 3.*x*x)/(A02*A12*A23)*ty0;
divshape(16) = (a01 + a03 + a13 - 2.*A013*x + 3.*x*x)/(A02*A12*A23)*ty1;
divshape(17) = (a01 + a03 + a13 - 2.*A013*x + 3.*x*x)/(A02*A12*A23)*ty2;
// y = p[1] (interior)
divshape(18) = -(a02 + a03 + a23 - 2.*A023*y + 3.*y*y)/(A01*A12*A13)*tx0;
divshape(19) = -(a02 + a03 + a23 - 2.*A023*y + 3.*y*y)/(A01*A12*A13)*tx1;
divshape(20) = -(a02 + a03 + a23 - 2.*A023*y + 3.*y*y)/(A01*A12*A13)*tx2;
// y = p[2] (interior)
divshape(21) = (a01 + a03 + a13 - 2.*A013*y + 3.*y*y)/(A02*A12*A23)*tx0;
divshape(22) = (a01 + a03 + a13 - 2.*A013*y + 3.*y*y)/(A02*A12*A23)*tx1;
divshape(23) = (a01 + a03 + a13 - 2.*A013*y + 3.*y*y)/(A02*A12*A23)*tx2;
}
const double RT2QuadFiniteElement::nk[24][2] =
{
// y = 0
{0,-1}, {0,-1}, {0,-1},
// x = 1
{1, 0}, {1, 0}, {1, 0},
// y = 1
{0, 1}, {0, 1}, {0, 1},
// x = 0
{-1,0}, {-1,0}, {-1,0},
// x = p[1] (interior)
{1, 0}, {1, 0}, {1, 0},
// x = p[2] (interior)
{1, 0}, {1, 0}, {1, 0},
// y = p[1] (interior)
{0, 1}, {0, 1}, {0, 1},
// y = p[1] (interior)
{0, 1}, {0, 1}, {0, 1}
};
void RT2QuadFiniteElement::GetLocalInterpolation (
ElementTransformation &Trans, DenseMatrix &I) const
{
int k, j;
#ifdef MFEM_THREAD_SAFE
DenseMatrix vshape(dof, dim);
DenseMatrix Jinv(dim);
#endif
#ifdef MFEM_DEBUG
for (k = 0; k < 24; k++)
{
CalcVShape (Nodes.IntPoint(k), vshape);
for (j = 0; j < 24; j++)
{
double d = vshape(j,0)*nk[k][0]+vshape(j,1)*nk[k][1];
if (j == k) { d -= 1.0; }
if (fabs(d) > 1.0e-12)
{
mfem::err << "RT2QuadFiniteElement::GetLocalInterpolation (...)\n"
" k = " << k << ", j = " << j << ", d = " << d << endl;
mfem_error();
}
}
}
#endif
IntegrationPoint ip;
ip.x = ip.y = 0.0;
Trans.SetIntPoint (&ip);
// Trans must be linear (more to have embedding?)
// set Jinv = |J| J^{-t} = adj(J)^t
CalcAdjugateTranspose (Trans.Jacobian(), Jinv);
double vk[2];
Vector xk (vk, 2);
for (k = 0; k < 24; k++)
{
Trans.Transform (Nodes.IntPoint (k), xk);
ip.x = vk[0]; ip.y = vk[1];
CalcVShape (ip, vshape);
// vk = |J| J^{-t} nk
vk[0] = Jinv(0,0)*nk[k][0]+Jinv(0,1)*nk[k][1];
vk[1] = Jinv(1,0)*nk[k][0]+Jinv(1,1)*nk[k][1];
for (j = 0; j < 24; j++)
if (fabs (I(k,j) = vshape(j,0)*vk[0]+vshape(j,1)*vk[1]) < 1.0e-12)
{
I(k,j) = 0.0;
}
}
}
void RT2QuadFiniteElement::Project (
VectorCoefficient &vc, ElementTransformation &Trans, Vector &dofs) const
{
double vk[2];
Vector xk (vk, 2);
#ifdef MFEM_THREAD_SAFE
DenseMatrix Jinv(dim);
#endif
for (int k = 0; k < 24; k++)
{
Trans.SetIntPoint (&Nodes.IntPoint (k));
// set Jinv = |J| J^{-t} = adj(J)^t
CalcAdjugateTranspose (Trans.Jacobian(), Jinv);
vc.Eval (xk, Trans, Nodes.IntPoint (k));
// xk^t |J| J^{-t} nk
dofs(k) = (vk[0] * ( Jinv(0,0)*nk[k][0]+Jinv(0,1)*nk[k][1] ) +
vk[1] * ( Jinv(1,0)*nk[k][0]+Jinv(1,1)*nk[k][1] ));
}
}
P1SegmentFiniteElement::P1SegmentFiniteElement()
: NodalFiniteElement(1, Geometry::SEGMENT, 2, 1)
{
Nodes.IntPoint(0).x = 0.33333333333333333333;
Nodes.IntPoint(1).x = 0.66666666666666666667;
}
void P1SegmentFiniteElement::CalcShape(const IntegrationPoint &ip,
Vector &shape) const
{
double x = ip.x;
shape(0) = 2. - 3. * x;
shape(1) = 3. * x - 1.;
}
void P1SegmentFiniteElement::CalcDShape(const IntegrationPoint &ip,
DenseMatrix &dshape) const
{
dshape(0,0) = -3.;
dshape(1,0) = 3.;
}
P2SegmentFiniteElement::P2SegmentFiniteElement()
: NodalFiniteElement(1, Geometry::SEGMENT, 3, 2)
{
const double p = 0.11270166537925831148;
Nodes.IntPoint(0).x = p;
Nodes.IntPoint(1).x = 0.5;
Nodes.IntPoint(2).x = 1.-p;
}
void P2SegmentFiniteElement::CalcShape(const IntegrationPoint &ip,
Vector &shape) const
{
const double p = 0.11270166537925831148;
const double w = 1./((1-2*p)*(1-2*p));
double x = ip.x;
shape(0) = (2*x-1)*(x-1+p)*w;
shape(1) = 4*(x-1+p)*(p-x)*w;
shape(2) = (2*x-1)*(x-p)*w;
}
void P2SegmentFiniteElement::CalcDShape(const IntegrationPoint &ip,
DenseMatrix &dshape) const
{
const double p = 0.11270166537925831148;
const double w = 1./((1-2*p)*(1-2*p));
double x = ip.x;
dshape(0,0) = (-3+4*x+2*p)*w;
dshape(1,0) = (4-8*x)*w;
dshape(2,0) = (-1+4*x-2*p)*w;
}
Lagrange1DFiniteElement::Lagrange1DFiniteElement(int degree)
: NodalFiniteElement(1, Geometry::SEGMENT, degree+1, degree)
{
int i, m = degree;
Nodes.IntPoint(0).x = 0.0;
Nodes.IntPoint(1).x = 1.0;
for (i = 1; i < m; i++)
{
Nodes.IntPoint(i+1).x = double(i) / m;
}
rwk.SetSize(degree+1);
#ifndef MFEM_THREAD_SAFE
rxxk.SetSize(degree+1);
#endif
rwk(0) = 1.0;
for (i = 1; i <= m; i++)
{
rwk(i) = rwk(i-1) * ( (double)(m) / (double)(i) );
}
for (i = 0; i < m/2+1; i++)
{
rwk(m-i) = ( rwk(i) *= rwk(m-i) );
}
for (i = m-1; i >= 0; i -= 2)
{
rwk(i) = -rwk(i);
}
}
void Lagrange1DFiniteElement::CalcShape(const IntegrationPoint &ip,
Vector &shape) const
{
double w, wk, x = ip.x;
int i, k, m = GetOrder();
#ifdef MFEM_THREAD_SAFE
Vector rxxk(m+1);
#endif
k = (int) floor ( m * x + 0.5 );
k = k > m ? m : k < 0 ? 0 : k; // clamp k to [0,m]
wk = 1.0;
for (i = 0; i <= m; i++)
if (i != k)
{
wk *= ( rxxk(i) = x - (double)(i) / m );
}
w = wk * ( rxxk(k) = x - (double)(k) / m );
if (k != 0)
{
shape(0) = w * rwk(0) / rxxk(0);
}
else
{
shape(0) = wk * rwk(0);
}
if (k != m)
{
shape(1) = w * rwk(m) / rxxk(m);
}
else
{
shape(1) = wk * rwk(k);
}
for (i = 1; i < m; i++)
if (i != k)
{
shape(i+1) = w * rwk(i) / rxxk(i);
}
else
{
shape(k+1) = wk * rwk(k);
}
}
void Lagrange1DFiniteElement::CalcDShape(const IntegrationPoint &ip,
DenseMatrix &dshape) const
{
double s, srx, w, wk, x = ip.x;
int i, k, m = GetOrder();
#ifdef MFEM_THREAD_SAFE
Vector rxxk(m+1);
#endif
k = (int) floor ( m * x + 0.5 );
k = k > m ? m : k < 0 ? 0 : k; // clamp k to [0,m]
wk = 1.0;
for (i = 0; i <= m; i++)
if (i != k)
{
wk *= ( rxxk(i) = x - (double)(i) / m );
}
w = wk * ( rxxk(k) = x - (double)(k) / m );
for (i = 0; i <= m; i++)
{
rxxk(i) = 1.0 / rxxk(i);
}
srx = 0.0;
for (i = 0; i <= m; i++)
if (i != k)
{
srx += rxxk(i);
}
s = w * srx + wk;
if (k != 0)
{
dshape(0,0) = (s - w * rxxk(0)) * rwk(0) * rxxk(0);
}
else
{
dshape(0,0) = wk * srx * rwk(0);
}
if (k != m)
{
dshape(1,0) = (s - w * rxxk(m)) * rwk(m) * rxxk(m);
}
else
{
dshape(1,0) = wk * srx * rwk(k);
}
for (i = 1; i < m; i++)
if (i != k)
{
dshape(i+1,0) = (s - w * rxxk(i)) * rwk(i) * rxxk(i);
}
else
{
dshape(k+1,0) = wk * srx * rwk(k);
}
}
P1TetNonConfFiniteElement::P1TetNonConfFiniteElement()
: NodalFiniteElement(3, Geometry::TETRAHEDRON, 4, 1)
{
Nodes.IntPoint(0).x = 0.33333333333333333333;
Nodes.IntPoint(0).y = 0.33333333333333333333;
Nodes.IntPoint(0).z = 0.33333333333333333333;
Nodes.IntPoint(1).x = 0.0;
Nodes.IntPoint(1).y = 0.33333333333333333333;
Nodes.IntPoint(1).z = 0.33333333333333333333;
Nodes.IntPoint(2).x = 0.33333333333333333333;
Nodes.IntPoint(2).y = 0.0;
Nodes.IntPoint(2).z = 0.33333333333333333333;
Nodes.IntPoint(3).x = 0.33333333333333333333;
Nodes.IntPoint(3).y = 0.33333333333333333333;
Nodes.IntPoint(3).z = 0.0;
}
void P1TetNonConfFiniteElement::CalcShape(const IntegrationPoint &ip,
Vector &shape) const
{
double L0, L1, L2, L3;
L1 = ip.x; L2 = ip.y; L3 = ip.z; L0 = 1.0 - L1 - L2 - L3;
shape(0) = 1.0 - 3.0 * L0;
shape(1) = 1.0 - 3.0 * L1;
shape(2) = 1.0 - 3.0 * L2;
shape(3) = 1.0 - 3.0 * L3;
}
void P1TetNonConfFiniteElement::CalcDShape(const IntegrationPoint &ip,
DenseMatrix &dshape) const
{
dshape(0,0) = 3.0; dshape(0,1) = 3.0; dshape(0,2) = 3.0;
dshape(1,0) = -3.0; dshape(1,1) = 0.0; dshape(1,2) = 0.0;
dshape(2,0) = 0.0; dshape(2,1) = -3.0; dshape(2,2) = 0.0;
dshape(3,0) = 0.0; dshape(3,1) = 0.0; dshape(3,2) = -3.0;
}
P0TetFiniteElement::P0TetFiniteElement()
: NodalFiniteElement(3, Geometry::TETRAHEDRON, 1, 0)
{
Nodes.IntPoint(0).x = 0.25;
Nodes.IntPoint(0).y = 0.25;
Nodes.IntPoint(0).z = 0.25;
}
void P0TetFiniteElement::CalcShape(const IntegrationPoint &ip,
Vector &shape) const
{
shape(0) = 1.0;
}
void P0TetFiniteElement::CalcDShape(const IntegrationPoint &ip,
DenseMatrix &dshape) const
{
dshape(0,0) = 0.0; dshape(0,1) = 0.0; dshape(0,2) = 0.0;
}
P0HexFiniteElement::P0HexFiniteElement()
: NodalFiniteElement(3, Geometry::CUBE, 1, 0, FunctionSpace::Qk)
{
Nodes.IntPoint(0).x = 0.5;
Nodes.IntPoint(0).y = 0.5;
Nodes.IntPoint(0).z = 0.5;
}
void P0HexFiniteElement::CalcShape(const IntegrationPoint &ip,
Vector &shape) const
{
shape(0) = 1.0;
}
void P0HexFiniteElement::CalcDShape(const IntegrationPoint &ip,
DenseMatrix &dshape) const
{
dshape(0,0) = 0.0; dshape(0,1) = 0.0; dshape(0,2) = 0.0;
}
LagrangeHexFiniteElement::LagrangeHexFiniteElement (int degree)
: NodalFiniteElement(3, Geometry::CUBE, (degree+1)*(degree+1)*(degree+1),
degree, FunctionSpace::Qk)
{
if (degree == 2)
{
I = new int[dof];
J = new int[dof];
K = new int[dof];
// nodes
I[ 0] = 0; J[ 0] = 0; K[ 0] = 0;
I[ 1] = 1; J[ 1] = 0; K[ 1] = 0;
I[ 2] = 1; J[ 2] = 1; K[ 2] = 0;
I[ 3] = 0; J[ 3] = 1; K[ 3] = 0;
I[ 4] = 0; J[ 4] = 0; K[ 4] = 1;
I[ 5] = 1; J[ 5] = 0; K[ 5] = 1;
I[ 6] = 1; J[ 6] = 1; K[ 6] = 1;
I[ 7] = 0; J[ 7] = 1; K[ 7] = 1;
// edges
I[ 8] = 2; J[ 8] = 0; K[ 8] = 0;
I[ 9] = 1; J[ 9] = 2; K[ 9] = 0;
I[10] = 2; J[10] = 1; K[10] = 0;
I[11] = 0; J[11] = 2; K[11] = 0;
I[12] = 2; J[12] = 0; K[12] = 1;
I[13] = 1; J[13] = 2; K[13] = 1;
I[14] = 2; J[14] = 1; K[14] = 1;
I[15] = 0; J[15] = 2; K[15] = 1;
I[16] = 0; J[16] = 0; K[16] = 2;
I[17] = 1; J[17] = 0; K[17] = 2;
I[18] = 1; J[18] = 1; K[18] = 2;
I[19] = 0; J[19] = 1; K[19] = 2;
// faces
I[20] = 2; J[20] = 2; K[20] = 0;
I[21] = 2; J[21] = 0; K[21] = 2;
I[22] = 1; J[22] = 2; K[22] = 2;
I[23] = 2; J[23] = 1; K[23] = 2;
I[24] = 0; J[24] = 2; K[24] = 2;
I[25] = 2; J[25] = 2; K[25] = 1;
// element
I[26] = 2; J[26] = 2; K[26] = 2;
}
else if (degree == 3)
{
I = new int[dof];
J = new int[dof];
K = new int[dof];
// nodes
I[ 0] = 0; J[ 0] = 0; K[ 0] = 0;
I[ 1] = 1; J[ 1] = 0; K[ 1] = 0;
I[ 2] = 1; J[ 2] = 1; K[ 2] = 0;
I[ 3] = 0; J[ 3] = 1; K[ 3] = 0;
I[ 4] = 0; J[ 4] = 0; K[ 4] = 1;
I[ 5] = 1; J[ 5] = 0; K[ 5] = 1;
I[ 6] = 1; J[ 6] = 1; K[ 6] = 1;
I[ 7] = 0; J[ 7] = 1; K[ 7] = 1;
// edges
I[ 8] = 2; J[ 8] = 0; K[ 8] = 0;
I[ 9] = 3; J[ 9] = 0; K[ 9] = 0;
I[10] = 1; J[10] = 2; K[10] = 0;
I[11] = 1; J[11] = 3; K[11] = 0;
I[12] = 2; J[12] = 1; K[12] = 0;
I[13] = 3; J[13] = 1; K[13] = 0;
I[14] = 0; J[14] = 2; K[14] = 0;
I[15] = 0; J[15] = 3; K[15] = 0;
I[16] = 2; J[16] = 0; K[16] = 1;
I[17] = 3; J[17] = 0; K[17] = 1;
I[18] = 1; J[18] = 2; K[18] = 1;
I[19] = 1; J[19] = 3; K[19] = 1;
I[20] = 2; J[20] = 1; K[20] = 1;
I[21] = 3; J[21] = 1; K[21] = 1;
I[22] = 0; J[22] = 2; K[22] = 1;
I[23] = 0; J[23] = 3; K[23] = 1;
I[24] = 0; J[24] = 0; K[24] = 2;
I[25] = 0; J[25] = 0; K[25] = 3;
I[26] = 1; J[26] = 0; K[26] = 2;
I[27] = 1; J[27] = 0; K[27] = 3;
I[28] = 1; J[28] = 1; K[28] = 2;
I[29] = 1; J[29] = 1; K[29] = 3;
I[30] = 0; J[30] = 1; K[30] = 2;
I[31] = 0; J[31] = 1; K[31] = 3;
// faces
I[32] = 2; J[32] = 3; K[32] = 0;
I[33] = 3; J[33] = 3; K[33] = 0;
I[34] = 2; J[34] = 2; K[34] = 0;
I[35] = 3; J[35] = 2; K[35] = 0;
I[36] = 2; J[36] = 0; K[36] = 2;
I[37] = 3; J[37] = 0; K[37] = 2;
I[38] = 2; J[38] = 0; K[38] = 3;
I[39] = 3; J[39] = 0; K[39] = 3;
I[40] = 1; J[40] = 2; K[40] = 2;
I[41] = 1; J[41] = 3; K[41] = 2;
I[42] = 1; J[42] = 2; K[42] = 3;
I[43] = 1; J[43] = 3; K[43] = 3;
I[44] = 3; J[44] = 1; K[44] = 2;
I[45] = 2; J[45] = 1; K[45] = 2;
I[46] = 3; J[46] = 1; K[46] = 3;
I[47] = 2; J[47] = 1; K[47] = 3;
I[48] = 0; J[48] = 3; K[48] = 2;
I[49] = 0; J[49] = 2; K[49] = 2;
I[50] = 0; J[50] = 3; K[50] = 3;
I[51] = 0; J[51] = 2; K[51] = 3;
I[52] = 2; J[52] = 2; K[52] = 1;
I[53] = 3; J[53] = 2; K[53] = 1;
I[54] = 2; J[54] = 3; K[54] = 1;
I[55] = 3; J[55] = 3; K[55] = 1;
// element
I[56] = 2; J[56] = 2; K[56] = 2;
I[57] = 3; J[57] = 2; K[57] = 2;
I[58] = 3; J[58] = 3; K[58] = 2;
I[59] = 2; J[59] = 3; K[59] = 2;
I[60] = 2; J[60] = 2; K[60] = 3;
I[61] = 3; J[61] = 2; K[61] = 3;
I[62] = 3; J[62] = 3; K[62] = 3;
I[63] = 2; J[63] = 3; K[63] = 3;
}
else
{
mfem_error ("LagrangeHexFiniteElement::LagrangeHexFiniteElement");
}
fe1d = new Lagrange1DFiniteElement(degree);
dof1d = fe1d -> GetDof();
#ifndef MFEM_THREAD_SAFE
shape1dx.SetSize(dof1d);
shape1dy.SetSize(dof1d);
shape1dz.SetSize(dof1d);
dshape1dx.SetSize(dof1d,1);
dshape1dy.SetSize(dof1d,1);
dshape1dz.SetSize(dof1d,1);
#endif
for (int n = 0; n < dof; n++)
{
Nodes.IntPoint(n).x = fe1d -> GetNodes().IntPoint(I[n]).x;
Nodes.IntPoint(n).y = fe1d -> GetNodes().IntPoint(J[n]).x;
Nodes.IntPoint(n).z = fe1d -> GetNodes().IntPoint(K[n]).x;
}
}
void LagrangeHexFiniteElement::CalcShape(const IntegrationPoint &ip,
Vector &shape) const
{
IntegrationPoint ipy, ipz;
ipy.x = ip.y;
ipz.x = ip.z;
#ifdef MFEM_THREAD_SAFE
Vector shape1dx(dof1d), shape1dy(dof1d), shape1dz(dof1d);
#endif
fe1d -> CalcShape(ip, shape1dx);
fe1d -> CalcShape(ipy, shape1dy);
fe1d -> CalcShape(ipz, shape1dz);
for (int n = 0; n < dof; n++)
{
shape(n) = shape1dx(I[n]) * shape1dy(J[n]) * shape1dz(K[n]);
}
}
void LagrangeHexFiniteElement::CalcDShape(const IntegrationPoint &ip,
DenseMatrix &dshape) const
{
IntegrationPoint ipy, ipz;
ipy.x = ip.y;
ipz.x = ip.z;
#ifdef MFEM_THREAD_SAFE
Vector shape1dx(dof1d), shape1dy(dof1d), shape1dz(dof1d);
DenseMatrix dshape1dx(dof1d,1), dshape1dy(dof1d,1), dshape1dz(dof1d,1);
#endif
fe1d -> CalcShape(ip, shape1dx);
fe1d -> CalcShape(ipy, shape1dy);
fe1d -> CalcShape(ipz, shape1dz);
fe1d -> CalcDShape(ip, dshape1dx);
fe1d -> CalcDShape(ipy, dshape1dy);
fe1d -> CalcDShape(ipz, dshape1dz);
for (int n = 0; n < dof; n++)
{
dshape(n,0) = dshape1dx(I[n],0) * shape1dy(J[n]) * shape1dz(K[n]);
dshape(n,1) = shape1dx(I[n]) * dshape1dy(J[n],0) * shape1dz(K[n]);
dshape(n,2) = shape1dx(I[n]) * shape1dy(J[n]) * dshape1dz(K[n],0);
}
}
LagrangeHexFiniteElement::~LagrangeHexFiniteElement ()
{
delete fe1d;
delete [] I;
delete [] J;
delete [] K;
}
RefinedLinear1DFiniteElement::RefinedLinear1DFiniteElement()
: NodalFiniteElement(1, Geometry::SEGMENT, 3, 4)
{
Nodes.IntPoint(0).x = 0.0;
Nodes.IntPoint(1).x = 1.0;
Nodes.IntPoint(2).x = 0.5;
}
void RefinedLinear1DFiniteElement::CalcShape(const IntegrationPoint &ip,
Vector &shape) const
{
double x = ip.x;
if (x <= 0.5)
{
shape(0) = 1.0 - 2.0 * x;
shape(1) = 0.0;
shape(2) = 2.0 * x;
}
else
{
shape(0) = 0.0;
shape(1) = 2.0 * x - 1.0;
shape(2) = 2.0 - 2.0 * x;
}
}
void RefinedLinear1DFiniteElement::CalcDShape(const IntegrationPoint &ip,
DenseMatrix &dshape) const
{
double x = ip.x;
if (x <= 0.5)
{
dshape(0,0) = - 2.0;
dshape(1,0) = 0.0;
dshape(2,0) = 2.0;
}
else
{
dshape(0,0) = 0.0;
dshape(1,0) = 2.0;
dshape(2,0) = - 2.0;
}
}
RefinedLinear2DFiniteElement::RefinedLinear2DFiniteElement()
: NodalFiniteElement(2, Geometry::TRIANGLE, 6, 5)
{
Nodes.IntPoint(0).x = 0.0;
Nodes.IntPoint(0).y = 0.0;
Nodes.IntPoint(1).x = 1.0;
Nodes.IntPoint(1).y = 0.0;
Nodes.IntPoint(2).x = 0.0;
Nodes.IntPoint(2).y = 1.0;
Nodes.IntPoint(3).x = 0.5;
Nodes.IntPoint(3).y = 0.0;
Nodes.IntPoint(4).x = 0.5;
Nodes.IntPoint(4).y = 0.5;
Nodes.IntPoint(5).x = 0.0;
Nodes.IntPoint(5).y = 0.5;
}
void RefinedLinear2DFiniteElement::CalcShape(const IntegrationPoint &ip,
Vector &shape) const
{
int i;
double L0, L1, L2;
L0 = 2.0 * ( 1. - ip.x - ip.y );
L1 = 2.0 * ( ip.x );
L2 = 2.0 * ( ip.y );
// The reference triangle is split in 4 triangles as follows:
//
// T0 - 0,3,5
// T1 - 1,3,4
// T2 - 2,4,5
// T3 - 3,4,5
for (i = 0; i < 6; i++)
{
shape(i) = 0.0;
}
if (L0 >= 1.0) // T0
{
shape(0) = L0 - 1.0;
shape(3) = L1;
shape(5) = L2;
}
else if (L1 >= 1.0) // T1
{
shape(3) = L0;
shape(1) = L1 - 1.0;
shape(4) = L2;
}
else if (L2 >= 1.0) // T2
{
shape(5) = L0;
shape(4) = L1;
shape(2) = L2 - 1.0;
}
else // T3
{
shape(3) = 1.0 - L2;
shape(4) = 1.0 - L0;
shape(5) = 1.0 - L1;
}
}
void RefinedLinear2DFiniteElement::CalcDShape(const IntegrationPoint &ip,
DenseMatrix &dshape) const
{
int i,j;
double L0, L1, L2;
L0 = 2.0 * ( 1. - ip.x - ip.y );
L1 = 2.0 * ( ip.x );
L2 = 2.0 * ( ip.y );
double DL0[2], DL1[2], DL2[2];
DL0[0] = -2.0; DL0[1] = -2.0;
DL1[0] = 2.0; DL1[1] = 0.0;
DL2[0] = 0.0; DL2[1] = 2.0;
for (i = 0; i < 6; i++)
for (j = 0; j < 2; j++)
{
dshape(i,j) = 0.0;
}
if (L0 >= 1.0) // T0
{
for (j = 0; j < 2; j++)
{
dshape(0,j) = DL0[j];
dshape(3,j) = DL1[j];
dshape(5,j) = DL2[j];
}
}
else if (L1 >= 1.0) // T1
{
for (j = 0; j < 2; j++)
{
dshape(3,j) = DL0[j];
dshape(1,j) = DL1[j];
dshape(4,j) = DL2[j];
}
}
else if (L2 >= 1.0) // T2
{
for (j = 0; j < 2; j++)
{
dshape(5,j) = DL0[j];
dshape(4,j) = DL1[j];
dshape(2,j) = DL2[j];
}
}
else // T3
{
for (j = 0; j < 2; j++)
{
dshape(3,j) = - DL2[j];
dshape(4,j) = - DL0[j];
dshape(5,j) = - DL1[j];
}
}
}
RefinedLinear3DFiniteElement::RefinedLinear3DFiniteElement()
: NodalFiniteElement(3, Geometry::TETRAHEDRON, 10, 4)
{
Nodes.IntPoint(0).x = 0.0;
Nodes.IntPoint(0).y = 0.0;
Nodes.IntPoint(0).z = 0.0;
Nodes.IntPoint(1).x = 1.0;
Nodes.IntPoint(1).y = 0.0;
Nodes.IntPoint(1).z = 0.0;
Nodes.IntPoint(2).x = 0.0;
Nodes.IntPoint(2).y = 1.0;
Nodes.IntPoint(2).z = 0.0;
Nodes.IntPoint(3).x = 0.0;
Nodes.IntPoint(3).y = 0.0;
Nodes.IntPoint(3).z = 1.0;
Nodes.IntPoint(4).x = 0.5;
Nodes.IntPoint(4).y = 0.0;
Nodes.IntPoint(4).z = 0.0;
Nodes.IntPoint(5).x = 0.0;
Nodes.IntPoint(5).y = 0.5;
Nodes.IntPoint(5).z = 0.0;
Nodes.IntPoint(6).x = 0.0;
Nodes.IntPoint(6).y = 0.0;
Nodes.IntPoint(6).z = 0.5;
Nodes.IntPoint(7).x = 0.5;
Nodes.IntPoint(7).y = 0.5;
Nodes.IntPoint(7).z = 0.0;
Nodes.IntPoint(8).x = 0.5;
Nodes.IntPoint(8).y = 0.0;
Nodes.IntPoint(8).z = 0.5;
Nodes.IntPoint(9).x = 0.0;
Nodes.IntPoint(9).y = 0.5;
Nodes.IntPoint(9).z = 0.5;
}
void RefinedLinear3DFiniteElement::CalcShape(const IntegrationPoint &ip,
Vector &shape) const
{
int i;
double L0, L1, L2, L3, L4, L5;
L0 = 2.0 * ( 1. - ip.x - ip.y - ip.z );
L1 = 2.0 * ( ip.x );
L2 = 2.0 * ( ip.y );
L3 = 2.0 * ( ip.z );
L4 = 2.0 * ( ip.x + ip.y );
L5 = 2.0 * ( ip.y + ip.z );
// The reference tetrahedron is split in 8 tetrahedra as follows:
//
// T0 - 0,4,5,6
// T1 - 1,4,7,8
// T2 - 2,5,7,9
// T3 - 3,6,8,9
// T4 - 4,5,6,8
// T5 - 4,5,7,8
// T6 - 5,6,8,9
// T7 - 5,7,8,9
for (i = 0; i < 10; i++)
{
shape(i) = 0.0;
}
if (L0 >= 1.0) // T0
{
shape(0) = L0 - 1.0;
shape(4) = L1;
shape(5) = L2;
shape(6) = L3;
}
else if (L1 >= 1.0) // T1
{
shape(4) = L0;
shape(1) = L1 - 1.0;
shape(7) = L2;
shape(8) = L3;
}
else if (L2 >= 1.0) // T2
{
shape(5) = L0;
shape(7) = L1;
shape(2) = L2 - 1.0;
shape(9) = L3;
}
else if (L3 >= 1.0) // T3
{
shape(6) = L0;
shape(8) = L1;
shape(9) = L2;
shape(3) = L3 - 1.0;
}
else if ((L4 <= 1.0) && (L5 <= 1.0)) // T4
{
shape(4) = 1.0 - L5;
shape(5) = L2;
shape(6) = 1.0 - L4;
shape(8) = 1.0 - L0;
}
else if ((L4 >= 1.0) && (L5 <= 1.0)) // T5
{
shape(4) = 1.0 - L5;
shape(5) = 1.0 - L1;
shape(7) = L4 - 1.0;
shape(8) = L3;
}
else if ((L4 <= 1.0) && (L5 >= 1.0)) // T6
{
shape(5) = 1.0 - L3;
shape(6) = 1.0 - L4;
shape(8) = L1;
shape(9) = L5 - 1.0;
}
else if ((L4 >= 1.0) && (L5 >= 1.0)) // T7
{
shape(5) = L0;
shape(7) = L4 - 1.0;
shape(8) = 1.0 - L2;
shape(9) = L5 - 1.0;
}
}
void RefinedLinear3DFiniteElement::CalcDShape(const IntegrationPoint &ip,
DenseMatrix &dshape) const
{
int i,j;
double L0, L1, L2, L3, L4, L5;
L0 = 2.0 * ( 1. - ip.x - ip.y - ip.z );
L1 = 2.0 * ( ip.x );
L2 = 2.0 * ( ip.y );
L3 = 2.0 * ( ip.z );
L4 = 2.0 * ( ip.x + ip.y );
L5 = 2.0 * ( ip.y + ip.z );
double DL0[3], DL1[3], DL2[3], DL3[3], DL4[3], DL5[3];
DL0[0] = -2.0; DL0[1] = -2.0; DL0[2] = -2.0;
DL1[0] = 2.0; DL1[1] = 0.0; DL1[2] = 0.0;
DL2[0] = 0.0; DL2[1] = 2.0; DL2[2] = 0.0;
DL3[0] = 0.0; DL3[1] = 0.0; DL3[2] = 2.0;
DL4[0] = 2.0; DL4[1] = 2.0; DL4[2] = 0.0;
DL5[0] = 0.0; DL5[1] = 2.0; DL5[2] = 2.0;
for (i = 0; i < 10; i++)
for (j = 0; j < 3; j++)
{
dshape(i,j) = 0.0;
}
if (L0 >= 1.0) // T0
{
for (j = 0; j < 3; j++)
{
dshape(0,j) = DL0[j];
dshape(4,j) = DL1[j];
dshape(5,j) = DL2[j];
dshape(6,j) = DL3[j];
}
}
else if (L1 >= 1.0) // T1
{
for (j = 0; j < 3; j++)
{
dshape(4,j) = DL0[j];
dshape(1,j) = DL1[j];
dshape(7,j) = DL2[j];
dshape(8,j) = DL3[j];
}
}
else if (L2 >= 1.0) // T2
{
for (j = 0; j < 3; j++)
{
dshape(5,j) = DL0[j];
dshape(7,j) = DL1[j];
dshape(2,j) = DL2[j];
dshape(9,j) = DL3[j];
}
}
else if (L3 >= 1.0) // T3
{
for (j = 0; j < 3; j++)
{
dshape(6,j) = DL0[j];
dshape(8,j) = DL1[j];
dshape(9,j) = DL2[j];
dshape(3,j) = DL3[j];
}
}
else if ((L4 <= 1.0) && (L5 <= 1.0)) // T4
{
for (j = 0; j < 3; j++)
{
dshape(4,j) = - DL5[j];
dshape(5,j) = DL2[j];
dshape(6,j) = - DL4[j];
dshape(8,j) = - DL0[j];
}
}
else if ((L4 >= 1.0) && (L5 <= 1.0)) // T5
{
for (j = 0; j < 3; j++)
{
dshape(4,j) = - DL5[j];
dshape(5,j) = - DL1[j];
dshape(7,j) = DL4[j];
dshape(8,j) = DL3[j];
}
}
else if ((L4 <= 1.0) && (L5 >= 1.0)) // T6
{
for (j = 0; j < 3; j++)
{
dshape(5,j) = - DL3[j];
dshape(6,j) = - DL4[j];
dshape(8,j) = DL1[j];
dshape(9,j) = DL5[j];
}
}
else if ((L4 >= 1.0) && (L5 >= 1.0)) // T7
{
for (j = 0; j < 3; j++)
{
dshape(5,j) = DL0[j];
dshape(7,j) = DL4[j];
dshape(8,j) = - DL2[j];
dshape(9,j) = DL5[j];
}
}
}
RefinedBiLinear2DFiniteElement::RefinedBiLinear2DFiniteElement()
: NodalFiniteElement(2, Geometry::SQUARE, 9, 1, FunctionSpace::rQk)
{
Nodes.IntPoint(0).x = 0.0;
Nodes.IntPoint(0).y = 0.0;
Nodes.IntPoint(1).x = 1.0;
Nodes.IntPoint(1).y = 0.0;
Nodes.IntPoint(2).x = 1.0;
Nodes.IntPoint(2).y = 1.0;
Nodes.IntPoint(3).x = 0.0;
Nodes.IntPoint(3).y = 1.0;
Nodes.IntPoint(4).x = 0.5;
Nodes.IntPoint(4).y = 0.0;
Nodes.IntPoint(5).x = 1.0;
Nodes.IntPoint(5).y = 0.5;
Nodes.IntPoint(6).x = 0.5;
Nodes.IntPoint(6).y = 1.0;
Nodes.IntPoint(7).x = 0.0;
Nodes.IntPoint(7).y = 0.5;
Nodes.IntPoint(8).x = 0.5;
Nodes.IntPoint(8).y = 0.5;
}
void RefinedBiLinear2DFiniteElement::CalcShape(const IntegrationPoint &ip,
Vector &shape) const
{
int i;
double x = ip.x, y = ip.y;
double Lx, Ly;
Lx = 2.0 * ( 1. - x );
Ly = 2.0 * ( 1. - y );
// The reference square is split in 4 squares as follows:
//
// T0 - 0,4,7,8
// T1 - 1,4,5,8
// T2 - 2,5,6,8
// T3 - 3,6,7,8
for (i = 0; i < 9; i++)
{
shape(i) = 0.0;
}
if ((x <= 0.5) && (y <= 0.5)) // T0
{
shape(0) = (Lx - 1.0) * (Ly - 1.0);
shape(4) = (2.0 - Lx) * (Ly - 1.0);
shape(8) = (2.0 - Lx) * (2.0 - Ly);
shape(7) = (Lx - 1.0) * (2.0 - Ly);
}
else if ((x >= 0.5) && (y <= 0.5)) // T1
{
shape(4) = Lx * (Ly - 1.0);
shape(1) = (1.0 - Lx) * (Ly - 1.0);
shape(5) = (1.0 - Lx) * (2.0 - Ly);
shape(8) = Lx * (2.0 - Ly);
}
else if ((x >= 0.5) && (y >= 0.5)) // T2
{
shape(8) = Lx * Ly ;
shape(5) = (1.0 - Lx) * Ly ;
shape(2) = (1.0 - Lx) * (1.0 - Ly);
shape(6) = Lx * (1.0 - Ly);
}
else if ((x <= 0.5) && (y >= 0.5)) // T3
{
shape(7) = (Lx - 1.0) * Ly ;
shape(8) = (2.0 - Lx) * Ly ;
shape(6) = (2.0 - Lx) * (1.0 - Ly);
shape(3) = (Lx - 1.0) * (1.0 - Ly);
}
}
void RefinedBiLinear2DFiniteElement::CalcDShape(const IntegrationPoint &ip,
DenseMatrix &dshape) const
{
int i,j;
double x = ip.x, y = ip.y;
double Lx, Ly;
Lx = 2.0 * ( 1. - x );
Ly = 2.0 * ( 1. - y );
for (i = 0; i < 9; i++)
for (j = 0; j < 2; j++)
{
dshape(i,j) = 0.0;
}
if ((x <= 0.5) && (y <= 0.5)) // T0
{
dshape(0,0) = 2.0 * (1.0 - Ly);
dshape(0,1) = 2.0 * (1.0 - Lx);
dshape(4,0) = 2.0 * (Ly - 1.0);
dshape(4,1) = -2.0 * (2.0 - Lx);
dshape(8,0) = 2.0 * (2.0 - Ly);
dshape(8,1) = 2.0 * (2.0 - Lx);
dshape(7,0) = -2.0 * (2.0 - Ly);
dshape(7,0) = 2.0 * (Lx - 1.0);
}
else if ((x >= 0.5) && (y <= 0.5)) // T1
{
dshape(4,0) = -2.0 * (Ly - 1.0);
dshape(4,1) = -2.0 * Lx;
dshape(1,0) = 2.0 * (Ly - 1.0);
dshape(1,1) = -2.0 * (1.0 - Lx);
dshape(5,0) = 2.0 * (2.0 - Ly);
dshape(5,1) = 2.0 * (1.0 - Lx);
dshape(8,0) = -2.0 * (2.0 - Ly);
dshape(8,1) = 2.0 * Lx;
}
else if ((x >= 0.5) && (y >= 0.5)) // T2
{
dshape(8,0) = -2.0 * Ly;
dshape(8,1) = -2.0 * Lx;
dshape(5,0) = 2.0 * Ly;
dshape(5,1) = -2.0 * (1.0 - Lx);
dshape(2,0) = 2.0 * (1.0 - Ly);
dshape(2,1) = 2.0 * (1.0 - Lx);
dshape(6,0) = -2.0 * (1.0 - Ly);
dshape(6,1) = 2.0 * Lx;
}
else if ((x <= 0.5) && (y >= 0.5)) // T3
{
dshape(7,0) = -2.0 * Ly;
dshape(7,1) = -2.0 * (Lx - 1.0);
dshape(8,0) = 2.0 * Ly ;
dshape(8,1) = -2.0 * (2.0 - Lx);
dshape(6,0) = 2.0 * (1.0 - Ly);
dshape(6,1) = 2.0 * (2.0 - Lx);
dshape(3,0) = -2.0 * (1.0 - Ly);
dshape(3,1) = 2.0 * (Lx - 1.0);
}
}
RefinedTriLinear3DFiniteElement::RefinedTriLinear3DFiniteElement()
: NodalFiniteElement(3, Geometry::CUBE, 27, 2, FunctionSpace::rQk)
{
double I[27];
double J[27];
double K[27];
// nodes
I[ 0] = 0.0; J[ 0] = 0.0; K[ 0] = 0.0;
I[ 1] = 1.0; J[ 1] = 0.0; K[ 1] = 0.0;
I[ 2] = 1.0; J[ 2] = 1.0; K[ 2] = 0.0;
I[ 3] = 0.0; J[ 3] = 1.0; K[ 3] = 0.0;
I[ 4] = 0.0; J[ 4] = 0.0; K[ 4] = 1.0;
I[ 5] = 1.0; J[ 5] = 0.0; K[ 5] = 1.0;
I[ 6] = 1.0; J[ 6] = 1.0; K[ 6] = 1.0;
I[ 7] = 0.0; J[ 7] = 1.0; K[ 7] = 1.0;
// edges
I[ 8] = 0.5; J[ 8] = 0.0; K[ 8] = 0.0;
I[ 9] = 1.0; J[ 9] = 0.5; K[ 9] = 0.0;
I[10] = 0.5; J[10] = 1.0; K[10] = 0.0;
I[11] = 0.0; J[11] = 0.5; K[11] = 0.0;
I[12] = 0.5; J[12] = 0.0; K[12] = 1.0;
I[13] = 1.0; J[13] = 0.5; K[13] = 1.0;
I[14] = 0.5; J[14] = 1.0; K[14] = 1.0;
I[15] = 0.0; J[15] = 0.5; K[15] = 1.0;
I[16] = 0.0; J[16] = 0.0; K[16] = 0.5;
I[17] = 1.0; J[17] = 0.0; K[17] = 0.5;
I[18] = 1.0; J[18] = 1.0; K[18] = 0.5;
I[19] = 0.0; J[19] = 1.0; K[19] = 0.5;
// faces
I[20] = 0.5; J[20] = 0.5; K[20] = 0.0;
I[21] = 0.5; J[21] = 0.0; K[21] = 0.5;
I[22] = 1.0; J[22] = 0.5; K[22] = 0.5;
I[23] = 0.5; J[23] = 1.0; K[23] = 0.5;
I[24] = 0.0; J[24] = 0.5; K[24] = 0.5;
I[25] = 0.5; J[25] = 0.5; K[25] = 1.0;
// element
I[26] = 0.5; J[26] = 0.5; K[26] = 0.5;
for (int n = 0; n < 27; n++)
{
Nodes.IntPoint(n).x = I[n];
Nodes.IntPoint(n).y = J[n];
Nodes.IntPoint(n).z = K[n];
}
}
void RefinedTriLinear3DFiniteElement::CalcShape(const IntegrationPoint &ip,
Vector &shape) const
{
int i, N[8];
double Lx, Ly, Lz;
double x = ip.x, y = ip.y, z = ip.z;
for (i = 0; i < 27; i++)
{
shape(i) = 0.0;
}
if ((x <= 0.5) && (y <= 0.5) && (z <= 0.5)) // T0
{
Lx = 1.0 - 2.0 * x;
Ly = 1.0 - 2.0 * y;
Lz = 1.0 - 2.0 * z;
N[0] = 0;
N[1] = 8;
N[2] = 20;
N[3] = 11;
N[4] = 16;
N[5] = 21;
N[6] = 26;
N[7] = 24;
}
else if ((x >= 0.5) && (y <= 0.5) && (z <= 0.5)) // T1
{
Lx = 2.0 - 2.0 * x;
Ly = 1.0 - 2.0 * y;
Lz = 1.0 - 2.0 * z;
N[0] = 8;
N[1] = 1;
N[2] = 9;
N[3] = 20;
N[4] = 21;
N[5] = 17;
N[6] = 22;
N[7] = 26;
}
else if ((x <= 0.5) && (y >= 0.5) && (z <= 0.5)) // T2
{
Lx = 2.0 - 2.0 * x;
Ly = 2.0 - 2.0 * y;
Lz = 1.0 - 2.0 * z;
N[0] = 20;
N[1] = 9;
N[2] = 2;
N[3] = 10;
N[4] = 26;
N[5] = 22;
N[6] = 18;
N[7] = 23;
}
else if ((x >= 0.5) && (y >= 0.5) && (z <= 0.5)) // T3
{
Lx = 1.0 - 2.0 * x;
Ly = 2.0 - 2.0 * y;
Lz = 1.0 - 2.0 * z;
N[0] = 11;
N[1] = 20;
N[2] = 10;
N[3] = 3;
N[4] = 24;
N[5] = 26;
N[6] = 23;
N[7] = 19;
}
else if ((x <= 0.5) && (y <= 0.5) && (z >= 0.5)) // T4
{
Lx = 1.0 - 2.0 * x;
Ly = 1.0 - 2.0 * y;
Lz = 2.0 - 2.0 * z;
N[0] = 16;
N[1] = 21;
N[2] = 26;
N[3] = 24;
N[4] = 4;
N[5] = 12;
N[6] = 25;
N[7] = 15;
}
else if ((x >= 0.5) && (y <= 0.5) && (z >= 0.5)) // T5
{
Lx = 2.0 - 2.0 * x;
Ly = 1.0 - 2.0 * y;
Lz = 2.0 - 2.0 * z;
N[0] = 21;
N[1] = 17;
N[2] = 22;
N[3] = 26;
N[4] = 12;
N[5] = 5;
N[6] = 13;
N[7] = 25;
}
else if ((x <= 0.5) && (y >= 0.5) && (z >= 0.5)) // T6
{
Lx = 2.0 - 2.0 * x;
Ly = 2.0 - 2.0 * y;
Lz = 2.0 - 2.0 * z;
N[0] = 26;
N[1] = 22;
N[2] = 18;
N[3] = 23;
N[4] = 25;
N[5] = 13;
N[6] = 6;
N[7] = 14;
}
else // T7
{
Lx = 1.0 - 2.0 * x;
Ly = 2.0 - 2.0 * y;
Lz = 2.0 - 2.0 * z;
N[0] = 24;
N[1] = 26;
N[2] = 23;
N[3] = 19;
N[4] = 15;
N[5] = 25;
N[6] = 14;
N[7] = 7;
}
shape(N[0]) = Lx * Ly * Lz;
shape(N[1]) = (1 - Lx) * Ly * Lz;
shape(N[2]) = (1 - Lx) * (1 - Ly) * Lz;
shape(N[3]) = Lx * (1 - Ly) * Lz;
shape(N[4]) = Lx * Ly * (1 - Lz);
shape(N[5]) = (1 - Lx) * Ly * (1 - Lz);
shape(N[6]) = (1 - Lx) * (1 - Ly) * (1 - Lz);
shape(N[7]) = Lx * (1 - Ly) * (1 - Lz);
}
void RefinedTriLinear3DFiniteElement::CalcDShape(const IntegrationPoint &ip,
DenseMatrix &dshape) const
{
int i, j, N[8];
double Lx, Ly, Lz;
double x = ip.x, y = ip.y, z = ip.z;
for (i = 0; i < 27; i++)
for (j = 0; j < 3; j++)
{
dshape(i,j) = 0.0;
}
if ((x <= 0.5) && (y <= 0.5) && (z <= 0.5)) // T0
{
Lx = 1.0 - 2.0 * x;
Ly = 1.0 - 2.0 * y;
Lz = 1.0 - 2.0 * z;
N[0] = 0;
N[1] = 8;
N[2] = 20;
N[3] = 11;
N[4] = 16;
N[5] = 21;
N[6] = 26;
N[7] = 24;
}
else if ((x >= 0.5) && (y <= 0.5) && (z <= 0.5)) // T1
{
Lx = 2.0 - 2.0 * x;
Ly = 1.0 - 2.0 * y;
Lz = 1.0 - 2.0 * z;
N[0] = 8;
N[1] = 1;
N[2] = 9;
N[3] = 20;
N[4] = 21;
N[5] = 17;
N[6] = 22;
N[7] = 26;
}
else if ((x <= 0.5) && (y >= 0.5) && (z <= 0.5)) // T2
{
Lx = 2.0 - 2.0 * x;
Ly = 2.0 - 2.0 * y;
Lz = 1.0 - 2.0 * z;
N[0] = 20;
N[1] = 9;
N[2] = 2;
N[3] = 10;
N[4] = 26;
N[5] = 22;
N[6] = 18;
N[7] = 23;
}
else if ((x >= 0.5) && (y >= 0.5) && (z <= 0.5)) // T3
{
Lx = 1.0 - 2.0 * x;
Ly = 2.0 - 2.0 * y;
Lz = 1.0 - 2.0 * z;
N[0] = 11;
N[1] = 20;
N[2] = 10;
N[3] = 3;
N[4] = 24;
N[5] = 26;
N[6] = 23;
N[7] = 19;
}
else if ((x <= 0.5) && (y <= 0.5) && (z >= 0.5)) // T4
{
Lx = 1.0 - 2.0 * x;
Ly = 1.0 - 2.0 * y;
Lz = 2.0 - 2.0 * z;
N[0] = 16;
N[1] = 21;
N[2] = 26;
N[3] = 24;
N[4] = 4;
N[5] = 12;
N[6] = 25;
N[7] = 15;
}
else if ((x >= 0.5) && (y <= 0.5) && (z >= 0.5)) // T5
{
Lx = 2.0 - 2.0 * x;
Ly = 1.0 - 2.0 * y;
Lz = 2.0 - 2.0 * z;
N[0] = 21;
N[1] = 17;
N[2] = 22;
N[3] = 26;
N[4] = 12;
N[5] = 5;
N[6] = 13;
N[7] = 25;
}
else if ((x <= 0.5) && (y >= 0.5) && (z >= 0.5)) // T6
{
Lx = 2.0 - 2.0 * x;
Ly = 2.0 - 2.0 * y;
Lz = 2.0 - 2.0 * z;
N[0] = 26;
N[1] = 22;
N[2] = 18;
N[3] = 23;
N[4] = 25;
N[5] = 13;
N[6] = 6;
N[7] = 14;
}
else // T7
{
Lx = 1.0 - 2.0 * x;
Ly = 2.0 - 2.0 * y;
Lz = 2.0 - 2.0 * z;
N[0] = 24;
N[1] = 26;
N[2] = 23;
N[3] = 19;
N[4] = 15;
N[5] = 25;
N[6] = 14;
N[7] = 7;
}
dshape(N[0],0) = -2.0 * Ly * Lz ;
dshape(N[0],1) = -2.0 * Lx * Lz ;
dshape(N[0],2) = -2.0 * Lx * Ly ;
dshape(N[1],0) = 2.0 * Ly * Lz ;
dshape(N[1],1) = -2.0 * (1 - Lx) * Lz ;
dshape(N[1],2) = -2.0 * (1 - Lx) * Ly ;
dshape(N[2],0) = 2.0 * (1 - Ly) * Lz ;
dshape(N[2],1) = 2.0 * (1 - Lx) * Lz ;
dshape(N[2],2) = -2.0 * (1 - Lx) * (1 - Ly);
dshape(N[3],0) = -2.0 * (1 - Ly) * Lz ;
dshape(N[3],1) = 2.0 * Lx * Lz ;
dshape(N[3],2) = -2.0 * Lx * (1 - Ly);
dshape(N[4],0) = -2.0 * Ly * (1 - Lz);
dshape(N[4],1) = -2.0 * Lx * (1 - Lz);
dshape(N[4],2) = 2.0 * Lx * Ly ;
dshape(N[5],0) = 2.0 * Ly * (1 - Lz);
dshape(N[5],1) = -2.0 * (1 - Lx) * (1 - Lz);
dshape(N[5],2) = 2.0 * (1 - Lx) * Ly ;
dshape(N[6],0) = 2.0 * (1 - Ly) * (1 - Lz);
dshape(N[6],1) = 2.0 * (1 - Lx) * (1 - Lz);
dshape(N[6],2) = 2.0 * (1 - Lx) * (1 - Ly);
dshape(N[7],0) = -2.0 * (1 - Ly) * (1 - Lz);
dshape(N[7],1) = 2.0 * Lx * (1 - Lz);
dshape(N[7],2) = 2.0 * Lx * (1 - Ly);
}
Nedelec1HexFiniteElement::Nedelec1HexFiniteElement()
: VectorFiniteElement(3, Geometry::CUBE, 12, 1, H_CURL, FunctionSpace::Qk)
{
// not real nodes ...
Nodes.IntPoint(0).x = 0.5;
Nodes.IntPoint(0).y = 0.0;
Nodes.IntPoint(0).z = 0.0;
Nodes.IntPoint(1).x = 1.0;
Nodes.IntPoint(1).y = 0.5;
Nodes.IntPoint(1).z = 0.0;
Nodes.IntPoint(2).x = 0.5;
Nodes.IntPoint(2).y = 1.0;
Nodes.IntPoint(2).z = 0.0;
Nodes.IntPoint(3).x = 0.0;
Nodes.IntPoint(3).y = 0.5;
Nodes.IntPoint(3).z = 0.0;
Nodes.IntPoint(4).x = 0.5;
Nodes.IntPoint(4).y = 0.0;
Nodes.IntPoint(4).z = 1.0;
Nodes.IntPoint(5).x = 1.0;
Nodes.IntPoint(5).y = 0.5;
Nodes.IntPoint(5).z = 1.0;
Nodes.IntPoint(6).x = 0.5;
Nodes.IntPoint(6).y = 1.0;
Nodes.IntPoint(6).z = 1.0;
Nodes.IntPoint(7).x = 0.0;
Nodes.IntPoint(7).y = 0.5;
Nodes.IntPoint(7).z = 1.0;
Nodes.IntPoint(8).x = 0.0;
Nodes.IntPoint(8).y = 0.0;
Nodes.IntPoint(8).z = 0.5;
Nodes.IntPoint(9).x = 1.0;
Nodes.IntPoint(9).y = 0.0;
Nodes.IntPoint(9).z = 0.5;
Nodes.IntPoint(10).x= 1.0;
Nodes.IntPoint(10).y= 1.0;
Nodes.IntPoint(10).z= 0.5;
Nodes.IntPoint(11).x= 0.0;
Nodes.IntPoint(11).y= 1.0;
Nodes.IntPoint(11).z= 0.5;
}
void Nedelec1HexFiniteElement::CalcVShape(const IntegrationPoint &ip,
DenseMatrix &shape) const
{
double x = ip.x, y = ip.y, z = ip.z;
shape(0,0) = (1. - y) * (1. - z);
shape(0,1) = 0.;
shape(0,2) = 0.;
shape(2,0) = y * (1. - z);
shape(2,1) = 0.;
shape(2,2) = 0.;
shape(4,0) = z * (1. - y);
shape(4,1) = 0.;
shape(4,2) = 0.;
shape(6,0) = y * z;
shape(6,1) = 0.;
shape(6,2) = 0.;
shape(1,0) = 0.;
shape(1,1) = x * (1. - z);
shape(1,2) = 0.;
shape(3,0) = 0.;
shape(3,1) = (1. - x) * (1. - z);
shape(3,2) = 0.;
shape(5,0) = 0.;
shape(5,1) = x * z;
shape(5,2) = 0.;
shape(7,0) = 0.;
shape(7,1) = (1. - x) * z;
shape(7,2) = 0.;
shape(8,0) = 0.;
shape(8,1) = 0.;
shape(8,2) = (1. - x) * (1. - y);
shape(9,0) = 0.;
shape(9,1) = 0.;
shape(9,2) = x * (1. - y);
shape(10,0) = 0.;
shape(10,1) = 0.;
shape(10,2) = x * y;
shape(11,0) = 0.;
shape(11,1) = 0.;
shape(11,2) = y * (1. - x);
}
void Nedelec1HexFiniteElement::CalcCurlShape(const IntegrationPoint &ip,
DenseMatrix &curl_shape)
const
{
double x = ip.x, y = ip.y, z = ip.z;
curl_shape(0,0) = 0.;
curl_shape(0,1) = y - 1.;
curl_shape(0,2) = 1. - z;
curl_shape(2,0) = 0.;
curl_shape(2,1) = -y;
curl_shape(2,2) = z - 1.;
curl_shape(4,0) = 0;
curl_shape(4,1) = 1. - y;
curl_shape(4,2) = z;
curl_shape(6,0) = 0.;
curl_shape(6,1) = y;
curl_shape(6,2) = -z;
curl_shape(1,0) = x;
curl_shape(1,1) = 0.;
curl_shape(1,2) = 1. - z;
curl_shape(3,0) = 1. - x;
curl_shape(3,1) = 0.;
curl_shape(3,2) = z - 1.;
curl_shape(5,0) = -x;
curl_shape(5,1) = 0.;
curl_shape(5,2) = z;
curl_shape(7,0) = x - 1.;
curl_shape(7,1) = 0.;
curl_shape(7,2) = -z;
curl_shape(8,0) = x - 1.;
curl_shape(8,1) = 1. - y;
curl_shape(8,2) = 0.;
curl_shape(9,0) = -x;
curl_shape(9,1) = y - 1.;
curl_shape(9,2) = 0;
curl_shape(10,0) = x;
curl_shape(10,1) = -y;
curl_shape(10,2) = 0.;
curl_shape(11,0) = 1. - x;
curl_shape(11,1) = y;
curl_shape(11,2) = 0.;
}
const double Nedelec1HexFiniteElement::tk[12][3] =
{
{1,0,0}, {0,1,0}, {1,0,0}, {0,1,0},
{1,0,0}, {0,1,0}, {1,0,0}, {0,1,0},
{0,0,1}, {0,0,1}, {0,0,1}, {0,0,1}
};
void Nedelec1HexFiniteElement::GetLocalInterpolation (
ElementTransformation &Trans, DenseMatrix &I) const
{
int k, j;
#ifdef MFEM_THREAD_SAFE
DenseMatrix vshape(dof, dim);
#endif
#ifdef MFEM_DEBUG
for (k = 0; k < 12; k++)
{
CalcVShape (Nodes.IntPoint(k), vshape);
for (j = 0; j < 12; j++)
{
double d = ( vshape(j,0)*tk[k][0] + vshape(j,1)*tk[k][1] +
vshape(j,2)*tk[k][2] );
if (j == k) { d -= 1.0; }
if (fabs(d) > 1.0e-12)
{
mfem::err << "Nedelec1HexFiniteElement::GetLocalInterpolation (...)\n"
" k = " << k << ", j = " << j << ", d = " << d << endl;
mfem_error();
}
}
}
#endif
IntegrationPoint ip;
ip.x = ip.y = ip.z = 0.0;
Trans.SetIntPoint (&ip);
// Trans must be linear (more to have embedding?)
const DenseMatrix &J = Trans.Jacobian();
double vk[3];
Vector xk (vk, 3);
for (k = 0; k < 12; k++)
{
Trans.Transform (Nodes.IntPoint (k), xk);
ip.x = vk[0]; ip.y = vk[1]; ip.z = vk[2];
CalcVShape (ip, vshape);
// vk = J tk
vk[0] = J(0,0)*tk[k][0]+J(0,1)*tk[k][1]+J(0,2)*tk[k][2];
vk[1] = J(1,0)*tk[k][0]+J(1,1)*tk[k][1]+J(1,2)*tk[k][2];
vk[2] = J(2,0)*tk[k][0]+J(2,1)*tk[k][1]+J(2,2)*tk[k][2];
for (j = 0; j < 12; j++)
if (fabs (I(k,j) = (vshape(j,0)*vk[0]+vshape(j,1)*vk[1]+
vshape(j,2)*vk[2])) < 1.0e-12)
{
I(k,j) = 0.0;
}
}
}
void Nedelec1HexFiniteElement::Project (
VectorCoefficient &vc, ElementTransformation &Trans,
Vector &dofs) const
{
double vk[3];
Vector xk (vk, 3);
for (int k = 0; k < 12; k++)
{
Trans.SetIntPoint (&Nodes.IntPoint (k));
const DenseMatrix &J = Trans.Jacobian();
vc.Eval (xk, Trans, Nodes.IntPoint (k));
// xk^t J tk
dofs(k) =
vk[0] * ( J(0,0)*tk[k][0]+J(0,1)*tk[k][1]+J(0,2)*tk[k][2] ) +
vk[1] * ( J(1,0)*tk[k][0]+J(1,1)*tk[k][1]+J(1,2)*tk[k][2] ) +
vk[2] * ( J(2,0)*tk[k][0]+J(2,1)*tk[k][1]+J(2,2)*tk[k][2] );
}
}
Nedelec1TetFiniteElement::Nedelec1TetFiniteElement()
: VectorFiniteElement(3, Geometry::TETRAHEDRON, 6, 1, H_CURL)
{
// not real nodes ...
Nodes.IntPoint(0).x = 0.5;
Nodes.IntPoint(0).y = 0.0;
Nodes.IntPoint(0).z = 0.0;
Nodes.IntPoint(1).x = 0.0;
Nodes.IntPoint(1).y = 0.5;
Nodes.IntPoint(1).z = 0.0;
Nodes.IntPoint(2).x = 0.0;
Nodes.IntPoint(2).y = 0.0;
Nodes.IntPoint(2).z = 0.5;
Nodes.IntPoint(3).x = 0.5;
Nodes.IntPoint(3).y = 0.5;
Nodes.IntPoint(3).z = 0.0;
Nodes.IntPoint(4).x = 0.5;
Nodes.IntPoint(4).y = 0.0;
Nodes.IntPoint(4).z = 0.5;
Nodes.IntPoint(5).x = 0.0;
Nodes.IntPoint(5).y = 0.5;
Nodes.IntPoint(5).z = 0.5;
}
void Nedelec1TetFiniteElement::CalcVShape(const IntegrationPoint &ip,
DenseMatrix &shape) const
{
double x = ip.x, y = ip.y, z = ip.z;
shape(0,0) = 1. - y - z;
shape(0,1) = x;
shape(0,2) = x;
shape(1,0) = y;
shape(1,1) = 1. - x - z;
shape(1,2) = y;
shape(2,0) = z;
shape(2,1) = z;
shape(2,2) = 1. - x - y;
shape(3,0) = -y;
shape(3,1) = x;
shape(3,2) = 0.;
shape(4,0) = -z;
shape(4,1) = 0.;
shape(4,2) = x;
shape(5,0) = 0.;
shape(5,1) = -z;
shape(5,2) = y;
}
void Nedelec1TetFiniteElement::CalcCurlShape(const IntegrationPoint &ip,
DenseMatrix &curl_shape)
const
{
curl_shape(0,0) = 0.;
curl_shape(0,1) = -2.;
curl_shape(0,2) = 2.;
curl_shape(1,0) = 2.;
curl_shape(1,1) = 0.;
curl_shape(1,2) = -2.;
curl_shape(2,0) = -2.;
curl_shape(2,1) = 2.;
curl_shape(2,2) = 0.;
curl_shape(3,0) = 0.;
curl_shape(3,1) = 0.;
curl_shape(3,2) = 2.;
curl_shape(4,0) = 0.;
curl_shape(4,1) = -2.;
curl_shape(4,2) = 0.;
curl_shape(5,0) = 2.;
curl_shape(5,1) = 0.;
curl_shape(5,2) = 0.;
}
const double Nedelec1TetFiniteElement::tk[6][3] =
{{1,0,0}, {0,1,0}, {0,0,1}, {-1,1,0}, {-1,0,1}, {0,-1,1}};
void Nedelec1TetFiniteElement::GetLocalInterpolation (
ElementTransformation &Trans, DenseMatrix &I) const
{
int k, j;
#ifdef MFEM_THREAD_SAFE
DenseMatrix vshape(dof, dim);
#endif
#ifdef MFEM_DEBUG
for (k = 0; k < 6; k++)
{
CalcVShape (Nodes.IntPoint(k), vshape);
for (j = 0; j < 6; j++)
{
double d = ( vshape(j,0)*tk[k][0] + vshape(j,1)*tk[k][1] +
vshape(j,2)*tk[k][2] );
if (j == k) { d -= 1.0; }
if (fabs(d) > 1.0e-12)
{
mfem::err << "Nedelec1TetFiniteElement::GetLocalInterpolation (...)\n"
" k = " << k << ", j = " << j << ", d = " << d << endl;
mfem_error();
}
}
}
#endif
IntegrationPoint ip;
ip.x = ip.y = ip.z = 0.0;
Trans.SetIntPoint (&ip);
// Trans must be linear
const DenseMatrix &J = Trans.Jacobian();
double vk[3];
Vector xk (vk, 3);
for (k = 0; k < 6; k++)
{
Trans.Transform (Nodes.IntPoint (k), xk);
ip.x = vk[0]; ip.y = vk[1]; ip.z = vk[2];
CalcVShape (ip, vshape);
// vk = J tk
vk[0] = J(0,0)*tk[k][0]+J(0,1)*tk[k][1]+J(0,2)*tk[k][2];
vk[1] = J(1,0)*tk[k][0]+J(1,1)*tk[k][1]+J(1,2)*tk[k][2];
vk[2] = J(2,0)*tk[k][0]+J(2,1)*tk[k][1]+J(2,2)*tk[k][2];
for (j = 0; j < 6; j++)
if (fabs (I(k,j) = (vshape(j,0)*vk[0]+vshape(j,1)*vk[1]+
vshape(j,2)*vk[2])) < 1.0e-12)
{
I(k,j) = 0.0;
}
}
}
void Nedelec1TetFiniteElement::Project (
VectorCoefficient &vc, ElementTransformation &Trans,
Vector &dofs) const
{
double vk[3];
Vector xk (vk, 3);
for (int k = 0; k < 6; k++)
{
Trans.SetIntPoint (&Nodes.IntPoint (k));
const DenseMatrix &J = Trans.Jacobian();
vc.Eval (xk, Trans, Nodes.IntPoint (k));
// xk^t J tk
dofs(k) =
vk[0] * ( J(0,0)*tk[k][0]+J(0,1)*tk[k][1]+J(0,2)*tk[k][2] ) +
vk[1] * ( J(1,0)*tk[k][0]+J(1,1)*tk[k][1]+J(1,2)*tk[k][2] ) +
vk[2] * ( J(2,0)*tk[k][0]+J(2,1)*tk[k][1]+J(2,2)*tk[k][2] );
}
}
RT0HexFiniteElement::RT0HexFiniteElement()
: VectorFiniteElement(3, Geometry::CUBE, 6, 1, H_DIV, FunctionSpace::Qk)
{
// not real nodes ...
// z = 0, y = 0, x = 1, y = 1, x = 0, z = 1
Nodes.IntPoint(0).x = 0.5;
Nodes.IntPoint(0).y = 0.5;
Nodes.IntPoint(0).z = 0.0;
Nodes.IntPoint(1).x = 0.5;
Nodes.IntPoint(1).y = 0.0;
Nodes.IntPoint(1).z = 0.5;
Nodes.IntPoint(2).x = 1.0;
Nodes.IntPoint(2).y = 0.5;
Nodes.IntPoint(2).z = 0.5;
Nodes.IntPoint(3).x = 0.5;
Nodes.IntPoint(3).y = 1.0;
Nodes.IntPoint(3).z = 0.5;
Nodes.IntPoint(4).x = 0.0;
Nodes.IntPoint(4).y = 0.5;
Nodes.IntPoint(4).z = 0.5;
Nodes.IntPoint(5).x = 0.5;
Nodes.IntPoint(5).y = 0.5;
Nodes.IntPoint(5).z = 1.0;
}
void RT0HexFiniteElement::CalcVShape(const IntegrationPoint &ip,
DenseMatrix &shape) const
{
double x = ip.x, y = ip.y, z = ip.z;
// z = 0
shape(0,0) = 0.;
shape(0,1) = 0.;
shape(0,2) = z - 1.;
// y = 0
shape(1,0) = 0.;
shape(1,1) = y - 1.;
shape(1,2) = 0.;
// x = 1
shape(2,0) = x;
shape(2,1) = 0.;
shape(2,2) = 0.;
// y = 1
shape(3,0) = 0.;
shape(3,1) = y;
shape(3,2) = 0.;
// x = 0
shape(4,0) = x - 1.;
shape(4,1) = 0.;
shape(4,2) = 0.;
// z = 1
shape(5,0) = 0.;
shape(5,1) = 0.;
shape(5,2) = z;
}
void RT0HexFiniteElement::CalcDivShape(const IntegrationPoint &ip,
Vector &divshape) const
{
divshape(0) = 1.;
divshape(1) = 1.;
divshape(2) = 1.;
divshape(3) = 1.;
divshape(4) = 1.;
divshape(5) = 1.;
}
const double RT0HexFiniteElement::nk[6][3] =
{{0,0,-1}, {0,-1,0}, {1,0,0}, {0,1,0}, {-1,0,0}, {0,0,1}};
void RT0HexFiniteElement::GetLocalInterpolation (
ElementTransformation &Trans, DenseMatrix &I) const
{
int k, j;
#ifdef MFEM_THREAD_SAFE
DenseMatrix vshape(dof, dim);
DenseMatrix Jinv(dim);
#endif
#ifdef MFEM_DEBUG
for (k = 0; k < 6; k++)
{
CalcVShape (Nodes.IntPoint(k), vshape);
for (j = 0; j < 6; j++)
{
double d = ( vshape(j,0)*nk[k][0] + vshape(j,1)*nk[k][1] +
vshape(j,2)*nk[k][2] );
if (j == k) { d -= 1.0; }
if (fabs(d) > 1.0e-12)
{
mfem::err << "RT0HexFiniteElement::GetLocalInterpolation (...)\n"
" k = " << k << ", j = " << j << ", d = " << d << endl;
mfem_error();
}
}
}
#endif
IntegrationPoint ip;
ip.x = ip.y = ip.z = 0.0;
Trans.SetIntPoint (&ip);
// Trans must be linear
// set Jinv = |J| J^{-t} = adj(J)^t
CalcAdjugateTranspose (Trans.Jacobian(), Jinv);
double vk[3];
Vector xk (vk, 3);
for (k = 0; k < 6; k++)
{
Trans.Transform (Nodes.IntPoint (k), xk);
ip.x = vk[0]; ip.y = vk[1]; ip.z = vk[2];
CalcVShape (ip, vshape);
// vk = |J| J^{-t} nk
vk[0] = Jinv(0,0)*nk[k][0]+Jinv(0,1)*nk[k][1]+Jinv(0,2)*nk[k][2];
vk[1] = Jinv(1,0)*nk[k][0]+Jinv(1,1)*nk[k][1]+Jinv(1,2)*nk[k][2];
vk[2] = Jinv(2,0)*nk[k][0]+Jinv(2,1)*nk[k][1]+Jinv(2,2)*nk[k][2];
for (j = 0; j < 6; j++)
if (fabs (I(k,j) = (vshape(j,0)*vk[0]+vshape(j,1)*vk[1]+
vshape(j,2)*vk[2])) < 1.0e-12)
{
I(k,j) = 0.0;
}
}
}
void RT0HexFiniteElement::Project (
VectorCoefficient &vc, ElementTransformation &Trans,
Vector &dofs) const
{
double vk[3];
Vector xk (vk, 3);
#ifdef MFEM_THREAD_SAFE
DenseMatrix Jinv(dim);
#endif
for (int k = 0; k < 6; k++)
{
Trans.SetIntPoint (&Nodes.IntPoint (k));
// set Jinv = |J| J^{-t} = adj(J)^t
CalcAdjugateTranspose (Trans.Jacobian(), Jinv);
vc.Eval (xk, Trans, Nodes.IntPoint (k));
// xk^t |J| J^{-t} nk
dofs(k) =
vk[0] * ( Jinv(0,0)*nk[k][0]+Jinv(0,1)*nk[k][1]+Jinv(0,2)*nk[k][2] ) +
vk[1] * ( Jinv(1,0)*nk[k][0]+Jinv(1,1)*nk[k][1]+Jinv(1,2)*nk[k][2] ) +
vk[2] * ( Jinv(2,0)*nk[k][0]+Jinv(2,1)*nk[k][1]+Jinv(2,2)*nk[k][2] );
}
}
RT1HexFiniteElement::RT1HexFiniteElement()
: VectorFiniteElement(3, Geometry::CUBE, 36, 2, H_DIV, FunctionSpace::Qk)
{
// z = 0
Nodes.IntPoint(2).x = 1./3.;
Nodes.IntPoint(2).y = 1./3.;
Nodes.IntPoint(2).z = 0.0;
Nodes.IntPoint(3).x = 2./3.;
Nodes.IntPoint(3).y = 1./3.;
Nodes.IntPoint(3).z = 0.0;
Nodes.IntPoint(0).x = 1./3.;
Nodes.IntPoint(0).y = 2./3.;
Nodes.IntPoint(0).z = 0.0;
Nodes.IntPoint(1).x = 2./3.;
Nodes.IntPoint(1).y = 2./3.;
Nodes.IntPoint(1).z = 0.0;
// y = 0
Nodes.IntPoint(4).x = 1./3.;
Nodes.IntPoint(4).y = 0.0;
Nodes.IntPoint(4).z = 1./3.;
Nodes.IntPoint(5).x = 2./3.;
Nodes.IntPoint(5).y = 0.0;
Nodes.IntPoint(5).z = 1./3.;
Nodes.IntPoint(6).x = 1./3.;
Nodes.IntPoint(6).y = 0.0;
Nodes.IntPoint(6).z = 2./3.;
Nodes.IntPoint(7).x = 2./3.;
Nodes.IntPoint(7).y = 0.0;
Nodes.IntPoint(7).z = 2./3.;
// x = 1
Nodes.IntPoint(8).x = 1.0;
Nodes.IntPoint(8).y = 1./3.;
Nodes.IntPoint(8).z = 1./3.;
Nodes.IntPoint(9).x = 1.0;
Nodes.IntPoint(9).y = 2./3.;
Nodes.IntPoint(9).z = 1./3.;
Nodes.IntPoint(10).x = 1.0;
Nodes.IntPoint(10).y = 1./3.;
Nodes.IntPoint(10).z = 2./3.;
Nodes.IntPoint(11).x = 1.0;
Nodes.IntPoint(11).y = 2./3.;
Nodes.IntPoint(11).z = 2./3.;
// y = 1
Nodes.IntPoint(13).x = 1./3.;
Nodes.IntPoint(13).y = 1.0;
Nodes.IntPoint(13).z = 1./3.;
Nodes.IntPoint(12).x = 2./3.;
Nodes.IntPoint(12).y = 1.0;
Nodes.IntPoint(12).z = 1./3.;
Nodes.IntPoint(15).x = 1./3.;
Nodes.IntPoint(15).y = 1.0;
Nodes.IntPoint(15).z = 2./3.;
Nodes.IntPoint(14).x = 2./3.;
Nodes.IntPoint(14).y = 1.0;
Nodes.IntPoint(14).z = 2./3.;
// x = 0
Nodes.IntPoint(17).x = 0.0;
Nodes.IntPoint(17).y = 1./3.;
Nodes.IntPoint(17).z = 1./3.;
Nodes.IntPoint(16).x = 0.0;
Nodes.IntPoint(16).y = 2./3.;
Nodes.IntPoint(16).z = 1./3.;
Nodes.IntPoint(19).x = 0.0;
Nodes.IntPoint(19).y = 1./3.;
Nodes.IntPoint(19).z = 2./3.;
Nodes.IntPoint(18).x = 0.0;
Nodes.IntPoint(18).y = 2./3.;
Nodes.IntPoint(18).z = 2./3.;
// z = 1
Nodes.IntPoint(20).x = 1./3.;
Nodes.IntPoint(20).y = 1./3.;
Nodes.IntPoint(20).z = 1.0;
Nodes.IntPoint(21).x = 2./3.;
Nodes.IntPoint(21).y = 1./3.;
Nodes.IntPoint(21).z = 1.0;
Nodes.IntPoint(22).x = 1./3.;
Nodes.IntPoint(22).y = 2./3.;
Nodes.IntPoint(22).z = 1.0;
Nodes.IntPoint(23).x = 2./3.;
Nodes.IntPoint(23).y = 2./3.;
Nodes.IntPoint(23).z = 1.0;
// x = 0.5 (interior)
Nodes.IntPoint(24).x = 0.5;
Nodes.IntPoint(24).y = 1./3.;
Nodes.IntPoint(24).z = 1./3.;
Nodes.IntPoint(25).x = 0.5;
Nodes.IntPoint(25).y = 1./3.;
Nodes.IntPoint(25).z = 2./3.;
Nodes.IntPoint(26).x = 0.5;
Nodes.IntPoint(26).y = 2./3.;
Nodes.IntPoint(26).z = 1./3.;
Nodes.IntPoint(27).x = 0.5;
Nodes.IntPoint(27).y = 2./3.;
Nodes.IntPoint(27).z = 2./3.;
// y = 0.5 (interior)
Nodes.IntPoint(28).x = 1./3.;
Nodes.IntPoint(28).y = 0.5;
Nodes.IntPoint(28).z = 1./3.;
Nodes.IntPoint(29).x = 1./3.;
Nodes.IntPoint(29).y = 0.5;
Nodes.IntPoint(29).z = 2./3.;
Nodes.IntPoint(30).x = 2./3.;
Nodes.IntPoint(30).y = 0.5;
Nodes.IntPoint(30).z = 1./3.;
Nodes.IntPoint(31).x = 2./3.;
Nodes.IntPoint(31).y = 0.5;
Nodes.IntPoint(31).z = 2./3.;
// z = 0.5 (interior)
Nodes.IntPoint(32).x = 1./3.;
Nodes.IntPoint(32).y = 1./3.;
Nodes.IntPoint(32).z = 0.5;
Nodes.IntPoint(33).x = 1./3.;
Nodes.IntPoint(33).y = 2./3.;
Nodes.IntPoint(33).z = 0.5;
Nodes.IntPoint(34).x = 2./3.;
Nodes.IntPoint(34).y = 1./3.;
Nodes.IntPoint(34).z = 0.5;
Nodes.IntPoint(35).x = 2./3.;
Nodes.IntPoint(35).y = 2./3.;
Nodes.IntPoint(35).z = 0.5;
}
void RT1HexFiniteElement::CalcVShape(const IntegrationPoint &ip,
DenseMatrix &shape) const
{
double x = ip.x, y = ip.y, z = ip.z;
// z = 0
shape(2,0) = 0.;
shape(2,1) = 0.;
shape(2,2) = -(1. - 3.*z + 2.*z*z)*( 2. - 3.*x)*( 2. - 3.*y);
shape(3,0) = 0.;
shape(3,1) = 0.;
shape(3,2) = -(1. - 3.*z + 2.*z*z)*(-1. + 3.*x)*( 2. - 3.*y);
shape(0,0) = 0.;
shape(0,1) = 0.;
shape(0,2) = -(1. - 3.*z + 2.*z*z)*( 2. - 3.*x)*(-1. + 3.*y);
shape(1,0) = 0.;
shape(1,1) = 0.;
shape(1,2) = -(1. - 3.*z + 2.*z*z)*(-1. + 3.*x)*(-1. + 3.*y);
// y = 0
shape(4,0) = 0.;
shape(4,1) = -(1. - 3.*y + 2.*y*y)*( 2. - 3.*x)*( 2. - 3.*z);
shape(4,2) = 0.;
shape(5,0) = 0.;
shape(5,1) = -(1. - 3.*y + 2.*y*y)*(-1. + 3.*x)*( 2. - 3.*z);
shape(5,2) = 0.;
shape(6,0) = 0.;
shape(6,1) = -(1. - 3.*y + 2.*y*y)*( 2. - 3.*x)*(-1. + 3.*z);
shape(6,2) = 0.;
shape(7,0) = 0.;
shape(7,1) = -(1. - 3.*y + 2.*y*y)*(-1. + 3.*x)*(-1. + 3.*z);
shape(7,2) = 0.;
// x = 1
shape(8,0) = (-x + 2.*x*x)*( 2. - 3.*y)*( 2. - 3.*z);
shape(8,1) = 0.;
shape(8,2) = 0.;
shape(9,0) = (-x + 2.*x*x)*(-1. + 3.*y)*( 2. - 3.*z);
shape(9,1) = 0.;
shape(9,2) = 0.;
shape(10,0) = (-x + 2.*x*x)*( 2. - 3.*y)*(-1. + 3.*z);
shape(10,1) = 0.;
shape(10,2) = 0.;
shape(11,0) = (-x + 2.*x*x)*(-1. + 3.*y)*(-1. + 3.*z);
shape(11,1) = 0.;
shape(11,2) = 0.;
// y = 1
shape(13,0) = 0.;
shape(13,1) = (-y + 2.*y*y)*( 2. - 3.*x)*( 2. - 3.*z);
shape(13,2) = 0.;
shape(12,0) = 0.;
shape(12,1) = (-y + 2.*y*y)*(-1. + 3.*x)*( 2. - 3.*z);
shape(12,2) = 0.;
shape(15,0) = 0.;
shape(15,1) = (-y + 2.*y*y)*( 2. - 3.*x)*(-1. + 3.*z);
shape(15,2) = 0.;
shape(14,0) = 0.;
shape(14,1) = (-y + 2.*y*y)*(-1. + 3.*x)*(-1. + 3.*z);
shape(14,2) = 0.;
// x = 0
shape(17,0) = -(1. - 3.*x + 2.*x*x)*( 2. - 3.*y)*( 2. - 3.*z);
shape(17,1) = 0.;
shape(17,2) = 0.;
shape(16,0) = -(1. - 3.*x + 2.*x*x)*(-1. + 3.*y)*( 2. - 3.*z);
shape(16,1) = 0.;
shape(16,2) = 0.;
shape(19,0) = -(1. - 3.*x + 2.*x*x)*( 2. - 3.*y)*(-1. + 3.*z);
shape(19,1) = 0.;
shape(19,2) = 0.;
shape(18,0) = -(1. - 3.*x + 2.*x*x)*(-1. + 3.*y)*(-1. + 3.*z);
shape(18,1) = 0.;
shape(18,2) = 0.;
// z = 1
shape(20,0) = 0.;
shape(20,1) = 0.;
shape(20,2) = (-z + 2.*z*z)*( 2. - 3.*x)*( 2. - 3.*y);
shape(21,0) = 0.;
shape(21,1) = 0.;
shape(21,2) = (-z + 2.*z*z)*(-1. + 3.*x)*( 2. - 3.*y);
shape(22,0) = 0.;
shape(22,1) = 0.;
shape(22,2) = (-z + 2.*z*z)*( 2. - 3.*x)*(-1. + 3.*y);
shape(23,0) = 0.;
shape(23,1) = 0.;
shape(23,2) = (-z + 2.*z*z)*(-1. + 3.*x)*(-1. + 3.*y);
// x = 0.5 (interior)
shape(24,0) = (4.*x - 4.*x*x)*( 2. - 3.*y)*( 2. - 3.*z);
shape(24,1) = 0.;
shape(24,2) = 0.;
shape(25,0) = (4.*x - 4.*x*x)*( 2. - 3.*y)*(-1. + 3.*z);
shape(25,1) = 0.;
shape(25,2) = 0.;
shape(26,0) = (4.*x - 4.*x*x)*(-1. + 3.*y)*( 2. - 3.*z);
shape(26,1) = 0.;
shape(26,2) = 0.;
shape(27,0) = (4.*x - 4.*x*x)*(-1. + 3.*y)*(-1. + 3.*z);
shape(27,1) = 0.;
shape(27,2) = 0.;
// y = 0.5 (interior)
shape(28,0) = 0.;
shape(28,1) = (4.*y - 4.*y*y)*( 2. - 3.*x)*( 2. - 3.*z);
shape(28,2) = 0.;
shape(29,0) = 0.;
shape(29,1) = (4.*y - 4.*y*y)*( 2. - 3.*x)*(-1. + 3.*z);
shape(29,2) = 0.;
shape(30,0) = 0.;
shape(30,1) = (4.*y - 4.*y*y)*(-1. + 3.*x)*( 2. - 3.*z);
shape(30,2) = 0.;
shape(31,0) = 0.;
shape(31,1) = (4.*y - 4.*y*y)*(-1. + 3.*x)*(-1. + 3.*z);
shape(31,2) = 0.;
// z = 0.5 (interior)
shape(32,0) = 0.;
shape(32,1) = 0.;
shape(32,2) = (4.*z - 4.*z*z)*( 2. - 3.*x)*( 2. - 3.*y);
shape(33,0) = 0.;
shape(33,1) = 0.;
shape(33,2) = (4.*z - 4.*z*z)*( 2. - 3.*x)*(-1. + 3.*y);
shape(34,0) = 0.;
shape(34,1) = 0.;
shape(34,2) = (4.*z - 4.*z*z)*(-1. + 3.*x)*( 2. - 3.*y);
shape(35,0) = 0.;
shape(35,1) = 0.;
shape(35,2) = (4.*z - 4.*z*z)*(-1. + 3.*x)*(-1. + 3.*y);
}
void RT1HexFiniteElement::CalcDivShape(const IntegrationPoint &ip,
Vector &divshape) const
{
double x = ip.x, y = ip.y, z = ip.z;
// z = 0
divshape(2) = -(-3. + 4.*z)*( 2. - 3.*x)*( 2. - 3.*y);
divshape(3) = -(-3. + 4.*z)*(-1. + 3.*x)*( 2. - 3.*y);
divshape(0) = -(-3. + 4.*z)*( 2. - 3.*x)*(-1. + 3.*y);
divshape(1) = -(-3. + 4.*z)*(-1. + 3.*x)*(-1. + 3.*y);
// y = 0
divshape(4) = -(-3. + 4.*y)*( 2. - 3.*x)*( 2. - 3.*z);
divshape(5) = -(-3. + 4.*y)*(-1. + 3.*x)*( 2. - 3.*z);
divshape(6) = -(-3. + 4.*y)*( 2. - 3.*x)*(-1. + 3.*z);
divshape(7) = -(-3. + 4.*y)*(-1. + 3.*x)*(-1. + 3.*z);
// x = 1
divshape(8) = (-1. + 4.*x)*( 2. - 3.*y)*( 2. - 3.*z);
divshape(9) = (-1. + 4.*x)*(-1. + 3.*y)*( 2. - 3.*z);
divshape(10) = (-1. + 4.*x)*( 2. - 3.*y)*(-1. + 3.*z);
divshape(11) = (-1. + 4.*x)*(-1. + 3.*y)*(-1. + 3.*z);
// y = 1
divshape(13) = (-1. + 4.*y)*( 2. - 3.*x)*( 2. - 3.*z);
divshape(12) = (-1. + 4.*y)*(-1. + 3.*x)*( 2. - 3.*z);
divshape(15) = (-1. + 4.*y)*( 2. - 3.*x)*(-1. + 3.*z);
divshape(14) = (-1. + 4.*y)*(-1. + 3.*x)*(-1. + 3.*z);
// x = 0
divshape(17) = -(-3. + 4.*x)*( 2. - 3.*y)*( 2. - 3.*z);
divshape(16) = -(-3. + 4.*x)*(-1. + 3.*y)*( 2. - 3.*z);
divshape(19) = -(-3. + 4.*x)*( 2. - 3.*y)*(-1. + 3.*z);
divshape(18) = -(-3. + 4.*x)*(-1. + 3.*y)*(-1. + 3.*z);
// z = 1
divshape(20) = (-1. + 4.*z)*( 2. - 3.*x)*( 2. - 3.*y);
divshape(21) = (-1. + 4.*z)*(-1. + 3.*x)*( 2. - 3.*y);
divshape(22) = (-1. + 4.*z)*( 2. - 3.*x)*(-1. + 3.*y);
divshape(23) = (-1. + 4.*z)*(-1. + 3.*x)*(-1. + 3.*y);
// x = 0.5 (interior)
divshape(24) = ( 4. - 8.*x)*( 2. - 3.*y)*( 2. - 3.*z);
divshape(25) = ( 4. - 8.*x)*( 2. - 3.*y)*(-1. + 3.*z);
divshape(26) = ( 4. - 8.*x)*(-1. + 3.*y)*( 2. - 3.*z);
divshape(27) = ( 4. - 8.*x)*(-1. + 3.*y)*(-1. + 3.*z);
// y = 0.5 (interior)
divshape(28) = ( 4. - 8.*y)*( 2. - 3.*x)*( 2. - 3.*z);
divshape(29) = ( 4. - 8.*y)*( 2. - 3.*x)*(-1. + 3.*z);
divshape(30) = ( 4. - 8.*y)*(-1. + 3.*x)*( 2. - 3.*z);
divshape(31) = ( 4. - 8.*y)*(-1. + 3.*x)*(-1. + 3.*z);
// z = 0.5 (interior)
divshape(32) = ( 4. - 8.*z)*( 2. - 3.*x)*( 2. - 3.*y);
divshape(33) = ( 4. - 8.*z)*( 2. - 3.*x)*(-1. + 3.*y);
divshape(34) = ( 4. - 8.*z)*(-1. + 3.*x)*( 2. - 3.*y);
divshape(35) = ( 4. - 8.*z)*(-1. + 3.*x)*(-1. + 3.*y);
}
const double RT1HexFiniteElement::nk[36][3] =
{
{0, 0,-1}, {0, 0,-1}, {0, 0,-1}, {0, 0,-1},
{0,-1, 0}, {0,-1, 0}, {0,-1, 0}, {0,-1, 0},
{1, 0, 0}, {1, 0, 0}, {1, 0, 0}, {1, 0, 0},
{0, 1, 0}, {0, 1, 0}, {0, 1, 0}, {0, 1, 0},
{-1,0, 0}, {-1,0, 0}, {-1,0, 0}, {-1,0, 0},
{0, 0, 1}, {0, 0, 1}, {0, 0, 1}, {0, 0, 1},
{1, 0, 0}, {1, 0, 0}, {1, 0, 0}, {1, 0, 0},
{0, 1, 0}, {0, 1, 0}, {0, 1, 0}, {0, 1, 0},
{0, 0, 1}, {0, 0, 1}, {0, 0, 1}, {0, 0, 1}
};
void RT1HexFiniteElement::GetLocalInterpolation (
ElementTransformation &Trans, DenseMatrix &I) const
{
int k, j;
#ifdef MFEM_THREAD_SAFE
DenseMatrix vshape(dof, dim);
DenseMatrix Jinv(dim);
#endif
#ifdef MFEM_DEBUG
for (k = 0; k < 36; k++)
{
CalcVShape (Nodes.IntPoint(k), vshape);
for (j = 0; j < 36; j++)
{
double d = ( vshape(j,0)*nk[k][0] + vshape(j,1)*nk[k][1] +
vshape(j,2)*nk[k][2] );
if (j == k) { d -= 1.0; }
if (fabs(d) > 1.0e-12)
{
mfem::err << "RT0HexFiniteElement::GetLocalInterpolation (...)\n"
" k = " << k << ", j = " << j << ", d = " << d << endl;
mfem_error();
}
}
}
#endif
IntegrationPoint ip;
ip.x = ip.y = ip.z = 0.0;
Trans.SetIntPoint (&ip);
// Trans must be linear
// set Jinv = |J| J^{-t} = adj(J)^t
CalcAdjugateTranspose (Trans.Jacobian(), Jinv);
double vk[3];
Vector xk (vk, 3);
for (k = 0; k < 36; k++)
{
Trans.Transform (Nodes.IntPoint (k), xk);
ip.x = vk[0]; ip.y = vk[1]; ip.z = vk[2];
CalcVShape (ip, vshape);
// vk = |J| J^{-t} nk
vk[0] = Jinv(0,0)*nk[k][0]+Jinv(0,1)*nk[k][1]+Jinv(0,2)*nk[k][2];
vk[1] = Jinv(1,0)*nk[k][0]+Jinv(1,1)*nk[k][1]+Jinv(1,2)*nk[k][2];
vk[2] = Jinv(2,0)*nk[k][0]+Jinv(2,1)*nk[k][1]+Jinv(2,2)*nk[k][2];
for (j = 0; j < 36; j++)
if (fabs (I(k,j) = (vshape(j,0)*vk[0]+vshape(j,1)*vk[1]+
vshape(j,2)*vk[2])) < 1.0e-12)
{
I(k,j) = 0.0;
}
}
}
void RT1HexFiniteElement::Project (
VectorCoefficient &vc, ElementTransformation &Trans,
Vector &dofs) const
{
double vk[3];
Vector xk (vk, 3);
#ifdef MFEM_THREAD_SAFE
DenseMatrix Jinv(dim);
#endif
for (int k = 0; k < 36; k++)
{
Trans.SetIntPoint (&Nodes.IntPoint (k));
// set Jinv = |J| J^{-t} = adj(J)^t
CalcAdjugateTranspose (Trans.Jacobian(), Jinv);
vc.Eval (xk, Trans, Nodes.IntPoint (k));
// xk^t |J| J^{-t} nk
dofs(k) =
vk[0] * ( Jinv(0,0)*nk[k][0]+Jinv(0,1)*nk[k][1]+Jinv(0,2)*nk[k][2] ) +
vk[1] * ( Jinv(1,0)*nk[k][0]+Jinv(1,1)*nk[k][1]+Jinv(1,2)*nk[k][2] ) +
vk[2] * ( Jinv(2,0)*nk[k][0]+Jinv(2,1)*nk[k][1]+Jinv(2,2)*nk[k][2] );
}
}
RT0TetFiniteElement::RT0TetFiniteElement()
: VectorFiniteElement(3, Geometry::TETRAHEDRON, 4, 1, H_DIV)
{
// not real nodes ...
Nodes.IntPoint(0).x = 0.33333333333333333333;
Nodes.IntPoint(0).y = 0.33333333333333333333;
Nodes.IntPoint(0).z = 0.33333333333333333333;
Nodes.IntPoint(1).x = 0.0;
Nodes.IntPoint(1).y = 0.33333333333333333333;
Nodes.IntPoint(1).z = 0.33333333333333333333;
Nodes.IntPoint(2).x = 0.33333333333333333333;
Nodes.IntPoint(2).y = 0.0;
Nodes.IntPoint(2).z = 0.33333333333333333333;
Nodes.IntPoint(3).x = 0.33333333333333333333;
Nodes.IntPoint(3).y = 0.33333333333333333333;
Nodes.IntPoint(3).z = 0.0;
}
void RT0TetFiniteElement::CalcVShape(const IntegrationPoint &ip,
DenseMatrix &shape) const
{
double x2 = 2.0*ip.x, y2 = 2.0*ip.y, z2 = 2.0*ip.z;
shape(0,0) = x2;
shape(0,1) = y2;
shape(0,2) = z2;
shape(1,0) = x2 - 2.0;
shape(1,1) = y2;
shape(1,2) = z2;
shape(2,0) = x2;
shape(2,1) = y2 - 2.0;
shape(2,2) = z2;
shape(3,0) = x2;
shape(3,1) = y2;
shape(3,2) = z2 - 2.0;
}
void RT0TetFiniteElement::CalcDivShape(const IntegrationPoint &ip,
Vector &divshape) const
{
divshape(0) = 6.0;
divshape(1) = 6.0;
divshape(2) = 6.0;
divshape(3) = 6.0;
}
const double RT0TetFiniteElement::nk[4][3] =
{{.5,.5,.5}, {-.5,0,0}, {0,-.5,0}, {0,0,-.5}};
void RT0TetFiniteElement::GetLocalInterpolation (
ElementTransformation &Trans, DenseMatrix &I) const
{
int k, j;
#ifdef MFEM_THREAD_SAFE
DenseMatrix vshape(dof, dim);
DenseMatrix Jinv(dim);
#endif
#ifdef MFEM_DEBUG
for (k = 0; k < 4; k++)
{
CalcVShape (Nodes.IntPoint(k), vshape);
for (j = 0; j < 4; j++)
{
double d = ( vshape(j,0)*nk[k][0] + vshape(j,1)*nk[k][1] +
vshape(j,2)*nk[k][2] );
if (j == k) { d -= 1.0; }
if (fabs(d) > 1.0e-12)
{
mfem::err << "RT0TetFiniteElement::GetLocalInterpolation (...)\n"
" k = " << k << ", j = " << j << ", d = " << d << endl;
mfem_error();
}
}
}
#endif
IntegrationPoint ip;
ip.x = ip.y = ip.z = 0.0;
Trans.SetIntPoint (&ip);
// Trans must be linear
// set Jinv = |J| J^{-t} = adj(J)^t
CalcAdjugateTranspose (Trans.Jacobian(), Jinv);
double vk[3];
Vector xk (vk, 3);
for (k = 0; k < 4; k++)
{
Trans.Transform (Nodes.IntPoint (k), xk);
ip.x = vk[0]; ip.y = vk[1]; ip.z = vk[2];
CalcVShape (ip, vshape);
// vk = |J| J^{-t} nk
vk[0] = Jinv(0,0)*nk[k][0]+Jinv(0,1)*nk[k][1]+Jinv(0,2)*nk[k][2];
vk[1] = Jinv(1,0)*nk[k][0]+Jinv(1,1)*nk[k][1]+Jinv(1,2)*nk[k][2];
vk[2] = Jinv(2,0)*nk[k][0]+Jinv(2,1)*nk[k][1]+Jinv(2,2)*nk[k][2];
for (j = 0; j < 4; j++)
if (fabs (I(k,j) = (vshape(j,0)*vk[0]+vshape(j,1)*vk[1]+
vshape(j,2)*vk[2])) < 1.0e-12)
{
I(k,j) = 0.0;
}
}
}
void RT0TetFiniteElement::Project (
VectorCoefficient &vc, ElementTransformation &Trans,
Vector &dofs) const
{
double vk[3];
Vector xk (vk, 3);
#ifdef MFEM_THREAD_SAFE
DenseMatrix Jinv(dim);
#endif
for (int k = 0; k < 4; k++)
{
Trans.SetIntPoint (&Nodes.IntPoint (k));
// set Jinv = |J| J^{-t} = adj(J)^t
CalcAdjugateTranspose (Trans.Jacobian(), Jinv);
vc.Eval (xk, Trans, Nodes.IntPoint (k));
// xk^t |J| J^{-t} nk
dofs(k) =
vk[0] * ( Jinv(0,0)*nk[k][0]+Jinv(0,1)*nk[k][1]+Jinv(0,2)*nk[k][2] ) +
vk[1] * ( Jinv(1,0)*nk[k][0]+Jinv(1,1)*nk[k][1]+Jinv(1,2)*nk[k][2] ) +
vk[2] * ( Jinv(2,0)*nk[k][0]+Jinv(2,1)*nk[k][1]+Jinv(2,2)*nk[k][2] );
}
}
RotTriLinearHexFiniteElement::RotTriLinearHexFiniteElement()
: NodalFiniteElement(3, Geometry::CUBE, 6, 2, FunctionSpace::Qk)
{
Nodes.IntPoint(0).x = 0.5;
Nodes.IntPoint(0).y = 0.5;
Nodes.IntPoint(0).z = 0.0;
Nodes.IntPoint(1).x = 0.5;
Nodes.IntPoint(1).y = 0.0;
Nodes.IntPoint(1).z = 0.5;
Nodes.IntPoint(2).x = 1.0;
Nodes.IntPoint(2).y = 0.5;
Nodes.IntPoint(2).z = 0.5;
Nodes.IntPoint(3).x = 0.5;
Nodes.IntPoint(3).y = 1.0;
Nodes.IntPoint(3).z = 0.5;
Nodes.IntPoint(4).x = 0.0;
Nodes.IntPoint(4).y = 0.5;
Nodes.IntPoint(4).z = 0.5;
Nodes.IntPoint(5).x = 0.5;
Nodes.IntPoint(5).y = 0.5;
Nodes.IntPoint(5).z = 1.0;
}
void RotTriLinearHexFiniteElement::CalcShape(const IntegrationPoint &ip,
Vector &shape) const
{
double x = 2. * ip.x - 1.;
double y = 2. * ip.y - 1.;
double z = 2. * ip.z - 1.;
double f5 = x * x - y * y;
double f6 = y * y - z * z;
shape(0) = (1./6.) * (1. - 3. * z - f5 - 2. * f6);
shape(1) = (1./6.) * (1. - 3. * y - f5 + f6);
shape(2) = (1./6.) * (1. + 3. * x + 2. * f5 + f6);
shape(3) = (1./6.) * (1. + 3. * y - f5 + f6);
shape(4) = (1./6.) * (1. - 3. * x + 2. * f5 + f6);
shape(5) = (1./6.) * (1. + 3. * z - f5 - 2. * f6);
}
void RotTriLinearHexFiniteElement::CalcDShape(const IntegrationPoint &ip,
DenseMatrix &dshape) const
{
const double a = 2./3.;
double xt = a * (1. - 2. * ip.x);
double yt = a * (1. - 2. * ip.y);
double zt = a * (1. - 2. * ip.z);
dshape(0,0) = xt;
dshape(0,1) = yt;
dshape(0,2) = -1. - 2. * zt;
dshape(1,0) = xt;
dshape(1,1) = -1. - 2. * yt;
dshape(1,2) = zt;
dshape(2,0) = 1. - 2. * xt;
dshape(2,1) = yt;
dshape(2,2) = zt;
dshape(3,0) = xt;
dshape(3,1) = 1. - 2. * yt;
dshape(3,2) = zt;
dshape(4,0) = -1. - 2. * xt;
dshape(4,1) = yt;
dshape(4,2) = zt;
dshape(5,0) = xt;
dshape(5,1) = yt;
dshape(5,2) = 1. - 2. * zt;
}
Poly_1D::Basis::Basis(const int p, const double *nodes, EvalType etype)
: etype(etype)
{
switch (etype)
{
case ChangeOfBasis:
{
x.SetSize(p + 1);
w.SetSize(p + 1);
DenseMatrix A(p + 1);
for (int i = 0; i <= p; i++)
{
CalcBasis(p, nodes[i], A.GetColumn(i));
}
Ai.Factor(A);
// mfem::out << "Poly_1D::Basis(" << p << ",...) : "; Ai.TestInversion();
break;
}
case Barycentric:
{
x.SetSize(p + 1);
w.SetSize(p + 1);
x = nodes;
w = 1.0;
for (int i = 0; i <= p; i++)
{
for (int j = 0; j < i; j++)
{
double xij = x(i) - x(j);
w(i) *= xij;
w(j) *= -xij;
}
}
for (int i = 0; i <= p; i++)
{
w(i) = 1.0/w(i);
}
#ifdef MFEM_DEBUG
// Make sure the nodes are increasing
for (int i = 0; i < p; i++)
{
if (x(i) >= x(i+1))
{
mfem_error("Poly_1D::Basis::Basis : nodes are not increasing!");
}
}
#endif
break;
}
case Positive:
x.SetDataAndSize(NULL, p + 1); // use x to store (p + 1)
break;
default: break;
}
}
void Poly_1D::Basis::Eval(const double y, Vector &u) const
{
switch (etype)
{
case ChangeOfBasis:
{
CalcBasis(Ai.Width() - 1, y, x);
Ai.Mult(x, u);
break;
}
case Barycentric:
{
int i, k, p = x.Size() - 1;
double l, lk;
if (p == 0)
{
u(0) = 1.0;
return;
}
lk = 1.0;
for (k = 0; k < p; k++)
{
if (y >= (x(k) + x(k+1))/2)
{
lk *= y - x(k);
}
else
{
for (i = k+1; i <= p; i++)
{
lk *= y - x(i);
}
break;
}
}
l = lk * (y - x(k));
for (i = 0; i < k; i++)
{
u(i) = l * w(i) / (y - x(i));
}
u(k) = lk * w(k);
for (i++; i <= p; i++)
{
u(i) = l * w(i) / (y - x(i));
}
break;
}
case Positive:
CalcBernstein(x.Size() - 1, y, u);
break;
default: break;
}
}
void Poly_1D::Basis::Eval(const double y, Vector &u, Vector &d) const
{
switch (etype)
{
case ChangeOfBasis:
{
CalcBasis(Ai.Width() - 1, y, x, w);
Ai.Mult(x, u);
Ai.Mult(w, d);
break;
}
case Barycentric:
{
int i, k, p = x.Size() - 1;
double l, lp, lk, sk, si;
if (p == 0)
{
u(0) = 1.0;
d(0) = 0.0;
return;
}
lk = 1.0;
for (k = 0; k < p; k++)
{
if (y >= (x(k) + x(k+1))/2)
{
lk *= y - x(k);
}
else
{
for (i = k+1; i <= p; i++)
{
lk *= y - x(i);
}
break;
}
}
l = lk * (y - x(k));
sk = 0.0;
for (i = 0; i < k; i++)
{
si = 1.0/(y - x(i));
sk += si;
u(i) = l * si * w(i);
}
u(k) = lk * w(k);
for (i++; i <= p; i++)
{
si = 1.0/(y - x(i));
sk += si;
u(i) = l * si * w(i);
}
lp = l * sk + lk;
for (i = 0; i < k; i++)
{
d(i) = (lp * w(i) - u(i))/(y - x(i));
}
d(k) = sk * u(k);
for (i++; i <= p; i++)
{
d(i) = (lp * w(i) - u(i))/(y - x(i));
}
break;
}
case Positive:
CalcBernstein(x.Size() - 1, y, u, d);
break;
default: break;
}
}
void Poly_1D::Basis::Eval(const double y, Vector &u, Vector &d,
Vector &d2) const
{
MFEM_VERIFY(etype == Barycentric,
"Basis::Eval with second order derivatives not implemented for"
" etype = " << etype);
switch (etype)
{
case ChangeOfBasis:
{
CalcBasis(Ai.Width() - 1, y, x, w);
Ai.Mult(x, u);
Ai.Mult(w, d);
// set d2 (not implemented yet)
break;
}
case Barycentric:
{
int i, k, p = x.Size() - 1;
double l, lp, lp2, lk, sk, si, sk2;
if (p == 0)
{
u(0) = 1.0;
d(0) = 0.0;
d2(0) = 0.0;
return;
}
lk = 1.0;
for (k = 0; k < p; k++)
{
if (y >= (x(k) + x(k+1))/2)
{
lk *= y - x(k);
}
else
{
for (i = k+1; i <= p; i++)
{
lk *= y - x(i);
}
break;
}
}
l = lk * (y - x(k));
sk = 0.0;
sk2 = 0.0;
for (i = 0; i < k; i++)
{
si = 1.0/(y - x(i));
sk += si;
sk2 -= si * si;
u(i) = l * si * w(i);
}
u(k) = lk * w(k);
for (i++; i <= p; i++)
{
si = 1.0/(y - x(i));
sk += si;
sk2 -= si * si;
u(i) = l * si * w(i);
}
lp = l * sk + lk;
lp2 = lp * sk + l * sk2 + sk * lk;
for (i = 0; i < k; i++)
{
d(i) = (lp * w(i) - u(i))/(y - x(i));
d2(i) = (lp2 * w(i) - 2 * d(i))/(y - x(i));
}
d(k) = sk * u(k);
d2(k) = sk2 * u(k) + sk * d(k);
for (i++; i <= p; i++)
{
d(i) = (lp * w(i) - u(i))/(y - x(i));
d2(i) = (lp2 * w(i) - 2 * d(i))/(y - x(i));
}
break;
}
case Positive:
CalcBernstein(x.Size() - 1, y, u, d);
break;
default: break;
}
}
const int *Poly_1D::Binom(const int p)
{
if (binom.NumCols() <= p)
{
binom.SetSize(p + 1, p + 1);
for (int i = 0; i <= p; i++)
{
binom(i,0) = binom(i,i) = 1;
for (int j = 1; j < i; j++)
{
binom(i,j) = binom(i-1,j) + binom(i-1,j-1);
}
}
}
return binom[p];
}
void Poly_1D::ChebyshevPoints(const int p, double *x)
{
for (int i = 0; i <= p; i++)
{
// x[i] = 0.5*(1. + cos(M_PI*(p - i + 0.5)/(p + 1)));
double s = sin(M_PI_2*(i + 0.5)/(p + 1));
x[i] = s*s;
}
}
void Poly_1D::CalcMono(const int p, const double x, double *u)
{
double xn;
u[0] = xn = 1.;
for (int n = 1; n <= p; n++)
{
u[n] = (xn *= x);
}
}
void Poly_1D::CalcMono(const int p, const double x, double *u, double *d)
{
double xn;
u[0] = xn = 1.;
d[0] = 0.;
for (int n = 1; n <= p; n++)
{
d[n] = n * xn;
u[n] = (xn *= x);
}
}
void Poly_1D::CalcBinomTerms(const int p, const double x, const double y,
double *u)
{
if (p == 0)
{
u[0] = 1.;
}
else
{
int i;
const int *b = Binom(p);
double z = x;
for (i = 1; i < p; i++)
{
u[i] = b[i]*z;
z *= x;
}
u[p] = z;
z = y;
for (i--; i > 0; i--)
{
u[i] *= z;
z *= y;
}
u[0] = z;
}
}
void Poly_1D::CalcBinomTerms(const int p, const double x, const double y,
double *u, double *d)
{
if (p == 0)
{
u[0] = 1.;
d[0] = 0.;
}
else
{
int i;
const int *b = Binom(p);
const double xpy = x + y, ptx = p*x;
double z = 1.;
for (i = 1; i < p; i++)
{
d[i] = b[i]*z*(i*xpy - ptx);
z *= x;
u[i] = b[i]*z;
}
d[p] = p*z;
u[p] = z*x;
z = 1.;
for (i--; i > 0; i--)
{
d[i] *= z;
z *= y;
u[i] *= z;
}
d[0] = -p*z;
u[0] = z*y;
}
}
void Poly_1D::CalcDBinomTerms(const int p, const double x, const double y,
double *d)
{
if (p == 0)
{
d[0] = 0.;
}
else
{
int i;
const int *b = Binom(p);
const double xpy = x + y, ptx = p*x;
double z = 1.;
for (i = 1; i < p; i++)
{
d[i] = b[i]*z*(i*xpy - ptx);
z *= x;
}
d[p] = p*z;
z = 1.;
for (i--; i > 0; i--)
{
d[i] *= z;
z *= y;
}
d[0] = -p*z;
}
}
void Poly_1D::CalcLegendre(const int p, const double x, double *u)
{
// use the recursive definition for [-1,1]:
// (n+1)*P_{n+1}(z) = (2*n+1)*z*P_n(z)-n*P_{n-1}(z)
double z;
u[0] = 1.;
if (p == 0) { return; }
u[1] = z = 2.*x - 1.;
for (int n = 1; n < p; n++)
{
u[n+1] = ((2*n + 1)*z*u[n] - n*u[n-1])/(n + 1);
}
}
void Poly_1D::CalcLegendre(const int p, const double x, double *u, double *d)
{
// use the recursive definition for [-1,1]:
// (n+1)*P_{n+1}(z) = (2*n+1)*z*P_n(z)-n*P_{n-1}(z)
// for the derivative use, z in [-1,1]:
// P'_{n+1}(z) = (2*n+1)*P_n(z)+P'_{n-1}(z)
double z;
u[0] = 1.;
d[0] = 0.;
if (p == 0) { return; }
u[1] = z = 2.*x - 1.;
d[1] = 2.;
for (int n = 1; n < p; n++)
{
u[n+1] = ((2*n + 1)*z*u[n] - n*u[n-1])/(n + 1);
d[n+1] = (4*n + 2)*u[n] + d[n-1];
}
}
void Poly_1D::CalcChebyshev(const int p, const double x, double *u)
{
// recursive definition, z in [-1,1]
// T_0(z) = 1, T_1(z) = z
// T_{n+1}(z) = 2*z*T_n(z) - T_{n-1}(z)
double z;
u[0] = 1.;
if (p == 0) { return; }
u[1] = z = 2.*x - 1.;
for (int n = 1; n < p; n++)
{
u[n+1] = 2*z*u[n] - u[n-1];
}
}
void Poly_1D::CalcChebyshev(const int p, const double x, double *u, double *d)
{
// recursive definition, z in [-1,1]
// T_0(z) = 1, T_1(z) = z
// T_{n+1}(z) = 2*z*T_n(z) - T_{n-1}(z)
// T'_n(z) = n*U_{n-1}(z)
// U_0(z) = 1 U_1(z) = 2*z
// U_{n+1}(z) = 2*z*U_n(z) - U_{n-1}(z)
// U_n(z) = z*U_{n-1}(z) + T_n(z) = z*T'_n(z)/n + T_n(z)
// T'_{n+1}(z) = (n + 1)*(z*T'_n(z)/n + T_n(z))
double z;
u[0] = 1.;
d[0] = 0.;
if (p == 0) { return; }
u[1] = z = 2.*x - 1.;
d[1] = 2.;
for (int n = 1; n < p; n++)
{
u[n+1] = 2*z*u[n] - u[n-1];
d[n+1] = (n + 1)*(z*d[n]/n + 2*u[n]);
}
}
void Poly_1D::CalcChebyshev(const int p, const double x, double *u, double *d,
double *dd)
{
// recursive definition, z in [-1,1]
// T_0(z) = 1, T_1(z) = z
// T_{n+1}(z) = 2*z*T_n(z) - T_{n-1}(z)
// T'_n(z) = n*U_{n-1}(z)
// U_0(z) = 1 U_1(z) = 2*z
// U_{n+1}(z) = 2*z*U_n(z) - U_{n-1}(z)
// U_n(z) = z*U_{n-1}(z) + T_n(z) = z*T'_n(z)/n + T_n(z)
// T'_{n+1}(z) = (n + 1)*(z*T'_n(z)/n + T_n(z))
// T''_{n+1}(z) = (n + 1)*(2*(n + 1)*T'_n(z) + z*T''_n(z)) / n
double z;
u[0] = 1.;
d[0] = 0.;
dd[0]= 0.;
if (p == 0) { return; }
u[1] = z = 2.*x - 1.;
d[1] = 2.;
dd[1] = 0;
for (int n = 1; n < p; n++)
{
u[n+1] = 2*z*u[n] - u[n-1];
d[n+1] = (n + 1)*(z*d[n]/n + 2*u[n]);
dd[n+1] = (n + 1)*(2.*(n + 1)*d[n] + z*dd[n])/n;
}
}
const double *Poly_1D::GetPoints(const int p, const int btype)
{
BasisType::Check(btype);
const int qtype = BasisType::GetQuadrature1D(btype);
if (qtype == Quadrature1D::Invalid) { return NULL; }
if (points_container.find(btype) == points_container.end())
{
points_container[btype] = new Array<double*>(h_mt);
}
Array<double*> &pts = *points_container[btype];
if (pts.Size() <= p)
{
pts.SetSize(p + 1, NULL);
}
if (pts[p] == NULL)
{
pts[p] = new double[p + 1];
quad_func.GivePolyPoints(p+1, pts[p], qtype);
}
return pts[p];
}
Poly_1D::Basis &Poly_1D::GetBasis(const int p, const int btype)
{
BasisType::Check(btype);
if ( bases_container.find(btype) == bases_container.end() )
{
// we haven't been asked for basis or points of this type yet
bases_container[btype] = new Array<Basis*>(h_mt);
}
Array<Basis*> &bases = *bases_container[btype];
if (bases.Size() <= p)
{
bases.SetSize(p + 1, NULL);
}
if (bases[p] == NULL)
{
EvalType etype = (btype == BasisType::Positive) ? Positive : Barycentric;
bases[p] = new Basis(p, GetPoints(p, btype), etype);
}
return *bases[p];
}
Poly_1D::~Poly_1D()
{
for (PointsMap::iterator it = points_container.begin();
it != points_container.end() ; ++it)
{
Array<double*>& pts = *it->second;
for ( int i = 0 ; i < pts.Size() ; ++i )
{
delete [] pts[i];
}
delete it->second;
}
for (BasisMap::iterator it = bases_container.begin();
it != bases_container.end() ; ++it)
{
Array<Basis*>& bases = *it->second;
for ( int i = 0 ; i < bases.Size() ; ++i )
{
delete bases[i];
}
delete it->second;
}
}
Array2D<int> Poly_1D::binom;
Poly_1D poly1d;
TensorBasisElement::TensorBasisElement(const int dims, const int p,
const int btype, const DofMapType dmtype)
: b_type(btype),
basis1d(poly1d.GetBasis(p, b_type))
{
if (dmtype == H1_DOF_MAP || dmtype == Sr_DOF_MAP)
{
switch (dims)
{
case 1:
{
dof_map.SetSize(p + 1);
dof_map[0] = 0;
dof_map[p] = 1;
for (int i = 1; i < p; i++)
{
dof_map[i] = i+1;
}
break;
}
case 2:
{
const int p1 = p + 1;
dof_map.SetSize(p1*p1);
// vertices
dof_map[0 + 0*p1] = 0;
dof_map[p + 0*p1] = 1;
dof_map[p + p*p1] = 2;
dof_map[0 + p*p1] = 3;
// edges
int o = 4;
for (int i = 1; i < p; i++)
{
dof_map[i + 0*p1] = o++;
}
for (int i = 1; i < p; i++)
{
dof_map[p + i*p1] = o++;
}
for (int i = 1; i < p; i++)
{
dof_map[(p-i) + p*p1] = o++;
}
for (int i = 1; i < p; i++)
{
dof_map[0 + (p-i)*p1] = o++;
}
// interior
for (int j = 1; j < p; j++)
{
for (int i = 1; i < p; i++)
{
dof_map[i + j*p1] = o++;
}
}
break;
}
case 3:
{
const int p1 = p + 1;
dof_map.SetSize(p1*p1*p1);
// vertices
dof_map[0 + (0 + 0*p1)*p1] = 0;
dof_map[p + (0 + 0*p1)*p1] = 1;
dof_map[p + (p + 0*p1)*p1] = 2;
dof_map[0 + (p + 0*p1)*p1] = 3;
dof_map[0 + (0 + p*p1)*p1] = 4;
dof_map[p + (0 + p*p1)*p1] = 5;
dof_map[p + (p + p*p1)*p1] = 6;
dof_map[0 + (p + p*p1)*p1] = 7;
// edges (see Hexahedron::edges in mesh/hexahedron.cpp).
// edges (see Constants<Geometry::CUBE>::Edges in fem/geom.cpp).
int o = 8;
for (int i = 1; i < p; i++)
{
dof_map[i + (0 + 0*p1)*p1] = o++; // (0,1)
}
for (int i = 1; i < p; i++)
{
dof_map[p + (i + 0*p1)*p1] = o++; // (1,2)
}
for (int i = 1; i < p; i++)
{
dof_map[i + (p + 0*p1)*p1] = o++; // (3,2)
}
for (int i = 1; i < p; i++)
{
dof_map[0 + (i + 0*p1)*p1] = o++; // (0,3)
}
for (int i = 1; i < p; i++)
{
dof_map[i + (0 + p*p1)*p1] = o++; // (4,5)
}
for (int i = 1; i < p; i++)
{
dof_map[p + (i + p*p1)*p1] = o++; // (5,6)
}
for (int i = 1; i < p; i++)
{
dof_map[i + (p + p*p1)*p1] = o++; // (7,6)
}
for (int i = 1; i < p; i++)
{
dof_map[0 + (i + p*p1)*p1] = o++; // (4,7)
}
for (int i = 1; i < p; i++)
{
dof_map[0 + (0 + i*p1)*p1] = o++; // (0,4)
}
for (int i = 1; i < p; i++)
{
dof_map[p + (0 + i*p1)*p1] = o++; // (1,5)
}
for (int i = 1; i < p; i++)
{
dof_map[p + (p + i*p1)*p1] = o++; // (2,6)
}
for (int i = 1; i < p; i++)
{
dof_map[0 + (p + i*p1)*p1] = o++; // (3,7)
}
// faces (see Mesh::GenerateFaces in mesh/mesh.cpp)
for (int j = 1; j < p; j++)
{
for (int i = 1; i < p; i++)
{
dof_map[i + ((p-j) + 0*p1)*p1] = o++; // (3,2,1,0)
}
}
for (int j = 1; j < p; j++)
{
for (int i = 1; i < p; i++)
{
dof_map[i + (0 + j*p1)*p1] = o++; // (0,1,5,4)
}
}
for (int j = 1; j < p; j++)
{
for (int i = 1; i < p; i++)
{
dof_map[p + (i + j*p1)*p1] = o++; // (1,2,6,5)
}
}
for (int j = 1; j < p; j++)
{
for (int i = 1; i < p; i++)
{
dof_map[(p-i) + (p + j*p1)*p1] = o++; // (2,3,7,6)
}
}
for (int j = 1; j < p; j++)
{
for (int i = 1; i < p; i++)
{
dof_map[0 + ((p-i) + j*p1)*p1] = o++; // (3,0,4,7)
}
}
for (int j = 1; j < p; j++)
{
for (int i = 1; i < p; i++)
{
dof_map[i + (j + p*p1)*p1] = o++; // (4,5,6,7)
}
}
// interior
for (int k = 1; k < p; k++)
{
for (int j = 1; j < p; j++)
{
for (int i = 1; i < p; i++)
{
dof_map[i + (j + k*p1)*p1] = o++;
}
}
}
break;
}
default:
MFEM_ABORT("invalid dimension: " << dims);
break;
}
}
else if (dmtype == L2_DOF_MAP)
{
// leave dof_map empty, indicating that the dofs are ordered
// lexicographically, i.e. the dof_map is identity
}
else
{
MFEM_ABORT("invalid DofMapType: " << dmtype);
}
}
NodalTensorFiniteElement::NodalTensorFiniteElement(const int dims,
const int p,
const int btype,
const DofMapType dmtype)
: NodalFiniteElement(dims, GetTensorProductGeometry(dims), Pow(p + 1, dims),
p, dims > 1 ? FunctionSpace::Qk : FunctionSpace::Pk),
TensorBasisElement(dims, p, VerifyNodal(btype), dmtype)
{
lex_ordering = dof_map;
}
PositiveTensorFiniteElement::PositiveTensorFiniteElement(
const int dims, const int p, const DofMapType dmtype)
: PositiveFiniteElement(dims, GetTensorProductGeometry(dims),
Pow(p + 1, dims), p,
dims > 1 ? FunctionSpace::Qk : FunctionSpace::Pk),
TensorBasisElement(dims, p, BasisType::Positive, dmtype) { }
VectorTensorFiniteElement::VectorTensorFiniteElement(const int dims,
const int d,
const int p,
const int cbtype,
const int obtype,
const int M,
const DofMapType dmtype)
: VectorFiniteElement(dims, GetTensorProductGeometry(dims), d,
p, M, FunctionSpace::Qk),
TensorBasisElement(dims, p, VerifyNodal(cbtype), dmtype),
cbasis1d(poly1d.GetBasis(p, VerifyClosed(cbtype))),
obasis1d(poly1d.GetBasis(p - 1, VerifyOpen(obtype))) { }
H1_SegmentElement::H1_SegmentElement(const int p, const int btype)
: NodalTensorFiniteElement(1, p, VerifyClosed(btype), H1_DOF_MAP)
{
const double *cp = poly1d.ClosedPoints(p, b_type);
#ifndef MFEM_THREAD_SAFE
shape_x.SetSize(p+1);
dshape_x.SetSize(p+1);
d2shape_x.SetSize(p+1);
#endif
Nodes.IntPoint(0).x = cp[0];
Nodes.IntPoint(1).x = cp[p];
for (int i = 1; i < p; i++)
{
Nodes.IntPoint(i+1).x = cp[i];
}
}
void H1_SegmentElement::CalcShape(const IntegrationPoint &ip,
Vector &shape) const
{
const int p = order;
#ifdef MFEM_THREAD_SAFE
Vector shape_x(p+1);
#endif
basis1d.Eval(ip.x, shape_x);
shape(0) = shape_x(0);
shape(1) = shape_x(p);
for (int i = 1; i < p; i++)
{
shape(i+1) = shape_x(i);
}
}
void H1_SegmentElement::CalcDShape(const IntegrationPoint &ip,
DenseMatrix &dshape) const
{
const int p = order;
#ifdef MFEM_THREAD_SAFE
Vector shape_x(p+1), dshape_x(p+1);
#endif
basis1d.Eval(ip.x, shape_x, dshape_x);
dshape(0,0) = dshape_x(0);
dshape(1,0) = dshape_x(p);
for (int i = 1; i < p; i++)
{
dshape(i+1,0) = dshape_x(i);
}
}
void H1_SegmentElement::CalcHessian(const IntegrationPoint &ip,
DenseMatrix &Hessian) const
{
const int p = order;
#ifdef MFEM_THREAD_SAFE
Vector shape_x(p+1), dshape_x(p+1), d2shape_x(p+1);
#endif
basis1d.Eval(ip.x, shape_x, dshape_x, d2shape_x);
Hessian(0,0) = d2shape_x(0);
Hessian(1,0) = d2shape_x(p);
for (int i = 1; i < p; i++)
{
Hessian(i+1,0) = d2shape_x(i);
}
}
void H1_SegmentElement::ProjectDelta(int vertex, Vector &dofs) const
{
const int p = order;
const double *cp = poly1d.ClosedPoints(p, b_type);
switch (vertex)
{
case 0:
dofs(0) = poly1d.CalcDelta(p, (1.0 - cp[0]));
dofs(1) = poly1d.CalcDelta(p, (1.0 - cp[p]));
for (int i = 1; i < p; i++)
{
dofs(i+1) = poly1d.CalcDelta(p, (1.0 - cp[i]));
}
break;
case 1:
dofs(0) = poly1d.CalcDelta(p, cp[0]);
dofs(1) = poly1d.CalcDelta(p, cp[p]);
for (int i = 1; i < p; i++)
{
dofs(i+1) = poly1d.CalcDelta(p, cp[i]);
}
break;
}
}
H1_QuadrilateralElement::H1_QuadrilateralElement(const int p, const int btype)
: NodalTensorFiniteElement(2, p, VerifyClosed(btype), H1_DOF_MAP)
{
const double *cp = poly1d.ClosedPoints(p, b_type);
#ifndef MFEM_THREAD_SAFE
const int p1 = p + 1;
shape_x.SetSize(p1);
shape_y.SetSize(p1);
dshape_x.SetSize(p1);
dshape_y.SetSize(p1);
d2shape_x.SetSize(p1);
d2shape_y.SetSize(p1);
#endif
int o = 0;
for (int j = 0; j <= p; j++)
{
for (int i = 0; i <= p; i++)
{
Nodes.IntPoint(dof_map[o++]).Set2(cp[i], cp[j]);
}
}
}
void H1_QuadrilateralElement::CalcShape(const IntegrationPoint &ip,
Vector &shape) const
{
const int p = order;
#ifdef MFEM_THREAD_SAFE
Vector shape_x(p+1), shape_y(p+1);
#endif
basis1d.Eval(ip.x, shape_x);
basis1d.Eval(ip.y, shape_y);
for (int o = 0, j = 0; j <= p; j++)
for (int i = 0; i <= p; i++)
{
shape(dof_map[o++]) = shape_x(i)*shape_y(j);
}
}
void H1_QuadrilateralElement::CalcDShape(const IntegrationPoint &ip,
DenseMatrix &dshape) const
{
const int p = order;
#ifdef MFEM_THREAD_SAFE
Vector shape_x(p+1), shape_y(p+1), dshape_x(p+1), dshape_y(p+1);
#endif
basis1d.Eval(ip.x, shape_x, dshape_x);
basis1d.Eval(ip.y, shape_y, dshape_y);
for (int o = 0, j = 0; j <= p; j++)
{
for (int i = 0; i <= p; i++)
{
dshape(dof_map[o],0) = dshape_x(i)* shape_y(j);
dshape(dof_map[o],1) = shape_x(i)*dshape_y(j); o++;
}
}
}
void H1_QuadrilateralElement::CalcHessian(const IntegrationPoint &ip,
DenseMatrix &Hessian) const
{
const int p = order;
#ifdef MFEM_THREAD_SAFE
Vector shape_x(p+1), shape_y(p+1), dshape_x(p+1), dshape_y(p+1),
d2shape_x(p+1), d2shape_y(p+1);
#endif
basis1d.Eval(ip.x, shape_x, dshape_x, d2shape_x);
basis1d.Eval(ip.y, shape_y, dshape_y, d2shape_y);
for (int o = 0, j = 0; j <= p; j++)
{
for (int i = 0; i <= p; i++)
{
Hessian(dof_map[o],0) = d2shape_x(i)* shape_y(j);
Hessian(dof_map[o],1) = dshape_x(i)* dshape_y(j);
Hessian(dof_map[o],2) = shape_x(i)*d2shape_y(j); o++;
}
}
}
void H1_QuadrilateralElement::ProjectDelta(int vertex, Vector &dofs) const
{
const int p = order;
const double *cp = poly1d.ClosedPoints(p, b_type);
#ifdef MFEM_THREAD_SAFE
Vector shape_x(p+1), shape_y(p+1);
#endif
for (int i = 0; i <= p; i++)
{
shape_x(i) = poly1d.CalcDelta(p, (1.0 - cp[i]));
shape_y(i) = poly1d.CalcDelta(p, cp[i]);
}
switch (vertex)
{
case 0:
for (int o = 0, j = 0; j <= p; j++)
for (int i = 0; i <= p; i++)
{
dofs(dof_map[o++]) = shape_x(i)*shape_x(j);
}
break;
case 1:
for (int o = 0, j = 0; j <= p; j++)
for (int i = 0; i <= p; i++)
{
dofs(dof_map[o++]) = shape_y(i)*shape_x(j);
}
break;
case 2:
for (int o = 0, j = 0; j <= p; j++)
for (int i = 0; i <= p; i++)
{
dofs(dof_map[o++]) = shape_y(i)*shape_y(j);
}
break;
case 3:
for (int o = 0, j = 0; j <= p; j++)
for (int i = 0; i <= p; i++)
{
dofs(dof_map[o++]) = shape_x(i)*shape_y(j);
}
break;
}
}
H1_HexahedronElement::H1_HexahedronElement(const int p, const int btype)
: NodalTensorFiniteElement(3, p, VerifyClosed(btype), H1_DOF_MAP)
{
const double *cp = poly1d.ClosedPoints(p, b_type);
#ifndef MFEM_THREAD_SAFE
const int p1 = p + 1;
shape_x.SetSize(p1);
shape_y.SetSize(p1);
shape_z.SetSize(p1);
dshape_x.SetSize(p1);
dshape_y.SetSize(p1);
dshape_z.SetSize(p1);
d2shape_x.SetSize(p1);
d2shape_y.SetSize(p1);
d2shape_z.SetSize(p1);
#endif
int o = 0;
for (int k = 0; k <= p; k++)
for (int j = 0; j <= p; j++)
for (int i = 0; i <= p; i++)
{
Nodes.IntPoint(dof_map[o++]).Set3(cp[i], cp[j], cp[k]);
}
}
void H1_HexahedronElement::CalcShape(const IntegrationPoint &ip,
Vector &shape) const
{
const int p = order;
#ifdef MFEM_THREAD_SAFE
Vector shape_x(p+1), shape_y(p+1), shape_z(p+1);
#endif
basis1d.Eval(ip.x, shape_x);
basis1d.Eval(ip.y, shape_y);
basis1d.Eval(ip.z, shape_z);
for (int o = 0, k = 0; k <= p; k++)
for (int j = 0; j <= p; j++)
for (int i = 0; i <= p; i++)
{
shape(dof_map[o++]) = shape_x(i)*shape_y(j)*shape_z(k);
}
}
void H1_HexahedronElement::CalcDShape(const IntegrationPoint &ip,
DenseMatrix &dshape) const
{
const int p = order;
#ifdef MFEM_THREAD_SAFE
Vector shape_x(p+1), shape_y(p+1), shape_z(p+1);
Vector dshape_x(p+1), dshape_y(p+1), dshape_z(p+1);
#endif
basis1d.Eval(ip.x, shape_x, dshape_x);
basis1d.Eval(ip.y, shape_y, dshape_y);
basis1d.Eval(ip.z, shape_z, dshape_z);
for (int o = 0, k = 0; k <= p; k++)
for (int j = 0; j <= p; j++)
for (int i = 0; i <= p; i++)
{
dshape(dof_map[o],0) = dshape_x(i)* shape_y(j)* shape_z(k);
dshape(dof_map[o],1) = shape_x(i)*dshape_y(j)* shape_z(k);
dshape(dof_map[o],2) = shape_x(i)* shape_y(j)*dshape_z(k); o++;
}
}
void H1_HexahedronElement::CalcHessian(const IntegrationPoint &ip,
DenseMatrix &Hessian) const
{
const int p = order;
#ifdef MFEM_THREAD_SAFE
Vector shape_x(p+1), shape_y(p+1), shape_z(p+1);
Vector dshape_x(p+1), dshape_y(p+1), dshape_z(p+1);
Vector d2shape_x(p+1), d2shape_y(p+1), d2shape_z(p+1);
#endif
basis1d.Eval(ip.x, shape_x, dshape_x, d2shape_x);
basis1d.Eval(ip.y, shape_y, dshape_y, d2shape_y);
basis1d.Eval(ip.z, shape_z, dshape_z, d2shape_z);
for (int o = 0, k = 0; k <= p; k++)
for (int j = 0; j <= p; j++)
for (int i = 0; i <= p; i++)
{
Hessian(dof_map[o],0) = d2shape_x(i)* shape_y(j)* shape_z(k);
Hessian(dof_map[o],1) = dshape_x(i)* dshape_y(j)* shape_z(k);
Hessian(dof_map[o],2) = dshape_x(i)* shape_y(j)* dshape_z(k);
Hessian(dof_map[o],3) = shape_x(i)*d2shape_y(j)* shape_z(k);
Hessian(dof_map[o],4) = shape_x(i)* dshape_y(j)* dshape_z(k);
Hessian(dof_map[o],5) = shape_x(i)* shape_y(j)*d2shape_z(k);
o++;
}
}
void H1_HexahedronElement::ProjectDelta(int vertex, Vector &dofs) const
{
const int p = order;
const double *cp = poly1d.ClosedPoints(p,b_type);
#ifdef MFEM_THREAD_SAFE
Vector shape_x(p+1), shape_y(p+1);
#endif
for (int i = 0; i <= p; i++)
{
shape_x(i) = poly1d.CalcDelta(p, (1.0 - cp[i]));
shape_y(i) = poly1d.CalcDelta(p, cp[i]);
}
switch (vertex)
{
case 0:
for (int o = 0, k = 0; k <= p; k++)
for (int j = 0; j <= p; j++)
for (int i = 0; i <= p; i++)
{
dofs(dof_map[o++]) = shape_x(i)*shape_x(j)*shape_x(k);
}
break;
case 1:
for (int o = 0, k = 0; k <= p; k++)
for (int j = 0; j <= p; j++)
for (int i = 0; i <= p; i++)
{
dofs(dof_map[o++]) = shape_y(i)*shape_x(j)*shape_x(k);
}
break;
case 2:
for (int o = 0, k = 0; k <= p; k++)
for (int j = 0; j <= p; j++)
for (int i = 0; i <= p; i++)
{
dofs(dof_map[o++]) = shape_y(i)*shape_y(j)*shape_x(k);
}
break;
case 3:
for (int o = 0, k = 0; k <= p; k++)
for (int j = 0; j <= p; j++)
for (int i = 0; i <= p; i++)
{
dofs(dof_map[o++]) = shape_x(i)*shape_y(j)*shape_x(k);
}
break;
case 4:
for (int o = 0, k = 0; k <= p; k++)
for (int j = 0; j <= p; j++)
for (int i = 0; i <= p; i++)
{
dofs(dof_map[o++]) = shape_x(i)*shape_x(j)*shape_y(k);
}
break;
case 5:
for (int o = 0, k = 0; k <= p; k++)
for (int j = 0; j <= p; j++)
for (int i = 0; i <= p; i++)
{
dofs(dof_map[o++]) = shape_y(i)*shape_x(j)*shape_y(k);
}
break;
case 6:
for (int o = 0, k = 0; k <= p; k++)
for (int j = 0; j <= p; j++)
for (int i = 0; i <= p; i++)
{
dofs(dof_map[o++]) = shape_y(i)*shape_y(j)*shape_y(k);
}
break;
case 7:
for (int o = 0, k = 0; k <= p; k++)
for (int j = 0; j <= p; j++)
for (int i = 0; i <= p; i++)
{
dofs(dof_map[o++]) = shape_x(i)*shape_y(j)*shape_y(k);
}
break;
}
}
H1Pos_SegmentElement::H1Pos_SegmentElement(const int p)
: PositiveTensorFiniteElement(1, p, H1_DOF_MAP)
{
#ifndef MFEM_THREAD_SAFE
// thread private versions; see class header.
shape_x.SetSize(p+1);
dshape_x.SetSize(p+1);
#endif
// Endpoints need to be first in the list, so reorder them.
Nodes.IntPoint(0).x = 0.0;
Nodes.IntPoint(1).x = 1.0;
for (int i = 1; i < p; i++)
{
Nodes.IntPoint(i+1).x = double(i)/p;
}
}
void H1Pos_SegmentElement::CalcShape(const IntegrationPoint &ip,
Vector &shape) const
{
const int p = order;
#ifdef MFEM_THREAD_SAFE
Vector shape_x(p+1);
#endif
Poly_1D::CalcBernstein(p, ip.x, shape_x.GetData() );
// Endpoints need to be first in the list, so reorder them.
shape(0) = shape_x(0);
shape(1) = shape_x(p);
for (int i = 1; i < p; i++)
{
shape(i+1) = shape_x(i);
}
}
void H1Pos_SegmentElement::CalcDShape(const IntegrationPoint &ip,
DenseMatrix &dshape) const
{
const int p = order;
#ifdef MFEM_THREAD_SAFE
Vector shape_x(p+1), dshape_x(p+1);
#endif
Poly_1D::CalcBernstein(p, ip.x, shape_x.GetData(), dshape_x.GetData() );
// Endpoints need to be first in the list, so reorder them.
dshape(0,0) = dshape_x(0);
dshape(1,0) = dshape_x(p);
for (int i = 1; i < p; i++)
{
dshape(i+1,0) = dshape_x(i);
}
}
void H1Pos_SegmentElement::ProjectDelta(int vertex, Vector &dofs) const
{
dofs = 0.0;
dofs[vertex] = 1.0;
}
H1Pos_QuadrilateralElement::H1Pos_QuadrilateralElement(const int p)
: PositiveTensorFiniteElement(2, p, H1_DOF_MAP)
{
#ifndef MFEM_THREAD_SAFE
const int p1 = p + 1;
shape_x.SetSize(p1);
shape_y.SetSize(p1);
dshape_x.SetSize(p1);
dshape_y.SetSize(p1);
#endif
int o = 0;
for (int j = 0; j <= p; j++)
for (int i = 0; i <= p; i++)
{
Nodes.IntPoint(dof_map[o++]).Set2(double(i)/p, double(j)/p);
}
}
void H1Pos_QuadrilateralElement::CalcShape(const IntegrationPoint &ip,
Vector &shape) const
{
const int p = order;
#ifdef MFEM_THREAD_SAFE
Vector shape_x(p+1), shape_y(p+1);
#endif
Poly_1D::CalcBernstein(p, ip.x, shape_x.GetData() );
Poly_1D::CalcBernstein(p, ip.y, shape_y.GetData() );
// Reorder so that vertices are at the beginning of the list
for (int o = 0, j = 0; j <= p; j++)
for (int i = 0; i <= p; i++)
{
shape(dof_map[o++]) = shape_x(i)*shape_y(j);
}
}
void H1Pos_QuadrilateralElement::CalcDShape(const IntegrationPoint &ip,
DenseMatrix &dshape) const
{
const int p = order;
#ifdef MFEM_THREAD_SAFE
Vector shape_x(p+1), shape_y(p+1), dshape_x(p+1), dshape_y(p+1);
#endif
Poly_1D::CalcBernstein(p, ip.x, shape_x.GetData(), dshape_x.GetData() );
Poly_1D::CalcBernstein(p, ip.y, shape_y.GetData(), dshape_y.GetData() );
// Reorder so that vertices are at the beginning of the list
for (int o = 0, j = 0; j <= p; j++)
for (int i = 0; i <= p; i++)
{
dshape(dof_map[o],0) = dshape_x(i)* shape_y(j);
dshape(dof_map[o],1) = shape_x(i)*dshape_y(j); o++;
}
}
void H1Pos_QuadrilateralElement::ProjectDelta(int vertex, Vector &dofs) const
{
dofs = 0.0;
dofs[vertex] = 1.0;
}
H1Pos_HexahedronElement::H1Pos_HexahedronElement(const int p)
: PositiveTensorFiniteElement(3, p, H1_DOF_MAP)
{
#ifndef MFEM_THREAD_SAFE
const int p1 = p + 1;
shape_x.SetSize(p1);
shape_y.SetSize(p1);
shape_z.SetSize(p1);
dshape_x.SetSize(p1);
dshape_y.SetSize(p1);
dshape_z.SetSize(p1);
#endif
int o = 0;
for (int k = 0; k <= p; k++)
for (int j = 0; j <= p; j++)
for (int i = 0; i <= p; i++)
Nodes.IntPoint(dof_map[o++]).Set3(double(i)/p, double(j)/p,
double(k)/p);
}
void H1Pos_HexahedronElement::CalcShape(const IntegrationPoint &ip,
Vector &shape) const
{
const int p = order;
#ifdef MFEM_THREAD_SAFE
Vector shape_x(p+1), shape_y(p+1), shape_z(p+1);
#endif
Poly_1D::CalcBernstein(p, ip.x, shape_x.GetData() );
Poly_1D::CalcBernstein(p, ip.y, shape_y.GetData() );
Poly_1D::CalcBernstein(p, ip.z, shape_z.GetData() );
for (int o = 0, k = 0; k <= p; k++)
for (int j = 0; j <= p; j++)
for (int i = 0; i <= p; i++)
{
shape(dof_map[o++]) = shape_x(i)*shape_y(j)*shape_z(k);
}
}
void H1Pos_HexahedronElement::CalcDShape(const IntegrationPoint &ip,
DenseMatrix &dshape) const
{
const int p = order;
#ifdef MFEM_THREAD_SAFE
Vector shape_x(p+1), shape_y(p+1), shape_z(p+1);
Vector dshape_x(p+1), dshape_y(p+1), dshape_z(p+1);
#endif
Poly_1D::CalcBernstein(p, ip.x, shape_x.GetData(), dshape_x.GetData() );
Poly_1D::CalcBernstein(p, ip.y, shape_y.GetData(), dshape_y.GetData() );
Poly_1D::CalcBernstein(p, ip.z, shape_z.GetData(), dshape_z.GetData() );
for (int o = 0, k = 0; k <= p; k++)
for (int j = 0; j <= p; j++)
for (int i = 0; i <= p; i++)
{
dshape(dof_map[o],0) = dshape_x(i)* shape_y(j)* shape_z(k);
dshape(dof_map[o],1) = shape_x(i)*dshape_y(j)* shape_z(k);
dshape(dof_map[o],2) = shape_x(i)* shape_y(j)*dshape_z(k); o++;
}
}
void H1Pos_HexahedronElement::ProjectDelta(int vertex, Vector &dofs) const
{
dofs = 0.0;
dofs[vertex] = 1.0;
}
H1_TriangleElement::H1_TriangleElement(const int p, const int btype)
: NodalFiniteElement(2, Geometry::TRIANGLE, ((p + 1)*(p + 2))/2, p,
FunctionSpace::Pk)
{
const double *cp = poly1d.ClosedPoints(p, VerifyNodal(VerifyClosed(btype)));
#ifndef MFEM_THREAD_SAFE
shape_x.SetSize(p + 1);
shape_y.SetSize(p + 1);
shape_l.SetSize(p + 1);
dshape_x.SetSize(p + 1);
dshape_y.SetSize(p + 1);
dshape_l.SetSize(p + 1);
ddshape_x.SetSize(p + 1);
ddshape_y.SetSize(p + 1);
ddshape_l.SetSize(p + 1);
u.SetSize(dof);
du.SetSize(dof, dim);
ddu.SetSize(dof, (dim * (dim + 1)) / 2 );
#else
Vector shape_x(p + 1), shape_y(p + 1), shape_l(p + 1);
#endif
int p2p3 = 2*p + 3;
auto idx = [p2p3](int i, int j) { return ((p2p3-j)*j)/2+i; };
lex_ordering.SetSize(dof);
// vertices
lex_ordering[idx(0,0)] = 0;
Nodes.IntPoint(0).Set2(cp[0], cp[0]);
lex_ordering[idx(p,0)] = 1;
Nodes.IntPoint(1).Set2(cp[p], cp[0]);
lex_ordering[idx(0,p)] = 2;
Nodes.IntPoint(2).Set2(cp[0], cp[p]);
// edges
int o = 3;
for (int i = 1; i < p; i++)
{
lex_ordering[idx(i,0)] = o;
Nodes.IntPoint(o++).Set2(cp[i], cp[0]);
}
for (int i = 1; i < p; i++)
{
lex_ordering[idx(p-i,i)] = o;
Nodes.IntPoint(o++).Set2(cp[p-i], cp[i]);
}
for (int i = 1; i < p; i++)
{
lex_ordering[idx(0,p-i)] = o;
Nodes.IntPoint(o++).Set2(cp[0], cp[p-i]);
}
// interior
for (int j = 1; j < p; j++)
for (int i = 1; i + j < p; i++)
{
const double w = cp[i] + cp[j] + cp[p-i-j];
lex_ordering[idx(i,j)] = o;
Nodes.IntPoint(o++).Set2(cp[i]/w, cp[j]/w);
}
DenseMatrix T(dof);
for (int k = 0; k < dof; k++)
{
IntegrationPoint &ip = Nodes.IntPoint(k);
poly1d.CalcBasis(p, ip.x, shape_x);
poly1d.CalcBasis(p, ip.y, shape_y);
poly1d.CalcBasis(p, 1. - ip.x - ip.y, shape_l);
o = 0;
for (int j = 0; j <= p; j++)
for (int i = 0; i + j <= p; i++)
{
T(o++, k) = shape_x(i)*shape_y(j)*shape_l(p-i-j);
}
}
Ti.Factor(T);
// mfem::out << "H1_TriangleElement(" << p << ") : "; Ti.TestInversion();
}
void H1_TriangleElement::CalcShape(const IntegrationPoint &ip,
Vector &shape) const
{
const int p = order;
#ifdef MFEM_THREAD_SAFE
Vector shape_x(p + 1), shape_y(p + 1), shape_l(p + 1), u(dof);
#endif
poly1d.CalcBasis(p, ip.x, shape_x);
poly1d.CalcBasis(p, ip.y, shape_y);
poly1d.CalcBasis(p, 1. - ip.x - ip.y, shape_l);
for (int o = 0, j = 0; j <= p; j++)
for (int i = 0; i + j <= p; i++)
{
u(o++) = shape_x(i)*shape_y(j)*shape_l(p-i-j);
}
Ti.Mult(u, shape);
}
void H1_TriangleElement::CalcDShape(const IntegrationPoint &ip,
DenseMatrix &dshape) const
{
const int p = order;
#ifdef MFEM_THREAD_SAFE
Vector shape_x(p + 1), shape_y(p + 1), shape_l(p + 1);
Vector dshape_x(p + 1), dshape_y(p + 1), dshape_l(p + 1);
DenseMatrix du(dof, dim);
#endif
poly1d.CalcBasis(p, ip.x, shape_x, dshape_x);
poly1d.CalcBasis(p, ip.y, shape_y, dshape_y);
poly1d.CalcBasis(p, 1. - ip.x - ip.y, shape_l, dshape_l);
for (int o = 0, j = 0; j <= p; j++)
for (int i = 0; i + j <= p; i++)
{
int k = p - i - j;
du(o,0) = ((dshape_x(i)* shape_l(k)) -
( shape_x(i)*dshape_l(k)))*shape_y(j);
du(o,1) = ((dshape_y(j)* shape_l(k)) -
( shape_y(j)*dshape_l(k)))*shape_x(i);
o++;
}
Ti.Mult(du, dshape);
}
void H1_TriangleElement::CalcHessian(const IntegrationPoint &ip,
DenseMatrix &ddshape) const
{
const int p = order;
#ifdef MFEM_THREAD_SAFE
Vector shape_x(p + 1), shape_y(p + 1), shape_l(p + 1);
Vector dshape_x(p + 1), dshape_y(p + 1), dshape_l(p + 1);
Vector ddshape_x(p + 1), ddshape_y(p + 1), ddshape_l(p + 1);
DenseMatrix ddu(dof, dim);
#endif
poly1d.CalcBasis(p, ip.x, shape_x, dshape_x, ddshape_x);
poly1d.CalcBasis(p, ip.y, shape_y, dshape_y, ddshape_y);
poly1d.CalcBasis(p, 1. - ip.x - ip.y, shape_l, dshape_l, ddshape_l);
for (int o = 0, j = 0; j <= p; j++)
for (int i = 0; i + j <= p; i++)
{
int k = p - i - j;
// u_xx, u_xy, u_yy
ddu(o,0) = ((ddshape_x(i) * shape_l(k)) - 2. * (dshape_x(i) * dshape_l(k)) +
(shape_x(i) * ddshape_l(k))) * shape_y(j);
ddu(o,1) = (((shape_x(i) * ddshape_l(k)) - dshape_x(i) * dshape_l(k)) * shape_y(
j)) + (((dshape_x(i) * shape_l(k)) - (shape_x(i) * dshape_l(k))) * dshape_y(j));
ddu(o,2) = ((ddshape_y(j) * shape_l(k)) - 2. * (dshape_y(j) * dshape_l(k)) +
(shape_y(j) * ddshape_l(k))) * shape_x(i);
o++;
}
Ti.Mult(ddu, ddshape);
}
H1_TetrahedronElement::H1_TetrahedronElement(const int p, const int btype)
: NodalFiniteElement(3, Geometry::TETRAHEDRON, ((p + 1)*(p + 2)*(p + 3))/6,
p, FunctionSpace::Pk)
{
const double *cp = poly1d.ClosedPoints(p, VerifyNodal(VerifyClosed(btype)));
#ifndef MFEM_THREAD_SAFE
shape_x.SetSize(p + 1);
shape_y.SetSize(p + 1);
shape_z.SetSize(p + 1);
shape_l.SetSize(p + 1);
dshape_x.SetSize(p + 1);
dshape_y.SetSize(p + 1);
dshape_z.SetSize(p + 1);
dshape_l.SetSize(p + 1);
ddshape_x.SetSize(p + 1);
ddshape_y.SetSize(p + 1);
ddshape_z.SetSize(p + 1);
ddshape_l.SetSize(p + 1);
u.SetSize(dof);
du.SetSize(dof, dim);
ddu.SetSize(dof, (dim * (dim + 1)) / 2);
#else
Vector shape_x(p + 1), shape_y(p + 1), shape_z(p + 1), shape_l(p + 1);
#endif
auto tri = [](int k) { return (k*(k + 1))/2; };
auto tet = [](int k) { return (k*(k + 1)*(k + 2))/6; };
int ndof = tet(p+1);
auto idx = [tri, tet, p, ndof](int i, int j, int k)
{
return ndof - tet(p - k) - tri(p + 1 - k - j) + i;
};
lex_ordering.SetSize(dof);
// vertices
lex_ordering[idx(0,0,0)] = 0;
Nodes.IntPoint(0).Set3(cp[0], cp[0], cp[0]);
lex_ordering[idx(p,0,0)] = 1;
Nodes.IntPoint(1).Set3(cp[p], cp[0], cp[0]);
lex_ordering[idx(0,p,0)] = 2;
Nodes.IntPoint(2).Set3(cp[0], cp[p], cp[0]);
lex_ordering[idx(0,0,p)] = 3;
Nodes.IntPoint(3).Set3(cp[0], cp[0], cp[p]);
// edges (see Tetrahedron::edges in mesh/tetrahedron.cpp)
int o = 4;
for (int i = 1; i < p; i++) // (0,1)
{
lex_ordering[idx(i,0,0)] = o;
Nodes.IntPoint(o++).Set3(cp[i], cp[0], cp[0]);
}
for (int i = 1; i < p; i++) // (0,2)
{
lex_ordering[idx(0,i,0)] = o;
Nodes.IntPoint(o++).Set3(cp[0], cp[i], cp[0]);
}
for (int i = 1; i < p; i++) // (0,3)
{
lex_ordering[idx(0,0,i)] = o;
Nodes.IntPoint(o++).Set3(cp[0], cp[0], cp[i]);
}
for (int i = 1; i < p; i++) // (1,2)
{
lex_ordering[idx(p-i,i,0)] = o;
Nodes.IntPoint(o++).Set3(cp[p-i], cp[i], cp[0]);
}
for (int i = 1; i < p; i++) // (1,3)
{
lex_ordering[idx(p-i,0,i)] = o;
Nodes.IntPoint(o++).Set3(cp[p-i], cp[0], cp[i]);
}
for (int i = 1; i < p; i++) // (2,3)
{
lex_ordering[idx(0,p-i,i)] = o;
Nodes.IntPoint(o++).Set3(cp[0], cp[p-i], cp[i]);
}
// faces (see Mesh::GenerateFaces in mesh/mesh.cpp)
for (int j = 1; j < p; j++)
for (int i = 1; i + j < p; i++) // (1,2,3)
{
lex_ordering[idx(p-i-j,i,j)] = o;
double w = cp[i] + cp[j] + cp[p-i-j];
Nodes.IntPoint(o++).Set3(cp[p-i-j]/w, cp[i]/w, cp[j]/w);
}
for (int j = 1; j < p; j++)
for (int i = 1; i + j < p; i++) // (0,3,2)
{
lex_ordering[idx(0,j,i)] = o;
double w = cp[i] + cp[j] + cp[p-i-j];
Nodes.IntPoint(o++).Set3(cp[0], cp[j]/w, cp[i]/w);
}
for (int j = 1; j < p; j++)
for (int i = 1; i + j < p; i++) // (0,1,3)
{
lex_ordering[idx(i,0,j)] = o;
double w = cp[i] + cp[j] + cp[p-i-j];
Nodes.IntPoint(o++).Set3(cp[i]/w, cp[0], cp[j]/w);
}
for (int j = 1; j < p; j++)
for (int i = 1; i + j < p; i++) // (0,2,1)
{
lex_ordering[idx(j,i,0)] = o;
double w = cp[i] + cp[j] + cp[p-i-j];
Nodes.IntPoint(o++).Set3(cp[j]/w, cp[i]/w, cp[0]);
}
// interior
for (int k = 1; k < p; k++)
for (int j = 1; j + k < p; j++)
for (int i = 1; i + j + k < p; i++)
{
lex_ordering[idx(i,j,k)] = o;
double w = cp[i] + cp[j] + cp[k] + cp[p-i-j-k];
Nodes.IntPoint(o++).Set3(cp[i]/w, cp[j]/w, cp[k]/w);
}
DenseMatrix T(dof);
for (int m = 0; m < dof; m++)
{
IntegrationPoint &ip = Nodes.IntPoint(m);
poly1d.CalcBasis(p, ip.x, shape_x);
poly1d.CalcBasis(p, ip.y, shape_y);
poly1d.CalcBasis(p, ip.z, shape_z);
poly1d.CalcBasis(p, 1. - ip.x - ip.y - ip.z, shape_l);
o = 0;
for (int k = 0; k <= p; k++)
for (int j = 0; j + k <= p; j++)
for (int i = 0; i + j + k <= p; i++)
{
T(o++, m) = shape_x(i)*shape_y(j)*shape_z(k)*shape_l(p-i-j-k);
}
}
Ti.Factor(T);
// mfem::out << "H1_TetrahedronElement(" << p << ") : "; Ti.TestInversion();
}
void H1_TetrahedronElement::CalcShape(const IntegrationPoint &ip,
Vector &shape) const
{
const int p = order;
#ifdef MFEM_THREAD_SAFE
Vector shape_x(p + 1), shape_y(p + 1), shape_z(p + 1), shape_l(p + 1);
Vector u(dof);
#endif
poly1d.CalcBasis(p, ip.x, shape_x);
poly1d.CalcBasis(p, ip.y, shape_y);
poly1d.CalcBasis(p, ip.z, shape_z);
poly1d.CalcBasis(p, 1. - ip.x - ip.y - ip.z, shape_l);
for (int o = 0, k = 0; k <= p; k++)
for (int j = 0; j + k <= p; j++)
for (int i = 0; i + j + k <= p; i++)
{
u(o++) = shape_x(i)*shape_y(j)*shape_z(k)*shape_l(p-i-j-k);
}
Ti.Mult(u, shape);
}
void H1_TetrahedronElement::CalcDShape(const IntegrationPoint &ip,
DenseMatrix &dshape) const
{
const int p = order;
#ifdef MFEM_THREAD_SAFE
Vector shape_x(p + 1), shape_y(p + 1), shape_z(p + 1), shape_l(p + 1);
Vector dshape_x(p + 1), dshape_y(p + 1), dshape_z(p + 1), dshape_l(p + 1);
DenseMatrix du(dof, dim);
#endif
poly1d.CalcBasis(p, ip.x, shape_x, dshape_x);
poly1d.CalcBasis(p, ip.y, shape_y, dshape_y);
poly1d.CalcBasis(p, ip.z, shape_z, dshape_z);
poly1d.CalcBasis(p, 1. - ip.x - ip.y - ip.z, shape_l, dshape_l);
for (int o = 0, k = 0; k <= p; k++)
for (int j = 0; j + k <= p; j++)
for (int i = 0; i + j + k <= p; i++)
{
int l = p - i - j - k;
du(o,0) = ((dshape_x(i)* shape_l(l)) -
( shape_x(i)*dshape_l(l)))*shape_y(j)*shape_z(k);
du(o,1) = ((dshape_y(j)* shape_l(l)) -
( shape_y(j)*dshape_l(l)))*shape_x(i)*shape_z(k);
du(o,2) = ((dshape_z(k)* shape_l(l)) -
( shape_z(k)*dshape_l(l)))*shape_x(i)*shape_y(j);
o++;
}
Ti.Mult(du, dshape);
}
void H1_TetrahedronElement::CalcHessian(const IntegrationPoint &ip,
DenseMatrix &ddshape) const
{
const int p = order;
#ifdef MFEM_THREAD_SAFE
Vector shape_x(p + 1), shape_y(p + 1), shape_z(p + 1), shape_l(p + 1);
Vector dshape_x(p + 1), dshape_y(p + 1), dshape_z(p + 1), dshape_l(p + 1);
Vector ddshape_x(p + 1), ddshape_y(p + 1), ddshape_z(p + 1), ddshape_l(p + 1);
DenseMatrix ddu(dof, ((dim + 1) * dim) / 2);
#endif
poly1d.CalcBasis(p, ip.x, shape_x, dshape_x, ddshape_x);
poly1d.CalcBasis(p, ip.y, shape_y, dshape_y, ddshape_y);
poly1d.CalcBasis(p, ip.z, shape_z, dshape_z, ddshape_z);
poly1d.CalcBasis(p, 1. - ip.x - ip.y - ip.z, shape_l, dshape_l, ddshape_l);
for (int o = 0, k = 0; k <= p; k++)
for (int j = 0; j + k <= p; j++)
for (int i = 0; i + j + k <= p; i++)
{
// u_xx, u_xy, u_xz, u_yy, u_yz, u_zz
int l = p - i - j - k;
ddu(o,0) = ((ddshape_x(i) * shape_l(l)) - 2. * (dshape_x(i) * dshape_l(l)) +
(shape_x(i) * ddshape_l(l))) * shape_y(j) * shape_z(k);
ddu(o,1) = ((dshape_y(j) * ((dshape_x(i) * shape_l(l)) -
(shape_x(i) * dshape_l(l)))) +
(shape_y(j) * ((ddshape_l(l) * shape_x(i)) -
(dshape_x(i) * dshape_l(l)))))* shape_z(k);
ddu(o,2) = ((dshape_z(k) * ((dshape_x(i) * shape_l(l)) -
(shape_x(i) * dshape_l(l)))) +
(shape_z(k) * ((ddshape_l(l) * shape_x(i)) -
(dshape_x(i) * dshape_l(l)))))* shape_y(j);
ddu(o,3) = ((ddshape_y(j) * shape_l(l)) - 2. * (dshape_y(j) * dshape_l(l)) +
(shape_y(j) * ddshape_l(l))) * shape_x(i) * shape_z(k);
ddu(o,4) = ((dshape_z(k) * ((dshape_y(j) * shape_l(l)) -
(shape_y(j)*dshape_l(l))) ) +
(shape_z(k)* ((ddshape_l(l)*shape_y(j)) -
(dshape_y(j) * dshape_l(l)) ) ) )* shape_x(i);
ddu(o,5) = ((ddshape_z(k) * shape_l(l)) - 2. * (dshape_z(k) * dshape_l(l)) +
(shape_z(k) * ddshape_l(l))) * shape_y(j) * shape_x(i);
o++;
}
Ti.Mult(ddu, ddshape);
}
H1Pos_TriangleElement::H1Pos_TriangleElement(const int p)
: PositiveFiniteElement(2, Geometry::TRIANGLE, ((p + 1)*(p + 2))/2, p,
FunctionSpace::Pk)
{
#ifndef MFEM_THREAD_SAFE
m_shape.SetSize(dof);
dshape_1d.SetSize(p + 1);
m_dshape.SetSize(dof, dim);
#endif
dof_map.SetSize(dof);
struct Index
{
int p2p3;
Index(int p) { p2p3 = 2*p + 3; }
int operator()(int i, int j) { return ((p2p3-j)*j)/2+i; }
};
Index idx(p);
// vertices
dof_map[idx(0,0)] = 0;
Nodes.IntPoint(0).Set2(0., 0.);
dof_map[idx(p,0)] = 1;
Nodes.IntPoint(1).Set2(1., 0.);
dof_map[idx(0,p)] = 2;
Nodes.IntPoint(2).Set2(0., 1.);
// edges
int o = 3;
for (int i = 1; i < p; i++)
{
dof_map[idx(i,0)] = o;
Nodes.IntPoint(o++).Set2(double(i)/p, 0.);
}
for (int i = 1; i < p; i++)
{
dof_map[idx(p-i,i)] = o;
Nodes.IntPoint(o++).Set2(double(p-i)/p, double(i)/p);
}
for (int i = 1; i < p; i++)
{
dof_map[idx(0,p-i)] = o;
Nodes.IntPoint(o++).Set2(0., double(p-i)/p);
}
// interior
for (int j = 1; j < p; j++)
for (int i = 1; i + j < p; i++)
{
dof_map[idx(i,j)] = o;
Nodes.IntPoint(o++).Set2(double(i)/p, double(j)/p);
}
}
// static method
void H1Pos_TriangleElement::CalcShape(
const int p, const double l1, const double l2, double *shape)
{
const double l3 = 1. - l1 - l2;
// The (i,j) basis function is given by: T(i,j,p-i-j) l1^i l2^j l3^{p-i-j},
// where T(i,j,k) = (i+j+k)! / (i! j! k!)
// Another expression is given by the terms of the expansion:
// (l1 + l2 + l3)^p =
// \sum_{j=0}^p \binom{p}{j} l2^j
// \sum_{i=0}^{p-j} \binom{p-j}{i} l1^i l3^{p-j-i}
const int *bp = Poly_1D::Binom(p);
double z = 1.;
for (int o = 0, j = 0; j <= p; j++)
{
Poly_1D::CalcBinomTerms(p - j, l1, l3, &shape[o]);
double s = bp[j]*z;
for (int i = 0; i <= p - j; i++)
{
shape[o++] *= s;
}
z *= l2;
}
}
// static method
void H1Pos_TriangleElement::CalcDShape(
const int p, const double l1, const double l2,
double *dshape_1d, double *dshape)
{
const int dof = ((p + 1)*(p + 2))/2;
const double l3 = 1. - l1 - l2;
const int *bp = Poly_1D::Binom(p);
double z = 1.;
for (int o = 0, j = 0; j <= p; j++)
{
Poly_1D::CalcDBinomTerms(p - j, l1, l3, dshape_1d);
double s = bp[j]*z;
for (int i = 0; i <= p - j; i++)
{
dshape[o++] = s*dshape_1d[i];
}
z *= l2;
}
z = 1.;
for (int i = 0; i <= p; i++)
{
Poly_1D::CalcDBinomTerms(p - i, l2, l3, dshape_1d);
double s = bp[i]*z;
for (int o = i, j = 0; j <= p - i; j++)
{
dshape[dof + o] = s*dshape_1d[j];
o += p + 1 - j;
}
z *= l1;
}
}
void H1Pos_TriangleElement::CalcShape(const IntegrationPoint &ip,
Vector &shape) const
{
#ifdef MFEM_THREAD_SAFE
Vector m_shape(dof);
#endif
CalcShape(order, ip.x, ip.y, m_shape.GetData());
for (int i = 0; i < dof; i++)
{
shape(dof_map[i]) = m_shape(i);
}
}
void H1Pos_TriangleElement::CalcDShape(const IntegrationPoint &ip,
DenseMatrix &dshape) const
{
#ifdef MFEM_THREAD_SAFE
Vector dshape_1d(order + 1);
DenseMatrix m_dshape(dof, dim);
#endif
CalcDShape(order, ip.x, ip.y, dshape_1d.GetData(), m_dshape.Data());
for (int d = 0; d < 2; d++)
{
for (int i = 0; i < dof; i++)
{
dshape(dof_map[i],d) = m_dshape(i,d);
}
}
}
H1Pos_TetrahedronElement::H1Pos_TetrahedronElement(const int p)
: PositiveFiniteElement(3, Geometry::TETRAHEDRON,
((p + 1)*(p + 2)*(p + 3))/6, p, FunctionSpace::Pk)
{
#ifndef MFEM_THREAD_SAFE
m_shape.SetSize(dof);
dshape_1d.SetSize(p + 1);
m_dshape.SetSize(dof, dim);
#endif
dof_map.SetSize(dof);
struct Index
{
int p, dof;
int tri(int k) { return (k*(k + 1))/2; }
int tet(int k) { return (k*(k + 1)*(k + 2))/6; }
Index(int p_) { p = p_; dof = tet(p + 1); }
int operator()(int i, int j, int k)
{ return dof - tet(p - k) - tri(p + 1 - k - j) + i; }
};
Index idx(p);
// vertices
dof_map[idx(0,0,0)] = 0;
Nodes.IntPoint(0).Set3(0., 0., 0.);
dof_map[idx(p,0,0)] = 1;
Nodes.IntPoint(1).Set3(1., 0., 0.);
dof_map[idx(0,p,0)] = 2;
Nodes.IntPoint(2).Set3(0., 1., 0.);
dof_map[idx(0,0,p)] = 3;
Nodes.IntPoint(3).Set3(0., 0., 1.);
// edges (see Tetrahedron::edges in mesh/tetrahedron.cpp)
int o = 4;
for (int i = 1; i < p; i++) // (0,1)
{
dof_map[idx(i,0,0)] = o;
Nodes.IntPoint(o++).Set3(double(i)/p, 0., 0.);
}
for (int i = 1; i < p; i++) // (0,2)
{
dof_map[idx(0,i,0)] = o;
Nodes.IntPoint(o++).Set3(0., double(i)/p, 0.);
}
for (int i = 1; i < p; i++) // (0,3)
{
dof_map[idx(0,0,i)] = o;
Nodes.IntPoint(o++).Set3(0., 0., double(i)/p);
}
for (int i = 1; i < p; i++) // (1,2)
{
dof_map[idx(p-i,i,0)] = o;
Nodes.IntPoint(o++).Set3(double(p-i)/p, double(i)/p, 0.);
}
for (int i = 1; i < p; i++) // (1,3)
{
dof_map[idx(p-i,0,i)] = o;
Nodes.IntPoint(o++).Set3(double(p-i)/p, 0., double(i)/p);
}
for (int i = 1; i < p; i++) // (2,3)
{
dof_map[idx(0,p-i,i)] = o;
Nodes.IntPoint(o++).Set3(0., double(p-i)/p, double(i)/p);
}
// faces (see Mesh::GenerateFaces in mesh/mesh.cpp)
for (int j = 1; j < p; j++)
for (int i = 1; i + j < p; i++) // (1,2,3)
{
dof_map[idx(p-i-j,i,j)] = o;
Nodes.IntPoint(o++).Set3(double(p-i-j)/p, double(i)/p, double(j)/p);
}
for (int j = 1; j < p; j++)
for (int i = 1; i + j < p; i++) // (0,3,2)
{
dof_map[idx(0,j,i)] = o;
Nodes.IntPoint(o++).Set3(0., double(j)/p, double(i)/p);
}
for (int j = 1; j < p; j++)
for (int i = 1; i + j < p; i++) // (0,1,3)
{
dof_map[idx(i,0,j)] = o;
Nodes.IntPoint(o++).Set3(double(i)/p, 0., double(j)/p);
}
for (int j = 1; j < p; j++)
for (int i = 1; i + j < p; i++) // (0,2,1)
{
dof_map[idx(j,i,0)] = o;
Nodes.IntPoint(o++).Set3(double(j)/p, double(i)/p, 0.);
}
// interior
for (int k = 1; k < p; k++)
for (int j = 1; j + k < p; j++)
for (int i = 1; i + j + k < p; i++)
{
dof_map[idx(i,j,k)] = o;
Nodes.IntPoint(o++).Set3(double(i)/p, double(j)/p, double(k)/p);
}
}
// static method
void H1Pos_TetrahedronElement::CalcShape(
const int p, const double l1, const double l2, const double l3,
double *shape)
{
const double l4 = 1. - l1 - l2 - l3;
// The basis functions are the terms in the expansion:
// (l1 + l2 + l3 + l4)^p =
// \sum_{k=0}^p \binom{p}{k} l3^k
// \sum_{j=0}^{p-k} \binom{p-k}{j} l2^j
// \sum_{i=0}^{p-k-j} \binom{p-k-j}{i} l1^i l4^{p-k-j-i}
const int *bp = Poly_1D::Binom(p);
double l3k = 1.;
for (int o = 0, k = 0; k <= p; k++)
{
const int *bpk = Poly_1D::Binom(p - k);
const double ek = bp[k]*l3k;
double l2j = 1.;
for (int j = 0; j <= p - k; j++)
{
Poly_1D::CalcBinomTerms(p - k - j, l1, l4, &shape[o]);
double ekj = ek*bpk[j]*l2j;
for (int i = 0; i <= p - k - j; i++)
{
shape[o++] *= ekj;
}
l2j *= l2;
}
l3k *= l3;
}
}
// static method
void H1Pos_TetrahedronElement::CalcDShape(
const int p, const double l1, const double l2, const double l3,
double *dshape_1d, double *dshape)
{
const int dof = ((p + 1)*(p + 2)*(p + 3))/6;
const double l4 = 1. - l1 - l2 - l3;
// For the x derivatives, differentiate the terms of the expression:
// \sum_{k=0}^p \binom{p}{k} l3^k
// \sum_{j=0}^{p-k} \binom{p-k}{j} l2^j
// \sum_{i=0}^{p-k-j} \binom{p-k-j}{i} l1^i l4^{p-k-j-i}
const int *bp = Poly_1D::Binom(p);
double l3k = 1.;
for (int o = 0, k = 0; k <= p; k++)
{
const int *bpk = Poly_1D::Binom(p - k);
const double ek = bp[k]*l3k;
double l2j = 1.;
for (int j = 0; j <= p - k; j++)
{
Poly_1D::CalcDBinomTerms(p - k - j, l1, l4, dshape_1d);
double ekj = ek*bpk[j]*l2j;
for (int i = 0; i <= p - k - j; i++)
{
dshape[o++] = dshape_1d[i]*ekj;
}
l2j *= l2;
}
l3k *= l3;
}
// For the y derivatives, differentiate the terms of the expression:
// \sum_{k=0}^p \binom{p}{k} l3^k
// \sum_{i=0}^{p-k} \binom{p-k}{i} l1^i
// \sum_{j=0}^{p-k-i} \binom{p-k-i}{j} l2^j l4^{p-k-j-i}
l3k = 1.;
for (int ok = 0, k = 0; k <= p; k++)
{
const int *bpk = Poly_1D::Binom(p - k);
const double ek = bp[k]*l3k;
double l1i = 1.;
for (int i = 0; i <= p - k; i++)
{
Poly_1D::CalcDBinomTerms(p - k - i, l2, l4, dshape_1d);
double eki = ek*bpk[i]*l1i;
int o = ok + i;
for (int j = 0; j <= p - k - i; j++)
{
dshape[dof + o] = dshape_1d[j]*eki;
o += p - k - j + 1;
}
l1i *= l1;
}
l3k *= l3;
ok += ((p - k + 2)*(p - k + 1))/2;
}
// For the z derivatives, differentiate the terms of the expression:
// \sum_{j=0}^p \binom{p}{j} l2^j
// \sum_{i=0}^{p-j} \binom{p-j}{i} l1^i
// \sum_{k=0}^{p-j-i} \binom{p-j-i}{k} l3^k l4^{p-k-j-i}
double l2j = 1.;
for (int j = 0; j <= p; j++)
{
const int *bpj = Poly_1D::Binom(p - j);
const double ej = bp[j]*l2j;
double l1i = 1.;
for (int i = 0; i <= p - j; i++)
{
Poly_1D::CalcDBinomTerms(p - j - i, l3, l4, dshape_1d);
double eji = ej*bpj[i]*l1i;
int m = ((p + 2)*(p + 1))/2;
int n = ((p - j + 2)*(p - j + 1))/2;
for (int o = i, k = 0; k <= p - j - i; k++)
{
// m = ((p - k + 2)*(p - k + 1))/2;
// n = ((p - k - j + 2)*(p - k - j + 1))/2;
o += m;
dshape[2*dof + o - n] = dshape_1d[k]*eji;
m -= p - k + 1;
n -= p - k - j + 1;
}
l1i *= l1;
}
l2j *= l2;
}
}
void H1Pos_TetrahedronElement::CalcShape(const IntegrationPoint &ip,
Vector &shape) const
{
#ifdef MFEM_THREAD_SAFE
Vector m_shape(dof);
#endif
CalcShape(order, ip.x, ip.y, ip.z, m_shape.GetData());
for (int i = 0; i < dof; i++)
{
shape(dof_map[i]) = m_shape(i);
}
}
void H1Pos_TetrahedronElement::CalcDShape(const IntegrationPoint &ip,
DenseMatrix &dshape) const
{
#ifdef MFEM_THREAD_SAFE
Vector dshape_1d(order + 1);
DenseMatrix m_dshape(dof, dim);
#endif
CalcDShape(order, ip.x, ip.y, ip.z, dshape_1d.GetData(), m_dshape.Data());
for (int d = 0; d < 3; d++)
{
for (int i = 0; i < dof; i++)
{
dshape(dof_map[i],d) = m_dshape(i,d);
}
}
}
H1_WedgeElement::H1_WedgeElement(const int p,
const int btype)
: NodalFiniteElement(3, Geometry::PRISM, ((p + 1)*(p + 1)*(p + 2))/2,
p, FunctionSpace::Qk),
TriangleFE(p, btype),
SegmentFE(p, btype)
{
#ifndef MFEM_THREAD_SAFE
t_shape.SetSize(TriangleFE.GetDof());
s_shape.SetSize(SegmentFE.GetDof());
t_dshape.SetSize(TriangleFE.GetDof(), 2);
s_dshape.SetSize(SegmentFE.GetDof(), 1);
#endif
t_dof.SetSize(dof);
s_dof.SetSize(dof);
int p2p3 = 2*p + 3, ntri = ((p + 1)*(p + 2))/2;
auto idx = [p2p3,ntri](int i, int j, int k)
{
return k*ntri + ((p2p3-j)*j)/2+i;
};
lex_ordering.SetSize(dof);
int o = 0;
// Nodal DoFs
lex_ordering[idx(0,0,0)] = o++;
lex_ordering[idx(p,0,0)] = o++;
lex_ordering[idx(0,p,0)] = o++;
lex_ordering[idx(0,0,p)] = o++;
lex_ordering[idx(p,0,p)] = o++;
lex_ordering[idx(0,p,p)] = o++;
t_dof[0] = 0; s_dof[0] = 0;
t_dof[1] = 1; s_dof[1] = 0;
t_dof[2] = 2; s_dof[2] = 0;
t_dof[3] = 0; s_dof[3] = 1;
t_dof[4] = 1; s_dof[4] = 1;
t_dof[5] = 2; s_dof[5] = 1;
// Edge DoFs
int k = 0;
int ne = p-1;
for (int i=1; i<p; i++)
{
lex_ordering[idx(i,0,0)] = o + 0*ne + k;
lex_ordering[idx(p-i,i,0)] = o + 1*ne + k;
lex_ordering[idx(0,p-i,0)] = o + 2*ne + k;
lex_ordering[idx(i,0,p)] = o + 3*ne + k;
lex_ordering[idx(p-i,i,p)] = o + 4*ne + k;
lex_ordering[idx(0,p-i,p)] = o + 5*ne + k;
lex_ordering[idx(0,0,i)] = o + 6*ne + k;
lex_ordering[idx(p,0,i)] = o + 7*ne + k;
lex_ordering[idx(0,p,i)] = o + 8*ne + k;
t_dof[5 + 0 * ne + i] = 2 + 0 * ne + i; s_dof[5 + 0 * ne + i] = 0;
t_dof[5 + 1 * ne + i] = 2 + 1 * ne + i; s_dof[5 + 1 * ne + i] = 0;
t_dof[5 + 2 * ne + i] = 2 + 2 * ne + i; s_dof[5 + 2 * ne + i] = 0;
t_dof[5 + 3 * ne + i] = 2 + 0 * ne + i; s_dof[5 + 3 * ne + i] = 1;
t_dof[5 + 4 * ne + i] = 2 + 1 * ne + i; s_dof[5 + 4 * ne + i] = 1;
t_dof[5 + 5 * ne + i] = 2 + 2 * ne + i; s_dof[5 + 5 * ne + i] = 1;
t_dof[5 + 6 * ne + i] = 0; s_dof[5 + 6 * ne + i] = i + 1;
t_dof[5 + 7 * ne + i] = 1; s_dof[5 + 7 * ne + i] = i + 1;
t_dof[5 + 8 * ne + i] = 2; s_dof[5 + 8 * ne + i] = i + 1;
++k;
}
o += 9*ne;
// Triangular Face DoFs
k=0;
int nt = (p-1)*(p-2)/2;
for (int j=1; j<p; j++)
{
for (int i=1; i<p-j; i++)
{
int l = j - p + (((2 * p - 1) - i) * i) / 2;
lex_ordering[idx(i,j,0)] = o+l;
lex_ordering[idx(i,j,p)] = o+nt+k;
t_dof[6 + 9 * ne + k] = 3 * p + l; s_dof[6 + 9 * ne + k] = 0;
t_dof[6 + 9 * ne + nt + k] = 3 * p + k; s_dof[6 + 9 * ne + nt + k] = 1;
k++;
}
}
o += 2*nt;
// Quadrilateral Face DoFs
k=0;
int nq = (p-1)*(p-1);
for (int j=1; j<p; j++)
{
for (int i=1; i<p; i++)
{
lex_ordering[idx(i,0,j)] = o+k;
lex_ordering[idx(p-i,i,j)] = o+nq+k;
lex_ordering[idx(0,p-i,j)] = o+2*nq+k;
t_dof[6 + 9 * ne + 2 * nt + 0 * nq + k] = 2 + 0 * ne + i;
t_dof[6 + 9 * ne + 2 * nt + 1 * nq + k] = 2 + 1 * ne + i;
t_dof[6 + 9 * ne + 2 * nt + 2 * nq + k] = 2 + 2 * ne + i;
s_dof[6 + 9 * ne + 2 * nt + 0 * nq + k] = 1 + j;
s_dof[6 + 9 * ne + 2 * nt + 1 * nq + k] = 1 + j;
s_dof[6 + 9 * ne + 2 * nt + 2 * nq + k] = 1 + j;
k++;
}
}
o += 3*nq;
// Interior DoFs
int m=0;
for (int k=1; k<p; k++)
{
int l=0;
for (int j=1; j<p; j++)
{
for (int i=1; i+j<p; i++)
{
lex_ordering[idx(i,j,k)] = o++;
t_dof[6 + 9 * ne + 2 * nt + 3 * nq + m] = 3 * p + l;
s_dof[6 + 9 * ne + 2 * nt + 3 * nq + m] = 1 + k;
l++; m++;
}
}
}
// Define Nodes
const IntegrationRule & t_Nodes = TriangleFE.GetNodes();
const IntegrationRule & s_Nodes = SegmentFE.GetNodes();
for (int i=0; i<dof; i++)
{
Nodes.IntPoint(i).x = t_Nodes.IntPoint(t_dof[i]).x;
Nodes.IntPoint(i).y = t_Nodes.IntPoint(t_dof[i]).y;
Nodes.IntPoint(i).z = s_Nodes.IntPoint(s_dof[i]).x;
}
}
void H1_WedgeElement::CalcShape(const IntegrationPoint &ip,
Vector &shape) const
{
#ifdef MFEM_THREAD_SAFE
Vector t_shape(TriangleFE.GetDof());
Vector s_shape(SegmentFE.GetDof());
#endif
IntegrationPoint ipz; ipz.x = ip.z; ipz.y = 0.0; ipz.z = 0.0;
TriangleFE.CalcShape(ip, t_shape);
SegmentFE.CalcShape(ipz, s_shape);
for (int i=0; i<dof; i++)
{
shape[i] = t_shape[t_dof[i]] * s_shape[s_dof[i]];
}
}
void H1_WedgeElement::CalcDShape(const IntegrationPoint &ip,
DenseMatrix &dshape) const
{
#ifdef MFEM_THREAD_SAFE
Vector t_shape(TriangleFE.GetDof());
DenseMatrix t_dshape(TriangleFE.GetDof(), 2);
Vector s_shape(SegmentFE.GetDof());
DenseMatrix s_dshape(SegmentFE.GetDof(), 1);
#endif
IntegrationPoint ipz; ipz.x = ip.z; ipz.y = 0.0; ipz.z = 0.0;
TriangleFE.CalcShape(ip, t_shape);
TriangleFE.CalcDShape(ip, t_dshape);
SegmentFE.CalcShape(ipz, s_shape);
SegmentFE.CalcDShape(ipz, s_dshape);
for (int i=0; i<dof; i++)
{
dshape(i, 0) = t_dshape(t_dof[i],0) * s_shape[s_dof[i]];
dshape(i, 1) = t_dshape(t_dof[i],1) * s_shape[s_dof[i]];
dshape(i, 2) = t_shape[t_dof[i]] * s_dshape(s_dof[i],0);
}
}
H1Pos_WedgeElement::H1Pos_WedgeElement(const int p)
: PositiveFiniteElement(3, Geometry::PRISM,
((p + 1)*(p + 1)*(p + 2))/2, p, FunctionSpace::Qk),
TriangleFE(p),
SegmentFE(p)
{
#ifndef MFEM_THREAD_SAFE
t_shape.SetSize(TriangleFE.GetDof());
s_shape.SetSize(SegmentFE.GetDof());
t_dshape.SetSize(TriangleFE.GetDof(), 2);
s_dshape.SetSize(SegmentFE.GetDof(), 1);
#endif
t_dof.SetSize(dof);
s_dof.SetSize(dof);
// Nodal DoFs
t_dof[0] = 0; s_dof[0] = 0;
t_dof[1] = 1; s_dof[1] = 0;
t_dof[2] = 2; s_dof[2] = 0;
t_dof[3] = 0; s_dof[3] = 1;
t_dof[4] = 1; s_dof[4] = 1;
t_dof[5] = 2; s_dof[5] = 1;
// Edge DoFs
int ne = p-1;
for (int i=1; i<p; i++)
{
t_dof[5 + 0 * ne + i] = 2 + 0 * ne + i; s_dof[5 + 0 * ne + i] = 0;
t_dof[5 + 1 * ne + i] = 2 + 1 * ne + i; s_dof[5 + 1 * ne + i] = 0;
t_dof[5 + 2 * ne + i] = 2 + 2 * ne + i; s_dof[5 + 2 * ne + i] = 0;
t_dof[5 + 3 * ne + i] = 2 + 0 * ne + i; s_dof[5 + 3 * ne + i] = 1;
t_dof[5 + 4 * ne + i] = 2 + 1 * ne + i; s_dof[5 + 4 * ne + i] = 1;
t_dof[5 + 5 * ne + i] = 2 + 2 * ne + i; s_dof[5 + 5 * ne + i] = 1;
t_dof[5 + 6 * ne + i] = 0; s_dof[5 + 6 * ne + i] = i + 1;
t_dof[5 + 7 * ne + i] = 1; s_dof[5 + 7 * ne + i] = i + 1;
t_dof[5 + 8 * ne + i] = 2; s_dof[5 + 8 * ne + i] = i + 1;
}
// Triangular Face DoFs
int k=0;
int nt = (p-1)*(p-2)/2;
for (int j=1; j<p; j++)
{
for (int i=1; i<j; i++)
{
t_dof[6 + 9 * ne + k] = 3 * p + k; s_dof[6 + 9 * ne + k] = 0;
t_dof[6 + 9 * ne + nt + k] = 3 * p + k; s_dof[6 + 9 * ne + nt + k] = 1;
k++;
}
}
// Quadrilateral Face DoFs
k=0;
int nq = (p-1)*(p-1);
for (int j=1; j<p; j++)
{
for (int i=1; i<p; i++)
{
t_dof[6 + 9 * ne + 2 * nt + 0 * nq + k] = 2 + 0 * ne + i;
t_dof[6 + 9 * ne + 2 * nt + 1 * nq + k] = 2 + 1 * ne + i;
t_dof[6 + 9 * ne + 2 * nt + 2 * nq + k] = 2 + 2 * ne + i;
s_dof[6 + 9 * ne + 2 * nt + 0 * nq + k] = 1 + j;
s_dof[6 + 9 * ne + 2 * nt + 1 * nq + k] = 1 + j;
s_dof[6 + 9 * ne + 2 * nt + 2 * nq + k] = 1 + j;
k++;
}
}
// Interior DoFs
int m=0;
for (int k=1; k<p; k++)
{
int l=0;
for (int j=1; j<p; j++)
{
for (int i=1; i<j; i++)
{
t_dof[6 + 9 * ne + 2 * nt + 3 * nq + m] = 3 * p + l;
s_dof[6 + 9 * ne + 2 * nt + 3 * nq + m] = 1 + k;
l++; m++;
}
}
}
// Define Nodes
const IntegrationRule & t_Nodes = TriangleFE.GetNodes();
const IntegrationRule & s_Nodes = SegmentFE.GetNodes();
for (int i=0; i<dof; i++)
{
Nodes.IntPoint(i).x = t_Nodes.IntPoint(t_dof[i]).x;
Nodes.IntPoint(i).y = t_Nodes.IntPoint(t_dof[i]).y;
Nodes.IntPoint(i).z = s_Nodes.IntPoint(s_dof[i]).x;
}
}
void H1Pos_WedgeElement::CalcShape(const IntegrationPoint &ip,
Vector &shape) const
{
#ifdef MFEM_THREAD_SAFE
Vector t_shape(TriangleFE.GetDof());
Vector s_shape(SegmentFE.GetDof());
#endif
IntegrationPoint ipz; ipz.x = ip.z; ipz.y = 0.0; ipz.z = 0.0;
TriangleFE.CalcShape(ip, t_shape);
SegmentFE.CalcShape(ipz, s_shape);
for (int i=0; i<dof; i++)
{
shape[i] = t_shape[t_dof[i]] * s_shape[s_dof[i]];
}
}
void H1Pos_WedgeElement::CalcDShape(const IntegrationPoint &ip,
DenseMatrix &dshape) const
{
#ifdef MFEM_THREAD_SAFE
Vector t_shape(TriangleFE.GetDof());
DenseMatrix t_dshape(TriangleFE.GetDof(), 2);
Vector s_shape(SegmentFE.GetDof());
DenseMatrix s_dshape(SegmentFE.GetDof(), 1);
#endif
IntegrationPoint ipz; ipz.x = ip.z; ipz.y = 0.0; ipz.z = 0.0;
TriangleFE.CalcShape(ip, t_shape);
TriangleFE.CalcDShape(ip, t_dshape);
SegmentFE.CalcShape(ipz, s_shape);
SegmentFE.CalcDShape(ipz, s_dshape);
for (int i=0; i<dof; i++)
{
dshape(i, 0) = t_dshape(t_dof[i],0) * s_shape[s_dof[i]];
dshape(i, 1) = t_dshape(t_dof[i],1) * s_shape[s_dof[i]];
dshape(i, 2) = t_shape[t_dof[i]] * s_dshape(s_dof[i],0);
}
}
L2_SegmentElement::L2_SegmentElement(const int p, const int btype)
: NodalTensorFiniteElement(1, p, VerifyOpen(btype), L2_DOF_MAP)
{
const double *op = poly1d.OpenPoints(p, btype);
#ifndef MFEM_THREAD_SAFE
shape_x.SetSize(p + 1);
dshape_x.SetDataAndSize(NULL, p + 1);
#endif
for (int i = 0; i <= p; i++)
{
Nodes.IntPoint(i).x = op[i];
}
}
void L2_SegmentElement::CalcShape(const IntegrationPoint &ip,
Vector &shape) const
{
basis1d.Eval(ip.x, shape);
}
void L2_SegmentElement::CalcDShape(const IntegrationPoint &ip,
DenseMatrix &dshape) const
{
#ifdef MFEM_THREAD_SAFE
Vector shape_x(dof), dshape_x(dshape.Data(), dof);
#else
dshape_x.SetData(dshape.Data());
#endif
basis1d.Eval(ip.x, shape_x, dshape_x);
}
void L2_SegmentElement::ProjectDelta(int vertex, Vector &dofs) const
{
const int p = order;
const double *op = poly1d.OpenPoints(p, b_type);
switch (vertex)
{
case 0:
for (int i = 0; i <= p; i++)
{
dofs(i) = poly1d.CalcDelta(p,(1.0 - op[i]));
}
break;
case 1:
for (int i = 0; i <= p; i++)
{
dofs(i) = poly1d.CalcDelta(p,op[i]);
}
break;
}
}
L2Pos_SegmentElement::L2Pos_SegmentElement(const int p)
: PositiveTensorFiniteElement(1, p, L2_DOF_MAP)
{
#ifndef MFEM_THREAD_SAFE
shape_x.SetSize(p + 1);
dshape_x.SetDataAndSize(NULL, p + 1);
#endif
if (p == 0)
{
Nodes.IntPoint(0).x = 0.5;
}
else
{
for (int i = 0; i <= p; i++)
{
Nodes.IntPoint(i).x = double(i)/p;
}
}
}
void L2Pos_SegmentElement::CalcShape(const IntegrationPoint &ip,
Vector &shape) const
{
Poly_1D::CalcBernstein(order, ip.x, shape);
}
void L2Pos_SegmentElement::CalcDShape(const IntegrationPoint &ip,
DenseMatrix &dshape) const
{
#ifdef MFEM_THREAD_SAFE
Vector shape_x(dof), dshape_x(dshape.Data(), dof);
#else
dshape_x.SetData(dshape.Data());
#endif
Poly_1D::CalcBernstein(order, ip.x, shape_x, dshape_x);
}
void L2Pos_SegmentElement::ProjectDelta(int vertex, Vector &dofs) const
{
dofs = 0.0;
dofs[vertex*order] = 1.0;
}
L2_QuadrilateralElement::L2_QuadrilateralElement(const int p, const int btype)
: NodalTensorFiniteElement(2, p, VerifyOpen(btype), L2_DOF_MAP)
{
const double *op = poly1d.OpenPoints(p, b_type);
#ifndef MFEM_THREAD_SAFE
shape_x.SetSize(p + 1);
shape_y.SetSize(p + 1);
dshape_x.SetSize(p + 1);
dshape_y.SetSize(p + 1);
#endif
for (int o = 0, j = 0; j <= p; j++)
for (int i = 0; i <= p; i++)
{
Nodes.IntPoint(o++).Set2(op[i], op[j]);
}
}
void L2_QuadrilateralElement::CalcShape(const IntegrationPoint &ip,
Vector &shape) const
{
const int p = order;
#ifdef MFEM_THREAD_SAFE
Vector shape_x(p+1), shape_y(p+1);
#endif
basis1d.Eval(ip.x, shape_x);
basis1d.Eval(ip.y, shape_y);
for (int o = 0, j = 0; j <= p; j++)
for (int i = 0; i <= p; i++)
{
shape(o++) = shape_x(i)*shape_y(j);
}
}
void L2_QuadrilateralElement::CalcDShape(const IntegrationPoint &ip,
DenseMatrix &dshape) const
{
const int p = order;
#ifdef MFEM_THREAD_SAFE
Vector shape_x(p+1), shape_y(p+1), dshape_x(p+1), dshape_y(p+1);
#endif
basis1d.Eval(ip.x, shape_x, dshape_x);
basis1d.Eval(ip.y, shape_y, dshape_y);
for (int o = 0, j = 0; j <= p; j++)
for (int i = 0; i <= p; i++)
{
dshape(o,0) = dshape_x(i)* shape_y(j);
dshape(o,1) = shape_x(i)*dshape_y(j); o++;
}
}
void L2_QuadrilateralElement::ProjectDelta(int vertex, Vector &dofs) const
{
const int p = order;
const double *op = poly1d.OpenPoints(p, b_type);
#ifdef MFEM_THREAD_SAFE
Vector shape_x(p+1), shape_y(p+1);
#endif
for (int i = 0; i <= p; i++)
{
shape_x(i) = poly1d.CalcDelta(p,(1.0 - op[i]));
shape_y(i) = poly1d.CalcDelta(p,op[i]);
}
switch (vertex)
{
case 0:
for (int o = 0, j = 0; j <= p; j++)
for (int i = 0; i <= p; i++)
{
dofs[o++] = shape_x(i)*shape_x(j);
}
break;
case 1:
for (int o = 0, j = 0; j <= p; j++)
for (int i = 0; i <= p; i++)
{
dofs[o++] = shape_y(i)*shape_x(j);
}
break;
case 2:
for (int o = 0, j = 0; j <= p; j++)
for (int i = 0; i <= p; i++)
{
dofs[o++] = shape_y(i)*shape_y(j);
}
break;
case 3:
for (int o = 0, j = 0; j <= p; j++)
for (int i = 0; i <= p; i++)
{
dofs[o++] = shape_x(i)*shape_y(j);
}
break;
}
}
L2Pos_QuadrilateralElement::L2Pos_QuadrilateralElement(const int p)
: PositiveTensorFiniteElement(2, p, L2_DOF_MAP)
{
#ifndef MFEM_THREAD_SAFE
shape_x.SetSize(p + 1);
shape_y.SetSize(p + 1);
dshape_x.SetSize(p + 1);
dshape_y.SetSize(p + 1);
#endif
if (p == 0)
{
Nodes.IntPoint(0).Set2(0.5, 0.5);
}
else
{
for (int o = 0, j = 0; j <= p; j++)
for (int i = 0; i <= p; i++)
{
Nodes.IntPoint(o++).Set2(double(i)/p, double(j)/p);
}
}
}
void L2Pos_QuadrilateralElement::CalcShape(const IntegrationPoint &ip,
Vector &shape) const
{
const int p = order;
#ifdef MFEM_THREAD_SAFE
Vector shape_x(p+1), shape_y(p+1);
#endif
Poly_1D::CalcBernstein(p, ip.x, shape_x);
Poly_1D::CalcBernstein(p, ip.y, shape_y);
for (int o = 0, j = 0; j <= p; j++)
for (int i = 0; i <= p; i++)
{
shape(o++) = shape_x(i)*shape_y(j);
}
}
void L2Pos_QuadrilateralElement::CalcDShape(const IntegrationPoint &ip,
DenseMatrix &dshape) const
{
const int p = order;
#ifdef MFEM_THREAD_SAFE
Vector shape_x(p+1), shape_y(p+1), dshape_x(p+1), dshape_y(p+1);
#endif
Poly_1D::CalcBernstein(p, ip.x, shape_x, dshape_x);
Poly_1D::CalcBernstein(p, ip.y, shape_y, dshape_y);
for (int o = 0, j = 0; j <= p; j++)
for (int i = 0; i <= p; i++)
{
dshape(o,0) = dshape_x(i)* shape_y(j);
dshape(o,1) = shape_x(i)*dshape_y(j); o++;
}
}
void L2Pos_QuadrilateralElement::ProjectDelta(int vertex, Vector &dofs) const
{
const int p = order;
dofs = 0.0;
switch (vertex)
{
case 0: dofs[0] = 1.0; break;
case 1: dofs[p] = 1.0; break;
case 2: dofs[p*(p + 2)] = 1.0; break;
case 3: dofs[p*(p + 1)] = 1.0; break;
}
}
L2_HexahedronElement::L2_HexahedronElement(const int p, const int btype)
: NodalTensorFiniteElement(3, p, VerifyOpen(btype), L2_DOF_MAP)
{
const double *op = poly1d.OpenPoints(p, btype);
#ifndef MFEM_THREAD_SAFE
shape_x.SetSize(p + 1);
shape_y.SetSize(p + 1);
shape_z.SetSize(p + 1);
dshape_x.SetSize(p + 1);
dshape_y.SetSize(p + 1);
dshape_z.SetSize(p + 1);
#endif
for (int o = 0, k = 0; k <= p; k++)
for (int j = 0; j <= p; j++)
for (int i = 0; i <= p; i++)
{
Nodes.IntPoint(o++).Set3(op[i], op[j], op[k]);
}
}
void L2_HexahedronElement::CalcShape(const IntegrationPoint &ip,
Vector &shape) const
{
const int p = order;
#ifdef MFEM_THREAD_SAFE
Vector shape_x(p+1), shape_y(p+1), shape_z(p+1);
#endif
basis1d.Eval(ip.x, shape_x);
basis1d.Eval(ip.y, shape_y);
basis1d.Eval(ip.z, shape_z);
for (int o = 0, k = 0; k <= p; k++)
for (int j = 0; j <= p; j++)
for (int i = 0; i <= p; i++)
{
shape(o++) = shape_x(i)*shape_y(j)*shape_z(k);
}
}
void L2_HexahedronElement::CalcDShape(const IntegrationPoint &ip,
DenseMatrix &dshape) const
{
const int p = order;
#ifdef MFEM_THREAD_SAFE
Vector shape_x(p+1), shape_y(p+1), shape_z(p+1);
Vector dshape_x(p+1), dshape_y(p+1), dshape_z(p+1);
#endif
basis1d.Eval(ip.x, shape_x, dshape_x);
basis1d.Eval(ip.y, shape_y, dshape_y);
basis1d.Eval(ip.z, shape_z, dshape_z);
for (int o = 0, k = 0; k <= p; k++)
for (int j = 0; j <= p; j++)
for (int i = 0; i <= p; i++)
{
dshape(o,0) = dshape_x(i)* shape_y(j)* shape_z(k);
dshape(o,1) = shape_x(i)*dshape_y(j)* shape_z(k);
dshape(o,2) = shape_x(i)* shape_y(j)*dshape_z(k); o++;
}
}
void L2_HexahedronElement::ProjectDelta(int vertex, Vector &dofs) const
{
const int p = order;
const double *op = poly1d.OpenPoints(p, b_type);
#ifdef MFEM_THREAD_SAFE
Vector shape_x(p+1), shape_y(p+1);
#endif
for (int i = 0; i <= p; i++)
{
shape_x(i) = poly1d.CalcDelta(p,(1.0 - op[i]));
shape_y(i) = poly1d.CalcDelta(p,op[i]);
}
switch (vertex)
{
case 0:
for (int o = 0, k = 0; k <= p; k++)
for (int j = 0; j <= p; j++)
for (int i = 0; i <= p; i++)
{
dofs[o++] = shape_x(i)*shape_x(j)*shape_x(k);
}
break;
case 1:
for (int o = 0, k = 0; k <= p; k++)
for (int j = 0; j <= p; j++)
for (int i = 0; i <= p; i++)
{
dofs[o++] = shape_y(i)*shape_x(j)*shape_x(k);
}
break;
case 2:
for (int o = 0, k = 0; k <= p; k++)
for (int j = 0; j <= p; j++)
for (int i = 0; i <= p; i++)
{
dofs[o++] = shape_y(i)*shape_y(j)*shape_x(k);
}
break;
case 3:
for (int o = 0, k = 0; k <= p; k++)
for (int j = 0; j <= p; j++)
for (int i = 0; i <= p; i++)
{
dofs[o++] = shape_x(i)*shape_y(j)*shape_x(k);
}
break;
case 4:
for (int o = 0, k = 0; k <= p; k++)
for (int j = 0; j <= p; j++)
for (int i = 0; i <= p; i++)
{
dofs[o++] = shape_x(i)*shape_x(j)*shape_y(k);
}
break;
case 5:
for (int o = 0, k = 0; k <= p; k++)
for (int j = 0; j <= p; j++)
for (int i = 0; i <= p; i++)
{
dofs[o++] = shape_y(i)*shape_x(j)*shape_y(k);
}
break;
case 6:
for (int o = 0, k = 0; k <= p; k++)
for (int j = 0; j <= p; j++)
for (int i = 0; i <= p; i++)
{
dofs[o++] = shape_y(i)*shape_y(j)*shape_y(k);
}
break;
case 7:
for (int o = 0, k = 0; k <= p; k++)
for (int j = 0; j <= p; j++)
for (int i = 0; i <= p; i++)
{
dofs[o++] = shape_x(i)*shape_y(j)*shape_y(k);
}
break;
}
}
L2Pos_HexahedronElement::L2Pos_HexahedronElement(const int p)
: PositiveTensorFiniteElement(3, p, L2_DOF_MAP)
{
#ifndef MFEM_THREAD_SAFE
shape_x.SetSize(p + 1);
shape_y.SetSize(p + 1);
shape_z.SetSize(p + 1);
dshape_x.SetSize(p + 1);
dshape_y.SetSize(p + 1);
dshape_z.SetSize(p + 1);
#endif
if (p == 0)
{
Nodes.IntPoint(0).Set3(0.5, 0.5, 0.5);
}
else
{
for (int o = 0, k = 0; k <= p; k++)
for (int j = 0; j <= p; j++)
for (int i = 0; i <= p; i++)
{
Nodes.IntPoint(o++).Set3(double(i)/p, double(j)/p, double(k)/p);
}
}
}
void L2Pos_HexahedronElement::CalcShape(const IntegrationPoint &ip,
Vector &shape) const
{
const int p = order;
#ifdef MFEM_THREAD_SAFE
Vector shape_x(p+1), shape_y(p+1), shape_z(p+1);
#endif
Poly_1D::CalcBernstein(p, ip.x, shape_x);
Poly_1D::CalcBernstein(p, ip.y, shape_y);
Poly_1D::CalcBernstein(p, ip.z, shape_z);
for (int o = 0, k = 0; k <= p; k++)
for (int j = 0; j <= p; j++)
for (int i = 0; i <= p; i++)
{
shape(o++) = shape_x(i)*shape_y(j)*shape_z(k);
}
}
void L2Pos_HexahedronElement::CalcDShape(const IntegrationPoint &ip,
DenseMatrix &dshape) const
{
const int p = order;
#ifdef MFEM_THREAD_SAFE
Vector shape_x(p+1), shape_y(p+1), shape_z(p+1);
Vector dshape_x(p+1), dshape_y(p+1), dshape_z(p+1);
#endif
Poly_1D::CalcBernstein(p, ip.x, shape_x, dshape_x);
Poly_1D::CalcBernstein(p, ip.y, shape_y, dshape_y);
Poly_1D::CalcBernstein(p, ip.z, shape_z, dshape_z);
for (int o = 0, k = 0; k <= p; k++)
for (int j = 0; j <= p; j++)
for (int i = 0; i <= p; i++)
{
dshape(o,0) = dshape_x(i)* shape_y(j)* shape_z(k);
dshape(o,1) = shape_x(i)*dshape_y(j)* shape_z(k);
dshape(o,2) = shape_x(i)* shape_y(j)*dshape_z(k); o++;
}
}
void L2Pos_HexahedronElement::ProjectDelta(int vertex, Vector &dofs) const
{
const int p = order;
dofs = 0.0;
switch (vertex)
{
case 0: dofs[0] = 1.0; break;
case 1: dofs[p] = 1.0; break;
case 2: dofs[p*(p + 2)] = 1.0; break;
case 3: dofs[p*(p + 1)] = 1.0; break;
case 4: dofs[p*(p + 1)*(p + 1)] = 1.0; break;
case 5: dofs[p + p*(p + 1)*(p + 1)] = 1.0; break;
case 6: dofs[dof - 1] = 1.0; break;
case 7: dofs[dof - p - 1] = 1.0; break;
}
}
L2_TriangleElement::L2_TriangleElement(const int p, const int btype)
: NodalFiniteElement(2, Geometry::TRIANGLE, ((p + 1)*(p + 2))/2, p,
FunctionSpace::Pk)
{
const double *op = poly1d.OpenPoints(p, VerifyNodal(VerifyOpen(btype)));
#ifndef MFEM_THREAD_SAFE
shape_x.SetSize(p + 1);
shape_y.SetSize(p + 1);
shape_l.SetSize(p + 1);
dshape_x.SetSize(p + 1);
dshape_y.SetSize(p + 1);
dshape_l.SetSize(p + 1);
u.SetSize(dof);
du.SetSize(dof, dim);
#else
Vector shape_x(p + 1), shape_y(p + 1), shape_l(p + 1);
#endif
for (int o = 0, j = 0; j <= p; j++)
for (int i = 0; i + j <= p; i++)
{
double w = op[i] + op[j] + op[p-i-j];
Nodes.IntPoint(o++).Set2(op[i]/w, op[j]/w);
}
DenseMatrix T(dof);
for (int k = 0; k < dof; k++)
{
IntegrationPoint &ip = Nodes.IntPoint(k);
poly1d.CalcBasis(p, ip.x, shape_x);
poly1d.CalcBasis(p, ip.y, shape_y);
poly1d.CalcBasis(p, 1. - ip.x - ip.y, shape_l);
for (int o = 0, j = 0; j <= p; j++)
for (int i = 0; i + j <= p; i++)
{
T(o++, k) = shape_x(i)*shape_y(j)*shape_l(p-i-j);
}
}
Ti.Factor(T);
// mfem::out << "L2_TriangleElement(" << p << ") : "; Ti.TestInversion();
}
void L2_TriangleElement::CalcShape(const IntegrationPoint &ip,
Vector &shape) const
{
const int p = order;
#ifdef MFEM_THREAD_SAFE
Vector shape_x(p + 1), shape_y(p + 1), shape_l(p + 1), u(dof);
#endif
poly1d.CalcBasis(p, ip.x, shape_x);
poly1d.CalcBasis(p, ip.y, shape_y);
poly1d.CalcBasis(p, 1. - ip.x - ip.y, shape_l);
for (int o = 0, j = 0; j <= p; j++)
for (int i = 0; i + j <= p; i++)
{
u(o++) = shape_x(i)*shape_y(j)*shape_l(p-i-j);
}
Ti.Mult(u, shape);
}
void L2_TriangleElement::CalcDShape(const IntegrationPoint &ip,
DenseMatrix &dshape) const
{
const int p = order;
#ifdef MFEM_THREAD_SAFE
Vector shape_x(p + 1), shape_y(p + 1), shape_l(p + 1);
Vector dshape_x(p + 1), dshape_y(p + 1), dshape_l(p + 1);
DenseMatrix du(dof, dim);
#endif
poly1d.CalcBasis(p, ip.x, shape_x, dshape_x);
poly1d.CalcBasis(p, ip.y, shape_y, dshape_y);
poly1d.CalcBasis(p, 1. - ip.x - ip.y, shape_l, dshape_l);
for (int o = 0, j = 0; j <= p; j++)
for (int i = 0; i + j <= p; i++)
{
int k = p - i - j;
du(o,0) = ((dshape_x(i)* shape_l(k)) -
( shape_x(i)*dshape_l(k)))*shape_y(j);
du(o,1) = ((dshape_y(j)* shape_l(k)) -
( shape_y(j)*dshape_l(k)))*shape_x(i);
o++;
}
Ti.Mult(du, dshape);
}
void L2_TriangleElement::ProjectDelta(int vertex, Vector &dofs) const
{
switch (vertex)
{
case 0:
for (int i = 0; i < dof; i++)
{
const IntegrationPoint &ip = Nodes.IntPoint(i);
dofs[i] = pow(1.0 - ip.x - ip.y, order);
}
break;
case 1:
for (int i = 0; i < dof; i++)
{
const IntegrationPoint &ip = Nodes.IntPoint(i);
dofs[i] = pow(ip.x, order);
}
break;
case 2:
for (int i = 0; i < dof; i++)
{
const IntegrationPoint &ip = Nodes.IntPoint(i);
dofs[i] = pow(ip.y, order);
}
break;
}
}
L2Pos_TriangleElement::L2Pos_TriangleElement(const int p)
: PositiveFiniteElement(2, Geometry::TRIANGLE, ((p + 1)*(p + 2))/2, p,
FunctionSpace::Pk)
{
#ifndef MFEM_THREAD_SAFE
dshape_1d.SetSize(p + 1);
#endif
if (p == 0)
{
Nodes.IntPoint(0).Set2(1./3, 1./3);
}
else
{
for (int o = 0, j = 0; j <= p; j++)
for (int i = 0; i + j <= p; i++)
{
Nodes.IntPoint(o++).Set2(double(i)/p, double(j)/p);
}
}
}
void L2Pos_TriangleElement::CalcShape(const IntegrationPoint &ip,
Vector &shape) const
{
H1Pos_TriangleElement::CalcShape(order, ip.x, ip.y, shape.GetData());
}
void L2Pos_TriangleElement::CalcDShape(const IntegrationPoint &ip,
DenseMatrix &dshape) const
{
#ifdef MFEM_THREAD_SAFE
Vector dshape_1d(order + 1);
#endif
H1Pos_TriangleElement::CalcDShape(order, ip.x, ip.y, dshape_1d.GetData(),
dshape.Data());
}
void L2Pos_TriangleElement::ProjectDelta(int vertex, Vector &dofs) const
{
dofs = 0.0;
switch (vertex)
{
case 0: dofs[0] = 1.0; break;
case 1: dofs[order] = 1.0; break;
case 2: dofs[dof-1] = 1.0; break;
}
}
L2_TetrahedronElement::L2_TetrahedronElement(const int p, const int btype)
: NodalFiniteElement(3, Geometry::TETRAHEDRON, ((p + 1)*(p + 2)*(p + 3))/6,
p, FunctionSpace::Pk)
{
const double *op = poly1d.OpenPoints(p, VerifyNodal(VerifyOpen(btype)));
#ifndef MFEM_THREAD_SAFE
shape_x.SetSize(p + 1);
shape_y.SetSize(p + 1);
shape_z.SetSize(p + 1);
shape_l.SetSize(p + 1);
dshape_x.SetSize(p + 1);
dshape_y.SetSize(p + 1);
dshape_z.SetSize(p + 1);
dshape_l.SetSize(p + 1);
u.SetSize(dof);
du.SetSize(dof, dim);
#else
Vector shape_x(p + 1), shape_y(p + 1), shape_z(p + 1), shape_l(p + 1);
#endif
for (int o = 0, k = 0; k <= p; k++)
for (int j = 0; j + k <= p; j++)
for (int i = 0; i + j + k <= p; i++)
{
double w = op[i] + op[j] + op[k] + op[p-i-j-k];
Nodes.IntPoint(o++).Set3(op[i]/w, op[j]/w, op[k]/w);
}
DenseMatrix T(dof);
for (int m = 0; m < dof; m++)
{
IntegrationPoint &ip = Nodes.IntPoint(m);
poly1d.CalcBasis(p, ip.x, shape_x);
poly1d.CalcBasis(p, ip.y, shape_y);
poly1d.CalcBasis(p, ip.z, shape_z);
poly1d.CalcBasis(p, 1. - ip.x - ip.y - ip.z, shape_l);
for (int o = 0, k = 0; k <= p; k++)
for (int j = 0; j + k <= p; j++)
for (int i = 0; i + j + k <= p; i++)
{
T(o++, m) = shape_x(i)*shape_y(j)*shape_z(k)*shape_l(p-i-j-k);
}
}
Ti.Factor(T);
// mfem::out << "L2_TetrahedronElement(" << p << ") : "; Ti.TestInversion();
}
void L2_TetrahedronElement::CalcShape(const IntegrationPoint &ip,
Vector &shape) const
{
const int p = order;
#ifdef MFEM_THREAD_SAFE
Vector shape_x(p + 1), shape_y(p + 1), shape_z(p + 1), shape_l(p + 1);
Vector u(dof);
#endif
poly1d.CalcBasis(p, ip.x, shape_x);
poly1d.CalcBasis(p, ip.y, shape_y);
poly1d.CalcBasis(p, ip.z, shape_z);
poly1d.CalcBasis(p, 1. - ip.x - ip.y - ip.z, shape_l);
for (int o = 0, k = 0; k <= p; k++)
for (int j = 0; j + k <= p; j++)
for (int i = 0; i + j + k <= p; i++)
{
u(o++) = shape_x(i)*shape_y(j)*shape_z(k)*shape_l(p-i-j-k);
}
Ti.Mult(u, shape);
}
void L2_TetrahedronElement::CalcDShape(const IntegrationPoint &ip,
DenseMatrix &dshape) const
{
const int p = order;
#ifdef MFEM_THREAD_SAFE
Vector shape_x(p + 1), shape_y(p + 1), shape_z(p + 1), shape_l(p + 1);
Vector dshape_x(p + 1), dshape_y(p + 1), dshape_z(p + 1), dshape_l(p + 1);
DenseMatrix du(dof, dim);
#endif
poly1d.CalcBasis(p, ip.x, shape_x, dshape_x);
poly1d.CalcBasis(p, ip.y, shape_y, dshape_y);
poly1d.CalcBasis(p, ip.z, shape_z, dshape_z);
poly1d.CalcBasis(p, 1. - ip.x - ip.y - ip.z, shape_l, dshape_l);
for (int o = 0, k = 0; k <= p; k++)
for (int j = 0; j + k <= p; j++)
for (int i = 0; i + j + k <= p; i++)
{
int l = p - i - j - k;
du(o,0) = ((dshape_x(i)* shape_l(l)) -
( shape_x(i)*dshape_l(l)))*shape_y(j)*shape_z(k);
du(o,1) = ((dshape_y(j)* shape_l(l)) -
( shape_y(j)*dshape_l(l)))*shape_x(i)*shape_z(k);
du(o,2) = ((dshape_z(k)* shape_l(l)) -
( shape_z(k)*dshape_l(l)))*shape_x(i)*shape_y(j);
o++;
}
Ti.Mult(du, dshape);
}
void L2_TetrahedronElement::ProjectDelta(int vertex, Vector &dofs) const
{
switch (vertex)
{
case 0:
for (int i = 0; i < dof; i++)
{
const IntegrationPoint &ip = Nodes.IntPoint(i);
dofs[i] = pow(1.0 - ip.x - ip.y - ip.z, order);
}
break;
case 1:
for (int i = 0; i < dof; i++)
{
const IntegrationPoint &ip = Nodes.IntPoint(i);
dofs[i] = pow(ip.x, order);
}
break;
case 2:
for (int i = 0; i < dof; i++)
{
const IntegrationPoint &ip = Nodes.IntPoint(i);
dofs[i] = pow(ip.y, order);
}
break;
case 3:
for (int i = 0; i < dof; i++)
{
const IntegrationPoint &ip = Nodes.IntPoint(i);
dofs[i] = pow(ip.z, order);
}
break;
}
}
L2Pos_TetrahedronElement::L2Pos_TetrahedronElement(const int p)
: PositiveFiniteElement(3, Geometry::TETRAHEDRON,
((p + 1)*(p + 2)*(p + 3))/6, p, FunctionSpace::Pk)
{
#ifndef MFEM_THREAD_SAFE
dshape_1d.SetSize(p + 1);
#endif
if (p == 0)
{
Nodes.IntPoint(0).Set3(0.25, 0.25, 0.25);
}
else
{
for (int o = 0, k = 0; k <= p; k++)
for (int j = 0; j + k <= p; j++)
for (int i = 0; i + j + k <= p; i++)
{
Nodes.IntPoint(o++).Set3(double(i)/p, double(j)/p, double(k)/p);
}
}
}
void L2Pos_TetrahedronElement::CalcShape(const IntegrationPoint &ip,
Vector &shape) const
{
H1Pos_TetrahedronElement::CalcShape(order, ip.x, ip.y, ip.z,
shape.GetData());
}
void L2Pos_TetrahedronElement::CalcDShape(const IntegrationPoint &ip,
DenseMatrix &dshape) const
{
#ifdef MFEM_THREAD_SAFE
Vector dshape_1d(order + 1);
#endif
H1Pos_TetrahedronElement::CalcDShape(order, ip.x, ip.y, ip.z,
dshape_1d.GetData(), dshape.Data());
}
void L2Pos_TetrahedronElement::ProjectDelta(int vertex, Vector &dofs) const
{
dofs = 0.0;
switch (vertex)
{
case 0: dofs[0] = 1.0; break;
case 1: dofs[order] = 1.0; break;
case 2: dofs[(order*(order+3))/2] = 1.0; break;
case 3: dofs[dof-1] = 1.0; break;
}
}
L2_WedgeElement::L2_WedgeElement(const int p, const int btype)
: NodalFiniteElement(3, Geometry::PRISM, ((p + 1)*(p + 1)*(p + 2))/2,
p, FunctionSpace::Qk),
TriangleFE(p, btype),
SegmentFE(p, btype)
{
#ifndef MFEM_THREAD_SAFE
t_shape.SetSize(TriangleFE.GetDof());
s_shape.SetSize(SegmentFE.GetDof());
t_dshape.SetSize(TriangleFE.GetDof(), 2);
s_dshape.SetSize(SegmentFE.GetDof(), 1);
#endif
t_dof.SetSize(dof);
s_dof.SetSize(dof);
// Interior DoFs
int m=0;
for (int k=0; k<=p; k++)
{
int l=0;
for (int j=0; j<=p; j++)
{
for (int i=0; i<=j; i++)
{
t_dof[m] = l;
s_dof[m] = k;
l++; m++;
}
}
}
// Define Nodes
const IntegrationRule & t_Nodes = TriangleFE.GetNodes();
const IntegrationRule & s_Nodes = SegmentFE.GetNodes();
for (int i=0; i<dof; i++)
{
Nodes.IntPoint(i).x = t_Nodes.IntPoint(t_dof[i]).x;
Nodes.IntPoint(i).y = t_Nodes.IntPoint(t_dof[i]).y;
Nodes.IntPoint(i).z = s_Nodes.IntPoint(s_dof[i]).x;
}
}
void L2_WedgeElement::CalcShape(const IntegrationPoint &ip,
Vector &shape) const
{
#ifdef MFEM_THREAD_SAFE
Vector t_shape(TriangleFE.GetDof());
Vector s_shape(SegmentFE.GetDof());
#endif
IntegrationPoint ipz; ipz.x = ip.z; ipz.y = 0.0; ipz.z = 0.0;
TriangleFE.CalcShape(ip, t_shape);
SegmentFE.CalcShape(ipz, s_shape);
for (int i=0; i<dof; i++)
{
shape[i] = t_shape[t_dof[i]] * s_shape[s_dof[i]];
}
}
void L2_WedgeElement::CalcDShape(const IntegrationPoint &ip,
DenseMatrix &dshape) const
{
#ifdef MFEM_THREAD_SAFE
Vector t_shape(TriangleFE.GetDof());
DenseMatrix t_dshape(TriangleFE.GetDof(), 2);
Vector s_shape(SegmentFE.GetDof());
DenseMatrix s_dshape(SegmentFE.GetDof(), 1);
#endif
IntegrationPoint ipz; ipz.x = ip.z; ipz.y = 0.0; ipz.z = 0.0;
TriangleFE.CalcShape(ip, t_shape);
TriangleFE.CalcDShape(ip, t_dshape);
SegmentFE.CalcShape(ipz, s_shape);
SegmentFE.CalcDShape(ipz, s_dshape);
for (int i=0; i<dof; i++)
{
dshape(i, 0) = t_dshape(t_dof[i],0) * s_shape[s_dof[i]];
dshape(i, 1) = t_dshape(t_dof[i],1) * s_shape[s_dof[i]];
dshape(i, 2) = t_shape[t_dof[i]] * s_dshape(s_dof[i],0);
}
}
L2Pos_WedgeElement::L2Pos_WedgeElement(const int p)
: PositiveFiniteElement(3, Geometry::PRISM,
((p + 1)*(p + 1)*(p + 2))/2, p, FunctionSpace::Qk),
TriangleFE(p),
SegmentFE(p)
{
#ifndef MFEM_THREAD_SAFE
t_shape.SetSize(TriangleFE.GetDof());
s_shape.SetSize(SegmentFE.GetDof());
t_dshape.SetSize(TriangleFE.GetDof(), 2);
s_dshape.SetSize(SegmentFE.GetDof(), 1);
#endif
t_dof.SetSize(dof);
s_dof.SetSize(dof);
// Interior DoFs
int m=0;
for (int k=0; k<=p; k++)
{
int l=0;
for (int j=0; j<=p; j++)
{
for (int i=0; i<=j; i++)
{
t_dof[m] = l;
s_dof[m] = k;
l++; m++;
}
}
}
// Define Nodes
const IntegrationRule & t_Nodes = TriangleFE.GetNodes();
const IntegrationRule & s_Nodes = SegmentFE.GetNodes();
for (int i=0; i<dof; i++)
{
Nodes.IntPoint(i).x = t_Nodes.IntPoint(t_dof[i]).x;
Nodes.IntPoint(i).y = t_Nodes.IntPoint(t_dof[i]).y;
Nodes.IntPoint(i).z = s_Nodes.IntPoint(s_dof[i]).x;
}
}
void L2Pos_WedgeElement::CalcShape(const IntegrationPoint &ip,
Vector &shape) const
{
#ifdef MFEM_THREAD_SAFE
Vector t_shape(TriangleFE.GetDof());
Vector s_shape(SegmentFE.GetDof());
#endif
IntegrationPoint ipz; ipz.x = ip.z; ipz.y = 0.0; ipz.z = 0.0;
TriangleFE.CalcShape(ip, t_shape);
SegmentFE.CalcShape(ipz, s_shape);
for (int i=0; i<dof; i++)
{
shape[i] = t_shape[t_dof[i]] * s_shape[s_dof[i]];
}
}
void L2Pos_WedgeElement::CalcDShape(const IntegrationPoint &ip,
DenseMatrix &dshape) const
{
#ifdef MFEM_THREAD_SAFE
Vector t_shape(TriangleFE.GetDof());
DenseMatrix t_dshape(TriangleFE.GetDof(), 2);
Vector s_shape(SegmentFE.GetDof());
DenseMatrix s_dshape(SegmentFE.GetDof(), 1);
#endif
IntegrationPoint ipz; ipz.x = ip.z; ipz.y = 0.0; ipz.z = 0.0;
TriangleFE.CalcShape(ip, t_shape);
TriangleFE.CalcDShape(ip, t_dshape);
SegmentFE.CalcShape(ipz, s_shape);
SegmentFE.CalcDShape(ipz, s_dshape);
for (int i=0; i<dof; i++)
{
dshape(i, 0) = t_dshape(t_dof[i],0) * s_shape[s_dof[i]];
dshape(i, 1) = t_dshape(t_dof[i],1) * s_shape[s_dof[i]];
dshape(i, 2) = t_shape[t_dof[i]] * s_dshape(s_dof[i],0);
}
}
const double RT_QuadrilateralElement::nk[8] =
{ 0., -1., 1., 0., 0., 1., -1., 0. };
RT_QuadrilateralElement::RT_QuadrilateralElement(const int p,
const int cb_type,
const int ob_type)
: VectorTensorFiniteElement(2, 2*(p + 1)*(p + 2), p + 1, cb_type, ob_type,
H_DIV, DofMapType::L2_DOF_MAP),
dof2nk(dof)
{
dof_map.SetSize(dof);
const double *cp = poly1d.ClosedPoints(p + 1, cb_type);
const double *op = poly1d.OpenPoints(p, ob_type);
const int dof2 = dof/2;
#ifndef MFEM_THREAD_SAFE
shape_cx.SetSize(p + 2);
shape_ox.SetSize(p + 1);
shape_cy.SetSize(p + 2);
shape_oy.SetSize(p + 1);
dshape_cx.SetSize(p + 2);
dshape_cy.SetSize(p + 2);
#endif
// edges
int o = 0;
for (int i = 0; i <= p; i++) // (0,1)
{
dof_map[1*dof2 + i + 0*(p + 1)] = o++;
}
for (int i = 0; i <= p; i++) // (1,2)
{
dof_map[0*dof2 + (p + 1) + i*(p + 2)] = o++;
}
for (int i = 0; i <= p; i++) // (2,3)
{
dof_map[1*dof2 + (p - i) + (p + 1)*(p + 1)] = o++;
}
for (int i = 0; i <= p; i++) // (3,0)
{
dof_map[0*dof2 + 0 + (p - i)*(p + 2)] = o++;
}
// interior
for (int j = 0; j <= p; j++) // x-components
for (int i = 1; i <= p; i++)
{
dof_map[0*dof2 + i + j*(p + 2)] = o++;
}
for (int j = 1; j <= p; j++) // y-components
for (int i = 0; i <= p; i++)
{
dof_map[1*dof2 + i + j*(p + 1)] = o++;
}
// dof orientations
// x-components
for (int j = 0; j <= p; j++)
for (int i = 0; i <= p/2; i++)
{
int idx = 0*dof2 + i + j*(p + 2);
dof_map[idx] = -1 - dof_map[idx];
}
if (p%2 == 1)
for (int j = p/2 + 1; j <= p; j++)
{
int idx = 0*dof2 + (p/2 + 1) + j*(p + 2);
dof_map[idx] = -1 - dof_map[idx];
}
// y-components
for (int j = 0; j <= p/2; j++)
for (int i = 0; i <= p; i++)
{
int idx = 1*dof2 + i + j*(p + 1);
dof_map[idx] = -1 - dof_map[idx];
}
if (p%2 == 1)
for (int i = 0; i <= p/2; i++)
{
int idx = 1*dof2 + i + (p/2 + 1)*(p + 1);
dof_map[idx] = -1 - dof_map[idx];
}
o = 0;
for (int j = 0; j <= p; j++)
for (int i = 0; i <= p + 1; i++)
{
int idx;
if ((idx = dof_map[o++]) < 0)
{
idx = -1 - idx;
dof2nk[idx] = 3;
}
else
{
dof2nk[idx] = 1;
}
Nodes.IntPoint(idx).Set2(cp[i], op[j]);
}
for (int j = 0; j <= p + 1; j++)
for (int i = 0; i <= p; i++)
{
int idx;
if ((idx = dof_map[o++]) < 0)
{
idx = -1 - idx;
dof2nk[idx] = 0;
}
else
{
dof2nk[idx] = 2;
}
Nodes.IntPoint(idx).Set2(op[i], cp[j]);
}
}
void RT_QuadrilateralElement::CalcVShape(const IntegrationPoint &ip,
DenseMatrix &shape) const
{
const int pp1 = order;
#ifdef MFEM_THREAD_SAFE
Vector shape_cx(pp1 + 1), shape_ox(pp1), shape_cy(pp1 + 1), shape_oy(pp1);
#endif
cbasis1d.Eval(ip.x, shape_cx);
obasis1d.Eval(ip.x, shape_ox);
cbasis1d.Eval(ip.y, shape_cy);
obasis1d.Eval(ip.y, shape_oy);
int o = 0;
for (int j = 0; j < pp1; j++)
for (int i = 0; i <= pp1; i++)
{
int idx, s;
if ((idx = dof_map[o++]) < 0)
{
idx = -1 - idx, s = -1;
}
else
{
s = +1;
}
shape(idx,0) = s*shape_cx(i)*shape_oy(j);
shape(idx,1) = 0.;
}
for (int j = 0; j <= pp1; j++)
for (int i = 0; i < pp1; i++)
{
int idx, s;
if ((idx = dof_map[o++]) < 0)
{
idx = -1 - idx, s = -1;
}
else
{
s = +1;
}
shape(idx,0) = 0.;
shape(idx,1) = s*shape_ox(i)*shape_cy(j);
}
}
void RT_QuadrilateralElement::CalcDivShape(const IntegrationPoint &ip,
Vector &divshape) const
{
const int pp1 = order;
#ifdef MFEM_THREAD_SAFE
Vector shape_cx(pp1 + 1), shape_ox(pp1), shape_cy(pp1 + 1), shape_oy(pp1);
Vector dshape_cx(pp1 + 1), dshape_cy(pp1 + 1);
#endif
cbasis1d.Eval(ip.x, shape_cx, dshape_cx);
obasis1d.Eval(ip.x, shape_ox);
cbasis1d.Eval(ip.y, shape_cy, dshape_cy);
obasis1d.Eval(ip.y, shape_oy);
int o = 0;
for (int j = 0; j < pp1; j++)
for (int i = 0; i <= pp1; i++)
{
int idx, s;
if ((idx = dof_map[o++]) < 0)
{
idx = -1 - idx, s = -1;
}
else
{
s = +1;
}
divshape(idx) = s*dshape_cx(i)*shape_oy(j);
}
for (int j = 0; j <= pp1; j++)
for (int i = 0; i < pp1; i++)
{
int idx, s;
if ((idx = dof_map[o++]) < 0)
{
idx = -1 - idx, s = -1;
}
else
{
s = +1;
}
divshape(idx) = s*shape_ox(i)*dshape_cy(j);
}
}
const double RT_HexahedronElement::nk[18] =
{ 0.,0.,-1., 0.,-1.,0., 1.,0.,0., 0.,1.,0., -1.,0.,0., 0.,0.,1. };
RT_HexahedronElement::RT_HexahedronElement(const int p,
const int cb_type,
const int ob_type)
: VectorTensorFiniteElement(3, 3*(p + 1)*(p + 1)*(p + 2), p + 1, cb_type,
ob_type, H_DIV, DofMapType::L2_DOF_MAP),
dof2nk(dof)
{
dof_map.SetSize(dof);
const double *cp = poly1d.ClosedPoints(p + 1, cb_type);
const double *op = poly1d.OpenPoints(p, ob_type);
const int dof3 = dof/3;
#ifndef MFEM_THREAD_SAFE
shape_cx.SetSize(p + 2);
shape_ox.SetSize(p + 1);
shape_cy.SetSize(p + 2);
shape_oy.SetSize(p + 1);
shape_cz.SetSize(p + 2);
shape_oz.SetSize(p + 1);
dshape_cx.SetSize(p + 2);
dshape_cy.SetSize(p + 2);
dshape_cz.SetSize(p + 2);
#endif
// faces
int o = 0;
for (int j = 0; j <= p; j++) // (3,2,1,0) -- bottom
for (int i = 0; i <= p; i++)
{
dof_map[2*dof3 + i + ((p - j) + 0*(p + 1))*(p + 1)] = o++;
}
for (int j = 0; j <= p; j++) // (0,1,5,4) -- front
for (int i = 0; i <= p; i++)
{
dof_map[1*dof3 + i + (0 + j*(p + 2))*(p + 1)] = o++;
}
for (int j = 0; j <= p; j++) // (1,2,6,5) -- right
for (int i = 0; i <= p; i++)
{
dof_map[0*dof3 + (p + 1) + (i + j*(p + 1))*(p + 2)] = o++;
}
for (int j = 0; j <= p; j++) // (2,3,7,6) -- back
for (int i = 0; i <= p; i++)
{
dof_map[1*dof3 + (p - i) + ((p + 1) + j*(p + 2))*(p + 1)] = o++;
}
for (int j = 0; j <= p; j++) // (3,0,4,7) -- left
for (int i = 0; i <= p; i++)
{
dof_map[0*dof3 + 0 + ((p - i) + j*(p + 1))*(p + 2)] = o++;
}
for (int j = 0; j <= p; j++) // (4,5,6,7) -- top
for (int i = 0; i <= p; i++)
{
dof_map[2*dof3 + i + (j + (p + 1)*(p + 1))*(p + 1)] = o++;
}
// interior
// x-components
for (int k = 0; k <= p; k++)
for (int j = 0; j <= p; j++)
for (int i = 1; i <= p; i++)
{
dof_map[0*dof3 + i + (j + k*(p + 1))*(p + 2)] = o++;
}
// y-components
for (int k = 0; k <= p; k++)
for (int j = 1; j <= p; j++)
for (int i = 0; i <= p; i++)
{
dof_map[1*dof3 + i + (j + k*(p + 2))*(p + 1)] = o++;
}
// z-components
for (int k = 1; k <= p; k++)
for (int j = 0; j <= p; j++)
for (int i = 0; i <= p; i++)
{
dof_map[2*dof3 + i + (j + k*(p + 1))*(p + 1)] = o++;
}
// dof orientations
// for odd p, do not change the orientations in the mid-planes
// {i = p/2 + 1}, {j = p/2 + 1}, {k = p/2 + 1} in the x, y, z-components
// respectively.
// x-components
for (int k = 0; k <= p; k++)
for (int j = 0; j <= p; j++)
for (int i = 0; i <= p/2; i++)
{
int idx = 0*dof3 + i + (j + k*(p + 1))*(p + 2);
dof_map[idx] = -1 - dof_map[idx];
}
// y-components
for (int k = 0; k <= p; k++)
for (int j = 0; j <= p/2; j++)
for (int i = 0; i <= p; i++)
{
int idx = 1*dof3 + i + (j + k*(p + 2))*(p + 1);
dof_map[idx] = -1 - dof_map[idx];
}
// z-components
for (int k = 0; k <= p/2; k++)
for (int j = 0; j <= p; j++)
for (int i = 0; i <= p; i++)
{
int idx = 2*dof3 + i + (j + k*(p + 1))*(p + 1);
dof_map[idx] = -1 - dof_map[idx];
}
o = 0;
// x-components
for (int k = 0; k <= p; k++)
for (int j = 0; j <= p; j++)
for (int i = 0; i <= p + 1; i++)
{
int idx;
if ((idx = dof_map[o++]) < 0)
{
idx = -1 - idx;
dof2nk[idx] = 4;
}
else
{
dof2nk[idx] = 2;
}
Nodes.IntPoint(idx).Set3(cp[i], op[j], op[k]);
}
// y-components
for (int k = 0; k <= p; k++)
for (int j = 0; j <= p + 1; j++)
for (int i = 0; i <= p; i++)
{
int idx;
if ((idx = dof_map[o++]) < 0)
{
idx = -1 - idx;
dof2nk[idx] = 1;
}
else
{
dof2nk[idx] = 3;
}
Nodes.IntPoint(idx).Set3(op[i], cp[j], op[k]);
}
// z-components
for (int k = 0; k <= p + 1; k++)
for (int j = 0; j <= p; j++)
for (int i = 0; i <= p; i++)
{
int idx;
if ((idx = dof_map[o++]) < 0)
{
idx = -1 - idx;
dof2nk[idx] = 0;
}
else
{
dof2nk[idx] = 5;
}
Nodes.IntPoint(idx).Set3(op[i], op[j], cp[k]);
}
}
void RT_HexahedronElement::CalcVShape(const IntegrationPoint &ip,
DenseMatrix &shape) const
{
const int pp1 = order;
#ifdef MFEM_THREAD_SAFE
Vector shape_cx(pp1 + 1), shape_ox(pp1), shape_cy(pp1 + 1), shape_oy(pp1);
Vector shape_cz(pp1 + 1), shape_oz(pp1);
#endif
cbasis1d.Eval(ip.x, shape_cx);
obasis1d.Eval(ip.x, shape_ox);
cbasis1d.Eval(ip.y, shape_cy);
obasis1d.Eval(ip.y, shape_oy);
cbasis1d.Eval(ip.z, shape_cz);
obasis1d.Eval(ip.z, shape_oz);
int o = 0;
// x-components
for (int k = 0; k < pp1; k++)
for (int j = 0; j < pp1; j++)
for (int i = 0; i <= pp1; i++)
{
int idx, s;
if ((idx = dof_map[o++]) < 0)
{
idx = -1 - idx, s = -1;
}
else
{
s = +1;
}
shape(idx,0) = s*shape_cx(i)*shape_oy(j)*shape_oz(k);
shape(idx,1) = 0.;
shape(idx,2) = 0.;
}
// y-components
for (int k = 0; k < pp1; k++)
for (int j = 0; j <= pp1; j++)
for (int i = 0; i < pp1; i++)
{
int idx, s;
if ((idx = dof_map[o++]) < 0)
{
idx = -1 - idx, s = -1;
}
else
{
s = +1;
}
shape(idx,0) = 0.;
shape(idx,1) = s*shape_ox(i)*shape_cy(j)*shape_oz(k);
shape(idx,2) = 0.;
}
// z-components
for (int k = 0; k <= pp1; k++)
for (int j = 0; j < pp1; j++)
for (int i = 0; i < pp1; i++)
{
int idx, s;
if ((idx = dof_map[o++]) < 0)
{
idx = -1 - idx, s = -1;
}
else
{
s = +1;
}
shape(idx,0) = 0.;
shape(idx,1) = 0.;
shape(idx,2) = s*shape_ox(i)*shape_oy(j)*shape_cz(k);
}
}
void RT_HexahedronElement::CalcDivShape(const IntegrationPoint &ip,
Vector &divshape) const
{
const int pp1 = order;
#ifdef MFEM_THREAD_SAFE
Vector shape_cx(pp1 + 1), shape_ox(pp1), shape_cy(pp1 + 1), shape_oy(pp1);
Vector shape_cz(pp1 + 1), shape_oz(pp1);
Vector dshape_cx(pp1 + 1), dshape_cy(pp1 + 1), dshape_cz(pp1 + 1);
#endif
cbasis1d.Eval(ip.x, shape_cx, dshape_cx);
obasis1d.Eval(ip.x, shape_ox);
cbasis1d.Eval(ip.y, shape_cy, dshape_cy);
obasis1d.Eval(ip.y, shape_oy);
cbasis1d.Eval(ip.z, shape_cz, dshape_cz);
obasis1d.Eval(ip.z, shape_oz);
int o = 0;
// x-components
for (int k = 0; k < pp1; k++)
for (int j = 0; j < pp1; j++)
for (int i = 0; i <= pp1; i++)
{
int idx, s;
if ((idx = dof_map[o++]) < 0)
{
idx = -1 - idx, s = -1;
}
else
{
s = +1;
}
divshape(idx) = s*dshape_cx(i)*shape_oy(j)*shape_oz(k);
}
// y-components
for (int k = 0; k < pp1; k++)
for (int j = 0; j <= pp1; j++)
for (int i = 0; i < pp1; i++)
{
int idx, s;
if ((idx = dof_map[o++]) < 0)
{
idx = -1 - idx, s = -1;
}
else
{
s = +1;
}
divshape(idx) = s*shape_ox(i)*dshape_cy(j)*shape_oz(k);
}
// z-components
for (int k = 0; k <= pp1; k++)
for (int j = 0; j < pp1; j++)
for (int i = 0; i < pp1; i++)
{
int idx, s;
if ((idx = dof_map[o++]) < 0)
{
idx = -1 - idx, s = -1;
}
else
{
s = +1;
}
divshape(idx) = s*shape_ox(i)*shape_oy(j)*dshape_cz(k);
}
}
const double RT_TriangleElement::nk[6] =
{ 0., -1., 1., 1., -1., 0. };
const double RT_TriangleElement::c = 1./3.;
RT_TriangleElement::RT_TriangleElement(const int p)
: VectorFiniteElement(2, Geometry::TRIANGLE, (p + 1)*(p + 3), p + 1,
H_DIV, FunctionSpace::Pk),
dof2nk(dof)
{
const double *iop = (p > 0) ? poly1d.OpenPoints(p - 1) : NULL;
const double *bop = poly1d.OpenPoints(p);
#ifndef MFEM_THREAD_SAFE
shape_x.SetSize(p + 1);
shape_y.SetSize(p + 1);
shape_l.SetSize(p + 1);
dshape_x.SetSize(p + 1);
dshape_y.SetSize(p + 1);
dshape_l.SetSize(p + 1);
u.SetSize(dof, dim);
divu.SetSize(dof);
#else
Vector shape_x(p + 1), shape_y(p + 1), shape_l(p + 1);
#endif
// edges
int o = 0;
for (int i = 0; i <= p; i++) // (0,1)
{
Nodes.IntPoint(o).Set2(bop[i], 0.);
dof2nk[o++] = 0;
}
for (int i = 0; i <= p; i++) // (1,2)
{
Nodes.IntPoint(o).Set2(bop[p-i], bop[i]);
dof2nk[o++] = 1;
}
for (int i = 0; i <= p; i++) // (2,0)
{
Nodes.IntPoint(o).Set2(0., bop[p-i]);
dof2nk[o++] = 2;
}
// interior
for (int j = 0; j < p; j++)
for (int i = 0; i + j < p; i++)
{
double w = iop[i] + iop[j] + iop[p-1-i-j];
Nodes.IntPoint(o).Set2(iop[i]/w, iop[j]/w);
dof2nk[o++] = 0;
Nodes.IntPoint(o).Set2(iop[i]/w, iop[j]/w);
dof2nk[o++] = 2;
}
DenseMatrix T(dof);
for (int k = 0; k < dof; k++)
{
const IntegrationPoint &ip = Nodes.IntPoint(k);
poly1d.CalcBasis(p, ip.x, shape_x);
poly1d.CalcBasis(p, ip.y, shape_y);
poly1d.CalcBasis(p, 1. - ip.x - ip.y, shape_l);
const double *n_k = nk + 2*dof2nk[k];
o = 0;
for (int j = 0; j <= p; j++)
for (int i = 0; i + j <= p; i++)
{
double s = shape_x(i)*shape_y(j)*shape_l(p-i-j);
T(o++, k) = s*n_k[0];
T(o++, k) = s*n_k[1];
}
for (int i = 0; i <= p; i++)
{
double s = shape_x(i)*shape_y(p-i);
T(o++, k) = s*((ip.x - c)*n_k[0] + (ip.y - c)*n_k[1]);
}
}
Ti.Factor(T);
// mfem::out << "RT_TriangleElement(" << p << ") : "; Ti.TestInversion();
}
void RT_TriangleElement::CalcVShape(const IntegrationPoint &ip,
DenseMatrix &shape) const
{
const int p = order - 1;
#ifdef MFEM_THREAD_SAFE
Vector shape_x(p + 1), shape_y(p + 1), shape_l(p + 1);
DenseMatrix u(dof, dim);
#endif
poly1d.CalcBasis(p, ip.x, shape_x);
poly1d.CalcBasis(p, ip.y, shape_y);
poly1d.CalcBasis(p, 1. - ip.x - ip.y, shape_l);
int o = 0;
for (int j = 0; j <= p; j++)
for (int i = 0; i + j <= p; i++)
{
double s = shape_x(i)*shape_y(j)*shape_l(p-i-j);
u(o,0) = s; u(o,1) = 0; o++;
u(o,0) = 0; u(o,1) = s; o++;
}
for (int i = 0; i <= p; i++)
{
double s = shape_x(i)*shape_y(p-i);
u(o,0) = (ip.x - c)*s;
u(o,1) = (ip.y - c)*s;
o++;
}
Ti.Mult(u, shape);
}
void RT_TriangleElement::CalcDivShape(const IntegrationPoint &ip,
Vector &divshape) const
{
const int p = order - 1;
#ifdef MFEM_THREAD_SAFE
Vector shape_x(p + 1), shape_y(p + 1), shape_l(p + 1);
Vector dshape_x(p + 1), dshape_y(p + 1), dshape_l(p + 1);
Vector divu(dof);
#endif
poly1d.CalcBasis(p, ip.x, shape_x, dshape_x);
poly1d.CalcBasis(p, ip.y, shape_y, dshape_y);
poly1d.CalcBasis(p, 1. - ip.x - ip.y, shape_l, dshape_l);
int o = 0;
for (int j = 0; j <= p; j++)
for (int i = 0; i + j <= p; i++)
{
int k = p - i - j;
divu(o++) = (dshape_x(i)*shape_l(k) -
shape_x(i)*dshape_l(k))*shape_y(j);
divu(o++) = (dshape_y(j)*shape_l(k) -
shape_y(j)*dshape_l(k))*shape_x(i);
}
for (int i = 0; i <= p; i++)
{
int j = p - i;
divu(o++) = ((shape_x(i) + (ip.x - c)*dshape_x(i))*shape_y(j) +
(shape_y(j) + (ip.y - c)*dshape_y(j))*shape_x(i));
}
Ti.Mult(divu, divshape);
}
const double RT_TetrahedronElement::nk[12] =
{ 1,1,1, -1,0,0, 0,-1,0, 0,0,-1 };
// { .5,.5,.5, -.5,0,0, 0,-.5,0, 0,0,-.5}; // n_F |F|
const double RT_TetrahedronElement::c = 1./4.;
RT_TetrahedronElement::RT_TetrahedronElement(const int p)
: VectorFiniteElement(3, Geometry::TETRAHEDRON, (p + 1)*(p + 2)*(p + 4)/2,
p + 1, H_DIV, FunctionSpace::Pk),
dof2nk(dof)
{
const double *iop = (p > 0) ? poly1d.OpenPoints(p - 1) : NULL;
const double *bop = poly1d.OpenPoints(p);
#ifndef MFEM_THREAD_SAFE
shape_x.SetSize(p + 1);
shape_y.SetSize(p + 1);
shape_z.SetSize(p + 1);
shape_l.SetSize(p + 1);
dshape_x.SetSize(p + 1);
dshape_y.SetSize(p + 1);
dshape_z.SetSize(p + 1);
dshape_l.SetSize(p + 1);
u.SetSize(dof, dim);
divu.SetSize(dof);
#else
Vector shape_x(p + 1), shape_y(p + 1), shape_z(p + 1), shape_l(p + 1);
#endif
int o = 0;
// faces (see Mesh::GenerateFaces in mesh/mesh.cpp,
// the constructor of H1_TetrahedronElement)
for (int j = 0; j <= p; j++)
for (int i = 0; i + j <= p; i++) // (1,2,3)
{
double w = bop[i] + bop[j] + bop[p-i-j];
Nodes.IntPoint(o).Set3(bop[p-i-j]/w, bop[i]/w, bop[j]/w);
dof2nk[o++] = 0;
}
for (int j = 0; j <= p; j++)
for (int i = 0; i + j <= p; i++) // (0,3,2)
{
double w = bop[i] + bop[j] + bop[p-i-j];
Nodes.IntPoint(o).Set3(0., bop[j]/w, bop[i]/w);
dof2nk[o++] = 1;
}
for (int j = 0; j <= p; j++)
for (int i = 0; i + j <= p; i++) // (0,1,3)
{
double w = bop[i] + bop[j] + bop[p-i-j];
Nodes.IntPoint(o).Set3(bop[i]/w, 0., bop[j]/w);
dof2nk[o++] = 2;
}
for (int j = 0; j <= p; j++)
for (int i = 0; i + j <= p; i++) // (0,2,1)
{
double w = bop[i] + bop[j] + bop[p-i-j];
Nodes.IntPoint(o).Set3(bop[j]/w, bop[i]/w, 0.);
dof2nk[o++] = 3;
}
// interior
for (int k = 0; k < p; k++)
for (int j = 0; j + k < p; j++)
for (int i = 0; i + j + k < p; i++)
{
double w = iop[i] + iop[j] + iop[k] + iop[p-1-i-j-k];
Nodes.IntPoint(o).Set3(iop[i]/w, iop[j]/w, iop[k]/w);
dof2nk[o++] = 1;
Nodes.IntPoint(o).Set3(iop[i]/w, iop[j]/w, iop[k]/w);
dof2nk[o++] = 2;
Nodes.IntPoint(o).Set3(iop[i]/w, iop[j]/w, iop[k]/w);
dof2nk[o++] = 3;
}
DenseMatrix T(dof);
for (int m = 0; m < dof; m++)
{
const IntegrationPoint &ip = Nodes.IntPoint(m);
poly1d.CalcBasis(p, ip.x, shape_x);
poly1d.CalcBasis(p, ip.y, shape_y);
poly1d.CalcBasis(p, ip.z, shape_z);
poly1d.CalcBasis(p, 1. - ip.x - ip.y - ip.z, shape_l);
const double *nm = nk + 3*dof2nk[m];
o = 0;
for (int k = 0; k <= p; k++)
for (int j = 0; j + k <= p; j++)
for (int i = 0; i + j + k <= p; i++)
{
double s = shape_x(i)*shape_y(j)*shape_z(k)*shape_l(p-i-j-k);
T(o++, m) = s * nm[0];
T(o++, m) = s * nm[1];
T(o++, m) = s * nm[2];
}
for (int j = 0; j <= p; j++)
for (int i = 0; i + j <= p; i++)
{
double s = shape_x(i)*shape_y(j)*shape_z(p-i-j);
T(o++, m) = s*((ip.x - c)*nm[0] + (ip.y - c)*nm[1] +
(ip.z - c)*nm[2]);
}
}
Ti.Factor(T);
// mfem::out << "RT_TetrahedronElement(" << p << ") : "; Ti.TestInversion();
}
void RT_TetrahedronElement::CalcVShape(const IntegrationPoint &ip,
DenseMatrix &shape) const
{
const int p = order - 1;
#ifdef MFEM_THREAD_SAFE
Vector shape_x(p + 1), shape_y(p + 1), shape_z(p + 1), shape_l(p + 1);
DenseMatrix u(dof, dim);
#endif
poly1d.CalcBasis(p, ip.x, shape_x);
poly1d.CalcBasis(p, ip.y, shape_y);
poly1d.CalcBasis(p, ip.z, shape_z);
poly1d.CalcBasis(p, 1. - ip.x - ip.y - ip.z, shape_l);
int o = 0;
for (int k = 0; k <= p; k++)
for (int j = 0; j + k <= p; j++)
for (int i = 0; i + j + k <= p; i++)
{
double s = shape_x(i)*shape_y(j)*shape_z(k)*shape_l(p-i-j-k);
u(o,0) = s; u(o,1) = 0; u(o,2) = 0; o++;
u(o,0) = 0; u(o,1) = s; u(o,2) = 0; o++;
u(o,0) = 0; u(o,1) = 0; u(o,2) = s; o++;
}
for (int j = 0; j <= p; j++)
for (int i = 0; i + j <= p; i++)
{
double s = shape_x(i)*shape_y(j)*shape_z(p-i-j);
u(o,0) = (ip.x - c)*s; u(o,1) = (ip.y - c)*s; u(o,2) = (ip.z - c)*s;
o++;
}
Ti.Mult(u, shape);
}
void RT_TetrahedronElement::CalcDivShape(const IntegrationPoint &ip,
Vector &divshape) const
{
const int p = order - 1;
#ifdef MFEM_THREAD_SAFE
Vector shape_x(p + 1), shape_y(p + 1), shape_z(p + 1), shape_l(p + 1);
Vector dshape_x(p + 1), dshape_y(p + 1), dshape_z(p + 1), dshape_l(p + 1);
Vector divu(dof);
#endif
poly1d.CalcBasis(p, ip.x, shape_x, dshape_x);
poly1d.CalcBasis(p, ip.y, shape_y, dshape_y);
poly1d.CalcBasis(p, ip.z, shape_z, dshape_z);
poly1d.CalcBasis(p, 1. - ip.x - ip.y - ip.z, shape_l, dshape_l);
int o = 0;
for (int k = 0; k <= p; k++)
for (int j = 0; j + k <= p; j++)
for (int i = 0; i + j + k <= p; i++)
{
int l = p - i - j - k;
divu(o++) = (dshape_x(i)*shape_l(l) -
shape_x(i)*dshape_l(l))*shape_y(j)*shape_z(k);
divu(o++) = (dshape_y(j)*shape_l(l) -
shape_y(j)*dshape_l(l))*shape_x(i)*shape_z(k);
divu(o++) = (dshape_z(k)*shape_l(l) -
shape_z(k)*dshape_l(l))*shape_x(i)*shape_y(j);
}
for (int j = 0; j <= p; j++)
for (int i = 0; i + j <= p; i++)
{
int k = p - i - j;
divu(o++) =
(shape_x(i) + (ip.x - c)*dshape_x(i))*shape_y(j)*shape_z(k) +
(shape_y(j) + (ip.y - c)*dshape_y(j))*shape_x(i)*shape_z(k) +
(shape_z(k) + (ip.z - c)*dshape_z(k))*shape_x(i)*shape_y(j);
}
Ti.Mult(divu, divshape);
}
const double ND_HexahedronElement::tk[18] =
{ 1.,0.,0., 0.,1.,0., 0.,0.,1., -1.,0.,0., 0.,-1.,0., 0.,0.,-1. };
ND_HexahedronElement::ND_HexahedronElement(const int p,
const int cb_type, const int ob_type)
: VectorTensorFiniteElement(3, 3*p*(p + 1)*(p + 1), p, cb_type, ob_type,
H_CURL, DofMapType::L2_DOF_MAP),
dof2tk(dof)
{
dof_map.SetSize(dof);
const double *cp = poly1d.ClosedPoints(p, cb_type);
const double *op = poly1d.OpenPoints(p - 1, ob_type);
const int dof3 = dof/3;
#ifndef MFEM_THREAD_SAFE
shape_cx.SetSize(p + 1);
shape_ox.SetSize(p);
shape_cy.SetSize(p + 1);
shape_oy.SetSize(p);
shape_cz.SetSize(p + 1);
shape_oz.SetSize(p);
dshape_cx.SetSize(p + 1);
dshape_cy.SetSize(p + 1);
dshape_cz.SetSize(p + 1);
#endif
// edges
int o = 0;
for (int i = 0; i < p; i++) // (0,1)
{
dof_map[0*dof3 + i + (0 + 0*(p + 1))*p] = o++;
}
for (int i = 0; i < p; i++) // (1,2)
{
dof_map[1*dof3 + p + (i + 0*p)*(p + 1)] = o++;
}
for (int i = 0; i < p; i++) // (3,2)
{
dof_map[0*dof3 + i + (p + 0*(p + 1))*p] = o++;
}
for (int i = 0; i < p; i++) // (0,3)
{
dof_map[1*dof3 + 0 + (i + 0*p)*(p + 1)] = o++;
}
for (int i = 0; i < p; i++) // (4,5)
{
dof_map[0*dof3 + i + (0 + p*(p + 1))*p] = o++;
}
for (int i = 0; i < p; i++) // (5,6)
{
dof_map[1*dof3 + p + (i + p*p)*(p + 1)] = o++;
}
for (int i = 0; i < p; i++) // (7,6)
{
dof_map[0*dof3 + i + (p + p*(p + 1))*p] = o++;
}
for (int i = 0; i < p; i++) // (4,7)
{
dof_map[1*dof3 + 0 + (i + p*p)*(p + 1)] = o++;
}
for (int i = 0; i < p; i++) // (0,4)
{
dof_map[2*dof3 + 0 + (0 + i*(p + 1))*(p + 1)] = o++;
}
for (int i = 0; i < p; i++) // (1,5)
{
dof_map[2*dof3 + p + (0 + i*(p + 1))*(p + 1)] = o++;
}
for (int i = 0; i < p; i++) // (2,6)
{
dof_map[2*dof3 + p + (p + i*(p + 1))*(p + 1)] = o++;
}
for (int i = 0; i < p; i++) // (3,7)
{
dof_map[2*dof3 + 0 + (p + i*(p + 1))*(p + 1)] = o++;
}
// faces
// (3,2,1,0) -- bottom
for (int j = 1; j < p; j++) // x - components
for (int i = 0; i < p; i++)
{
dof_map[0*dof3 + i + ((p - j) + 0*(p + 1))*p] = o++;
}
for (int j = 0; j < p; j++) // y - components
for (int i = 1; i < p; i++)
{
dof_map[1*dof3 + i + ((p - 1 - j) + 0*p)*(p + 1)] = -1 - (o++);
}
// (0,1,5,4) -- front
for (int k = 1; k < p; k++) // x - components
for (int i = 0; i < p; i++)
{
dof_map[0*dof3 + i + (0 + k*(p + 1))*p] = o++;
}
for (int k = 0; k < p; k++) // z - components
for (int i = 1; i < p; i++ )
{
dof_map[2*dof3 + i + (0 + k*(p + 1))*(p + 1)] = o++;
}
// (1,2,6,5) -- right
for (int k = 1; k < p; k++) // y - components
for (int j = 0; j < p; j++)
{
dof_map[1*dof3 + p + (j + k*p)*(p + 1)] = o++;
}
for (int k = 0; k < p; k++) // z - components
for (int j = 1; j < p; j++)
{
dof_map[2*dof3 + p + (j + k*(p + 1))*(p + 1)] = o++;
}
// (2,3,7,6) -- back
for (int k = 1; k < p; k++) // x - components
for (int i = 0; i < p; i++)
{
dof_map[0*dof3 + (p - 1 - i) + (p + k*(p + 1))*p] = -1 - (o++);
}
for (int k = 0; k < p; k++) // z - components
for (int i = 1; i < p; i++)
{
dof_map[2*dof3 + (p - i) + (p + k*(p + 1))*(p + 1)] = o++;
}
// (3,0,4,7) -- left
for (int k = 1; k < p; k++) // y - components
for (int j = 0; j < p; j++)
{
dof_map[1*dof3 + 0 + ((p - 1 - j) + k*p)*(p + 1)] = -1 - (o++);
}
for (int k = 0; k < p; k++) // z - components
for (int j = 1; j < p; j++)
{
dof_map[2*dof3 + 0 + ((p - j) + k*(p + 1))*(p + 1)] = o++;
}
// (4,5,6,7) -- top
for (int j = 1; j < p; j++) // x - components
for (int i = 0; i < p; i++)
{
dof_map[0*dof3 + i + (j + p*(p + 1))*p] = o++;
}
for (int j = 0; j < p; j++) // y - components
for (int i = 1; i < p; i++)
{
dof_map[1*dof3 + i + (j + p*p)*(p + 1)] = o++;
}
// interior
// x-components
for (int k = 1; k < p; k++)
for (int j = 1; j < p; j++)
for (int i = 0; i < p; i++)
{
dof_map[0*dof3 + i + (j + k*(p + 1))*p] = o++;
}
// y-components
for (int k = 1; k < p; k++)
for (int j = 0; j < p; j++)
for (int i = 1; i < p; i++)
{
dof_map[1*dof3 + i + (j + k*p)*(p + 1)] = o++;
}
// z-components
for (int k = 0; k < p; k++)
for (int j = 1; j < p; j++)
for (int i = 1; i < p; i++)
{
dof_map[2*dof3 + i + (j + k*(p + 1))*(p + 1)] = o++;
}
// set dof2tk and Nodes
o = 0;
// x-components
for (int k = 0; k <= p; k++)
for (int j = 0; j <= p; j++)
for (int i = 0; i < p; i++)
{
int idx;
if ((idx = dof_map[o++]) < 0)
{
dof2tk[idx = -1 - idx] = 3;
}
else
{
dof2tk[idx] = 0;
}
Nodes.IntPoint(idx).Set3(op[i], cp[j], cp[k]);
}
// y-components
for (int k = 0; k <= p; k++)
for (int j = 0; j < p; j++)
for (int i = 0; i <= p; i++)
{
int idx;
if ((idx = dof_map[o++]) < 0)
{
dof2tk[idx = -1 - idx] = 4;
}
else
{
dof2tk[idx] = 1;
}
Nodes.IntPoint(idx).Set3(cp[i], op[j], cp[k]);
}
// z-components
for (int k = 0; k < p; k++)
for (int j = 0; j <= p; j++)
for (int i = 0; i <= p; i++)
{
int idx;
if ((idx = dof_map[o++]) < 0)
{
dof2tk[idx = -1 - idx] = 5;
}
else
{
dof2tk[idx] = 2;
}
Nodes.IntPoint(idx).Set3(cp[i], cp[j], op[k]);
}
}
void ND_HexahedronElement::CalcVShape(const IntegrationPoint &ip,
DenseMatrix &shape) const
{
const int p = order;
#ifdef MFEM_THREAD_SAFE
Vector shape_cx(p + 1), shape_ox(p), shape_cy(p + 1), shape_oy(p);
Vector shape_cz(p + 1), shape_oz(p);
#endif
cbasis1d.Eval(ip.x, shape_cx);
obasis1d.Eval(ip.x, shape_ox);
cbasis1d.Eval(ip.y, shape_cy);
obasis1d.Eval(ip.y, shape_oy);
cbasis1d.Eval(ip.z, shape_cz);
obasis1d.Eval(ip.z, shape_oz);
int o = 0;
// x-components
for (int k = 0; k <= p; k++)
for (int j = 0; j <= p; j++)
for (int i = 0; i < p; i++)
{
int idx, s;
if ((idx = dof_map[o++]) < 0)
{
idx = -1 - idx, s = -1;
}
else
{
s = +1;
}
shape(idx,0) = s*shape_ox(i)*shape_cy(j)*shape_cz(k);
shape(idx,1) = 0.;
shape(idx,2) = 0.;
}
// y-components
for (int k = 0; k <= p; k++)
for (int j = 0; j < p; j++)
for (int i = 0; i <= p; i++)
{
int idx, s;
if ((idx = dof_map[o++]) < 0)
{
idx = -1 - idx, s = -1;
}
else
{
s = +1;
}
shape(idx,0) = 0.;
shape(idx,1) = s*shape_cx(i)*shape_oy(j)*shape_cz(k);
shape(idx,2) = 0.;
}
// z-components
for (int k = 0; k < p; k++)
for (int j = 0; j <= p; j++)
for (int i = 0; i <= p; i++)
{
int idx, s;
if ((idx = dof_map[o++]) < 0)
{
idx = -1 - idx, s = -1;
}
else
{
s = +1;
}
shape(idx,0) = 0.;
shape(idx,1) = 0.;
shape(idx,2) = s*shape_cx(i)*shape_cy(j)*shape_oz(k);
}
}
void ND_HexahedronElement::CalcCurlShape(const IntegrationPoint &ip,
DenseMatrix &curl_shape) const
{
const int p = order;
#ifdef MFEM_THREAD_SAFE
Vector shape_cx(p + 1), shape_ox(p), shape_cy(p + 1), shape_oy(p);
Vector shape_cz(p + 1), shape_oz(p);
Vector dshape_cx(p + 1), dshape_cy(p + 1), dshape_cz(p + 1);
#endif
cbasis1d.Eval(ip.x, shape_cx, dshape_cx);
obasis1d.Eval(ip.x, shape_ox);
cbasis1d.Eval(ip.y, shape_cy, dshape_cy);
obasis1d.Eval(ip.y, shape_oy);
cbasis1d.Eval(ip.z, shape_cz, dshape_cz);
obasis1d.Eval(ip.z, shape_oz);
int o = 0;
// x-components
for (int k = 0; k <= p; k++)
for (int j = 0; j <= p; j++)
for (int i = 0; i < p; i++)
{
int idx, s;
if ((idx = dof_map[o++]) < 0)
{
idx = -1 - idx, s = -1;
}
else
{
s = +1;
}
curl_shape(idx,0) = 0.;
curl_shape(idx,1) = s*shape_ox(i)* shape_cy(j)*dshape_cz(k);
curl_shape(idx,2) = -s*shape_ox(i)*dshape_cy(j)* shape_cz(k);
}
// y-components
for (int k = 0; k <= p; k++)
for (int j = 0; j < p; j++)
for (int i = 0; i <= p; i++)
{
int idx, s;
if ((idx = dof_map[o++]) < 0)
{
idx = -1 - idx, s = -1;
}
else
{
s = +1;
}
curl_shape(idx,0) = -s* shape_cx(i)*shape_oy(j)*dshape_cz(k);
curl_shape(idx,1) = 0.;
curl_shape(idx,2) = s*dshape_cx(i)*shape_oy(j)* shape_cz(k);
}
// z-components
for (int k = 0; k < p; k++)
for (int j = 0; j <= p; j++)
for (int i = 0; i <= p; i++)
{
int idx, s;
if ((idx = dof_map[o++]) < 0)
{
idx = -1 - idx, s = -1;
}
else
{
s = +1;
}
curl_shape(idx,0) = s* shape_cx(i)*dshape_cy(j)*shape_oz(k);
curl_shape(idx,1) = -s*dshape_cx(i)* shape_cy(j)*shape_oz(k);
curl_shape(idx,2) = 0.;
}
}
const DofToQuad &VectorTensorFiniteElement::GetDofToQuad(
const IntegrationRule &ir,
DofToQuad::Mode mode) const
{
MFEM_VERIFY(mode != DofToQuad::FULL, "invalid mode requested");
return GetTensorDofToQuad(ir, mode, true);
}
const DofToQuad &VectorTensorFiniteElement::GetDofToQuadOpen(
const IntegrationRule &ir,
DofToQuad::Mode mode) const
{
MFEM_VERIFY(mode != DofToQuad::FULL, "invalid mode requested");
return GetTensorDofToQuad(ir, mode, false);
}
const DofToQuad &VectorTensorFiniteElement::GetTensorDofToQuad(
const IntegrationRule &ir,
DofToQuad::Mode mode,
const bool closed) const
{
MFEM_VERIFY(mode == DofToQuad::TENSOR, "invalid mode requested");
for (int i = 0;
i < (closed ? dof2quad_array.Size() : dof2quad_array_open.Size());
i++)
{
const DofToQuad &d2q = closed ? *dof2quad_array[i] : *dof2quad_array_open[i];
if (d2q.IntRule == &ir && d2q.mode == mode) { return d2q; }
}
DofToQuad *d2q = new DofToQuad;
const int ndof = closed ? order + 1 : order;
const int nqpt = (int)floor(pow(ir.GetNPoints(), 1.0/dim) + 0.5);
d2q->FE = this;
d2q->IntRule = &ir;
d2q->mode = mode;
d2q->ndof = ndof;
d2q->nqpt = nqpt;
d2q->B.SetSize(nqpt*ndof);
d2q->Bt.SetSize(ndof*nqpt);
d2q->G.SetSize(nqpt*ndof);
d2q->Gt.SetSize(ndof*nqpt);
Vector val(ndof), grad(ndof);
for (int i = 0; i < nqpt; i++)
{
// The first 'nqpt' points in 'ir' have the same x-coordinates as those
// of the 1D rule.
if (closed)
{
cbasis1d.Eval(ir.IntPoint(i).x, val, grad);
}
else
{
obasis1d.Eval(ir.IntPoint(i).x, val, grad);
}
for (int j = 0; j < ndof; j++)
{
d2q->B[i+nqpt*j] = d2q->Bt[j+ndof*i] = val(j);
d2q->G[i+nqpt*j] = d2q->Gt[j+ndof*i] = grad(j);
}
}
if (closed)
{
dof2quad_array.Append(d2q);
}
else
{
dof2quad_array_open.Append(d2q);
}
return *d2q;
}
VectorTensorFiniteElement::~VectorTensorFiniteElement()
{
for (int i = 0; i < dof2quad_array_open.Size(); i++)
{
delete dof2quad_array_open[i];
}
}
const double ND_QuadrilateralElement::tk[8] =
{ 1.,0., 0.,1., -1.,0., 0.,-1. };
ND_QuadrilateralElement::ND_QuadrilateralElement(const int p,
const int cb_type,
const int ob_type)
: VectorTensorFiniteElement(2, 2*p*(p + 1), p, cb_type, ob_type,
H_CURL, DofMapType::L2_DOF_MAP),
dof2tk(dof)
{
dof_map.SetSize(dof);
const double *cp = poly1d.ClosedPoints(p, cb_type);
const double *op = poly1d.OpenPoints(p - 1, ob_type);
const int dof2 = dof/2;
#ifndef MFEM_THREAD_SAFE
shape_cx.SetSize(p + 1);
shape_ox.SetSize(p);
shape_cy.SetSize(p + 1);
shape_oy.SetSize(p);
dshape_cx.SetSize(p + 1);
dshape_cy.SetSize(p + 1);
#endif
// edges
int o = 0;
for (int i = 0; i < p; i++) // (0,1)
{
dof_map[0*dof2 + i + 0*p] = o++;
}
for (int j = 0; j < p; j++) // (1,2)
{
dof_map[1*dof2 + p + j*(p + 1)] = o++;
}
for (int i = 0; i < p; i++) // (2,3)
{
dof_map[0*dof2 + (p - 1 - i) + p*p] = -1 - (o++);
}
for (int j = 0; j < p; j++) // (3,0)
{
dof_map[1*dof2 + 0 + (p - 1 - j)*(p + 1)] = -1 - (o++);
}
// interior
// x-components
for (int j = 1; j < p; j++)
for (int i = 0; i < p; i++)
{
dof_map[0*dof2 + i + j*p] = o++;
}
// y-components
for (int j = 0; j < p; j++)
for (int i = 1; i < p; i++)
{
dof_map[1*dof2 + i + j*(p + 1)] = o++;
}
// set dof2tk and Nodes
o = 0;
// x-components
for (int j = 0; j <= p; j++)
for (int i = 0; i < p; i++)
{
int idx;
if ((idx = dof_map[o++]) < 0)
{
dof2tk[idx = -1 - idx] = 2;
}
else
{
dof2tk[idx] = 0;
}
Nodes.IntPoint(idx).Set2(op[i], cp[j]);
}
// y-components
for (int j = 0; j < p; j++)
for (int i = 0; i <= p; i++)
{
int idx;
if ((idx = dof_map[o++]) < 0)
{
dof2tk[idx = -1 - idx] = 3;
}
else
{
dof2tk[idx] = 1;
}
Nodes.IntPoint(idx).Set2(cp[i], op[j]);
}
}
void ND_QuadrilateralElement::CalcVShape(const IntegrationPoint &ip,
DenseMatrix &shape) const
{
const int p = order;
#ifdef MFEM_THREAD_SAFE
Vector shape_cx(p + 1), shape_ox(p), shape_cy(p + 1), shape_oy(p);
#endif
cbasis1d.Eval(ip.x, shape_cx);
obasis1d.Eval(ip.x, shape_ox);
cbasis1d.Eval(ip.y, shape_cy);
obasis1d.Eval(ip.y, shape_oy);
int o = 0;
// x-components
for (int j = 0; j <= p; j++)
for (int i = 0; i < p; i++)
{
int idx, s;
if ((idx = dof_map[o++]) < 0)
{
idx = -1 - idx, s = -1;
}
else
{
s = +1;
}
shape(idx,0) = s*shape_ox(i)*shape_cy(j);
shape(idx,1) = 0.;
}
// y-components
for (int j = 0; j < p; j++)
for (int i = 0; i <= p; i++)
{
int idx, s;
if ((idx = dof_map[o++]) < 0)
{
idx = -1 - idx, s = -1;
}
else
{
s = +1;
}
shape(idx,0) = 0.;
shape(idx,1) = s*shape_cx(i)*shape_oy(j);
}
}
void ND_QuadrilateralElement::CalcCurlShape(const IntegrationPoint &ip,
DenseMatrix &curl_shape) const
{
const int p = order;
#ifdef MFEM_THREAD_SAFE
Vector shape_cx(p + 1), shape_ox(p), shape_cy(p + 1), shape_oy(p);
Vector dshape_cx(p + 1), dshape_cy(p + 1);
#endif
cbasis1d.Eval(ip.x, shape_cx, dshape_cx);
obasis1d.Eval(ip.x, shape_ox);
cbasis1d.Eval(ip.y, shape_cy, dshape_cy);
obasis1d.Eval(ip.y, shape_oy);
int o = 0;
// x-components
for (int j = 0; j <= p; j++)
for (int i = 0; i < p; i++)
{
int idx, s;
if ((idx = dof_map[o++]) < 0)
{
idx = -1 - idx, s = -1;
}
else
{
s = +1;
}
curl_shape(idx,0) = -s*shape_ox(i)*dshape_cy(j);
}
// y-components
for (int j = 0; j < p; j++)
for (int i = 0; i <= p; i++)
{
int idx, s;
if ((idx = dof_map[o++]) < 0)
{
idx = -1 - idx, s = -1;
}
else
{
s = +1;
}
curl_shape(idx,0) = s*dshape_cx(i)*shape_oy(j);
}
}
const double ND_TetrahedronElement::tk[18] =
{ 1.,0.,0., 0.,1.,0., 0.,0.,1., -1.,1.,0., -1.,0.,1., 0.,-1.,1. };
const double ND_TetrahedronElement::c = 1./4.;
ND_TetrahedronElement::ND_TetrahedronElement(const int p)
: VectorFiniteElement(3, Geometry::TETRAHEDRON, p*(p + 2)*(p + 3)/2, p,
H_CURL, FunctionSpace::Pk), dof2tk(dof)
{
const double *eop = poly1d.OpenPoints(p - 1);
const double *fop = (p > 1) ? poly1d.OpenPoints(p - 2) : NULL;
const double *iop = (p > 2) ? poly1d.OpenPoints(p - 3) : NULL;
const int pm1 = p - 1, pm2 = p - 2, pm3 = p - 3;
#ifndef MFEM_THREAD_SAFE
shape_x.SetSize(p);
shape_y.SetSize(p);
shape_z.SetSize(p);
shape_l.SetSize(p);
dshape_x.SetSize(p);
dshape_y.SetSize(p);
dshape_z.SetSize(p);
dshape_l.SetSize(p);
u.SetSize(dof, dim);
#else
Vector shape_x(p), shape_y(p), shape_z(p), shape_l(p);
#endif
int o = 0;
// edges
for (int i = 0; i < p; i++) // (0,1)
{
Nodes.IntPoint(o).Set3(eop[i], 0., 0.);
dof2tk[o++] = 0;
}
for (int i = 0; i < p; i++) // (0,2)
{
Nodes.IntPoint(o).Set3(0., eop[i], 0.);
dof2tk[o++] = 1;
}
for (int i = 0; i < p; i++) // (0,3)
{
Nodes.IntPoint(o).Set3(0., 0., eop[i]);
dof2tk[o++] = 2;
}
for (int i = 0; i < p; i++) // (1,2)
{
Nodes.IntPoint(o).Set3(eop[pm1-i], eop[i], 0.);
dof2tk[o++] = 3;
}
for (int i = 0; i < p; i++) // (1,3)
{
Nodes.IntPoint(o).Set3(eop[pm1-i], 0., eop[i]);
dof2tk[o++] = 4;
}
for (int i = 0; i < p; i++) // (2,3)
{
Nodes.IntPoint(o).Set3(0., eop[pm1-i], eop[i]);
dof2tk[o++] = 5;
}
// faces
for (int j = 0; j <= pm2; j++) // (1,2,3)
for (int i = 0; i + j <= pm2; i++)
{
double w = fop[i] + fop[j] + fop[pm2-i-j];
Nodes.IntPoint(o).Set3(fop[pm2-i-j]/w, fop[i]/w, fop[j]/w);
dof2tk[o++] = 3;
Nodes.IntPoint(o).Set3(fop[pm2-i-j]/w, fop[i]/w, fop[j]/w);
dof2tk[o++] = 4;
}
for (int j = 0; j <= pm2; j++) // (0,3,2)
for (int i = 0; i + j <= pm2; i++)
{
double w = fop[i] + fop[j] + fop[pm2-i-j];
Nodes.IntPoint(o).Set3(0., fop[j]/w, fop[i]/w);
dof2tk[o++] = 2;
Nodes.IntPoint(o).Set3(0., fop[j]/w, fop[i]/w);
dof2tk[o++] = 1;
}
for (int j = 0; j <= pm2; j++) // (0,1,3)
for (int i = 0; i + j <= pm2; i++)
{
double w = fop[i] + fop[j] + fop[pm2-i-j];
Nodes.IntPoint(o).Set3(fop[i]/w, 0., fop[j]/w);
dof2tk[o++] = 0;
Nodes.IntPoint(o).Set3(fop[i]/w, 0., fop[j]/w);
dof2tk[o++] = 2;
}
for (int j = 0; j <= pm2; j++) // (0,2,1)
for (int i = 0; i + j <= pm2; i++)
{
double w = fop[i] + fop[j] + fop[pm2-i-j];
Nodes.IntPoint(o).Set3(fop[j]/w, fop[i]/w, 0.);
dof2tk[o++] = 1;
Nodes.IntPoint(o).Set3(fop[j]/w, fop[i]/w, 0.);
dof2tk[o++] = 0;
}
// interior
for (int k = 0; k <= pm3; k++)
for (int j = 0; j + k <= pm3; j++)
for (int i = 0; i + j + k <= pm3; i++)
{
double w = iop[i] + iop[j] + iop[k] + iop[pm3-i-j-k];
Nodes.IntPoint(o).Set3(iop[i]/w, iop[j]/w, iop[k]/w);
dof2tk[o++] = 0;
Nodes.IntPoint(o).Set3(iop[i]/w, iop[j]/w, iop[k]/w);
dof2tk[o++] = 1;
Nodes.IntPoint(o).Set3(iop[i]/w, iop[j]/w, iop[k]/w);
dof2tk[o++] = 2;
}
DenseMatrix T(dof);
for (int m = 0; m < dof; m++)
{
const IntegrationPoint &ip = Nodes.IntPoint(m);
const double *tm = tk + 3*dof2tk[m];
o = 0;
poly1d.CalcBasis(pm1, ip.x, shape_x);
poly1d.CalcBasis(pm1, ip.y, shape_y);
poly1d.CalcBasis(pm1, ip.z, shape_z);
poly1d.CalcBasis(pm1, 1. - ip.x - ip.y - ip.z, shape_l);
for (int k = 0; k <= pm1; k++)
for (int j = 0; j + k <= pm1; j++)
for (int i = 0; i + j + k <= pm1; i++)
{
double s = shape_x(i)*shape_y(j)*shape_z(k)*shape_l(pm1-i-j-k);
T(o++, m) = s * tm[0];
T(o++, m) = s * tm[1];
T(o++, m) = s * tm[2];
}
for (int k = 0; k <= pm1; k++)
for (int j = 0; j + k <= pm1; j++)
{
double s = shape_x(pm1-j-k)*shape_y(j)*shape_z(k);
T(o++, m) = s*((ip.y - c)*tm[0] - (ip.x - c)*tm[1]);
T(o++, m) = s*((ip.z - c)*tm[0] - (ip.x - c)*tm[2]);
}
for (int k = 0; k <= pm1; k++)
{
T(o++, m) =
shape_y(pm1-k)*shape_z(k)*((ip.z - c)*tm[1] - (ip.y - c)*tm[2]);
}
}
Ti.Factor(T);
// mfem::out << "ND_TetrahedronElement(" << p << ") : "; Ti.TestInversion();
}
void ND_TetrahedronElement::CalcVShape(const IntegrationPoint &ip,
DenseMatrix &shape) const
{
const int pm1 = order - 1;
#ifdef MFEM_THREAD_SAFE
const int p = order;
Vector shape_x(p), shape_y(p), shape_z(p), shape_l(p);
DenseMatrix u(dof, dim);
#endif
poly1d.CalcBasis(pm1, ip.x, shape_x);
poly1d.CalcBasis(pm1, ip.y, shape_y);
poly1d.CalcBasis(pm1, ip.z, shape_z);
poly1d.CalcBasis(pm1, 1. - ip.x - ip.y - ip.z, shape_l);
int n = 0;
for (int k = 0; k <= pm1; k++)
for (int j = 0; j + k <= pm1; j++)
for (int i = 0; i + j + k <= pm1; i++)
{
double s = shape_x(i)*shape_y(j)*shape_z(k)*shape_l(pm1-i-j-k);
u(n,0) = s; u(n,1) = 0.; u(n,2) = 0.; n++;
u(n,0) = 0.; u(n,1) = s; u(n,2) = 0.; n++;
u(n,0) = 0.; u(n,1) = 0.; u(n,2) = s; n++;
}
for (int k = 0; k <= pm1; k++)
for (int j = 0; j + k <= pm1; j++)
{
double s = shape_x(pm1-j-k)*shape_y(j)*shape_z(k);
u(n,0) = s*(ip.y - c); u(n,1) = -s*(ip.x - c); u(n,2) = 0.; n++;
u(n,0) = s*(ip.z - c); u(n,1) = 0.; u(n,2) = -s*(ip.x - c); n++;
}
for (int k = 0; k <= pm1; k++)
{
double s = shape_y(pm1-k)*shape_z(k);
u(n,0) = 0.; u(n,1) = s*(ip.z - c); u(n,2) = -s*(ip.y - c); n++;
}
Ti.Mult(u, shape);
}
void ND_TetrahedronElement::CalcCurlShape(const IntegrationPoint &ip,
DenseMatrix &curl_shape) const
{
const int pm1 = order - 1;
#ifdef MFEM_THREAD_SAFE
const int p = order;
Vector shape_x(p), shape_y(p), shape_z(p), shape_l(p);
Vector dshape_x(p), dshape_y(p), dshape_z(p), dshape_l(p);
DenseMatrix u(dof, dim);
#endif
poly1d.CalcBasis(pm1, ip.x, shape_x, dshape_x);
poly1d.CalcBasis(pm1, ip.y, shape_y, dshape_y);
poly1d.CalcBasis(pm1, ip.z, shape_z, dshape_z);
poly1d.CalcBasis(pm1, 1. - ip.x - ip.y - ip.z, shape_l, dshape_l);
int n = 0;
for (int k = 0; k <= pm1; k++)
for (int j = 0; j + k <= pm1; j++)
for (int i = 0; i + j + k <= pm1; i++)
{
int l = pm1-i-j-k;
const double dx = (dshape_x(i)*shape_l(l) -
shape_x(i)*dshape_l(l))*shape_y(j)*shape_z(k);
const double dy = (dshape_y(j)*shape_l(l) -
shape_y(j)*dshape_l(l))*shape_x(i)*shape_z(k);
const double dz = (dshape_z(k)*shape_l(l) -
shape_z(k)*dshape_l(l))*shape_x(i)*shape_y(j);
u(n,0) = 0.; u(n,1) = dz; u(n,2) = -dy; n++;
u(n,0) = -dz; u(n,1) = 0.; u(n,2) = dx; n++;
u(n,0) = dy; u(n,1) = -dx; u(n,2) = 0.; n++;
}
for (int k = 0; k <= pm1; k++)
for (int j = 0; j + k <= pm1; j++)
{
int i = pm1 - j - k;
// s = shape_x(i)*shape_y(j)*shape_z(k);
// curl of s*(ip.y - c, -(ip.x - c), 0):
u(n,0) = shape_x(i)*(ip.x - c)*shape_y(j)*dshape_z(k);
u(n,1) = shape_x(i)*shape_y(j)*(ip.y - c)*dshape_z(k);
u(n,2) =
-((dshape_x(i)*(ip.x - c) + shape_x(i))*shape_y(j)*shape_z(k) +
(dshape_y(j)*(ip.y - c) + shape_y(j))*shape_x(i)*shape_z(k));
n++;
// curl of s*(ip.z - c, 0, -(ip.x - c)):
u(n,0) = -shape_x(i)*(ip.x - c)*dshape_y(j)*shape_z(k);
u(n,1) = (shape_x(i)*shape_y(j)*(dshape_z(k)*(ip.z - c) + shape_z(k)) +
(dshape_x(i)*(ip.x - c) + shape_x(i))*shape_y(j)*shape_z(k));
u(n,2) = -shape_x(i)*dshape_y(j)*shape_z(k)*(ip.z - c);
n++;
}
for (int k = 0; k <= pm1; k++)
{
int j = pm1 - k;
// curl of shape_y(j)*shape_z(k)*(0, ip.z - c, -(ip.y - c)):
u(n,0) = -((dshape_y(j)*(ip.y - c) + shape_y(j))*shape_z(k) +
shape_y(j)*(dshape_z(k)*(ip.z - c) + shape_z(k)));
u(n,1) = 0.;
u(n,2) = 0.; n++;
}
Ti.Mult(u, curl_shape);
}
const double ND_TriangleElement::tk[8] =
{ 1.,0., -1.,1., 0.,-1., 0.,1. };
const double ND_TriangleElement::c = 1./3.;
ND_TriangleElement::ND_TriangleElement(const int p)
: VectorFiniteElement(2, Geometry::TRIANGLE, p*(p + 2), p,
H_CURL, FunctionSpace::Pk),
dof2tk(dof)
{
const double *eop = poly1d.OpenPoints(p - 1);
const double *iop = (p > 1) ? poly1d.OpenPoints(p - 2) : NULL;
const int pm1 = p - 1, pm2 = p - 2;
#ifndef MFEM_THREAD_SAFE
shape_x.SetSize(p);
shape_y.SetSize(p);
shape_l.SetSize(p);
dshape_x.SetSize(p);
dshape_y.SetSize(p);
dshape_l.SetSize(p);
u.SetSize(dof, dim);
curlu.SetSize(dof);
#else
Vector shape_x(p), shape_y(p), shape_l(p);
#endif
int n = 0;
// edges
for (int i = 0; i < p; i++) // (0,1)
{
Nodes.IntPoint(n).Set2(eop[i], 0.);
dof2tk[n++] = 0;
}
for (int i = 0; i < p; i++) // (1,2)
{
Nodes.IntPoint(n).Set2(eop[pm1-i], eop[i]);
dof2tk[n++] = 1;
}
for (int i = 0; i < p; i++) // (2,0)
{
Nodes.IntPoint(n).Set2(0., eop[pm1-i]);
dof2tk[n++] = 2;
}
// interior
for (int j = 0; j <= pm2; j++)
for (int i = 0; i + j <= pm2; i++)
{
double w = iop[i] + iop[j] + iop[pm2-i-j];
Nodes.IntPoint(n).Set2(iop[i]/w, iop[j]/w);
dof2tk[n++] = 0;
Nodes.IntPoint(n).Set2(iop[i]/w, iop[j]/w);
dof2tk[n++] = 3;
}
DenseMatrix T(dof);
for (int m = 0; m < dof; m++)
{
const IntegrationPoint &ip = Nodes.IntPoint(m);
const double *tm = tk + 2*dof2tk[m];
n = 0;
poly1d.CalcBasis(pm1, ip.x, shape_x);
poly1d.CalcBasis(pm1, ip.y, shape_y);
poly1d.CalcBasis(pm1, 1. - ip.x - ip.y, shape_l);
for (int j = 0; j <= pm1; j++)
for (int i = 0; i + j <= pm1; i++)
{
double s = shape_x(i)*shape_y(j)*shape_l(pm1-i-j);
T(n++, m) = s * tm[0];
T(n++, m) = s * tm[1];
}
for (int j = 0; j <= pm1; j++)
{
T(n++, m) =
shape_x(pm1-j)*shape_y(j)*((ip.y - c)*tm[0] - (ip.x - c)*tm[1]);
}
}
Ti.Factor(T);
// mfem::out << "ND_TriangleElement(" << p << ") : "; Ti.TestInversion();
}
void ND_TriangleElement::CalcVShape(const IntegrationPoint &ip,
DenseMatrix &shape) const
{
const int pm1 = order - 1;
#ifdef MFEM_THREAD_SAFE
const int p = order;
Vector shape_x(p), shape_y(p), shape_l(p);
DenseMatrix u(dof, dim);
#endif
poly1d.CalcBasis(pm1, ip.x, shape_x);
poly1d.CalcBasis(pm1, ip.y, shape_y);
poly1d.CalcBasis(pm1, 1. - ip.x - ip.y, shape_l);
int n = 0;
for (int j = 0; j <= pm1; j++)
for (int i = 0; i + j <= pm1; i++)
{
double s = shape_x(i)*shape_y(j)*shape_l(pm1-i-j);
u(n,0) = s; u(n,1) = 0; n++;
u(n,0) = 0; u(n,1) = s; n++;
}
for (int j = 0; j <= pm1; j++)
{
double s = shape_x(pm1-j)*shape_y(j);
u(n,0) = s*(ip.y - c);
u(n,1) = -s*(ip.x - c);
n++;
}
Ti.Mult(u, shape);
}
void ND_TriangleElement::CalcCurlShape(const IntegrationPoint &ip,
DenseMatrix &curl_shape) const
{
const int pm1 = order - 1;
#ifdef MFEM_THREAD_SAFE
const int p = order;
Vector shape_x(p), shape_y(p), shape_l(p);
Vector dshape_x(p), dshape_y(p), dshape_l(p);
Vector curlu(dof);
#endif
poly1d.CalcBasis(pm1, ip.x, shape_x, dshape_x);
poly1d.CalcBasis(pm1, ip.y, shape_y, dshape_y);
poly1d.CalcBasis(pm1, 1. - ip.x - ip.y, shape_l, dshape_l);
int n = 0;
for (int j = 0; j <= pm1; j++)
for (int i = 0; i + j <= pm1; i++)
{
int l = pm1-i-j;
const double dx = (dshape_x(i)*shape_l(l) -
shape_x(i)*dshape_l(l)) * shape_y(j);
const double dy = (dshape_y(j)*shape_l(l) -
shape_y(j)*dshape_l(l)) * shape_x(i);
curlu(n++) = -dy;
curlu(n++) = dx;
}
for (int j = 0; j <= pm1; j++)
{
int i = pm1 - j;
// curl of shape_x(i)*shape_y(j) * (ip.y - c, -(ip.x - c), 0):
curlu(n++) = -((dshape_x(i)*(ip.x - c) + shape_x(i)) * shape_y(j) +
(dshape_y(j)*(ip.y - c) + shape_y(j)) * shape_x(i));
}
Vector curl2d(curl_shape.Data(),dof);
Ti.Mult(curlu, curl2d);
}
const double ND_SegmentElement::tk[1] = { 1. };
ND_SegmentElement::ND_SegmentElement(const int p, const int ob_type)
: VectorFiniteElement(1, Geometry::SEGMENT, p, p - 1,
H_CURL, FunctionSpace::Pk),
obasis1d(poly1d.GetBasis(p - 1, VerifyOpen(ob_type))),
dof2tk(dof)
{
const double *op = poly1d.OpenPoints(p - 1, ob_type);
// set dof2tk and Nodes
for (int i = 0; i < p; i++)
{
dof2tk[i] = 0;
Nodes.IntPoint(i).x = op[i];
}
}
void ND_SegmentElement::CalcVShape(const IntegrationPoint &ip,
DenseMatrix &shape) const
{
Vector vshape(shape.Data(), dof);
obasis1d.Eval(ip.x, vshape);
}
void NURBS1DFiniteElement::SetOrder() const
{
order = kv[0]->GetOrder();
dof = order + 1;
weights.SetSize(dof);
shape_x.SetSize(dof);
}
void NURBS1DFiniteElement::CalcShape(const IntegrationPoint &ip,
Vector &shape) const
{
kv[0]->CalcShape(shape, ijk[0], ip.x);
double sum = 0.0;
for (int i = 0; i <= order; i++)
{
sum += (shape(i) *= weights(i));
}
shape /= sum;
}
void NURBS1DFiniteElement::CalcDShape(const IntegrationPoint &ip,
DenseMatrix &dshape) const
{
Vector grad(dshape.Data(), dof);
kv[0]->CalcShape (shape_x, ijk[0], ip.x);
kv[0]->CalcDShape(grad, ijk[0], ip.x);
double sum = 0.0, dsum = 0.0;
for (int i = 0; i <= order; i++)
{
sum += (shape_x(i) *= weights(i));
dsum += ( grad(i) *= weights(i));
}
sum = 1.0/sum;
add(sum, grad, -dsum*sum*sum, shape_x, grad);
}
void NURBS1DFiniteElement::CalcHessian (const IntegrationPoint &ip,
DenseMatrix &hessian) const
{
Vector grad(dof);
Vector hess(hessian.Data(), dof);
kv[0]->CalcShape (shape_x, ijk[0], ip.x);
kv[0]->CalcDShape(grad, ijk[0], ip.x);
kv[0]->CalcD2Shape(hess, ijk[0], ip.x);
double sum = 0.0, dsum = 0.0, d2sum = 0.0;
for (int i = 0; i <= order; i++)
{
sum += (shape_x(i) *= weights(i));
dsum += ( grad(i) *= weights(i));
d2sum += ( hess(i) *= weights(i));
}
sum = 1.0/sum;
add(sum, hess, -2*dsum*sum*sum, grad, hess);
add(1.0, hess, (-d2sum + 2*dsum*dsum*sum)*sum*sum, shape_x, hess);
}
void NURBS2DFiniteElement::SetOrder() const
{
orders[0] = kv[0]->GetOrder();
orders[1] = kv[1]->GetOrder();
shape_x.SetSize(orders[0]+1);
shape_y.SetSize(orders[1]+1);
dshape_x.SetSize(orders[0]+1);
dshape_y.SetSize(orders[1]+1);
d2shape_x.SetSize(orders[0]+1);
d2shape_y.SetSize(orders[1]+1);
order = max(orders[0], orders[1]);
dof = (orders[0] + 1)*(orders[1] + 1);
u.SetSize(dof);
du.SetSize(dof);
weights.SetSize(dof);
}
void NURBS2DFiniteElement::CalcShape(const IntegrationPoint &ip,
Vector &shape) const
{
kv[0]->CalcShape(shape_x, ijk[0], ip.x);
kv[1]->CalcShape(shape_y, ijk[1], ip.y);
double sum = 0.0;
for (int o = 0, j = 0; j <= orders[1]; j++)
{
const double sy = shape_y(j);
for (int i = 0; i <= orders[0]; i++, o++)
{
sum += ( shape(o) = shape_x(i)*sy*weights(o) );
}
}
shape /= sum;
}
void NURBS2DFiniteElement::CalcDShape(const IntegrationPoint &ip,
DenseMatrix &dshape) const
{
double sum, dsum[2];
kv[0]->CalcShape ( shape_x, ijk[0], ip.x);
kv[1]->CalcShape ( shape_y, ijk[1], ip.y);
kv[0]->CalcDShape(dshape_x, ijk[0], ip.x);
kv[1]->CalcDShape(dshape_y, ijk[1], ip.y);
sum = dsum[0] = dsum[1] = 0.0;
for (int o = 0, j = 0; j <= orders[1]; j++)
{
const double sy = shape_y(j), dsy = dshape_y(j);
for (int i = 0; i <= orders[0]; i++, o++)
{
sum += ( u(o) = shape_x(i)*sy*weights(o) );
dsum[0] += ( dshape(o,0) = dshape_x(i)*sy *weights(o) );
dsum[1] += ( dshape(o,1) = shape_x(i)*dsy*weights(o) );
}
}
sum = 1.0/sum;
dsum[0] *= sum*sum;
dsum[1] *= sum*sum;
for (int o = 0; o < dof; o++)
{
dshape(o,0) = dshape(o,0)*sum - u(o)*dsum[0];
dshape(o,1) = dshape(o,1)*sum - u(o)*dsum[1];
}
}
void NURBS2DFiniteElement::CalcHessian (const IntegrationPoint &ip,
DenseMatrix &hessian) const
{
double sum, dsum[2], d2sum[3];
kv[0]->CalcShape ( shape_x, ijk[0], ip.x);
kv[1]->CalcShape ( shape_y, ijk[1], ip.y);
kv[0]->CalcDShape(dshape_x, ijk[0], ip.x);
kv[1]->CalcDShape(dshape_y, ijk[1], ip.y);
kv[0]->CalcD2Shape(d2shape_x, ijk[0], ip.x);
kv[1]->CalcD2Shape(d2shape_y, ijk[1], ip.y);
sum = dsum[0] = dsum[1] = 0.0;
d2sum[0] = d2sum[1] = d2sum[2] = 0.0;
for (int o = 0, j = 0; j <= orders[1]; j++)
{
const double sy = shape_y(j), dsy = dshape_y(j), d2sy = d2shape_y(j);
for (int i = 0; i <= orders[0]; i++, o++)
{
const double sx = shape_x(i), dsx = dshape_x(i), d2sx = d2shape_x(i);
sum += ( u(o) = sx*sy*weights(o) );
dsum[0] += ( du(o,0) = dsx*sy*weights(o) );
dsum[1] += ( du(o,1) = sx*dsy*weights(o) );
d2sum[0] += ( hessian(o,0) = d2sx*sy*weights(o) );
d2sum[1] += ( hessian(o,1) = dsx*dsy*weights(o) );
d2sum[2] += ( hessian(o,2) = sx*d2sy*weights(o) );
}
}
sum = 1.0/sum;
dsum[0] *= sum;
dsum[1] *= sum;
d2sum[0] *= sum;
d2sum[1] *= sum;
d2sum[2] *= sum;
for (int o = 0; o < dof; o++)
{
hessian(o,0) = hessian(o,0)*sum
- 2*du(o,0)*sum*dsum[0]
+ u[o]*sum*(2*dsum[0]*dsum[0] - d2sum[0]);
hessian(o,1) = hessian(o,1)*sum
- du(o,0)*sum*dsum[1]
- du(o,1)*sum*dsum[0]
+ u[o]*sum*(2*dsum[0]*dsum[1] - d2sum[1]);
hessian(o,2) = hessian(o,2)*sum
- 2*du(o,1)*sum*dsum[1]
+ u[o]*sum*(2*dsum[1]*dsum[1] - d2sum[2]);
}
}
void NURBS3DFiniteElement::SetOrder() const
{
orders[0] = kv[0]->GetOrder();
orders[1] = kv[1]->GetOrder();
orders[2] = kv[2]->GetOrder();
shape_x.SetSize(orders[0]+1);
shape_y.SetSize(orders[1]+1);
shape_z.SetSize(orders[2]+1);
dshape_x.SetSize(orders[0]+1);
dshape_y.SetSize(orders[1]+1);
dshape_z.SetSize(orders[2]+1);
d2shape_x.SetSize(orders[0]+1);
d2shape_y.SetSize(orders[1]+1);
d2shape_z.SetSize(orders[2]+1);
order = max(max(orders[0], orders[1]), orders[2]);
dof = (orders[0] + 1)*(orders[1] + 1)*(orders[2] + 1);
u.SetSize(dof);
du.SetSize(dof);
weights.SetSize(dof);
}
void NURBS3DFiniteElement::CalcShape(const IntegrationPoint &ip,
Vector &shape) const
{
kv[0]->CalcShape(shape_x, ijk[0], ip.x);
kv[1]->CalcShape(shape_y, ijk[1], ip.y);
kv[2]->CalcShape(shape_z, ijk[2], ip.z);
double sum = 0.0;
for (int o = 0, k = 0; k <= orders[2]; k++)
{
const double sz = shape_z(k);
for (int j = 0; j <= orders[1]; j++)
{
const double sy_sz = shape_y(j)*sz;
for (int i = 0; i <= orders[0]; i++, o++)
{
sum += ( shape(o) = shape_x(i)*sy_sz*weights(o) );
}
}
}
shape /= sum;
}
void NURBS3DFiniteElement::CalcDShape(const IntegrationPoint &ip,
DenseMatrix &dshape) const
{
double sum, dsum[3];
kv[0]->CalcShape ( shape_x, ijk[0], ip.x);
kv[1]->CalcShape ( shape_y, ijk[1], ip.y);
kv[2]->CalcShape ( shape_z, ijk[2], ip.z);
kv[0]->CalcDShape(dshape_x, ijk[0], ip.x);
kv[1]->CalcDShape(dshape_y, ijk[1], ip.y);
kv[2]->CalcDShape(dshape_z, ijk[2], ip.z);
sum = dsum[0] = dsum[1] = dsum[2] = 0.0;
for (int o = 0, k = 0; k <= orders[2]; k++)
{
const double sz = shape_z(k), dsz = dshape_z(k);
for (int j = 0; j <= orders[1]; j++)
{
const double sy_sz = shape_y(j)* sz;
const double dsy_sz = dshape_y(j)* sz;
const double sy_dsz = shape_y(j)*dsz;
for (int i = 0; i <= orders[0]; i++, o++)
{
sum += ( u(o) = shape_x(i)*sy_sz*weights(o) );
dsum[0] += ( dshape(o,0) = dshape_x(i)* sy_sz *weights(o) );
dsum[1] += ( dshape(o,1) = shape_x(i)*dsy_sz *weights(o) );
dsum[2] += ( dshape(o,2) = shape_x(i)* sy_dsz*weights(o) );
}
}
}
sum = 1.0/sum;
dsum[0] *= sum*sum;
dsum[1] *= sum*sum;
dsum[2] *= sum*sum;
for (int o = 0; o < dof; o++)
{
dshape(o,0) = dshape(o,0)*sum - u(o)*dsum[0];
dshape(o,1) = dshape(o,1)*sum - u(o)*dsum[1];
dshape(o,2) = dshape(o,2)*sum - u(o)*dsum[2];
}
}
void NURBS3DFiniteElement::CalcHessian (const IntegrationPoint &ip,
DenseMatrix &hessian) const
{
double sum, dsum[3], d2sum[6];
kv[0]->CalcShape ( shape_x, ijk[0], ip.x);
kv[1]->CalcShape ( shape_y, ijk[1], ip.y);
kv[2]->CalcShape ( shape_z, ijk[2], ip.z);
kv[0]->CalcDShape(dshape_x, ijk[0], ip.x);
kv[1]->CalcDShape(dshape_y, ijk[1], ip.y);
kv[2]->CalcDShape(dshape_z, ijk[2], ip.z);
kv[0]->CalcD2Shape(d2shape_x, ijk[0], ip.x);
kv[1]->CalcD2Shape(d2shape_y, ijk[1], ip.y);
kv[2]->CalcD2Shape(d2shape_z, ijk[2], ip.z);
sum = dsum[0] = dsum[1] = dsum[2] = 0.0;
d2sum[0] = d2sum[1] = d2sum[2] = d2sum[3] = d2sum[4] = d2sum[5] = 0.0;
for (int o = 0, k = 0; k <= orders[2]; k++)
{
const double sz = shape_z(k), dsz = dshape_z(k), d2sz = d2shape_z(k);
for (int j = 0; j <= orders[1]; j++)
{
const double sy = shape_y(j), dsy = dshape_y(j), d2sy = d2shape_y(j);
for (int i = 0; i <= orders[0]; i++, o++)
{
const double sx = shape_x(i), dsx = dshape_x(i), d2sx = d2shape_x(i);
sum += ( u(o) = sx*sy*sz*weights(o) );
dsum[0] += ( du(o,0) = dsx*sy*sz*weights(o) );
dsum[1] += ( du(o,1) = sx*dsy*sz*weights(o) );
dsum[2] += ( du(o,2) = sx*sy*dsz*weights(o) );
d2sum[0] += ( hessian(o,0) = d2sx*sy*sz*weights(o) );
d2sum[1] += ( hessian(o,1) = dsx*dsy*sz*weights(o) );
d2sum[2] += ( hessian(o,2) = dsx*sy*dsz*weights(o) );
d2sum[3] += ( hessian(o,3) = sx*dsy*dsz*weights(o) );
d2sum[4] += ( hessian(o,4) = sx*sy*d2sz*weights(o) );
d2sum[5] += ( hessian(o,5) = sx*d2sy*sz*weights(o) );
}
}
}
sum = 1.0/sum;
dsum[0] *= sum;
dsum[1] *= sum;
dsum[2] *= sum;
d2sum[0] *= sum;
d2sum[1] *= sum;
d2sum[2] *= sum;
d2sum[3] *= sum;
d2sum[4] *= sum;
d2sum[5] *= sum;
for (int o = 0; o < dof; o++)
{
hessian(o,0) = hessian(o,0)*sum
- 2*du(o,0)*sum*dsum[0]
+ u[o]*sum*(2*dsum[0]*dsum[0] - d2sum[0]);
hessian(o,1) = hessian(o,1)*sum
- du(o,0)*sum*dsum[1]
- du(o,1)*sum*dsum[0]
+ u[o]*sum*(2*dsum[0]*dsum[1] - d2sum[1]);
hessian(o,2) = hessian(o,2)*sum
- du(o,0)*sum*dsum[2]
- du(o,2)*sum*dsum[0]
+ u[o]*sum*(2*dsum[0]*dsum[2] - d2sum[2]);
hessian(o,3) = hessian(o,3)*sum
- du(o,1)*sum*dsum[2]
- du(o,2)*sum*dsum[1]
+ u[o]*sum*(2*dsum[1]*dsum[2] - d2sum[3]);
hessian(o,4) = hessian(o,4)*sum
- 2*du(o,2)*sum*dsum[2]
+ u[o]*sum*(2*dsum[2]*dsum[2] - d2sum[4]);
hessian(o,5) = hessian(o,5)*sum
- 2*du(o,1)*sum*dsum[1]
+ u[o]*sum*(2*dsum[1]*dsum[1] - d2sum[5]);
}
}
// Global object definitions
// Object declared in mesh/triangle.hpp.
// Defined here to ensure it is constructed before 'Geometries'.
Linear2DFiniteElement TriangleFE;
// Object declared in mesh/tetrahedron.hpp.
// Defined here to ensure it is constructed before 'Geometries'.
Linear3DFiniteElement TetrahedronFE;
// Object declared in mesh/wedge.hpp.
// Defined here to ensure it is constructed after 'poly1d' and before
// 'Geometries'.
// TODO: define as thread_local to prevent race conditions in GLVis, because
// there is no "LinearWedgeFiniteElement" and WedgeFE is in turn used from two
// different threads for different things in GLVis. We also don't want to turn
// MFEM_THREAD_SAFE on globally. (See PR #731)
H1_WedgeElement WedgeFE(1);
// Object declared in geom.hpp.
// Construct 'Geometries' after 'TriangleFE', 'TetrahedronFE', and 'WedgeFE'.
Geometry Geometries;
}
| 27.963809 | 104 | 0.48008 | [
"mesh",
"geometry",
"object",
"shape",
"vector",
"transform",
"3d"
] |
1424d8273e072ba31f94440922002ddd00924734 | 36,543 | cpp | C++ | Framework/Sources/o2/Scene/UI/Widget.cpp | zenkovich/o2 | cdbf10271f1bf0f3198c8005b13b66e6ca13a9db | [
"MIT"
] | 181 | 2015-12-09T08:53:36.000Z | 2022-03-26T20:48:39.000Z | Framework/Sources/o2/Scene/UI/Widget.cpp | zenkovich/o2 | cdbf10271f1bf0f3198c8005b13b66e6ca13a9db | [
"MIT"
] | 29 | 2016-04-22T08:24:04.000Z | 2022-03-06T07:06:28.000Z | Framework/Sources/o2/Scene/UI/Widget.cpp | zenkovich/o2 | cdbf10271f1bf0f3198c8005b13b66e6ca13a9db | [
"MIT"
] | 13 | 2018-04-24T17:12:04.000Z | 2021-11-12T23:49:53.000Z | #include "o2/stdafx.h"
#include "Widget.h"
#include "o2/Application/Input.h"
#include "o2/Render/Render.h"
#include "o2/Scene/Scene.h"
#include "o2/Scene/SceneLayer.h"
#include "o2/Scene/UI/UIManager.h"
#include "o2/Scene/UI/WidgetLayer.h"
#include "o2/Scene/UI/WidgetLayout.h"
#include "o2/Scene/UI/WidgetState.h"
namespace o2
{
Widget::Widget(ActorCreateMode mode /*= ActorCreateMode::Default*/):
Actor(mnew WidgetLayout(), mode), layout(dynamic_cast<WidgetLayout*>(transform))
{
if (IsFocusable() && UIManager::IsSingletonInitialzed())
o2UI.mFocusableWidgets.Add(this);
layout->SetOwner(this);
}
Widget::Widget(const ActorAssetRef& prototype, ActorCreateMode mode /*= ActorCreateMode::Default*/):
Actor(mnew WidgetLayout(), prototype, mode), layout(dynamic_cast<WidgetLayout*>(transform))
{
if (IsFocusable() && UIManager::IsSingletonInitialzed())
o2UI.mFocusableWidgets.Add(this);
layout->SetOwner(this);
}
Widget::Widget(Vector<Component*> components, ActorCreateMode mode /*= ActorCreateMode::Default*/):
Actor(mnew WidgetLayout(), components, mode), layout(dynamic_cast<WidgetLayout*>(transform))
{
if (IsFocusable() && UIManager::IsSingletonInitialzed())
o2UI.mFocusableWidgets.Add(this);
layout->SetOwner(this);
}
Widget::Widget(const Widget& other):
Actor(mnew WidgetLayout(*other.layout), other), layout(dynamic_cast<WidgetLayout*>(transform)),
mTransparency(other.mTransparency), transparency(this), resTransparency(this),
childrenWidgets(this), layers(this), states(this), childWidget(this), layer(this), state(this)
{
layout->SetOwner(this);
WidgetLayer::ICopyVisitor* layerCopyVisitor = nullptr;
if (dynamic_cast<InstantiatePrototypeCloneVisitor*>(other.mCopyVisitor) || other.mIsAsset)
layerCopyVisitor = mnew WidgetLayer::InstantiatePrototypeCloneVisitor();
if (dynamic_cast<MakePrototypeCloneVisitor*>(other.mCopyVisitor))
layerCopyVisitor = mnew WidgetLayer::MakePrototypeCloneVisitor();
if constexpr (IS_EDITOR)
{
if (dynamic_cast<InstantiatePrototypeCloneVisitor*>(other.mCopyVisitor) || other.mIsAsset)
{
layersEditable.prototypeLink = &other.layersEditable;
internalChildrenEditable.prototypeLink = &other.internalChildrenEditable;
}
}
for (auto layer : other.mLayers)
{
layer->mCopyVisitor = layerCopyVisitor;
auto newLayer = mnew WidgetLayer(*layer);
newLayer->SetOwnerWidget(this);
mLayers.Add(newLayer);
OnLayerAdded(newLayer);
}
if (layerCopyVisitor)
delete layerCopyVisitor;
for (auto child : mChildren)
{
Widget* childWidget = dynamic_cast<Widget*>(child);
if (childWidget)
{
childWidget->mParentWidget = this;
mChildWidgets.Add(childWidget);
OnChildAdded(childWidget);
if (childWidget->mOverrideDepth)
childWidget->AddToScene();
else
childWidget->RemoveFromScene();
}
}
for (auto child : other.mInternalWidgets)
{
auto newChild = child->CloneAs<Widget>();
newChild->RemoveFromScene();
newChild->SetInternalParent(this, false);
}
for (auto state : other.mStates)
{
WidgetState* newState = dynamic_cast<WidgetState*>(state->Clone());
AddState(newState, false);
}
if (IsFocusable() && UIManager::IsSingletonInitialzed())
o2UI.mFocusableWidgets.Add(this);
UpdateDrawingChildren();
UpdateLayersDrawingSequence();
RetargetStatesAnimations();
}
Widget::~Widget()
{
if (mParent)
mParent->OnChildRemoved(this);
for (auto layer : mLayers)
{
layer->mOwnerWidget = nullptr;
delete layer;
}
for (auto state : mStates)
delete state;
for (auto child : mInternalWidgets)
{
child->mParent = nullptr;
child->mParentWidget = nullptr;
delete child;
}
if (UIManager::IsSingletonInitialzed())
o2UI.mFocusableWidgets.Remove(this);
if (IsOnScene())
ISceneDrawable::OnRemoveFromScene();
}
Widget& Widget::operator=(const Widget& other)
{
auto layers = mLayers;
for (auto layer : layers)
delete layer;
auto states = mStates;
for (auto state : states)
delete state;
auto internalChildren = mInternalWidgets;
for (auto child : internalChildren)
delete child;
mInternalWidgets.Clear();
mLayers.Clear();
mStates.Clear();
mVisibleState = nullptr;
mFocusedState = nullptr;
layout->CopyFrom(*other.layout);
mTransparency = other.mTransparency;
mIsFocusable = other.mIsFocusable;
for (auto layer : other.mLayers)
{
auto newLayer = mnew WidgetLayer(*layer);
newLayer->SetOwnerWidget(this);
mLayers.Add(newLayer);
OnLayerAdded(newLayer);
}
mChildWidgets.Clear();
for (auto child : mChildren)
{
Widget* childWidget = dynamic_cast<Widget*>(child);
if (childWidget)
{
mChildWidgets.Add(childWidget);
OnChildAdded(childWidget);
}
}
for (auto child : other.mInternalWidgets)
{
auto newChild = child->CloneAs<Widget>();
newChild->RemoveFromScene();
newChild->SetInternalParent(this, false);
}
for (auto state : other.mStates)
{
WidgetState* newState = dynamic_cast<WidgetState*>(state->Clone());
AddState(newState, false);
}
UpdateLayersDrawingSequence();
return *this;
}
void Widget::Update(float dt)
{
if (mResEnabledInHierarchy)
{
if (GetLayoutData().updateFrame == 0)
{
for (auto child : mChildren)
child->transform->SetDirty(true);
for (auto child : mInternalWidgets)
child->transform->SetDirty(true);
UpdateSelfTransform();
}
if (!mIsClipped)
{
for (auto state : mStates)
{
if (state)
state->Update(dt);
}
}
for (auto comp : mComponents)
comp->Update(dt);
}
}
void Widget::UpdateChildren(float dt)
{
for (auto child : mChildren)
child->Update(dt);
RectF childrenWorldRect = GetLayoutData().childrenWorldRect;
GetLayoutData().childrenWorldRect = GetLayoutData().worldRectangle;
for (auto child : mInternalWidgets)
child->Update(dt);
GetLayoutData().childrenWorldRect = childrenWorldRect;
for (auto child : mChildren)
child->UpdateChildren(dt);
GetLayoutData().childrenWorldRect = GetLayoutData().worldRectangle;
for (auto child : mInternalWidgets)
child->UpdateChildren(dt);
GetLayoutData().childrenWorldRect = childrenWorldRect;
}
void Widget::UpdateTransform()
{
if (GetLayoutData().drivenByParent && mParentWidget) {
mParentWidget->UpdateTransform();
}
UpdateSelfTransform();
UpdateChildrenTransforms();
}
void Widget::UpdateChildrenTransforms()
{
Actor::UpdateChildrenTransforms();
RectF childrenWorldRect = GetLayoutData().childrenWorldRect;
GetLayoutData().childrenWorldRect = GetLayoutData().worldRectangle;
for (auto child : mInternalWidgets)
child->UpdateSelfTransform();
for (auto child : mInternalWidgets)
child->UpdateChildrenTransforms();
GetLayoutData().childrenWorldRect = childrenWorldRect;
}
void Widget::SetLayoutDirty()
{
layout->SetDirty(false);
}
void Widget::Draw()
{
if (!mResEnabledInHierarchy || mIsClipped)
{
if (mIsClipped)
{
for (auto child : mDrawingChildren)
child->Draw();
}
return;
}
for (auto layer : mDrawingLayers)
layer->Draw();
OnDrawn();
for (auto child : mDrawingChildren)
child->Draw();
for (auto child : mInternalWidgets)
child->Draw();
for (auto layer : mTopDrawingLayers)
layer->Draw();
DrawDebugFrame();
}
void Widget::DrawDebugFrame()
{
if (!IsUIDebugEnabled() && !o2Input.IsKeyDown(VK_F2))
return;
static int colr = 0;
static int lastFrame = 0;
if (lastFrame != o2Time.GetCurrentFrame())
colr = 0;
lastFrame = o2Time.GetCurrentFrame();
o2Render.DrawRectFrame(mBoundsWithChilds, Color4::SomeColor(colr++));
}
void Widget::SerializeRaw(DataValue& node) const
{
Actor::SerializeRaw(node);
node["InternalWidgets"] = mInternalWidgets;
node["Layers"] = mLayers;
node["States"] = mStates;
}
void Widget::DeserializeRaw(const DataValue& node)
{
Actor::DeserializeRaw(node);
if (auto internalWidgetsNode = node.FindMember("InternalWidgets"))
mInternalWidgets = *internalWidgetsNode;
if (auto layersNode = node.FindMember("Layers"))
mLayers = *layersNode;
if (auto statesNode = node.FindMember("States"))
mStates = *statesNode;
}
void Widget::SerializeWithProto(DataValue& node) const
{
Actor::SerializeWithProto(node);
if (!mInternalWidgets.IsEmpty())
{
auto& internalWidgetsNode = node.AddMember("InternalWidgets");
internalWidgetsNode.SetArray();
for (auto widget : mInternalWidgets)
{
auto& widgetNode = internalWidgetsNode.AddElement();
widgetNode.AddMember("Type") = widget->GetType().GetName();
widget->Serialize(widgetNode.AddMember("Data"));
}
}
if (!mLayers.IsEmpty())
{
auto& layersNode = node.AddMember("Layers");
layersNode.SetArray();
for (auto layer : mLayers)
layer->Serialize(layersNode.AddElement());
}
if (!mStates.IsEmpty())
{
const Widget* proto = dynamic_cast<const Widget*>(mPrototypeLink.Get());
auto& statesNode = node.AddMember("States");
for (auto state : mStates)
{
if (auto protoState = proto->GetStateObject(state->name))
{
auto& stateNode = statesNode.AddElement();
stateNode["mName"] = state->name;
stateNode.SetDelta(*state, *protoState);
}
else
statesNode.AddElement().Set(*state);
}
}
}
void Widget::DeserializeWithProto(const DataValue& node)
{
for (auto layer : mLayers)
{
layer->mOwnerWidget = nullptr;
delete layer;
}
for (auto state : mStates)
delete state;
for (auto child : mInternalWidgets)
{
child->mParent = nullptr;
child->mParentWidget = nullptr;
delete child;
}
mLayers.Clear();
mStates.Clear();
mInternalWidgets.Clear();
Actor::DeserializeWithProto(node);
auto internalWidgetsNode = node.FindMember("InternalWidgets");
if (internalWidgetsNode && internalWidgetsNode->IsArray())
{
for (auto& widgetNode : *internalWidgetsNode)
{
const DataValue* typeNode = widgetNode.FindMember("Type");
const DataValue* dataValue = widgetNode.FindMember("Data");
if (typeNode && dataValue)
{
const ObjectType* type = dynamic_cast<const ObjectType*>(o2Reflection.GetType(*typeNode));
if (type)
{
Widget* widget = dynamic_cast<Widget*>(type->DynamicCastToIObject(type->CreateSample()));
AddInternalWidget(widget);
widget->mCopyVisitor = mCopyVisitor;
widget->Deserialize(*dataValue);
widget->mCopyVisitor = nullptr;
}
}
}
}
auto layersNode = node.FindMember("Layers");
if (layersNode && layersNode->IsArray())
{
for (auto& layerNode : *layersNode)
{
WidgetLayer* layer = mnew WidgetLayer();
AddLayer(layer);
layer->Deserialize(layerNode);
}
}
auto statesNode = node.FindMember("States");
if (statesNode && statesNode->IsArray())
{
const Widget* proto = dynamic_cast<const Widget*>(mPrototypeLink.Get());
for (auto& stateNode : *statesNode)
{
WidgetState* state = mnew WidgetState();
stateNode["mName"].Get(state->name);
if (auto protoState = proto->GetStateObject(state->name))
stateNode.GetDelta(*state, *protoState);
else
stateNode.Get(*state);
AddState(state, false);
}
}
}
void Widget::OnDeserialized(const DataValue& node)
{
for (auto layer : mLayers)
layer->SetOwnerWidget(this);
for (auto layer : mLayers)
OnLayerAdded(layer);
mChildWidgets.Clear();
for (auto child : mChildren)
{
Widget* childWidget = dynamic_cast<Widget*>(child);
if (childWidget)
{
childWidget->mParentWidget = this;
mChildWidgets.Add(childWidget);
OnChildAdded(childWidget);
}
}
for (auto child : mInternalWidgets)
{
child->mParent = this;
child->mParentWidget = this;
child->RemoveFromScene();
}
RetargetStatesAnimations();
SetEnabledForcible(mEnabled);
UpdateLayersDrawingSequence();
}
void Widget::OnDeserializedDelta(const DataValue& node, const IObject& origin)
{
OnDeserialized(node);
}
void Widget::OnTransformUpdated()
{
mIsClipped = false;
Actor::OnTransformUpdated();
UpdateLayersLayouts();
onLayoutUpdated();
}
SceneLayer* Widget::GetSceneDrawableSceneLayer() const
{
return mLayer;
}
bool Widget::IsSceneDrawableEnabled() const
{
return mResEnabledInHierarchy;
}
void Widget::OnFocused()
{
onFocused();
}
void Widget::OnUnfocused()
{
onUnfocused();
}
Widget* Widget::GetParentWidget() const
{
return mParentWidget;
}
const RectF& Widget::GetChildrenWorldRect() const
{
return GetLayoutData().childrenWorldRect;
}
const Vector<Widget*>& Widget::GetChildWidgets() const
{
return mChildWidgets;
}
Actor* Widget::FindActorById(SceneUID id)
{
if (auto res = Actor::FindActorById(id))
return res;
for (auto widget : mInternalWidgets)
{
if (auto res = widget->FindActorById(id))
return res;
}
return nullptr;
}
String Widget::GetCreateMenuCategory()
{
return "UI";
}
WidgetLayer* Widget::AddLayer(WidgetLayer* layer)
{
if (layer->mParent)
layer->mParent->RemoveChild(layer, false);
else if (layer->mOwnerWidget)
layer->mOwnerWidget->RemoveLayer(layer, false);
mLayers.Add(layer);
layer->SetOwnerWidget(this);
UpdateLayersDrawingSequence();
OnLayerAdded(layer);
if constexpr (IS_EDITOR)
{
if (Scene::IsSingletonInitialzed() && IsOnScene())
{
o2Scene.OnObjectChanged(&layersEditable);
o2Scene.onChildrenHierarchyChanged(&layersEditable);
}
}
return layer;
}
WidgetLayer* Widget::AddLayer(const String& name, IRectDrawable* drawable,
const Layout& layout /*= Layout::Both()*/, float depth /*= 0.0f*/)
{
if (Math::Equals(depth, 0.0f))
depth = (float)mDrawingLayers.Count();
WidgetLayer* layer = mnew WidgetLayer();
layer->depth = depth;
layer->name = name;
layer->SetDrawable(drawable);
layer->layout = layout;
AddLayer(layer);
return layer;
}
WidgetLayer* Widget::GetLayer(const String& path) const
{
int delPos = path.Find("/");
WString pathPart = path.SubStr(0, delPos);
for (auto layer : mLayers)
{
if (layer->name == pathPart)
{
if (delPos == -1)
return layer;
else
return layer->GetChild(path.SubStr(delPos + 1));
}
}
return nullptr;
}
WidgetLayer* Widget::FindLayer(const String& name) const
{
for (auto childLayer : mLayers)
{
if (childLayer->name == name)
return childLayer;
WidgetLayer* layer = childLayer->FindChild(name);
if (layer)
return layer;
}
return nullptr;
}
void Widget::RemoveLayer(WidgetLayer* layer, bool release /*= true*/)
{
layer->SetOwnerWidget(nullptr);
mLayers.Remove(layer);
if (release)
delete layer;
UpdateLayersDrawingSequence();
OnChildrenChanged();
}
void Widget::RemoveLayer(const String& path)
{
auto layer = GetLayer(path);
if (!layer)
return;
if (layer->GetParent())
{
layer->GetParent()->RemoveChild(layer);
return;
}
mLayers.Remove(layer);
UpdateLayersDrawingSequence();
}
void Widget::RemoveAllLayers()
{
for (auto layer : mLayers)
delete layer;
mDrawingLayers.Clear();
mLayers.Clear();
}
const Vector<WidgetLayer*>& Widget::GetLayers() const
{
return mLayers;
}
WidgetState* Widget::AddState(const String& name)
{
WidgetState* newState = mnew WidgetState();
newState->name = name;
return AddState(newState);
}
WidgetState* Widget::AddState(const String& name, const AnimationClip& animation)
{
WidgetState* newState = mnew WidgetState();
newState->name = name;
newState->animationClip = animation;
return AddState(newState);
}
WidgetState* Widget::AddState(const String& name, const AnimationAssetRef& animation)
{
WidgetState* newState = mnew WidgetState();
newState->name = name;
newState->animationAsset = animation;
return AddState(newState);
}
WidgetState* Widget::AddState(WidgetState* state, bool showAnimErrors /*= true*/)
{
mStates.Add(state);
state->SetOwner(this, showAnimErrors);
if (state->name == "visible")
{
mVisibleState = state;
mVisibleState->SetStateForcible(mEnabled);
mVisibleState->onStateBecomesTrue += [&]()
{
mResEnabled = true;
UpdateResEnabledInHierarchy();
};
mVisibleState->onStateFullyFalse += [&]()
{
mResEnabled = false;
UpdateResEnabledInHierarchy();
};
}
if (state->name == "focused")
mFocusedState = state;
OnStateAdded(state);
return state;
}
bool Widget::RemoveState(const String& name)
{
int idx = mStates.IndexOf([&](WidgetState* state) { return state->name == name; });
if (idx < 0)
return false;
if (mStates[idx] == mVisibleState)
mVisibleState = nullptr;
if (mStates[idx] == mFocusedState)
mFocusedState = nullptr;
delete mStates[idx];
mStates.RemoveAt(idx);
return true;
}
bool Widget::RemoveState(WidgetState* state)
{
int idx = mStates.IndexOf(state);
if (idx < 0)
return false;
if (state == mVisibleState)
mVisibleState = nullptr;
delete mStates[idx];
mStates.RemoveAt(idx);
return true;
}
void Widget::RemoveAllStates()
{
for (auto state : mStates)
delete state;
mVisibleState = nullptr;
mFocusedState = nullptr;
mStates.Clear();
}
void Widget::SetState(const String& name, bool state)
{
auto stateObj = GetStateObject(name);
if (stateObj)
stateObj->SetState(state);
}
void Widget::SetStateForcible(const String& name, bool state)
{
auto stateObj = GetStateObject(name);
if (stateObj)
stateObj->SetStateForcible(state);
}
bool Widget::GetState(const String& name) const
{
auto state = GetStateObject(name);
if (state)
return state->GetState();
return false;
}
WidgetState* Widget::GetStateObject(const String& name) const
{
return mStates.FindOrDefault([&](auto state) { return state->name == name; });
}
const Vector<WidgetState*>& Widget::GetStates() const
{
return mStates;
}
void Widget::SetDepthOverridden(bool overrideDepth)
{
if (mOverrideDepth == overrideDepth)
return;
mOverrideDepth = overrideDepth;
if (mOverrideDepth)
{
AddToScene();
mLayer = o2Scene.GetLayer(mLayerName);
if (mParentWidget)
mParentWidget->mDrawingChildren.Remove(this);
}
else
{
mLayer->UnregisterDrawable(this);
RemoveFromScene();
if (mParentWidget)
mParentWidget->mDrawingChildren.Add(this);
}
}
bool Widget::IsDepthOverriden() const
{
return mOverrideDepth;
}
void Widget::SetTransparency(float transparency)
{
mTransparency = transparency;
UpdateTransparency();
}
float Widget::GetTransparency() const
{
return mTransparency;
}
float Widget::GetResTransparency() const
{
return mResTransparency;
}
void Widget::SetEnabledForcible(bool visible)
{
if (mVisibleState)
mVisibleState->SetStateForcible(visible);
mEnabled = visible;
Widget::UpdateResEnabled();
Widget::UpdateTransparency();
}
void Widget::Show(bool forcible /*= false*/)
{
if (forcible)
SetEnabledForcible(true);
else
SetEnabled(true);
}
void Widget::Hide(bool forcible /*= false*/)
{
if (forcible)
SetEnabledForcible(false);
else
SetEnabled(false);
}
void Widget::Focus()
{
o2UI.FocusWidget(this);
}
void Widget::Unfocus()
{
o2UI.FocusWidget(nullptr);
}
bool Widget::IsFocused() const
{
return mIsFocused;
}
bool Widget::IsFocusable() const
{
return mIsFocusable;
}
void Widget::SetFocusable(bool selectable)
{
mIsFocusable = selectable;
}
bool Widget::IsUnderPoint(const Vec2F& point)
{
return mDrawingScissorRect.IsInside(point) && layout->IsPointInside(point);
}
void Widget::SetIndexInSiblings(int index)
{
Actor::SetIndexInSiblings(index);
if (mParentWidget)
{
mParentWidget->UpdateChildWidgetsList();
mParentWidget->UpdateDrawingChildren();
}
}
float Widget::GetMinWidthWithChildren() const
{
return GetLayoutData().minSize.x;
}
float Widget::GetMinHeightWithChildren() const
{
return GetLayoutData().minSize.y;
}
float Widget::GetWidthWeightWithChildren() const
{
return GetLayoutData().weight.x;
}
float Widget::GetHeightWeightWithChildren() const
{
return GetLayoutData().weight.y;
}
void Widget::UpdateBoundsWithChilds()
{
if ((!mResEnabledInHierarchy || mIsClipped) && GetLayoutData().dirtyFrame != o2Time.GetCurrentFrame())
return;
mBoundsWithChilds = mBounds;
for (auto child : mChildWidgets)
mBoundsWithChilds.Expand(child->mBoundsWithChilds);
if (mParentWidget)
mParentWidget->UpdateBoundsWithChilds();
}
void Widget::CheckClipping(const RectF& clipArea)
{
mIsClipped = !mBoundsWithChilds.IsIntersects(clipArea);
for (auto child : mChildWidgets)
child->CheckClipping(clipArea);
}
void Widget::UpdateTransparency()
{
if (mParentWidget)
mResTransparency = mTransparency*mParentWidget->mResTransparency;
else
mResTransparency = mTransparency;
for (auto layer : mLayers)
layer->UpdateResTransparency();
for (auto child : mChildWidgets)
child->UpdateTransparency();
for (auto child : mInternalWidgets)
child->UpdateTransparency();
}
void Widget::UpdateVisibility(bool updateLayout /*= true*/)
{}
void Widget::OnChildFocused(Widget* child)
{
if (mParentWidget)
mParentWidget->OnChildFocused(child);
}
void Widget::RetargetStatesAnimations()
{
for (auto state : mStates)
{
state->player.SetTarget(this, false);
state->player.relTime = state->GetState() ? 1.0f : 0.0f;
}
}
void Widget::UpdateLayersLayouts()
{
for (auto layer : mLayers)
layer->UpdateLayout();
UpdateBounds();
}
void Widget::UpdateDrawingChildren()
{
mDrawingChildren.Clear();
for (auto child : mChildWidgets)
{
if (!child->mOverrideDepth)
mDrawingChildren.Add(child);
}
}
void Widget::UpdateBounds()
{
if ((!mResEnabledInHierarchy || mIsClipped) && GetLayoutData().dirtyFrame != o2Time.GetCurrentFrame())
return;
mBounds = GetLayoutData().worldRectangle;
for (auto layer : mDrawingLayers)
mBounds.Expand(layer->GetRect());
bool anyEnabled = false;
for (auto child : mChildWidgets)
{
if (child->mResEnabledInHierarchy)
{
anyEnabled = true;
break;
}
}
if (!anyEnabled)
UpdateBoundsWithChilds();
}
void Widget::UpdateLayersDrawingSequence()
{
const float topLayersDepth = 1000.0f;
mDrawingLayers.Clear();
mTopDrawingLayers.Clear();
for (auto layer : mLayers)
{
if (layer->GetDrawable())
{
if (layer->mDepth < topLayersDepth)
mDrawingLayers.Add(layer);
else
mTopDrawingLayers.Add(layer);
}
auto childLayers = layer->GetAllChilds();
for (auto childLayer : childLayers)
{
if (childLayer->GetDrawable())
{
if (childLayer->mDepth < topLayersDepth)
mDrawingLayers.Add(childLayer);
else
mTopDrawingLayers.Add(childLayer);
}
}
}
mDrawingLayers.Sort([](auto a, auto b) { return a->mDepth < b->mDepth; });
mTopDrawingLayers.Sort([](auto a, auto b) { return a->mDepth < b->mDepth; });
}
void Widget::SetParentWidget(Widget* widget)
{
SetParent(widget);
}
Widget* Widget::GetChildWidget(const String& path) const
{
Actor* actor = GetChild(path);
return dynamic_cast<Widget*>(actor);
}
Widget* Widget::AddChildWidget(Widget* widget)
{
return dynamic_cast<Widget*>(AddChild(widget));
}
Widget* Widget::AddChildWidget(Widget* widget, int position)
{
return dynamic_cast<Widget*>(AddChild(widget, position));
}
Vector<Widget*> Widget::GetChildrenNonConst()
{
return mChildWidgets;
}
Vector<WidgetLayer*> Widget::GetLayersNonConst()
{
return mLayers;
}
Vector<WidgetState*> Widget::GetStatesNonConst()
{
return mStates;
}
Map<String, WidgetLayer*> Widget::GetAllLayers()
{
Map<String, WidgetLayer*> res;
for (auto layer : mLayers)
res.Add(layer->name, layer);
return res;
}
Map<String, Widget*> Widget::GetAllChilds()
{
Map<String, Widget*> res;
for (auto child : mChildWidgets)
res.Add(child->GetName(), child);
return res;
}
Map<o2::String, Widget*> Widget::GetAllInternalWidgets()
{
Map<String, Widget*> res;
for (auto child : mInternalWidgets)
res.Add(child->GetName(), child);
return res;
}
Map<String, WidgetState*> Widget::GetAllStates()
{
Map<String, WidgetState*> res;
for (auto state : mStates)
res.Add(state->name, state);
return res;
}
void Widget::OnLayerAdded(WidgetLayer* layer)
{}
void Widget::OnStateAdded(WidgetState* state)
{}
void Widget::OnStatesListChanged()
{
auto statesCopy = mStates;
mStates.Clear();
for (auto state : statesCopy)
AddState(state);
}
void Widget::OnParentChanged(Actor* oldParent)
{
layout->SetDirty();
mParentWidget = dynamic_cast<Widget*>(mParent);
if (mParentWidget)
{
if (mOverrideDepth)
AddToScene();
else
RemoveFromScene(true);
}
else if (mParent && mParent->IsOnScene()) AddToScene();
}
void Widget::OnChildAdded(Actor* child)
{
layout->SetDirty(false);
Widget* widget = dynamic_cast<Widget*>(child);
if (widget)
{
UpdateChildWidgetsList();
UpdateDrawingChildren();
OnChildAdded(widget);
}
}
void Widget::OnChildAdded(Widget* child)
{}
void Widget::OnChildRemoved(Actor* child)
{
layout->SetDirty();
Widget* widget = dynamic_cast<Widget*>(child);
if (widget)
{
mChildWidgets.Remove(widget);
mInternalWidgets.Remove(widget);
UpdateDrawingChildren();
OnChildRemoved(widget);
}
}
void Widget::OnChildRemoved(Widget* child)
{}
void Widget::OnRemoveFromScene()
{
Actor::OnRemoveFromScene();
ISceneDrawable::OnRemoveFromScene();
if constexpr (IS_EDITOR)
{
o2Scene.mEditableObjects.Remove(&layersEditable);
o2Scene.mEditableObjects.Remove(&internalChildrenEditable);
}
for (auto layer : mLayers)
layer->OnRemoveFromScene();
for (auto child : mInternalWidgets)
child->OnRemoveFromScene();
}
void Widget::OnAddToScene()
{
Actor::OnAddToScene();
ISceneDrawable::OnAddToScene();
for (auto child : mInternalWidgets)
child->OnAddToScene();
for (auto layer : mLayers)
layer->OnAddToScene();
if constexpr (IS_EDITOR)
{
o2Scene.mEditableObjects.Add(&layersEditable);
o2Scene.mEditableObjects.Add(&internalChildrenEditable);
}
}
void Widget::UpdateChildWidgetsList()
{
mChildWidgets.Clear();
for (auto child : mChildren)
{
if (auto widget = dynamic_cast<Widget*>(child))
mChildWidgets.Add(widget);
}
}
WidgetLayoutData& Widget::GetLayoutData()
{
return *layout->mData;
}
const WidgetLayoutData& Widget::GetLayoutData() const
{
return *layout->mData;
}
void Widget::SetChildrenWorldRect(const RectF& childrenWorldRect)
{
layout->mData->childrenWorldRect = childrenWorldRect;
}
void Widget::ForceDraw(const RectF& area, float transparency)
{
Vec2F oldLayoutOffsetMin = GetLayoutData().offsetMin;
Vec2F oldLayoutOffsetMax = GetLayoutData().offsetMax;
float oldTransparency = mTransparency;
auto oldParent = mParent;
auto oldParentWidget = mParentWidget;
bool oldResEnabledInHierarchy = mResEnabledInHierarchy;
GetLayoutData().offsetMin = area.LeftBottom();
GetLayoutData().offsetMax = area.RightTop();
mTransparency = transparency;
mParent = nullptr;
mParentWidget = nullptr;
mIsClipped = false;
mResEnabledInHierarchy = true;
UpdateSelfTransform();
UpdateChildrenTransforms();
UpdateTransparency();
Draw();
GetLayoutData().offsetMin = oldLayoutOffsetMin;
GetLayoutData().offsetMax = oldLayoutOffsetMax;
mTransparency = oldTransparency;
mParent = oldParent;
mParentWidget = oldParentWidget;
mIsClipped = false;
mResEnabledInHierarchy = oldResEnabledInHierarchy;
UpdateSelfTransform();
UpdateChildrenTransforms();
GetLayoutData().dirtyFrame = o2Time.GetCurrentFrame();
UpdateBounds();
UpdateBoundsWithChilds();
UpdateTransparency();
}
void Widget::UpdateResEnabled()
{
if (mVisibleState)
mVisibleState->SetState(mEnabled);
else
Actor::UpdateResEnabled();
}
void Widget::UpdateResEnabledInHierarchy()
{
bool lastResEnabledInHierarchy = mResEnabledInHierarchy;
if (mParent)
mResEnabledInHierarchy = mResEnabled && mParent->mResEnabledInHierarchy;
else
mResEnabledInHierarchy = mResEnabled;
mIsClipped = false;
if (lastResEnabledInHierarchy != mResEnabledInHierarchy)
{
if (mResEnabledInHierarchy)
{
onShow();
if (mLayer && mSceneStatus == Actor::SceneStatus::InScene)
{
mLayer->OnActorEnabled(this);
ISceneDrawable::OnEnabled();
}
}
else
{
onHide();
if (mLayer && mSceneStatus == Actor::SceneStatus::InScene)
{
mLayer->OnActorDisabled(this);
ISceneDrawable::OnDisabled();
}
}
layout->SetDirty(false);
if constexpr (IS_EDITOR)
{
if (IsOnScene())
o2Scene.onEnableChanged(this);
}
OnEnableInHierarchyChanged();
OnChanged();
}
for (auto comp : mComponents)
comp->UpdateEnabled();
for (auto child : mChildren)
child->UpdateResEnabledInHierarchy();
for (auto child : mInternalWidgets)
child->UpdateResEnabledInHierarchy();
}
void Widget::SetInternalParent(Widget* parent, bool worldPositionStays /*= false*/)
{
SetParent(parent, worldPositionStays);
parent->mChildren.Remove(this);
parent->mChildWidgets.Remove(this);
parent->mDrawingChildren.Remove(this);
parent->mInternalWidgets.Add(this);
}
void Widget::AddInternalWidget(Widget* widget, bool worldPositionStays /*= false*/)
{
widget->SetInternalParent(this, worldPositionStays);
}
Widget* Widget::GetInternalWidget(const String& path) const
{
int delPos = path.Find("/");
WString pathPart = path.SubStr(0, delPos);
if (pathPart == "..")
{
if (mParent)
{
if (delPos == -1)
return mParentWidget;
else
return mParent->GetChildByType<Widget>(path.SubStr(delPos + 1));
}
return nullptr;
}
for (auto child : mInternalWidgets)
{
if (child->mName == pathPart)
{
if (delPos == -1)
return child;
else
return child->GetChildByType<Widget>(path.SubStr(delPos + 1));
}
}
return nullptr;
}
Widget* Widget::FindInternalWidget(const String& name) const
{
for (auto widget : mInternalWidgets)
{
if (widget->GetName() == name)
return widget;
if (Widget* res = widget->FindChildByTypeAndName<Widget>(name))
return res;
}
return nullptr;
}
void Widget::MoveAndCheckClipping(const Vec2F& delta, const RectF& clipArea)
{
mBoundsWithChilds += delta;
mIsClipped = !mBoundsWithChilds.IsIntersects(clipArea);
if (!mIsClipped)
UpdateSelfTransform();
for (auto child : mChildWidgets)
child->MoveAndCheckClipping(delta, clipArea);
RectF childrenWorldRect = GetLayoutData().childrenWorldRect;
GetLayoutData().childrenWorldRect = GetLayoutData().worldRectangle;
for (auto child : mInternalWidgets)
child->MoveAndCheckClipping(delta, clipArea);
GetLayoutData().childrenWorldRect = childrenWorldRect;
}
#if IS_EDITOR
bool Widget::isEditorLayersVisible = true;
bool Widget::isEditorInternalChildrenVisible = true;
void Widget::SetEditableParent(SceneEditableObject* object)
{
if (auto inter = dynamic_cast<InternalChildrenEditableEditable*>(object))
SetInternalParent(inter->widget);
else
Actor::SetEditableParent(object);
}
SceneEditableObject* Widget::GetEditableParent() const
{
if (mParentWidget && std::find(mParentWidget->mInternalWidgets.begin(),
mParentWidget->mInternalWidgets.end(), this) != mParentWidget->mInternalWidgets.end())
{
return &mParentWidget->internalChildrenEditable;
}
return Actor::GetEditableParent();
}
Vector<SceneEditableObject*> Widget::GetEditableChildren() const
{
Vector<SceneEditableObject*> res = Actor::GetEditableChildren();
if (isEditorInternalChildrenVisible)
res.Insert(const_cast<SceneEditableObject*>(dynamic_cast<const SceneEditableObject*>(&internalChildrenEditable)), 0);
if (isEditorLayersVisible)
res.Insert(const_cast<SceneEditableObject*>(dynamic_cast<const SceneEditableObject*>(&layersEditable)), 0);
return res;
}
void Widget::AddEditableChild(SceneEditableObject* object, int idx /*= -1*/)
{
if (auto actor = dynamic_cast<Actor*>(object))
{
if (idx < 0)
AddChild(actor);
else
AddChild(actor, idx);
}
else if (auto layer = dynamic_cast<WidgetLayer*>(object))
AddLayer(layer);
}
bool Widget::IsSupportsTransforming() const
{
return true;
}
Basis Widget::GetTransform() const
{
return layout->GetWorldBasis();
}
void Widget::SetTransform(const Basis& transform)
{
layout->SetWorldBasis(transform);
}
bool Widget::IsSupportsLayout() const
{
return true;
}
Layout Widget::GetLayout() const
{
return Layout(layout->GetAnchorMin(), layout->GetAnchorMax(), layout->GetOffsetMin(), layout->GetOffsetMax());
}
void Widget::SetLayout(const Layout& layout)
{
this->layout->SetAnchorMin(layout.anchorMin);
this->layout->SetAnchorMax(layout.anchorMax);
this->layout->SetOffsetMin(layout.offsetMin);
this->layout->SetOffsetMax(layout.offsetMax);
}
SceneEditableObject* Widget::GetEditableOwner()
{
return this;
}
Widget::LayersEditable::LayersEditable()
{}
Widget::LayersEditable::LayersEditable(Widget* widget):
widget(widget)
{}
SceneUID Widget::LayersEditable::GetID() const
{
return UID;
}
void Widget::LayersEditable::GenerateNewID(bool childs /*= true*/)
{
UID = Math::Random();
}
const String& Widget::LayersEditable::GetName() const
{
static String name = "layers";
return name;
}
void Widget::LayersEditable::SetName(const String& name)
{}
Vector<SceneEditableObject*> Widget::LayersEditable::GetEditableChildren() const
{
return widget->mLayers.Convert<SceneEditableObject*>([](WidgetLayer* x) { return dynamic_cast<SceneEditableObject*>(x); });
}
o2::SceneEditableObject* Widget::LayersEditable::GetEditableParent() const
{
return dynamic_cast<SceneEditableObject*>(widget);
}
void Widget::LayersEditable::SetEditableParent(SceneEditableObject* object)
{}
void Widget::LayersEditable::AddEditableChild(SceneEditableObject* object, int idx /*= -1*/)
{
if (WidgetLayer* layer = dynamic_cast<WidgetLayer*>(object))
widget->AddLayer(layer);
}
void Widget::LayersEditable::SetIndexInSiblings(int idx)
{}
bool Widget::LayersEditable::IsSupportsDeleting() const
{
return false;
}
Basis Widget::LayersEditable::GetTransform() const
{
return widget->GetTransform();
}
const SceneEditableObject* Widget::LayersEditable::GetEditableLink() const
{
return prototypeLink;
}
Widget::InternalChildrenEditableEditable::InternalChildrenEditableEditable()
{}
Widget::InternalChildrenEditableEditable::InternalChildrenEditableEditable(Widget* widget):
widget(widget)
{}
SceneUID Widget::InternalChildrenEditableEditable::GetID() const
{
return UID;
}
void Widget::InternalChildrenEditableEditable::GenerateNewID(bool childs /*= true*/)
{
UID = Math::Random();
}
const String& Widget::InternalChildrenEditableEditable::GetName() const
{
static String name = "internal children";
return name;
}
void Widget::InternalChildrenEditableEditable::SetName(const String& name)
{}
Vector<SceneEditableObject*> Widget::InternalChildrenEditableEditable::GetEditableChildren() const
{
return widget->mInternalWidgets.Convert<SceneEditableObject*>([](Widget* x) { return dynamic_cast<SceneEditableObject*>(x); });
}
o2::SceneEditableObject* Widget::InternalChildrenEditableEditable::GetEditableParent() const
{
return dynamic_cast<SceneEditableObject*>(widget);
}
void Widget::InternalChildrenEditableEditable::SetEditableParent(SceneEditableObject* object)
{}
void Widget::InternalChildrenEditableEditable::AddEditableChild(SceneEditableObject* object, int idx /*= -1*/)
{
if (Widget* widget = dynamic_cast<Widget*>(object))
widget->SetInternalParent(widget);
}
void Widget::InternalChildrenEditableEditable::SetIndexInSiblings(int idx)
{}
bool Widget::InternalChildrenEditableEditable::IsSupportsDeleting() const
{
return false;
}
Basis Widget::InternalChildrenEditableEditable::GetTransform() const
{
return widget->GetTransform();
}
const SceneEditableObject* Widget::InternalChildrenEditableEditable::GetEditableLink() const
{
return prototypeLink;
}
#endif // IS_EDITOR
}
DECLARE_CLASS(o2::Widget);
DECLARE_CLASS(o2::Widget::LayersEditable);
DECLARE_CLASS(o2::Widget::InternalChildrenEditableEditable);
| 21.357686 | 129 | 0.70194 | [
"render",
"object",
"vector",
"transform"
] |
142894b69aee5ca04b6cba1095563e9bc461d582 | 2,828 | cpp | C++ | haksaengine/haksaengine/ecs/collision_response.cpp | Skarmory/haksaengine | c41aefd24d11f1c1e8f4d7eac02083307c792f05 | [
"MIT"
] | 1 | 2019-01-07T19:23:07.000Z | 2019-01-07T19:23:07.000Z | haksaengine/haksaengine/ecs/collision_response.cpp | Skarmory/haksaengine | c41aefd24d11f1c1e8f4d7eac02083307c792f05 | [
"MIT"
] | null | null | null | haksaengine/haksaengine/ecs/collision_response.cpp | Skarmory/haksaengine | c41aefd24d11f1c1e8f4d7eac02083307c792f05 | [
"MIT"
] | null | null | null | #include "ecs/collision_response.h"
#include "services.h"
#include "ecs/collider.h"
#include "ecs/movement.h"
CollisionResponse::CollisionResponse(SystemOrdering order) : System(order)
{
}
void CollisionResponse::update(float delta)
{
// This system is very simple right now, and is not designed as a fully functional physics sim.
// Apply some gravity to entities that can move and check for terrain intersection
Terrain* terrain = Services::get().get_scene_manager()->get_terrain();
for (auto eid : _entities)
{
Entity* entity = Services::get().get_entity_manager()->get_entity(eid);
Transform* transform = entity->get_component<Transform>();
Collider* collider = entity->get_component<Collider>();
Movement* movement = entity->get_component<Movement>();
if (movement)
{
// Add gravity
movement->velocity += (_gravity * delta);
transform->translate_by(movement->velocity);
}
Ray to_ground;
to_ground.direction = glm::vec3(0.0f, -1.0f, 0.0f);
to_ground.position = transform->get_position();
to_ground.position.y = 1000.0f;
// Since this is primarily an RTS engine, stop entities from falling through the terrain
// Fire a ray at the ground from the entity's x,z position on the map and see where it intersects
glm::vec3 xsect_point;
if (terrain->intersect(to_ground, xsect_point)) // Is entity over the terrain at all?
{
if (movement)
{
// Cancel out the y velocity of this object now to stop it from accumulating further
movement->velocity.y += -movement->velocity.y;
}
glm::mat4 aabb_transform = transform->get_transform_scale_translate();
glm::vec3 aabb_min = aabb_transform * glm::vec4(collider->aabb.min, 1.0f);
// If AABB minimum y is less than ray terrain intersection point, the entity is clipping the terrain
if (aabb_min.y < xsect_point.y)
{
glm::vec3 translate_by = glm::vec3(0.0f, 0.0f, 0.0f);
translate_by.y = xsect_point.y - aabb_min.y;
transform->translate_by(translate_by);
}
}
// Kill-plane for entities that fall too far downwards. If they go this far down then they've fallen
// through the level most likely. Destroy them.
if (transform->get_position().y < -10000.0f)
Services::get().get_entity_manager()->destroy_entity(eid);
}
}
void CollisionResponse::on_event(Event e)
{
if (e.event_type == "EntityCreatedEvent")
{
Entity* entity = Services::get().get_entity_manager()->get_entity(e.arguments[0].as_uint);
if (entity->has_component<Collider>())
_entities.push_back(e.arguments[0].as_uint);
}
else if (e.event_type == "EntityDestroyedEvent")
{
std::vector<unsigned int>::iterator it;
if ((it = std::find(_entities.begin(), _entities.end(), e.arguments[0].as_uint)) != _entities.end())
{
std::iter_swap(it, _entities.end() - 1);
_entities.pop_back();
}
}
} | 31.775281 | 103 | 0.708274 | [
"object",
"vector",
"transform"
] |
142c7bb65ddb4f991d7bc2aa85fe6e7930b6c3d4 | 12,431 | cc | C++ | mindspore/ccsrc/backend/kernel_compiler/cpu/mirror_pad_grad_cpu_kernel.cc | 233-puchi/mindspore | e9d2684cdb7668eac48169feeff778eeffbfa70e | [
"Apache-2.0"
] | null | null | null | mindspore/ccsrc/backend/kernel_compiler/cpu/mirror_pad_grad_cpu_kernel.cc | 233-puchi/mindspore | e9d2684cdb7668eac48169feeff778eeffbfa70e | [
"Apache-2.0"
] | null | null | null | mindspore/ccsrc/backend/kernel_compiler/cpu/mirror_pad_grad_cpu_kernel.cc | 233-puchi/mindspore | e9d2684cdb7668eac48169feeff778eeffbfa70e | [
"Apache-2.0"
] | null | null | null | /**
* Copyright 2021 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 "backend/kernel_compiler/cpu/mirror_pad_grad_cpu_kernel.h"
#include "runtime/device/cpu/cpu_device_address.h"
namespace mindspore {
namespace kernel {
void MirrorPadGradCPUKernel::InitKernel(const CNodePtr &kernel_node) {
std::string mode = AnfAlgo::GetNodeAttr<std::string>(kernel_node, "mode");
dtype_ = AnfAlgo::GetPrevNodeOutputInferDataType(kernel_node, 0);
if (mode == "REFLECT") {
mode_ = 0;
} else if (mode == "SYMMETRIC") {
mode_ = 1;
} else {
MS_LOG(EXCEPTION) << "For mirror pad, only REFLECT and SYMMETRIC are supported.";
}
std::vector<size_t> input_shape = AnfAlgo::GetPrevNodeOutputInferShape(kernel_node, 0);
shape_size_ = input_shape.size();
if (shape_size_ == 4) { // shape adjustment from 2d/3d to 4d
} else if (shape_size_ == 3) {
auto it = input_shape.begin();
input_shape.insert(it, 1); // batch padding
shape_size_ = 4;
} else if (shape_size_ == 2) {
auto it = input_shape.begin();
input_shape.insert(it, 2, 1); // channel padding
shape_size_ = 4;
}
for (size_t i = 0; i < shape_size_; ++i) {
tensor_size_ *= input_shape[i];
input_shape_.push_back(SizeToLong(input_shape[i]));
}
std::vector<size_t> padding_shape = AnfAlgo::GetPrevNodeOutputInferShape(kernel_node, 1);
num_paddings_ = SizeToLong(padding_shape[0]);
std::vector<size_t> output_shape = AnfAlgo::GetOutputInferShape(kernel_node, 0);
if (output_shape.size() == 4) {
} else if (output_shape.size() == 3) {
auto it = output_shape.begin();
output_shape.insert(it, 1); // batch padding
} else if (output_shape.size() == 2) {
auto it = output_shape.begin();
output_shape.insert(it, 2, 1); // channel padding
}
for (auto x : output_shape) {
output_size_ *= x;
output_shape_.push_back(SizeToLong(x));
}
for (int i = 0; i < 2; i++) {
workspace_size_ *= output_shape[i];
workspace_size_ *= input_shape[i + 2];
}
int64_t max_width = input_shape_[3];
int64_t max_height = input_shape_[2];
// basic error check for padding value
if (mode_ == 1) { // symmetric
max_width = max_width + (2 * max_width);
max_height = max_height + (2 * max_height);
} else { // reflect
max_width = max_width + (2 * (max_width - 1));
max_height = max_height + (2 * (max_height - 1));
}
if (output_shape_[(output_shape_.size() - 2)] > max_height ||
output_shape_[(output_shape_.size() - 2) + 1] > max_width) {
MS_LOG(ERROR) << "ERROR: Padding value too high for input Tensor on 1 or more DIMS";
}
}
void extract_paddings_(const int64_t *paddings_arg, int64_t padd_dim, int64_t *extracted_paddings) {
const int64_t paddings_offset = MAX_PADDINGS - padd_dim;
for (int64_t i = 0; i < padd_dim; i++) {
extracted_paddings[(paddings_offset + i) * PADDING_SIZE] = paddings_arg[i * PADDING_SIZE];
extracted_paddings[(paddings_offset + i) * PADDING_SIZE + 1] = paddings_arg[i * PADDING_SIZE + 1];
}
}
bool range_check(int64_t x, int64_t y, int64_t padded_width, int64_t padded_height) {
if (((x >= 0) && (x <= padded_width - 1)) && ((y >= 0) && (y <= padded_height - 1))) {
return true;
}
return false;
}
bool MirrorPadGradCPUKernel::Launch(const std::vector<kernel::AddressPtr> &inputs,
const std::vector<kernel::AddressPtr> &workspace,
const std::vector<kernel::AddressPtr> &outputs) {
if (dtype_ == kNumberTypeFloat16) {
LaunchKernel<float16>(inputs, workspace, outputs);
} else if (dtype_ == kNumberTypeFloat32) {
LaunchKernel<float>(inputs, workspace, outputs);
} else if (dtype_ == kNumberTypeInt32) {
LaunchKernel<int>(inputs, workspace, outputs);
} else {
MS_LOG(EXCEPTION) << "Data type is " << TypeIdLabel(dtype_) << "is not support.";
}
return true;
}
template <typename T>
void MirrorPadGradCPUKernel::InitWorkspaceSize() {
workspace_size_list_.emplace_back(workspace_size_ * sizeof(T));
}
void MirrorPadGradCPUKernel::InitInputOutputSize(const CNodePtr &kernel_node) {
CPUKernel::InitInputOutputSize(kernel_node);
if (dtype_ == kNumberTypeFloat16) {
InitWorkspaceSize<float16>();
} else if (dtype_ == kNumberTypeFloat32) {
InitWorkspaceSize<float>();
} else if (dtype_ == kNumberTypeInt32) {
InitWorkspaceSize<int>();
}
}
template <typename T>
void MirrorPadGradCPUKernel::MirrorPadGrad_Width_Height(const size_t size, const T *interim_dy, const int64_t dx_height,
const int64_t dx_width, const int64_t dy_height,
const int64_t dy_width, const int64_t padd_dim,
const int64_t *paddings_arg, int64_t mode, T *dx) {
int64_t paddings[MAX_PADDINGS * PADDING_SIZE]; // local and fixed size to keep in registers
for (int i = 0; i < MAX_PADDINGS * PADDING_SIZE; i++) {
paddings[i] = 0; // init all to 0
}
extract_paddings_(paddings_arg, padd_dim, paddings);
// Create required anchor points for non-mirrored data inside new tensor
int64_t ap1_x = paddings[WIDTH];
int64_t ap2_x = paddings[WIDTH] + dx_width - 1;
int64_t ap1_y = paddings[HEIGHT];
int64_t ap2_y = paddings[HEIGHT] + dx_height - 1;
for (size_t pos = 0; pos < size; ++pos) {
int64_t dx_block_num = (SizeToLong(pos) / dx_width) / dx_height;
const int64_t grad_x = (SizeToLong(pos) % dx_width) + paddings[WIDTH];
const int64_t grad_y = ((SizeToLong(pos) / dx_width) % dx_height) + paddings[HEIGHT];
// copy position's own value into output
dx[pos] = interim_dy[(dx_block_num * dy_height + grad_y) * dy_width + grad_x];
int64_t x_dist_1 = (ap1_x - grad_x - mode);
int64_t y_dist_1 = (ap1_y - grad_y - mode);
int64_t x_dist_2 = (ap2_x - grad_x + mode);
int64_t y_dist_2 = (ap2_y - grad_y + mode);
int64_t axis_dist[] = {x_dist_1, x_dist_2, y_dist_1, y_dist_2};
int64_t anch_point[] = {ap1_x, ap2_x, ap1_y, ap2_y};
bool x_axis_check[] = {true, true, false, false}; // true - update X , false - update Y
int64_t temp_x = 0;
int64_t temp_y = 0;
// mirroring in axis lines
for (int x = 0; x < 4; x++) {
if (axis_dist[x] != 0) {
if (x_axis_check[x]) {
temp_y = grad_y;
temp_x = anch_point[x] + axis_dist[x];
} else {
temp_x = grad_x;
temp_y = anch_point[x] + axis_dist[x];
}
if (range_check(temp_x, temp_y, dy_width, dy_height)) {
dx[pos] = dx[pos] + interim_dy[(dx_block_num * dy_height + temp_y) * dy_width + temp_x];
}
}
}
// mirroring at corners
for (int x = 0; x < 2; x++) {
for (int y = 2; y < 4; y++) {
if ((axis_dist[x] != 0) && (axis_dist[y] != 0)) {
temp_x = anch_point[x] + axis_dist[x];
temp_y = anch_point[y] + axis_dist[y];
if (range_check(temp_x, temp_y, dy_width, dy_height)) {
dx[pos] = dx[pos] + interim_dy[(dx_block_num * dy_height + temp_y) * dy_width + temp_x];
}
}
}
}
}
return;
}
template <typename T>
void MirrorPadGradCPUKernel::MirrorPadGradBatchChannel(const size_t size, T *dy, T *interim_dy,
const int64_t dx_batches, const int64_t dx_channels,
const int64_t dy_height, const int64_t dy_width,
const int64_t padd_dim, const int64_t *paddings_arg,
int64_t mode) {
int64_t paddings[MAX_PADDINGS * PADDING_SIZE]; // local and fixed size to keep in registers
for (int i = 0; i < MAX_PADDINGS * PADDING_SIZE; i++) {
paddings[i] = 0; // init all to 0
}
extract_paddings_(paddings_arg, padd_dim, paddings);
// Create anchor points for non mirrored data inside new tensor
int64_t ap1_channel = paddings[CHANNEL];
int64_t ap2_channel = paddings[CHANNEL] + dx_channels - 1;
int64_t ap1_batch = paddings[BATCH];
int64_t ap2_batch = paddings[BATCH] + dx_batches - 1;
int64_t dy_channels = dx_channels + paddings[CHANNEL] + paddings[CHANNEL + RIGHT];
int64_t dy_batches = dx_batches + paddings[BATCH] + paddings[RIGHT];
for (size_t pos = 0; pos < size; ++pos) {
int64_t block_num = (SizeToLong(pos) / dy_width) / dy_height;
// Select exact position inside the dy_interim array
const int64_t interim_x = SizeToLong(pos) % dy_width;
const int64_t interim_y = (SizeToLong(pos) / dy_width) % dy_height;
const int64_t interim_channel = block_num % dx_channels;
const int64_t interim_batch = block_num / dx_channels;
interim_dy[pos] = T(0); // init
// map cur interim channel and batch to equivalent in padded dy array
const int64_t equiv_dy_channel = interim_channel + paddings[CHANNEL];
const int64_t equiv_dy_batch = interim_batch + paddings[BATCH];
int64_t target_batch = 0;
int64_t target_channel = 0;
int64_t equiv_block_num = 0;
equiv_block_num = ((equiv_dy_batch * dy_channels) + equiv_dy_channel);
// generate values to sweep over all possible mirrored points
int64_t batch_offsets[] = {2 * (ap1_batch - equiv_dy_batch) - mode, 0, 2 * (ap2_batch - equiv_dy_batch) + mode};
int64_t channel_offsets[] = {2 * (ap1_channel - equiv_dy_channel) - mode, 0,
2 * (ap2_channel - equiv_dy_channel) + mode};
for (int64_t b_adjust : batch_offsets) {
for (int64_t c_adjust : channel_offsets) {
target_batch = equiv_dy_batch + b_adjust;
target_channel = equiv_dy_channel + c_adjust;
// bounds check - if within bounds, mirrored value exists - copy dy
if ((target_batch < 0) || (target_batch > (dy_batches - 1)) || (target_channel < 0) ||
(target_channel > (dy_channels - 1))) {
continue; // no mirrored value with these target values
}
equiv_block_num = ((target_batch * dy_channels) + target_channel);
// Copy data and set value at input to 0 to avoid duplicates in reflect mode
interim_dy[pos] = T(interim_dy[pos] + dy[(equiv_block_num * dy_height + interim_y) * dy_width + interim_x]);
dy[(equiv_block_num * dy_height + interim_y) * dy_width + interim_x] = T(0);
}
}
}
return;
}
template <typename T>
void MirrorPadGradCPUKernel::LaunchKernel(const std::vector<AddressPtr> &inputs,
const std::vector<AddressPtr> &workspace,
const std::vector<AddressPtr> &outputs) {
auto inputs_addr = reinterpret_cast<T *>(inputs[0]->addr);
int64_t *paddings = reinterpret_cast<int64_t *>(inputs[1]->addr);
auto interim = reinterpret_cast<T *>(workspace[0]->addr);
auto outputs_addr = reinterpret_cast<T *>(outputs[0]->addr);
MirrorPadGradBatchChannel(workspace_size_, inputs_addr, interim, output_shape_[0], output_shape_[1], input_shape_[2],
input_shape_[3], num_paddings_, paddings, mode_);
MirrorPadGrad_Width_Height(output_size_, interim, output_shape_[2], output_shape_[3], input_shape_[2],
input_shape_[3], num_paddings_, paddings, mode_, outputs_addr);
}
void MirrorPadGradCPUKernel::CheckParam(const CNodePtr &kernel_node) {
size_t input_num = AnfAlgo::GetInputTensorNum(kernel_node);
if (input_num != 2) {
MS_LOG(EXCEPTION) << "Input number is " << input_num << ", but MirrorPadGradCPUKernel needs 2 inputs.";
}
size_t output_num = AnfAlgo::GetOutputTensorNum(kernel_node);
if (output_num != 1) {
MS_LOG(EXCEPTION) << "Output number is " << output_num << ", but MirrorPadGradCPUKernel needs 1 output.";
}
}
} // namespace kernel
} // namespace mindspore
| 43.163194 | 120 | 0.647333 | [
"shape",
"vector",
"3d"
] |
142cd6f38a55a8e81bb1fb334ece8b840bf991c7 | 29,336 | cpp | C++ | c_glib/arrow-cuda-glib/cuda.cpp | timkpaine/arrow | a96297e65e17e728e4321cdecc7ace146e1363fb | [
"CC-BY-3.0",
"Apache-2.0",
"CC0-1.0",
"MIT"
] | 9,734 | 2016-02-17T13:22:12.000Z | 2022-03-31T09:35:00.000Z | c_glib/arrow-cuda-glib/cuda.cpp | timkpaine/arrow | a96297e65e17e728e4321cdecc7ace146e1363fb | [
"CC-BY-3.0",
"Apache-2.0",
"CC0-1.0",
"MIT"
] | 11,470 | 2016-02-19T15:30:28.000Z | 2022-03-31T23:27:21.000Z | c_glib/arrow-cuda-glib/cuda.cpp | XpressAI/arrow | eafd885e06f6bbc1eb169ed64016f804c1810bec | [
"CC-BY-3.0",
"Apache-2.0",
"CC0-1.0",
"MIT"
] | 2,637 | 2016-02-17T10:56:29.000Z | 2022-03-31T08:20:13.000Z | /*
* 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-glib/buffer.hpp>
#include <arrow-glib/error.hpp>
#include <arrow-glib/input-stream.hpp>
#include <arrow-glib/ipc-options.hpp>
#include <arrow-glib/output-stream.hpp>
#include <arrow-glib/readable.hpp>
#include <arrow-glib/record-batch.hpp>
#include <arrow-glib/schema.hpp>
#include <arrow-cuda-glib/cuda.hpp>
G_BEGIN_DECLS
/**
* SECTION: cuda
* @section_id: cuda-classes
* @title: CUDA related classes
* @include: arrow-cuda-glib/arrow-cuda-glib.h
*
* The following classes provide CUDA support for Apache Arrow data.
*
* #GArrowCUDADeviceManager is the starting point. You need at
* least one #GArrowCUDAContext to process Apache Arrow data on
* NVIDIA GPU.
*
* #GArrowCUDAContext is a class to keep context for one GPU. You
* need to create #GArrowCUDAContext for each GPU that you want to
* use. You can create #GArrowCUDAContext by
* garrow_cuda_device_manager_get_context().
*
* #GArrowCUDABuffer is a class for data on GPU. You can copy data
* on GPU to/from CPU by garrow_cuda_buffer_copy_to_host() and
* garrow_cuda_buffer_copy_from_host(). You can share data on GPU
* with other processes by garrow_cuda_buffer_export() and
* garrow_cuda_buffer_new_ipc().
*
* #GArrowCUDAHostBuffer is a class for data on CPU that is
* directly accessible from GPU.
*
* #GArrowCUDAIPCMemoryHandle is a class to share data on GPU with
* other processes. You can export your data on GPU to other processes
* by garrow_cuda_buffer_export() and
* garrow_cuda_ipc_memory_handle_new(). You can import other
* process data on GPU by garrow_cuda_ipc_memory_handle_new() and
* garrow_cuda_buffer_new_ipc().
*
* #GArrowCUDABufferInputStream is a class to read data in
* #GArrowCUDABuffer.
*
* #GArrowCUDABufferOutputStream is a class to write data into
* #GArrowCUDABuffer.
*/
G_DEFINE_TYPE(GArrowCUDADeviceManager,
garrow_cuda_device_manager,
G_TYPE_OBJECT)
static void
garrow_cuda_device_manager_init(GArrowCUDADeviceManager *object)
{
}
static void
garrow_cuda_device_manager_class_init(GArrowCUDADeviceManagerClass *klass)
{
}
/**
* garrow_cuda_device_manager_new:
* @error: (nullable): Return location for a #GError or %NULL.
*
* Returns: A newly created #GArrowCUDADeviceManager on success,
* %NULL on error.
*
* Since: 0.8.0
*/
GArrowCUDADeviceManager *
garrow_cuda_device_manager_new(GError **error)
{
auto arrow_manager = arrow::cuda::CudaDeviceManager::Instance();
if (garrow::check(error, arrow_manager, "[cuda][device-manager][new]")) {
auto manager = g_object_new(GARROW_CUDA_TYPE_DEVICE_MANAGER,
NULL);
return GARROW_CUDA_DEVICE_MANAGER(manager);
} else {
return NULL;
}
}
/**
* garrow_cuda_device_manager_get_context:
* @manager: A #GArrowCUDADeviceManager.
* @gpu_number: A GPU device number for the target context.
* @error: (nullable): Return location for a #GError or %NULL.
*
* Returns: (transfer full): A newly created #GArrowCUDAContext on
* success, %NULL on error. Contexts for the same GPU device number
* share the same data internally.
*
* Since: 0.8.0
*/
GArrowCUDAContext *
garrow_cuda_device_manager_get_context(GArrowCUDADeviceManager *manager,
gint gpu_number,
GError **error)
{
auto arrow_manager = arrow::cuda::CudaDeviceManager::Instance();
auto arrow_cuda_context = (*arrow_manager)->GetContext(gpu_number);
if (garrow::check(error, arrow_cuda_context,
"[cuda][device-manager][get-context]]")) {
return garrow_cuda_context_new_raw(&(*arrow_cuda_context));
} else {
return NULL;
}
}
/**
* garrow_cuda_device_manager_get_n_devices:
* @manager: A #GArrowCUDADeviceManager.
*
* Returns: The number of GPU devices.
*
* Since: 0.8.0
*/
gsize
garrow_cuda_device_manager_get_n_devices(GArrowCUDADeviceManager *manager)
{
auto arrow_manager = arrow::cuda::CudaDeviceManager::Instance();
return (*arrow_manager)->num_devices();
}
typedef struct GArrowCUDAContextPrivate_ {
std::shared_ptr<arrow::cuda::CudaContext> context;
} GArrowCUDAContextPrivate;
enum {
PROP_CONTEXT = 1
};
G_DEFINE_TYPE_WITH_PRIVATE(GArrowCUDAContext,
garrow_cuda_context,
G_TYPE_OBJECT)
#define GARROW_CUDA_CONTEXT_GET_PRIVATE(object) \
static_cast<GArrowCUDAContextPrivate *>( \
garrow_cuda_context_get_instance_private( \
GARROW_CUDA_CONTEXT(object)))
static void
garrow_cuda_context_finalize(GObject *object)
{
auto priv = GARROW_CUDA_CONTEXT_GET_PRIVATE(object);
priv->context.~shared_ptr();
G_OBJECT_CLASS(garrow_cuda_context_parent_class)->finalize(object);
}
static void
garrow_cuda_context_set_property(GObject *object,
guint prop_id,
const GValue *value,
GParamSpec *pspec)
{
auto priv = GARROW_CUDA_CONTEXT_GET_PRIVATE(object);
switch (prop_id) {
case PROP_CONTEXT:
priv->context =
*static_cast<std::shared_ptr<arrow::cuda::CudaContext> *>(g_value_get_pointer(value));
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID(object, prop_id, pspec);
break;
}
}
static void
garrow_cuda_context_get_property(GObject *object,
guint prop_id,
GValue *value,
GParamSpec *pspec)
{
switch (prop_id) {
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID(object, prop_id, pspec);
break;
}
}
static void
garrow_cuda_context_init(GArrowCUDAContext *object)
{
auto priv = GARROW_CUDA_CONTEXT_GET_PRIVATE(object);
new(&priv->context) std::shared_ptr<arrow::cuda::CudaContext>;
}
static void
garrow_cuda_context_class_init(GArrowCUDAContextClass *klass)
{
GParamSpec *spec;
auto gobject_class = G_OBJECT_CLASS(klass);
gobject_class->finalize = garrow_cuda_context_finalize;
gobject_class->set_property = garrow_cuda_context_set_property;
gobject_class->get_property = garrow_cuda_context_get_property;
/**
* GArrowCUDAContext:context:
*
* Since: 0.8.0
*/
spec = g_param_spec_pointer("context",
"Context",
"The raw std::shared_ptr<arrow::cuda::CudaContext>",
static_cast<GParamFlags>(G_PARAM_WRITABLE |
G_PARAM_CONSTRUCT_ONLY));
g_object_class_install_property(gobject_class, PROP_CONTEXT, spec);
}
/**
* garrow_cuda_context_get_allocated_size:
* @context: A #GArrowCUDAContext.
*
* Returns: The allocated memory by this context in bytes.
*
* Since: 0.8.0
*/
gint64
garrow_cuda_context_get_allocated_size(GArrowCUDAContext *context)
{
auto arrow_context = garrow_cuda_context_get_raw(context);
return arrow_context->bytes_allocated();
}
G_DEFINE_TYPE(GArrowCUDABuffer,
garrow_cuda_buffer,
GARROW_TYPE_BUFFER)
static void
garrow_cuda_buffer_init(GArrowCUDABuffer *object)
{
}
static void
garrow_cuda_buffer_class_init(GArrowCUDABufferClass *klass)
{
}
/**
* garrow_cuda_buffer_new:
* @context: A #GArrowCUDAContext.
* @size: The number of bytes to be allocated on GPU device for this context.
* @error: (nullable): Return location for a #GError or %NULL.
*
* Returns: (transfer full): A newly created #GArrowCUDABuffer on
* success, %NULL on error.
*
* Since: 0.8.0
*/
GArrowCUDABuffer *
garrow_cuda_buffer_new(GArrowCUDAContext *context,
gint64 size,
GError **error)
{
auto arrow_context = garrow_cuda_context_get_raw(context);
auto arrow_buffer = arrow_context->Allocate(size);
if (garrow::check(error, arrow_buffer, "[cuda][buffer][new]")) {
return garrow_cuda_buffer_new_raw(&(*arrow_buffer));
} else {
return NULL;
}
}
/**
* garrow_cuda_buffer_new_ipc:
* @context: A #GArrowCUDAContext.
* @handle: A #GArrowCUDAIPCMemoryHandle to be communicated.
* @error: (nullable): Return location for a #GError or %NULL.
*
* Returns: (transfer full): A newly created #GArrowCUDABuffer on
* success, %NULL on error. The buffer has data from the IPC target.
*
* Since: 0.8.0
*/
GArrowCUDABuffer *
garrow_cuda_buffer_new_ipc(GArrowCUDAContext *context,
GArrowCUDAIPCMemoryHandle *handle,
GError **error)
{
auto arrow_context = garrow_cuda_context_get_raw(context);
auto arrow_handle = garrow_cuda_ipc_memory_handle_get_raw(handle);
auto arrow_buffer = arrow_context->OpenIpcBuffer(*arrow_handle);
if (garrow::check(error, arrow_buffer, "[cuda][buffer][new-ipc]")) {
return garrow_cuda_buffer_new_raw(&(*arrow_buffer));
} else {
return NULL;
}
}
/**
* garrow_cuda_buffer_new_record_batch:
* @context: A #GArrowCUDAContext.
* @record_batch: A #GArrowRecordBatch to be serialized.
* @error: (nullable): Return location for a #GError or %NULL.
*
* Returns: (transfer full): A newly created #GArrowCUDABuffer on
* success, %NULL on error. The buffer has serialized record batch
* data.
*
* Since: 0.8.0
*/
GArrowCUDABuffer *
garrow_cuda_buffer_new_record_batch(GArrowCUDAContext *context,
GArrowRecordBatch *record_batch,
GError **error)
{
auto arrow_context = garrow_cuda_context_get_raw(context);
auto arrow_record_batch = garrow_record_batch_get_raw(record_batch);
auto arrow_buffer = arrow::cuda::SerializeRecordBatch(*arrow_record_batch,
arrow_context.get());
if (garrow::check(error, arrow_buffer, "[cuda][buffer][new-record-batch]")) {
return garrow_cuda_buffer_new_raw(&(*arrow_buffer));
} else {
return NULL;
}
}
/**
* garrow_cuda_buffer_copy_to_host:
* @buffer: A #GArrowCUDABuffer.
* @position: The offset of memory on GPU device to be copied.
* @size: The size of memory on GPU device to be copied in bytes.
* @error: (nullable): Return location for a #GError or %NULL.
*
* Returns: (transfer full): A #GBytes that have copied memory on CPU
* host on success, %NULL on error.
*
* Since: 0.8.0
*/
GBytes *
garrow_cuda_buffer_copy_to_host(GArrowCUDABuffer *buffer,
gint64 position,
gint64 size,
GError **error)
{
auto arrow_buffer = garrow_cuda_buffer_get_raw(buffer);
auto data = static_cast<uint8_t *>(g_malloc(size));
auto status = arrow_buffer->CopyToHost(position, size, data);
if (garrow_error_check(error, status, "[cuda][buffer][copy-to-host]")) {
return g_bytes_new_take(data, size);
} else {
g_free(data);
return NULL;
}
}
/**
* garrow_cuda_buffer_copy_from_host:
* @buffer: A #GArrowCUDABuffer.
* @data: (array length=size): Data on CPU host to be copied.
* @size: The size of data on CPU host to be copied in bytes.
* @error: (nullable): Return location for a #GError or %NULL.
*
* Returns: %TRUE on success, %FALSE if there was an error.
*
* Since: 0.8.0
*/
gboolean
garrow_cuda_buffer_copy_from_host(GArrowCUDABuffer *buffer,
const guint8 *data,
gint64 size,
GError **error)
{
auto arrow_buffer = garrow_cuda_buffer_get_raw(buffer);
auto status = arrow_buffer->CopyFromHost(0, data, size);
return garrow_error_check(error,
status,
"[cuda][buffer][copy-from-host]");
}
/**
* garrow_cuda_buffer_export:
* @buffer: A #GArrowCUDABuffer.
* @error: (nullable): Return location for a #GError or %NULL.
*
* Returns: (transfer full): A newly created
* #GArrowCUDAIPCMemoryHandle to handle the exported buffer on
* success, %NULL on error
*
* Since: 0.8.0
*/
GArrowCUDAIPCMemoryHandle *
garrow_cuda_buffer_export(GArrowCUDABuffer *buffer, GError **error)
{
auto arrow_buffer = garrow_cuda_buffer_get_raw(buffer);
auto arrow_handle = arrow_buffer->ExportForIpc();
if (garrow::check(error, arrow_handle, "[cuda][buffer][export-for-ipc]")) {
return garrow_cuda_ipc_memory_handle_new_raw(&(*arrow_handle));
} else {
return NULL;
}
}
/**
* garrow_cuda_buffer_get_context:
* @buffer: A #GArrowCUDABuffer.
*
* Returns: (transfer full): A newly created #GArrowCUDAContext for the
* buffer. Contexts for the same buffer share the same data internally.
*
* Since: 0.8.0
*/
GArrowCUDAContext *
garrow_cuda_buffer_get_context(GArrowCUDABuffer *buffer)
{
auto arrow_buffer = garrow_cuda_buffer_get_raw(buffer);
auto arrow_context = arrow_buffer->context();
return garrow_cuda_context_new_raw(&arrow_context);
}
/**
* garrow_cuda_buffer_read_record_batch:
* @buffer: A #GArrowCUDABuffer.
* @schema: A #GArrowSchema for record batch.
* @options: (nullable): A #GArrowReadOptions.
* @error: (nullable): Return location for a #GError or %NULL.
*
* Returns: (transfer full): A newly created #GArrowRecordBatch on
* success, %NULL on error. The record batch data is located on GPU.
*
* Since: 0.8.0
*/
GArrowRecordBatch *
garrow_cuda_buffer_read_record_batch(GArrowCUDABuffer *buffer,
GArrowSchema *schema,
GArrowReadOptions *options,
GError **error)
{
auto arrow_buffer = garrow_cuda_buffer_get_raw(buffer);
auto arrow_schema = garrow_schema_get_raw(schema);
if (options) {
auto arrow_options = garrow_read_options_get_raw(options);
auto arrow_dictionary_memo =
garrow_read_options_get_dictionary_memo_raw(options);
auto arrow_record_batch =
arrow::cuda::ReadRecordBatch(arrow_schema,
arrow_dictionary_memo,
arrow_buffer,
arrow_options->memory_pool);
if (garrow::check(error, arrow_record_batch,
"[cuda][buffer][read-record-batch]")) {
return garrow_record_batch_new_raw(&(*arrow_record_batch));
} else {
return NULL;
}
} else {
auto arrow_pool = arrow::default_memory_pool();
auto arrow_record_batch =
arrow::cuda::ReadRecordBatch(arrow_schema,
nullptr,
arrow_buffer,
arrow_pool);
if (garrow::check(error, arrow_record_batch,
"[cuda][buffer][read-record-batch]")) {
return garrow_record_batch_new_raw(&(*arrow_record_batch));
} else {
return NULL;
}
}
}
G_DEFINE_TYPE(GArrowCUDAHostBuffer,
garrow_cuda_host_buffer,
GARROW_TYPE_MUTABLE_BUFFER)
static void
garrow_cuda_host_buffer_init(GArrowCUDAHostBuffer *object)
{
}
static void
garrow_cuda_host_buffer_class_init(GArrowCUDAHostBufferClass *klass)
{
}
/**
* garrow_cuda_host_buffer_new:
* @gpu_number: A GPU device number for the target context.
* @size: The number of bytes to be allocated on CPU host.
* @error: (nullable): Return location for a #GError or %NULL.
*
* Returns: A newly created #GArrowCUDAHostBuffer on success,
* %NULL on error. The allocated memory is accessible from GPU
* device for the @context.
*
* Since: 0.8.0
*/
GArrowCUDAHostBuffer *
garrow_cuda_host_buffer_new(gint gpu_number, gint64 size, GError **error)
{
auto arrow_manager = arrow::cuda::CudaDeviceManager::Instance();
auto arrow_buffer = (*arrow_manager)->AllocateHost(gpu_number, size);
if (garrow::check(error, arrow_buffer, "[cuda][host-buffer][new]")) {
return garrow_cuda_host_buffer_new_raw(&(*arrow_buffer));
} else {
return NULL;
}
}
typedef struct GArrowCUDAIPCMemoryHandlePrivate_ {
std::shared_ptr<arrow::cuda::CudaIpcMemHandle> ipc_memory_handle;
} GArrowCUDAIPCMemoryHandlePrivate;
enum {
PROP_IPC_MEMORY_HANDLE = 1
};
G_DEFINE_TYPE_WITH_PRIVATE(GArrowCUDAIPCMemoryHandle,
garrow_cuda_ipc_memory_handle,
G_TYPE_OBJECT)
#define GARROW_CUDA_IPC_MEMORY_HANDLE_GET_PRIVATE(object) \
static_cast<GArrowCUDAIPCMemoryHandlePrivate *>( \
garrow_cuda_ipc_memory_handle_get_instance_private( \
GARROW_CUDA_IPC_MEMORY_HANDLE(object)))
static void
garrow_cuda_ipc_memory_handle_finalize(GObject *object)
{
auto priv = GARROW_CUDA_IPC_MEMORY_HANDLE_GET_PRIVATE(object);
priv->ipc_memory_handle = nullptr;
G_OBJECT_CLASS(garrow_cuda_ipc_memory_handle_parent_class)->finalize(object);
}
static void
garrow_cuda_ipc_memory_handle_set_property(GObject *object,
guint prop_id,
const GValue *value,
GParamSpec *pspec)
{
auto priv = GARROW_CUDA_IPC_MEMORY_HANDLE_GET_PRIVATE(object);
switch (prop_id) {
case PROP_IPC_MEMORY_HANDLE:
priv->ipc_memory_handle =
*static_cast<std::shared_ptr<arrow::cuda::CudaIpcMemHandle> *>(g_value_get_pointer(value));
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID(object, prop_id, pspec);
break;
}
}
static void
garrow_cuda_ipc_memory_handle_get_property(GObject *object,
guint prop_id,
GValue *value,
GParamSpec *pspec)
{
switch (prop_id) {
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID(object, prop_id, pspec);
break;
}
}
static void
garrow_cuda_ipc_memory_handle_init(GArrowCUDAIPCMemoryHandle *object)
{
}
static void
garrow_cuda_ipc_memory_handle_class_init(GArrowCUDAIPCMemoryHandleClass *klass)
{
GParamSpec *spec;
auto gobject_class = G_OBJECT_CLASS(klass);
gobject_class->finalize = garrow_cuda_ipc_memory_handle_finalize;
gobject_class->set_property = garrow_cuda_ipc_memory_handle_set_property;
gobject_class->get_property = garrow_cuda_ipc_memory_handle_get_property;
/**
* GArrowCUDAIPCMemoryHandle:ipc-memory-handle:
*
* Since: 0.8.0
*/
spec = g_param_spec_pointer("ipc-memory-handle",
"IPC Memory Handle",
"The raw std::shared_ptr<arrow::cuda::CudaIpcMemHandle>",
static_cast<GParamFlags>(G_PARAM_WRITABLE |
G_PARAM_CONSTRUCT_ONLY));
g_object_class_install_property(gobject_class, PROP_IPC_MEMORY_HANDLE, spec);
}
/**
* garrow_cuda_ipc_memory_handle_new:
* @data: (array length=size): A serialized #GArrowCUDAIPCMemoryHandle.
* @size: The size of data.
* @error: (nullable): Return location for a #GError or %NULL.
*
* Returns: (transfer full): A newly created #GArrowCUDAIPCMemoryHandle
* on success, %NULL on error.
*
* Since: 0.8.0
*/
GArrowCUDAIPCMemoryHandle *
garrow_cuda_ipc_memory_handle_new(const guint8 *data,
gsize size,
GError **error)
{
auto arrow_handle = arrow::cuda::CudaIpcMemHandle::FromBuffer(data);
if (garrow::check(error, arrow_handle, "[cuda][ipc-memory-handle][new]")) {
return garrow_cuda_ipc_memory_handle_new_raw(&(*arrow_handle));
} else {
return NULL;
}
}
/**
* garrow_cuda_ipc_memory_handle_serialize:
* @handle: A #GArrowCUDAIPCMemoryHandle.
* @error: (nullable): Return location for a #GError or %NULL.
*
* Returns: (transfer full): A newly created #GArrowBuffer on success,
* %NULL on error. The buffer has serialized @handle. The serialized
* @handle can be deserialized by garrow_cuda_ipc_memory_handle_new()
* in other process.
*
* Since: 0.8.0
*/
GArrowBuffer *
garrow_cuda_ipc_memory_handle_serialize(GArrowCUDAIPCMemoryHandle *handle,
GError **error)
{
auto arrow_handle = garrow_cuda_ipc_memory_handle_get_raw(handle);
auto arrow_buffer = arrow_handle->Serialize(arrow::default_memory_pool());
if (garrow::check(error, arrow_buffer,
"[cuda][ipc-memory-handle][serialize]")) {
return garrow_buffer_new_raw(&(*arrow_buffer));
} else {
return NULL;
}
}
static GArrowBuffer *
garrow_cuda_buffer_input_stream_buffer_new_raw_readable_interface(std::shared_ptr<arrow::Buffer> *arrow_buffer)
{
auto arrow_cuda_buffer =
reinterpret_cast<std::shared_ptr<arrow::cuda::CudaBuffer> *>(arrow_buffer);
auto cuda_buffer = garrow_cuda_buffer_new_raw(arrow_cuda_buffer);
return GARROW_BUFFER(cuda_buffer);
}
static std::shared_ptr<arrow::io::Readable>
garrow_cuda_buffer_input_stream_get_raw_readable_interface(GArrowReadable *readable)
{
auto input_stream = GARROW_INPUT_STREAM(readable);
auto arrow_input_stream = garrow_input_stream_get_raw(input_stream);
return arrow_input_stream;
}
static void
garrow_cuda_buffer_input_stream_readable_interface_init(GArrowReadableInterface *iface)
{
iface->buffer_new_raw =
garrow_cuda_buffer_input_stream_buffer_new_raw_readable_interface;
iface->get_raw =
garrow_cuda_buffer_input_stream_get_raw_readable_interface;
}
G_DEFINE_TYPE_WITH_CODE(
GArrowCUDABufferInputStream,
garrow_cuda_buffer_input_stream,
GARROW_TYPE_BUFFER_INPUT_STREAM,
G_IMPLEMENT_INTERFACE(
GARROW_TYPE_READABLE,
garrow_cuda_buffer_input_stream_readable_interface_init))
static void
garrow_cuda_buffer_input_stream_init(GArrowCUDABufferInputStream *object)
{
}
static void
garrow_cuda_buffer_input_stream_class_init(GArrowCUDABufferInputStreamClass *klass)
{
}
/**
* garrow_cuda_buffer_input_stream_new:
* @buffer: A #GArrowCUDABuffer.
*
* Returns: (transfer full): A newly created
* #GArrowCUDABufferInputStream.
*
* Since: 0.8.0
*/
GArrowCUDABufferInputStream *
garrow_cuda_buffer_input_stream_new(GArrowCUDABuffer *buffer)
{
auto arrow_buffer = garrow_cuda_buffer_get_raw(buffer);
auto arrow_reader =
std::make_shared<arrow::cuda::CudaBufferReader>(arrow_buffer);
return garrow_cuda_buffer_input_stream_new_raw(&arrow_reader);
}
G_DEFINE_TYPE(GArrowCUDABufferOutputStream,
garrow_cuda_buffer_output_stream,
GARROW_TYPE_OUTPUT_STREAM)
static void
garrow_cuda_buffer_output_stream_init(GArrowCUDABufferOutputStream *object)
{
}
static void
garrow_cuda_buffer_output_stream_class_init(GArrowCUDABufferOutputStreamClass *klass)
{
}
/**
* garrow_cuda_buffer_output_stream_new:
* @buffer: A #GArrowCUDABuffer.
*
* Returns: (transfer full): A newly created
* #GArrowCUDABufferOutputStream.
*
* Since: 0.8.0
*/
GArrowCUDABufferOutputStream *
garrow_cuda_buffer_output_stream_new(GArrowCUDABuffer *buffer)
{
auto arrow_buffer = garrow_cuda_buffer_get_raw(buffer);
auto arrow_writer =
std::make_shared<arrow::cuda::CudaBufferWriter>(arrow_buffer);
return garrow_cuda_buffer_output_stream_new_raw(&arrow_writer);
}
/**
* garrow_cuda_buffer_output_stream_set_buffer_size:
* @stream: A #GArrowCUDABufferOutputStream.
* @size: A size of CPU buffer in bytes.
* @error: (nullable): Return location for a #GError or %NULL.
*
* Returns: %TRUE on success, %FALSE if there was an error.
*
* Sets CPU buffer size. to limit `cudaMemcpy()` calls. If CPU buffer
* size is `0`, buffering is disabled.
*
* The default is `0`.
*
* Since: 0.8.0
*/
gboolean
garrow_cuda_buffer_output_stream_set_buffer_size(GArrowCUDABufferOutputStream *stream,
gint64 size,
GError **error)
{
auto arrow_stream = garrow_cuda_buffer_output_stream_get_raw(stream);
auto status = arrow_stream->SetBufferSize(size);
return garrow_error_check(error,
status,
"[cuda][buffer-output-stream][set-buffer-size]");
}
/**
* garrow_cuda_buffer_output_stream_get_buffer_size:
* @stream: A #GArrowCUDABufferOutputStream.
*
* Returns: The CPU buffer size in bytes.
*
* See garrow_cuda_buffer_output_stream_set_buffer_size() for CPU
* buffer size details.
*
* Since: 0.8.0
*/
gint64
garrow_cuda_buffer_output_stream_get_buffer_size(GArrowCUDABufferOutputStream *stream)
{
auto arrow_stream = garrow_cuda_buffer_output_stream_get_raw(stream);
return arrow_stream->buffer_size();
}
/**
* garrow_cuda_buffer_output_stream_get_buffered_size:
* @stream: A #GArrowCUDABufferOutputStream.
*
* Returns: The size of buffered data in bytes.
*
* Since: 0.8.0
*/
gint64
garrow_cuda_buffer_output_stream_get_buffered_size(GArrowCUDABufferOutputStream *stream)
{
auto arrow_stream = garrow_cuda_buffer_output_stream_get_raw(stream);
return arrow_stream->num_bytes_buffered();
}
G_END_DECLS
GArrowCUDAContext *
garrow_cuda_context_new_raw(std::shared_ptr<arrow::cuda::CudaContext> *arrow_context)
{
return GARROW_CUDA_CONTEXT(g_object_new(GARROW_CUDA_TYPE_CONTEXT,
"context", arrow_context,
NULL));
}
std::shared_ptr<arrow::cuda::CudaContext>
garrow_cuda_context_get_raw(GArrowCUDAContext *context)
{
if (!context)
return nullptr;
auto priv = GARROW_CUDA_CONTEXT_GET_PRIVATE(context);
return priv->context;
}
GArrowCUDAIPCMemoryHandle *
garrow_cuda_ipc_memory_handle_new_raw(std::shared_ptr<arrow::cuda::CudaIpcMemHandle> *arrow_handle)
{
auto handle = g_object_new(GARROW_CUDA_TYPE_IPC_MEMORY_HANDLE,
"ipc-memory-handle", arrow_handle,
NULL);
return GARROW_CUDA_IPC_MEMORY_HANDLE(handle);
}
std::shared_ptr<arrow::cuda::CudaIpcMemHandle>
garrow_cuda_ipc_memory_handle_get_raw(GArrowCUDAIPCMemoryHandle *handle)
{
if (!handle)
return nullptr;
auto priv = GARROW_CUDA_IPC_MEMORY_HANDLE_GET_PRIVATE(handle);
return priv->ipc_memory_handle;
}
GArrowCUDABuffer *
garrow_cuda_buffer_new_raw(std::shared_ptr<arrow::cuda::CudaBuffer> *arrow_buffer)
{
return GARROW_CUDA_BUFFER(g_object_new(GARROW_CUDA_TYPE_BUFFER,
"buffer", arrow_buffer,
NULL));
}
std::shared_ptr<arrow::cuda::CudaBuffer>
garrow_cuda_buffer_get_raw(GArrowCUDABuffer *buffer)
{
if (!buffer)
return nullptr;
auto arrow_buffer = garrow_buffer_get_raw(GARROW_BUFFER(buffer));
return std::static_pointer_cast<arrow::cuda::CudaBuffer>(arrow_buffer);
}
GArrowCUDAHostBuffer *
garrow_cuda_host_buffer_new_raw(std::shared_ptr<arrow::cuda::CudaHostBuffer> *arrow_buffer)
{
auto buffer = g_object_new(GARROW_CUDA_TYPE_HOST_BUFFER,
"buffer", arrow_buffer,
NULL);
return GARROW_CUDA_HOST_BUFFER(buffer);
}
std::shared_ptr<arrow::cuda::CudaHostBuffer>
garrow_cuda_host_buffer_get_raw(GArrowCUDAHostBuffer *buffer)
{
if (!buffer)
return nullptr;
auto arrow_buffer = garrow_buffer_get_raw(GARROW_BUFFER(buffer));
return std::static_pointer_cast<arrow::cuda::CudaHostBuffer>(arrow_buffer);
}
GArrowCUDABufferInputStream *
garrow_cuda_buffer_input_stream_new_raw(std::shared_ptr<arrow::cuda::CudaBufferReader> *arrow_reader)
{
auto input_stream = g_object_new(GARROW_CUDA_TYPE_BUFFER_INPUT_STREAM,
"input-stream", arrow_reader,
NULL);
return GARROW_CUDA_BUFFER_INPUT_STREAM(input_stream);
}
std::shared_ptr<arrow::cuda::CudaBufferReader>
garrow_cuda_buffer_input_stream_get_raw(GArrowCUDABufferInputStream *input_stream)
{
if (!input_stream)
return nullptr;
auto arrow_reader =
garrow_input_stream_get_raw(GARROW_INPUT_STREAM(input_stream));
return std::static_pointer_cast<arrow::cuda::CudaBufferReader>(arrow_reader);
}
GArrowCUDABufferOutputStream *
garrow_cuda_buffer_output_stream_new_raw(std::shared_ptr<arrow::cuda::CudaBufferWriter> *arrow_writer)
{
auto output_stream = g_object_new(GARROW_CUDA_TYPE_BUFFER_OUTPUT_STREAM,
"output-stream", arrow_writer,
NULL);
return GARROW_CUDA_BUFFER_OUTPUT_STREAM(output_stream);
}
std::shared_ptr<arrow::cuda::CudaBufferWriter>
garrow_cuda_buffer_output_stream_get_raw(GArrowCUDABufferOutputStream *output_stream)
{
if (!output_stream)
return nullptr;
auto arrow_writer =
garrow_output_stream_get_raw(GARROW_OUTPUT_STREAM(output_stream));
return std::static_pointer_cast<arrow::cuda::CudaBufferWriter>(arrow_writer);
}
| 31.043386 | 111 | 0.698732 | [
"object"
] |
142d1748a8e0762aeef6c0e6d58ac544371d3739 | 15,384 | cpp | C++ | SPHINXsys/src/shared/simbody/state_engine.cpp | Irvise/SPHinXsys | dfa67ec02bbc85824e2d6adf6d0395bb887e2bdb | [
"Apache-2.0"
] | 3 | 2020-11-30T15:24:54.000Z | 2021-04-11T09:16:09.000Z | SPHINXsys/src/shared/simbody/state_engine.cpp | Bo-Zhang1995/SPHinXsys | ee03f41711cc8ee7dcf75cdff6afa0859b0a0e89 | [
"Apache-2.0"
] | null | null | null | SPHINXsys/src/shared/simbody/state_engine.cpp | Bo-Zhang1995/SPHinXsys | ee03f41711cc8ee7dcf75cdff6afa0859b0a0e89 | [
"Apache-2.0"
] | null | null | null | /**
* @file statengine.cpp
* @brief engine of state functions are defined here
* @author Chi Zhang and Xiangyu Hu
*/
#include "state_engine.h"
namespace SPH {
//===============================================================//
StateEngine::
StateEngine(SimTK::MultibodySystem& system)
{
mbsystem_ = system;
restart_folder_ = "./rstfile";
if (!fs::exists(restart_folder_))
{
fs::create_directory(restart_folder_);
}
}
//===============================================================//
void StateEngine::InitializeState()
{
/** Clear cached list of all related
StateVariables if any from a previousSystem.
*/
allstatevariables_.clear();
getMultibodySystem().invalidateSystemTopologyCache();
getMultibodySystem().realizeTopology();
/** Set the model's operating state (internal member variable) to the
default state that is stored inside the System.
*/
working_state_ = getMultibodySystem().getDefaultState();
/** Process the modified modeling option. */
getMultibodySystem().realizeModel(working_state_);
/** Realize instance variables that may have been set above. This
* means floating point parameters such as mass properties and
* geometry placements are frozen.
*/
getMultibodySystem().realize(working_state_, SimTK::Stage::Instance);
/** Realize the initial configuration in preparation. This
* initial configuration does not necessarily satisfy constraints.
*/
getMultibodySystem().realize(working_state_, SimTK::Stage::Position);
}
//===============================================================//
SimTK::MultibodySystem& StateEngine::getMultibodySystem()
{
return mbsystem_.getRef();
}
//===============================================================//
void StateEngine::addStateVariable(std::string statevariablename,
SimTK::Stage invalidatestage)
{
if( (invalidatestage < SimTK::Stage::Position) ||
(invalidatestage > SimTK::Stage::Dynamics))
{
std::stringstream msg;
msg << "StateEngine::addStateVariable: invalidatestage "
"must be Position, Velocity or Dynamics." << ".";
throw (msg.str(),__FILE__,__LINE__);
}
/** Allocate space for a new state variable. */
AddedStateVariable* asv =
new AddedStateVariable(statevariablename, *this, invalidatestage);
// Add it to the Component and let it take ownership
addStateVariable(asv);
}
//===============================================================//
void StateEngine::addStateVariable(StateEngine::StateVariable* statevariable)
{
std::string& statevariablename = statevariable->getName();
/** don't add state if there is another state variable with the same name. */
std::map<std::string, StateVariableInfo>::const_iterator it;
it = namedstatevariableinfo_.find(statevariablename);
if(it != namedstatevariableinfo_.end())
{
std::stringstream msg;
msg << "StateEngine::addStateVariable: State variable " <<
statevariablename<< " already exists."<< ".";
throw (msg.str(),__FILE__,__LINE__);
}
int order = (int)namedstatevariableinfo_.size();
/** assign a "slot" for a state variable by name
state variable index will be invalid by default
upon allocation during realizeTopology the index will be set
*/
namedstatevariableinfo_[statevariablename] = StateVariableInfo(statevariable, order);
AddedStateVariable* asv =
dynamic_cast<StateEngine::AddedStateVariable *>(statevariable);
}
//===============================================================//
StateEngine::StateVariable* StateEngine::
traverseToStateVariable(std::string& pathname)
{
auto it = namedstatevariableinfo_.find(pathname);
if (it != namedstatevariableinfo_.end())
{
return it->second.statevariable_.get();
}
else {
return NULL;
}
}
//===============================================================//.
Array<std::string> StateEngine::getStateVariableNames()
{
std::map<std::string, StateVariableInfo>::const_iterator it;
it = namedstatevariableinfo_.begin();
Array<std::string> names;//("",(int)namedstatevariableinfo_.size());
while(it != namedstatevariableinfo_.end())
{
names[it->second.order] = it->first;
it++;
}
return names;
}
//===============================================================//
int StateEngine::getNumOfStateVariables()
{
return getNumStateVariablesAddedByEngine();
}
//===============================================================//
bool StateEngine::isAllStatesVariablesListValid()
{
int nsv = getNumOfStateVariables();
/** Consider the list of all StateVariables to be valid if all of
the following conditions are true:
1. a System has been associated with the list of StateVariables
2. The list of all StateVariables is correctly sized (initialized)
3. The System associated with the StateVariables is the current System */
bool valid =
!statesassociatedsystem_.empty() &&
(int)allstatevariables_.size() == nsv &&
getMultibodySystem().isSameSystem(statesassociatedsystem_.getRef());
return valid;
}
//===============================================================//
SimTK::Vector StateEngine::getStateVariableValues()
{
int nsv = getNumOfStateVariables();
/** if the StateVariables are invalid, rebuild the list. */
if (!isAllStatesVariablesListValid())
{
statesassociatedsystem_.reset(&getMultibodySystem());
allstatevariables_.clear();
allstatevariables_.resize(nsv);
Array<std::string> names = getStateVariableNames();
for (int i = 0; i < nsv; ++i)
allstatevariables_[i].reset(traverseToStateVariable(names[i]));
}
SimTK::Vector statevariablevalues(nsv, SimTK::NaN);
for(int i=0; i<nsv; ++i){
statevariablevalues[i]= allstatevariables_[i]->getValue( );
std::cout<<statevariablevalues[i]<<std::endl;
}
return statevariablevalues;
}
//-----------------------------------------------------------------------------//
// OTHER REALIZE METHODS
//-----------------------------------------------------------------------------//
/** override virtual methods. */
Real StateEngine::AddedStateVariable::getValue()
{
SimTK::ZIndex zix(getVarIndex());
if(getSubsysIndex().isValid() && zix.isValid()){
const SimTK::Vector& z = getOwner().getDefaultSubsystem().getZ(getOwner().working_state_);
return z[SimTK::ZIndex(zix)];
}
std::stringstream msg;
msg << "StateEngine::AddedStateVariable::getValue: ERR- variable '"
<< getName() << "' is invalid! " <<".";
throw (msg.str(),__FILE__,__LINE__);
return SimTK::NaN;
}
//===============================================================//
void StateEngine::AddedStateVariable::setValue(Real value)
{
SimTK::ZIndex zix(getVarIndex());
if(getSubsysIndex().isValid() && zix.isValid()){
SimTK::Vector& z = getOwner().getDefaultSubsystem().updZ(getOwner().working_state_);
z[SimTK::ZIndex(zix)] = value;
return;
}
std::stringstream msg;
msg << "StateEngine::AddedStateVariable::setValue: ERR- variable '"
<< getName() << "' is invalid! " <<".";
throw (msg.str(),__FILE__,__LINE__);
}
//===============================================================//
double StateEngine::AddedStateVariable::
getDerivative()
{
//return getCacheVariableValue<double>(state, getName()+"_deriv");
return 0.0;
}
//===============================================================//
void StateEngine::AddedStateVariable::
setDerivative(Real deriv)
{
//return setCacheVariableValue<double>(state, getName()+"_deriv", deriv);
}
//===============================================================//
void StateEngine::reporter(SimTK::State& state_)
{
const SimTK::SimbodyMatterSubsystem& matter_ = getMultibodySystem().getMatterSubsystem();
for (SimTK::MobilizedBodyIndex mbx(0); mbx < matter_.getNumBodies(); ++mbx)
{
const SimTK::MobilizedBody& mobod = matter_.getMobilizedBody(mbx);
int num_q_ = mobod.getNumQ(state_);
for (int i = 0; i < num_q_; i++)
{
std::cout<< num_q_ << " " << mobod.getOneQ(state_, SimTK::QIndex(i)) <<std::endl;
}
int num_u_ = mobod.getNumU(state_);
for (int i = 0; i < num_u_; i++)
{
std::cout<<num_u_ << " " << mobod.getOneU(state_, SimTK::UIndex(i)) <<std::endl;
}
std::cout<< " Body Info : " << std::endl;
std::cout<< " Transform : " << mobod.getBodyTransform(state_) << std::endl;
std::cout<< " Rotation : " << mobod.getBodyRotation(state_) << std::endl;
std::cout<< " Origin : " << mobod.getBodyOriginLocation(state_) << std::endl;
}
}
//===============================================================//
void StateEngine::writeStateInfoToXml(int ite_rst_, const SimTK::State& state_)
{
std::string filefullpath = restart_folder_ + "/Simbody_Rst_" + std::to_string(ite_rst_) + ".xml";
std::unique_ptr<XmlEngine> state_xml(new XmlEngine("sate_xml", "mbsystem"));
const SimTK::SimbodyMatterSubsystem& matter_ = getMultibodySystem().getMatterSubsystem();
for (SimTK::MobilizedBodyIndex mbx(0); mbx < matter_.getNumBodies(); ++mbx)
{
state_xml->creatXmlElement("mbbody");
const SimTK::MobilizedBody& mobod = matter_.getMobilizedBody(mbx);
int num_q_ = mobod.getNumQ(state_);
for (int i = 0; i < num_q_; i++)
{
Real mobod_q = mobod.getOneQ(state_, SimTK::QIndex(i));
std::string ele_name = "QIndx_" + std::to_string(i);
state_xml->AddAttributeToElement(ele_name,mobod_q);
}
int num_u_ = mobod.getNumU(state_);
for (int i = 0; i < num_u_; i++)
{
Real mobod_u = mobod.getOneU(state_, SimTK::UIndex(i));
std::string ele_name = "UIndx_" + std::to_string(i);
state_xml->AddAttributeToElement(ele_name, mobod_u);
}
Vec3d transform_ = mobod.getBodyTransform(state_).p();
state_xml->AddAttributeToElement("Transform", transform_);
state_xml->AddElementToXmlDoc();
}
state_xml->WriteToXmlFile(filefullpath);
}
//===============================================================//
SimTK::State StateEngine::readAndSetStateInfoFromXml(int ite_rst_, SimTK::MultibodySystem& system_)
{
std::string filefullpath = restart_folder_ + "/Simbody_Rst_" + std::to_string(ite_rst_) + ".xml";
const SimTK::SimbodyMatterSubsystem& matter_ = system_.getMatterSubsystem();
SimTK::State state_ = system_.getDefaultState();
if (!fs::exists(filefullpath))
{
std::cout << "\n Error: the input file:"<< filefullpath << " is not valid" << std::endl;
std::cout << __FILE__ << ':' << __LINE__ << std::endl;
exit(1);
}else{
int num_mobod = 0;
std::unique_ptr<XmlEngine> read_xml(new XmlEngine());
read_xml->LoadXmlFile(filefullpath);
SimTK::Xml::element_iterator ele_ite_ = read_xml->root_element_.element_begin();
for (; ele_ite_ != read_xml->root_element_.element_end(); ++ele_ite_)
{
const SimTK::MobilizedBody& mobod = matter_.getMobilizedBody(SimTK::MobilizedBodyIndex(num_mobod));
int num_q_ = mobod.getNumQ(state_);
Real q_tmp_ = 0.0;
if(num_q_ != 0)
{
for (int i = 0; i < num_q_; i++)
{
std::string attr_name = "QIndx_" + std::to_string(i);
Real q_tmp_ = read_xml->GetRequiredAttributeValue<Real>(ele_ite_, attr_name);
mobod.setOneQ(state_, SimTK::QIndex(i), q_tmp_);
}
}
int num_u_ = mobod.getNumU(state_);
Real u_tmp_ = 0.0;
if(num_u_ != 0)
{
for (int i = 0; i < num_u_; i++)
{
std::string attr_name = "UIndx_" + std::to_string(i);
Real u_tmp_ = read_xml->GetRequiredAttributeValue<Real>(ele_ite_, attr_name);
mobod.setOneU(state_, SimTK::UIndex(i), u_tmp_);
}
}
Vec3d transform_ = read_xml->GetRequiredAttributeValue<Vec3d>(ele_ite_, "Transform");
mobod.setQToFitTransform(state_, SimTK::Transform(transform_));
num_mobod++;
}
}
system_.realizeModel(state_);
return state_;
}
//------------------------------------------------------------------------------
// REALIZE THE SYSTEM TO THE REQUIRED COMPUTATIONAL STAGE
//------------------------------------------------------------------------------
void StateEngine::realizeTime()
{
getMultibodySystem().realize(working_state_, SimTK::Stage::Time);
}
//===============================================================//
void StateEngine::realizePosition()
{
getMultibodySystem().realize(working_state_, SimTK::Stage::Position);
}
//===============================================================//
void StateEngine::realizeVelocity()
{
getMultibodySystem().realize(working_state_, SimTK::Stage::Velocity);
}
//===============================================================//
void StateEngine::realizeDynamics()
{
getMultibodySystem().realize(working_state_, SimTK::Stage::Dynamics);
}
//===============================================================//
void StateEngine::realizeAcceleration()
{
getMultibodySystem().realize(working_state_, SimTK::Stage::Acceleration);
}
//===============================================================//
void StateEngine::realizeReport( )
{
getMultibodySystem().realize(working_state_, SimTK::Stage::Report);
}
//===============================================================//
} | 43.704545 | 115 | 0.512285 | [
"geometry",
"vector",
"model",
"transform"
] |
28a134c398558e0f32b7fcf944c891d8a617c2b9 | 2,848 | cpp | C++ | LiquidMVC.cpp | VictorMNA/LiquidMVC | 8362b93c169ac3da3f4dc0dbce015e7dca49434d | [
"Apache-2.0"
] | null | null | null | LiquidMVC.cpp | VictorMNA/LiquidMVC | 8362b93c169ac3da3f4dc0dbce015e7dca49434d | [
"Apache-2.0"
] | null | null | null | LiquidMVC.cpp | VictorMNA/LiquidMVC | 8362b93c169ac3da3f4dc0dbce015e7dca49434d | [
"Apache-2.0"
] | null | null | null | // TODO: add header
#if defined(ARDUINO) && ARDUINO >= 100
#include "Arduino.h"
#else
#include "WProgram.h"
#endif
#include "LiquidMVC.h"
LiquidMVC::LiquidMVC(MenuRenderer& renderer, MenuController& controller):
_renderer(renderer),
_controller(controller)
{
};
void LiquidMVC::Init()
{
_renderer.Init();
_controller.Init();
};
void LiquidMVC::ListMenu()
{
Serial.println("- Start menu list");
for(int Index = 0; Index < _menuSystem.size(); Index++)
{
Serial.print(String(Index + 1) + ": " + _menuSystem[Index]->getTypeName() + " : " + _menuSystem[Index]->getName());
if(_menuSystem[Index]->getType() == MenuOption::Type::INT_VALUE)
{
Serial.println(" : " + String((static_cast<MenuOptionIntValue*>(_menuSystem[Index]))->getValue()));
(static_cast<MenuOptionIntValue*>(_menuSystem[Index]))->NextValue();
}
else
{
Serial.println();
}
}
Serial.println("- End menu list");
}
void LiquidMVC::ExecMenu()
{
NavigateMenu(_menuSystem);
}
void LiquidMVC::NavigateMenu(const Vector<MenuOption*>& array)
{
int OptionSelected = 0;
_editMode = false;
_renderer.Render(array, OptionSelected, _editMode);
while(true)
{
switch(_controller.Read())
{
case MenuController::Event::SELECT:
Serial.println("Controller returns Select");
if(OptionSelected == -1)
{
return;
}
else if(array[OptionSelected]->getType() == MenuOption::Type::ACTION)
{
(static_cast<MenuOptionAction*>(array[OptionSelected]))->ExecuteCallback();
}
else if(array[OptionSelected]->getType() == MenuOption::Type::INT_VALUE)
{
_editMode = !_editMode;
}
else if(array[OptionSelected]->getType() == MenuOption::Type::SUBMENU)
{
NavigateMenu((static_cast<MenuOptionSubmenu*>(array[OptionSelected]))->getMenu());
}
_renderer.Render(array, OptionSelected, _editMode);
break;
case MenuController::Event::PREV:
if(_editMode)
{
if(array[OptionSelected]->getType() == MenuOption::Type::INT_VALUE)
{
(static_cast<MenuOptionIntValue*>(array[OptionSelected]))->PrevValue();
}
}
else
{
if(OptionSelected >= 0)
{
OptionSelected--;
}
}
_renderer.Render(array, OptionSelected, _editMode);
break;
case MenuController::Event::NEXT:
if(_editMode)
{
(static_cast<MenuOptionIntValue*>(array[OptionSelected]))->NextValue();
}
else
{
if(OptionSelected < (((int)array.size()) - 1))
{
OptionSelected++;
}
}
_renderer.Render(array, OptionSelected, _editMode);
break;
}
}
}
| 23.154472 | 119 | 0.58743 | [
"render",
"vector"
] |
28a2047557c1d12a2261c68695083726bc2bef17 | 16,524 | cxx | C++ | arrows/core/hierarchical_bundle_adjust.cxx | acidburn0zzz/kwiver | 6e4205f1c46df04759c57c040f01cc804b27e00d | [
"BSD-3-Clause"
] | 1 | 2017-07-31T07:07:32.000Z | 2017-07-31T07:07:32.000Z | arrows/core/hierarchical_bundle_adjust.cxx | Acidburn0zzz/kwiver | 6e4205f1c46df04759c57c040f01cc804b27e00d | [
"BSD-3-Clause"
] | 3 | 2021-03-19T15:39:43.000Z | 2021-09-08T02:47:15.000Z | arrows/core/hierarchical_bundle_adjust.cxx | acidburn0zzz/kwiver | 6e4205f1c46df04759c57c040f01cc804b27e00d | [
"BSD-3-Clause"
] | null | null | null | /*ckwg +29
* Copyright 2014-2016 by Kitware, 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:
*
* * 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 name of Kitware, Inc. nor the names of any 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 AUTHORS 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.
*/
/**
* \file
* \brief Implementation of hierarchical_bundle_adjust
*/
#include "hierarchical_bundle_adjust.h"
#include <algorithm>
#include <iostream>
#include <limits>
#include <map>
#include <vector>
#include <math.h>
#include <vital/vital_foreach.h>
#include <vital/util/cpu_timer.h>
#include <vital/algo/optimize_cameras.h>
#include <vital/algo/triangulate_landmarks.h>
#include <arrows/core/metrics.h>
#include <arrows/core/interpolate_camera.h>
#include <vital/types/camera.h>
#include <vital/exceptions.h>
#include <vital/vital_types.h>
using namespace kwiver::vital;
namespace kwiver {
namespace arrows {
namespace core {
namespace // anonymous
{
/// subsample a every Nth camera
/**
* Subsamples are chosen based on camera order index instead of frame nubmer,
* as cameras given may not be in sequential order.
*
* The first camera in the map is given index 0 and the last given index
* (cameras.size() - 1).
*/
camera_map::map_camera_t
subsample_cameras(camera_map::map_camera_t const& cameras, unsigned n)
{
kwiver::vital::scoped_cpu_timer t( "Camera sub-sampling" );
// if sub-sample is 1, no sub-sampling occurs, just return a copy of the map
if (n == 1)
{
return cameras;
}
camera_map::map_camera_t subsample;
unsigned int i = 0;
VITAL_FOREACH(camera_map::map_camera_t::value_type const& p, cameras)
{
if (i % n == 0)
{
subsample[p.first] = p.second;
}
++i;
}
return subsample;
}
/// Integer interpolation -- used with indices, so can assume positive
frame_id_t
int_interp(frame_id_t a, frame_id_t b, double p)
{
// intend for static cast acts as floor in rounding.
return static_cast<frame_id_t>(a*(1.0-p) + b*p + 0.5);
}
} // end anonymous namespace
/// private implementation / data container for hierarchical_bundle_adjust
class hierarchical_bundle_adjust::priv
{
public:
priv()
: initial_sub_sample(1)
, interpolation_rate(0)
, rmse_reporting_enabled(false)
, m_logger( vital::get_logger( "arrows.core.hierarchical_bundle_adjust" ))
{
}
~priv() { }
unsigned int initial_sub_sample;
unsigned int interpolation_rate;
bool rmse_reporting_enabled;
vital::algo::bundle_adjust_sptr sba;
vital::algo::optimize_cameras_sptr camera_optimizer;
vital::algo::triangulate_landmarks_sptr lm_triangulator;
/// Logger handle
vital::logger_handle_t m_logger;
};
/// Constructor
hierarchical_bundle_adjust
::hierarchical_bundle_adjust()
: d_(new priv)
{ }
/// Destructor
hierarchical_bundle_adjust
::~hierarchical_bundle_adjust() VITAL_NOTHROW
{
}
/// Get this algorithm's \link kwiver::vital::config_block configuration block \endlink
vital::config_block_sptr
hierarchical_bundle_adjust
::get_configuration() const
{
vital::config_block_sptr config = vital::algo::bundle_adjust::get_configuration();
config->set_value("initial_sub_sample", d_->initial_sub_sample,
"Sub-sample the given cameras by this factor. Gaps will "
"then be filled in by iterations of interpolation.");
config->set_value("interpolation_rate", d_->interpolation_rate,
"Number of cameras to fill in each iteration. When this "
"is set to 0, we will interpolate all missing cameras "
"at the first moment possible.");
config->set_value("enable_rmse_reporting", d_->rmse_reporting_enabled,
"Enable the reporting of RMSE statistics at various "
"stages of this algorithm. Constant calculating of RMSE "
"may effect run time of the algorithm.");
vital::algo::bundle_adjust::get_nested_algo_configuration(
"sba_impl", config, d_->sba
);
vital::algo::optimize_cameras::get_nested_algo_configuration(
"camera_optimizer", config, d_->camera_optimizer
);
vital::algo::triangulate_landmarks::get_nested_algo_configuration(
"lm_triangulator", config, d_->lm_triangulator
);
return config;
}
/// Set this algorithm's properties via a config block
void
hierarchical_bundle_adjust
::set_configuration(vital::config_block_sptr config)
{
d_->initial_sub_sample = config->get_value<unsigned int>("initial_sub_sample", d_->initial_sub_sample);
d_->interpolation_rate = config->get_value<unsigned int>("interpolation_rate", d_->interpolation_rate);
d_->rmse_reporting_enabled = config->get_value<bool>("enable_rmse_reporting", d_->rmse_reporting_enabled);
vital::algo::bundle_adjust::set_nested_algo_configuration(
"sba_impl", config, d_->sba
);
vital::algo::optimize_cameras::set_nested_algo_configuration(
"camera_optimizer", config, d_->camera_optimizer
);
vital::algo::triangulate_landmarks::set_nested_algo_configuration(
"lm_triangulator", config, d_->lm_triangulator
);
}
/// Check that the algorithm's configuration vital::config_block is valid
bool
hierarchical_bundle_adjust
::check_configuration(vital::config_block_sptr config) const
{
bool valid = true;
#define HSBA_CHECK_FAIL(msg) \
LOG_DEBUG(d_->m_logger, "Config Check Fail: " << msg); \
valid = false
// using long to allow negatives and maintain numerical capacity of
// unsigned int as the values would otherwise be stored as.
if (config->has_value("initial_sub_sample")
&& config->get_value<long>("initial_sub_sample") <= 0)
{
HSBA_CHECK_FAIL("\"initial_sub_sample\" must be greater than 0. Given: "
<< config->get_value<long>("initial_sub_sample"));
}
if (config->has_value("interpolation_rate")
&& config->get_value<long>("interpolation_rate") < 0)
{
HSBA_CHECK_FAIL("\"interpolation_rate\" must be >= 0. Given: "
<< config->get_value<long>("interpolation_rate"));
}
if (!vital::algo::bundle_adjust::check_nested_algo_configuration("sba_impl", config))
{
HSBA_CHECK_FAIL("sba_impl configuration invalid.");
}
if (config->get_value<std::string>("camera_optimizer:type", "") == "")
{
LOG_DEBUG(d_->m_logger, "HSBA per-iteration camera optimization disabled");
}
else if (!vital::algo::optimize_cameras::check_nested_algo_configuration("camera_optimizer", config))
{
HSBA_CHECK_FAIL("camera_optimizer configuration invalid.");
}
if (config->get_value<std::string>("lm_triangulator:type", "") == "")
{
LOG_DEBUG(d_->m_logger, "HSBA per-iteration LM Triangulation disabled");
}
else if (!vital::algo::triangulate_landmarks::check_nested_algo_configuration("lm_triangulator", config))
{
LOG_DEBUG(d_->m_logger, "lm_triangulator type: \""
<< config->get_value<std::string>("lm_triangulator:type") << "\"");
HSBA_CHECK_FAIL("lm_triangulator configuration invalid.");
}
#undef HSBA_CHECK_FAIL
// camera optimizer and lm triangulator are optional. If not set, pointers
// will be 0.
return valid;
}
/// Optimize the camera and landmark parameters given a set of tracks
/**
* Making naive assuptions:
* - cameras we are given are in sequence (no previous sub-sampling and no frame gaps)
* - given camera map evenly interpolates with the current configuration
* - Assuming that all frames we interpolate have tracks/landmarks with which
* to optimize that camera over.
*/
void
hierarchical_bundle_adjust
::optimize(camera_map_sptr & cameras,
landmark_map_sptr & landmarks,
track_set_sptr tracks,
video_metadata_map_sptr metadata) const
{
using namespace std;
//frame_id_t orig_max_frame = cameras->cameras().rbegin()->first;
LOG_INFO(d_->m_logger, cameras->size() << " cameras provided");
size_t num_orig_cams = tracks->all_frame_ids().size();
// If interpolation rate is 0, then that means that all intermediate frames
// should be interpolated on the first step. Due to how the algorithm
// functions, set var to unsigned int max.
frame_id_t ir = d_->interpolation_rate;
if (ir == 0)
{
ir = std::numeric_limits<frame_id_t>::max();
}
LOG_DEBUG(d_->m_logger, "Interpolation rate: " << ir);
// Sub-sample cameras
// Always adding the last camera (if not already in there) to the sub-
// sampling in order to remove the complexity of interpolating into empty
// space (constant operation).
unsigned int ssr = d_->initial_sub_sample;
camera_map::map_camera_t input_cams = cameras->cameras(),
acm;
acm = subsample_cameras(input_cams, ssr);
acm[input_cams.rbegin()->first] = input_cams.rbegin()->second;
camera_map_sptr active_cam_map(new simple_camera_map(acm));
LOG_INFO(d_->m_logger, "Subsampled cameras: " << active_cam_map->size());
// need to have at least 2 cameras
if (active_cam_map->size() < 2)
{
throw invalid_value("Camera map given is of insufficient length.");
}
bool done = false;
do
{
LOG_INFO(d_->m_logger, "Optimizing " << active_cam_map->size() << " active cameras");
// updated active_cam_map and landmarks
{ // scope block
kwiver::vital::scoped_cpu_timer t( "inner-SBA iteration" );
d_->sba->optimize(active_cam_map, landmarks, tracks, metadata);
}
double rmse = kwiver::arrows::reprojection_rmse(active_cam_map->cameras(),
landmarks->landmarks(),
tracks->tracks());
LOG_DEBUG(d_->m_logger, "current RMSE: " << rmse);
// If we've just completed SBA with all original frames in the new map,
// then we're done.
LOG_DEBUG(d_->m_logger, "completion check: " << active_cam_map->size()
<< " >= " << num_orig_cams );
if (active_cam_map->size() >= num_orig_cams)
{
LOG_INFO(d_->m_logger, "complete");
done = true;
}
// perform interpolation between frames that have gaps in between them
else
{
camera_map::map_camera_t
// separated interpolated camera storage
interped_cams,
// concrete map of current active cameras
ac_map = active_cam_map->cameras();
// pre-allocation of variables for performance
size_t ir_l; // local interpolation rate as gaps available may be less than global rate
double f;
frame_id_t i2;
frame_id_t cur_frm, next_frm;
camera_sptr cur_cam, next_cam;
// Iterate through frames and cameras, interpolating across gaps when found
// ASSUMING even interpolation for now
camera_map::map_camera_t::const_iterator it = ac_map.begin();
{ // scope block
kwiver::vital::scoped_cpu_timer t( "interpolating cams" );
while (it != ac_map.end())
{
cur_frm = it->first;
cur_cam = it->second;
++it;
// If we're not at the end of the active camera sequence
if (it != ac_map.end())
{
next_frm = it->first;
next_cam = it->second;
// this specific gap's interpolation rate -- gap may be smaller than ir
ir_l = std::min(ir, next_frm - cur_frm - 1);
for (double i = 1; i <= ir_l; ++i)
{
// Determine the integer associated with the interpolation step,
// then determine the fraction location of that integer between
// the two end points.
// absolute fraction, might not land on integer
f = i / (ir_l + 1);
// aproximate interpolation snapped to nearest integer
i2 = int_interp(cur_frm, next_frm, f);
// fraction position of interpoated integer
f = static_cast<double>(i2 - cur_frm) / (next_frm - cur_frm);
interped_cams[i2] = kwiver::arrows::interpolate_camera(cur_cam, next_cam, f);
}
}
}
}
if(interped_cams.empty())
{
LOG_INFO(d_->m_logger, "No new cameras interpolated, done.");
break;
}
camera_map_sptr interped_cams_p(new simple_camera_map(interped_cams));
// Optimize new camers
if (d_->camera_optimizer)
{
LOG_INFO(d_->m_logger, "Optimizing new interpolated cameras ("
<< interped_cams.size() << " cams)");
if (d_->rmse_reporting_enabled)
{
LOG_DEBUG(d_->m_logger, "pre-optimization RMSE : "
<< reprojection_rmse(interped_cams_p->cameras(),
landmarks->landmarks(),
tracks->tracks()));
}
{ // scope block
kwiver::vital::scoped_cpu_timer t( "\t- cameras optimization" );
d_->camera_optimizer->optimize(interped_cams_p, tracks, landmarks, metadata);
}
if (d_->rmse_reporting_enabled)
{
LOG_DEBUG(d_->m_logger, "post-optimization RMSE : "
<< reprojection_rmse(interped_cams_p->cameras(),
landmarks->landmarks(),
tracks->tracks()));
}
}
// adding optimized interpolated cameras to the map of existing cameras
VITAL_FOREACH(camera_map::map_camera_t::value_type const& p, interped_cams_p->cameras())
{
ac_map[p.first] = p.second;
}
// Create new sptr of modified ac_map
active_cam_map = camera_map_sptr(new simple_camera_map(ac_map));
if (d_->rmse_reporting_enabled)
{
LOG_DEBUG(d_->m_logger, "combined map RMSE : "
<< reprojection_rmse(active_cam_map->cameras(),
landmarks->landmarks(),
tracks->tracks()));
}
// LM triangulation
if (d_->lm_triangulator)
{
LOG_INFO(d_->m_logger, "Triangulating landmarks after interpolating cameras");
if (d_->rmse_reporting_enabled)
{
LOG_DEBUG(d_->m_logger, "pre-triangulation RMSE : "
<< reprojection_rmse(active_cam_map->cameras(),
landmarks->landmarks(),
tracks->tracks()));
}
{ // scoped block
kwiver::vital::scoped_cpu_timer t( "\t- lm triangulation" );
d_->lm_triangulator->triangulate(active_cam_map, tracks, landmarks);
}
if (d_->rmse_reporting_enabled)
{
LOG_DEBUG(d_->m_logger, "post-triangulation RMSE : "
<< reprojection_rmse(active_cam_map->cameras(),
landmarks->landmarks(),
tracks->tracks()));
}
}
}
} while (!done);
// push up the resultant cameras
cameras = active_cam_map;
}
} // end namespace core
} // end namespace arrows
} // end namespace kwiver
| 34.35343 | 108 | 0.648995 | [
"vector"
] |
28a39152c4be94702b09d07f215b9e6383d1de2c | 18,546 | cc | C++ | src/webkit/plugins/ppapi/ppb_url_loader_impl.cc | jxjnjjn/chromium | 435c1d02fd1b99001dc9e1e831632c894523580d | [
"Apache-2.0"
] | 9 | 2018-09-21T05:36:12.000Z | 2021-11-15T15:14:36.000Z | src/webkit/plugins/ppapi/ppb_url_loader_impl.cc | jxjnjjn/chromium | 435c1d02fd1b99001dc9e1e831632c894523580d | [
"Apache-2.0"
] | null | null | null | src/webkit/plugins/ppapi/ppb_url_loader_impl.cc | jxjnjjn/chromium | 435c1d02fd1b99001dc9e1e831632c894523580d | [
"Apache-2.0"
] | 3 | 2018-11-28T14:54:13.000Z | 2020-07-02T07:36:07.000Z | // Copyright (c) 2012 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 "webkit/plugins/ppapi/ppb_url_loader_impl.h"
#include "base/logging.h"
#include "net/base/net_errors.h"
#include "ppapi/c/pp_completion_callback.h"
#include "ppapi/c/pp_errors.h"
#include "ppapi/c/ppb_url_loader.h"
#include "ppapi/c/trusted/ppb_url_loader_trusted.h"
#include "ppapi/shared_impl/ppapi_globals.h"
#include "ppapi/shared_impl/url_response_info_data.h"
#include "ppapi/thunk/enter.h"
#include "ppapi/thunk/ppb_url_request_info_api.h"
#include "third_party/WebKit/Source/Platform/chromium/public/WebURLError.h"
#include "third_party/WebKit/Source/Platform/chromium/public/WebURLLoader.h"
#include "third_party/WebKit/Source/Platform/chromium/public/WebURLRequest.h"
#include "third_party/WebKit/Source/Platform/chromium/public/WebURLResponse.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebDocument.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebElement.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebFrame.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebKit.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebPluginContainer.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebURLLoaderOptions.h"
#include "webkit/appcache/web_application_cache_host_impl.h"
#include "webkit/plugins/ppapi/common.h"
#include "webkit/plugins/ppapi/plugin_module.h"
#include "webkit/plugins/ppapi/ppapi_plugin_instance.h"
#include "webkit/plugins/ppapi/resource_helper.h"
#include "webkit/plugins/ppapi/url_request_info_util.h"
#include "webkit/plugins/ppapi/url_response_info_util.h"
using appcache::WebApplicationCacheHostImpl;
using ppapi::Resource;
using ppapi::thunk::EnterResourceNoLock;
using ppapi::thunk::PPB_URLLoader_API;
using ppapi::thunk::PPB_URLRequestInfo_API;
using ppapi::TrackedCallback;
using WebKit::WebFrame;
using WebKit::WebString;
using WebKit::WebURL;
using WebKit::WebURLError;
using WebKit::WebURLLoader;
using WebKit::WebURLLoaderOptions;
using WebKit::WebURLRequest;
using WebKit::WebURLResponse;
#ifdef _MSC_VER
// Do not warn about use of std::copy with raw pointers.
#pragma warning(disable : 4996)
#endif
namespace webkit {
namespace ppapi {
namespace {
WebFrame* GetFrameForResource(const Resource* resource) {
PluginInstance* plugin_instance = ResourceHelper::GetPluginInstance(resource);
if (!plugin_instance)
return NULL;
return plugin_instance->container()->element().document().frame();
}
} // namespace
PPB_URLLoader_Impl::PPB_URLLoader_Impl(PP_Instance instance,
bool main_document_loader)
: Resource(::ppapi::OBJECT_IS_IMPL, instance),
main_document_loader_(main_document_loader),
pending_callback_(),
bytes_sent_(0),
total_bytes_to_be_sent_(-1),
bytes_received_(0),
total_bytes_to_be_received_(-1),
user_buffer_(NULL),
user_buffer_size_(0),
done_status_(PP_OK_COMPLETIONPENDING),
is_streaming_to_file_(false),
is_asynchronous_load_suspended_(false),
has_universal_access_(false),
status_callback_(NULL) {
}
PPB_URLLoader_Impl::~PPB_URLLoader_Impl() {
// There is a path whereby the destructor for the loader_ member can
// invoke InstanceWasDeleted() upon this PPB_URLLoader_Impl, thereby
// re-entering the scoped_ptr destructor with the same scoped_ptr object
// via loader_.reset(). Be sure that loader_ is first NULL then destroy
// the scoped_ptr. See http://crbug.com/159429.
scoped_ptr<WebKit::WebURLLoader> for_destruction_only(loader_.release());
}
PPB_URLLoader_API* PPB_URLLoader_Impl::AsPPB_URLLoader_API() {
return this;
}
void PPB_URLLoader_Impl::InstanceWasDeleted() {
loader_.reset();
}
int32_t PPB_URLLoader_Impl::Open(PP_Resource request_id,
scoped_refptr<TrackedCallback> callback) {
EnterResourceNoLock<PPB_URLRequestInfo_API> enter_request(request_id, true);
if (enter_request.failed()) {
Log(PP_LOGLEVEL_ERROR,
"PPB_URLLoader.Open: invalid request resource ID. (Hint to C++ wrapper"
" users: use the ResourceRequest constructor that takes an instance or"
" else the request will be null.)");
return PP_ERROR_BADARGUMENT;
}
return Open(enter_request.object()->GetData(), 0, callback);
}
int32_t PPB_URLLoader_Impl::Open(
const ::ppapi::URLRequestInfoData& request_data,
int requestor_pid,
scoped_refptr<TrackedCallback> callback) {
// Main document loads are already open, so don't allow people to open them
// again.
if (main_document_loader_)
return PP_ERROR_INPROGRESS;
int32_t rv = ValidateCallback(callback);
if (rv != PP_OK)
return rv;
// Create a copy of the request data since CreateWebURLRequest will populate
// the file refs.
::ppapi::URLRequestInfoData filled_in_request_data = request_data;
if (URLRequestRequiresUniversalAccess(filled_in_request_data) &&
!has_universal_access_) {
Log(PP_LOGLEVEL_ERROR, "PPB_URLLoader.Open: The URL you're requesting is "
" on a different security origin than your plugin. To request "
" cross-origin resources, see "
" PP_URLREQUESTPROPERTY_ALLOWCROSSORIGINREQUESTS.");
return PP_ERROR_NOACCESS;
}
if (loader_.get())
return PP_ERROR_INPROGRESS;
WebFrame* frame = GetFrameForResource(this);
if (!frame)
return PP_ERROR_FAILED;
WebURLRequest web_request;
if (!CreateWebURLRequest(&filled_in_request_data, frame, &web_request))
return PP_ERROR_FAILED;
web_request.setRequestorProcessID(requestor_pid);
// Save a copy of the request info so the plugin can continue to use and
// change it while we're doing the request without affecting us. We must do
// this after CreateWebURLRequest since that fills out the file refs.
request_data_ = filled_in_request_data;
WebURLLoaderOptions options;
if (has_universal_access_) {
options.allowCredentials = true;
options.crossOriginRequestPolicy =
WebURLLoaderOptions::CrossOriginRequestPolicyAllow;
} else {
// All other HTTP requests are untrusted.
options.untrustedHTTP = true;
if (request_data_.allow_cross_origin_requests) {
// Allow cross-origin requests with access control. The request specifies
// if credentials are to be sent.
options.allowCredentials = request_data_.allow_credentials;
options.crossOriginRequestPolicy =
WebURLLoaderOptions::CrossOriginRequestPolicyUseAccessControl;
} else {
// Same-origin requests can always send credentials.
options.allowCredentials = true;
}
}
is_asynchronous_load_suspended_ = false;
loader_.reset(frame->createAssociatedURLLoader(options));
if (!loader_.get())
return PP_ERROR_FAILED;
loader_->loadAsynchronously(web_request, this);
// Notify completion when we receive a redirect or response headers.
RegisterCallback(callback);
return PP_OK_COMPLETIONPENDING;
}
int32_t PPB_URLLoader_Impl::FollowRedirect(
scoped_refptr<TrackedCallback> callback) {
int32_t rv = ValidateCallback(callback);
if (rv != PP_OK)
return rv;
SetDefersLoading(false); // Allow the redirect to continue.
RegisterCallback(callback);
return PP_OK_COMPLETIONPENDING;
}
PP_Bool PPB_URLLoader_Impl::GetUploadProgress(int64_t* bytes_sent,
int64_t* total_bytes_to_be_sent) {
if (!RecordUploadProgress()) {
*bytes_sent = 0;
*total_bytes_to_be_sent = 0;
return PP_FALSE;
}
*bytes_sent = bytes_sent_;
*total_bytes_to_be_sent = total_bytes_to_be_sent_;
return PP_TRUE;
}
PP_Bool PPB_URLLoader_Impl::GetDownloadProgress(
int64_t* bytes_received,
int64_t* total_bytes_to_be_received) {
if (!RecordDownloadProgress()) {
*bytes_received = 0;
*total_bytes_to_be_received = 0;
return PP_FALSE;
}
*bytes_received = bytes_received_;
*total_bytes_to_be_received = total_bytes_to_be_received_;
return PP_TRUE;
}
PP_Resource PPB_URLLoader_Impl::GetResponseInfo() {
::ppapi::thunk::EnterResourceCreationNoLock enter(pp_instance());
if (enter.failed() || !response_info_.get())
return 0;
// Since we're the "host" the process-local resource for the file ref is
// the same as the host resource. We pass a ref to the file ref.
if (!response_info_->body_as_file_ref.resource.is_null()) {
::ppapi::PpapiGlobals::Get()->GetResourceTracker()->AddRefResource(
response_info_->body_as_file_ref.resource.host_resource());
}
return enter.functions()->CreateURLResponseInfo(
pp_instance(),
*response_info_,
response_info_->body_as_file_ref.resource.host_resource());
}
int32_t PPB_URLLoader_Impl::ReadResponseBody(
void* buffer,
int32_t bytes_to_read,
scoped_refptr<TrackedCallback> callback) {
int32_t rv = ValidateCallback(callback);
if (rv != PP_OK)
return rv;
if (!response_info_.get() ||
!response_info_->body_as_file_ref.resource.is_null())
return PP_ERROR_FAILED;
if (bytes_to_read <= 0 || !buffer)
return PP_ERROR_BADARGUMENT;
user_buffer_ = static_cast<char*>(buffer);
user_buffer_size_ = bytes_to_read;
if (!buffer_.empty())
return FillUserBuffer();
// We may have already reached EOF.
if (done_status_ != PP_OK_COMPLETIONPENDING) {
user_buffer_ = NULL;
user_buffer_size_ = 0;
return done_status_;
}
RegisterCallback(callback);
return PP_OK_COMPLETIONPENDING;
}
int32_t PPB_URLLoader_Impl::FinishStreamingToFile(
scoped_refptr<TrackedCallback> callback) {
int32_t rv = ValidateCallback(callback);
if (rv != PP_OK)
return rv;
if (!response_info_.get() ||
response_info_->body_as_file_ref.resource.is_null())
return PP_ERROR_FAILED;
// We may have already reached EOF.
if (done_status_ != PP_OK_COMPLETIONPENDING)
return done_status_;
is_streaming_to_file_ = true;
if (is_asynchronous_load_suspended_)
SetDefersLoading(false);
// Wait for didFinishLoading / didFail.
RegisterCallback(callback);
return PP_OK_COMPLETIONPENDING;
}
void PPB_URLLoader_Impl::Close() {
if (loader_.get())
loader_->cancel();
else if (main_document_loader_)
GetFrameForResource(this)->stopLoading();
// We must not access the buffer provided by the caller from this point on.
user_buffer_ = NULL;
user_buffer_size_ = 0;
if (TrackedCallback::IsPending(pending_callback_))
pending_callback_->PostAbort();
}
void PPB_URLLoader_Impl::GrantUniversalAccess() {
has_universal_access_ = true;
}
void PPB_URLLoader_Impl::RegisterStatusCallback(
PP_URLLoaderTrusted_StatusCallback cb) {
status_callback_ = cb;
}
bool PPB_URLLoader_Impl::GetResponseInfoData(
::ppapi::URLResponseInfoData* data) {
if (!response_info_.get())
return false;
*data = *response_info_;
// We transfer one plugin reference to the FileRef to the caller.
if (!response_info_->body_as_file_ref.resource.is_null()) {
::ppapi::PpapiGlobals::Get()->GetResourceTracker()->AddRefResource(
response_info_->body_as_file_ref.resource.host_resource());
}
return true;
}
void PPB_URLLoader_Impl::willSendRequest(
WebURLLoader* loader,
WebURLRequest& new_request,
const WebURLResponse& redirect_response) {
if (!request_data_.follow_redirects) {
SaveResponse(redirect_response);
SetDefersLoading(true);
RunCallback(PP_OK);
}
}
void PPB_URLLoader_Impl::didSendData(
WebURLLoader* loader,
unsigned long long bytes_sent,
unsigned long long total_bytes_to_be_sent) {
// TODO(darin): Bounds check input?
bytes_sent_ = static_cast<int64_t>(bytes_sent);
total_bytes_to_be_sent_ = static_cast<int64_t>(total_bytes_to_be_sent);
UpdateStatus();
}
void PPB_URLLoader_Impl::didReceiveResponse(WebURLLoader* loader,
const WebURLResponse& response) {
SaveResponse(response);
// Sets -1 if the content length is unknown.
total_bytes_to_be_received_ = response.expectedContentLength();
UpdateStatus();
RunCallback(PP_OK);
}
void PPB_URLLoader_Impl::didDownloadData(WebURLLoader* loader,
int data_length) {
bytes_received_ += data_length;
UpdateStatus();
}
void PPB_URLLoader_Impl::didReceiveData(WebURLLoader* loader,
const char* data,
int data_length,
int encoded_data_length) {
// Note that |loader| will be NULL for document loads.
bytes_received_ += data_length;
UpdateStatus();
buffer_.insert(buffer_.end(), data, data + data_length);
// To avoid letting the network stack download an entire stream all at once,
// defer loading when we have enough buffer.
// Check for this before we run the callback, even though that could move
// data out of the buffer. Doing anything after the callback is unsafe.
DCHECK(request_data_.prefetch_buffer_lower_threshold <
request_data_.prefetch_buffer_upper_threshold);
if (!is_streaming_to_file_ &&
!is_asynchronous_load_suspended_ &&
(buffer_.size() >= static_cast<size_t>(
request_data_.prefetch_buffer_upper_threshold))) {
DVLOG(1) << "Suspending async load - buffer size: " << buffer_.size();
SetDefersLoading(true);
}
if (user_buffer_) {
RunCallback(FillUserBuffer());
} else {
DCHECK(!TrackedCallback::IsPending(pending_callback_));
}
}
void PPB_URLLoader_Impl::didFinishLoading(WebURLLoader* loader,
double finish_time) {
FinishLoading(PP_OK);
}
void PPB_URLLoader_Impl::didFail(WebURLLoader* loader,
const WebURLError& error) {
int32_t pp_error = PP_ERROR_FAILED;
if (error.domain.equals(WebString::fromUTF8(net::kErrorDomain))) {
// TODO(bbudge): Extend pp_errors.h to cover interesting network errors
// from the net error domain.
switch (error.reason) {
case net::ERR_ABORTED:
pp_error = PP_ERROR_ABORTED;
break;
case net::ERR_ACCESS_DENIED:
case net::ERR_NETWORK_ACCESS_DENIED:
pp_error = PP_ERROR_NOACCESS;
break;
}
} else {
// It's a WebKit error.
pp_error = PP_ERROR_NOACCESS;
}
FinishLoading(pp_error);
}
void PPB_URLLoader_Impl::SetDefersLoading(bool defers_loading) {
if (loader_.get()) {
loader_->setDefersLoading(defers_loading);
is_asynchronous_load_suspended_ = defers_loading;
}
// TODO(brettw) bug 96770: We need a way to set the defers loading flag on
// main document loads (when the loader_ is null).
}
void PPB_URLLoader_Impl::FinishLoading(int32_t done_status) {
done_status_ = done_status;
user_buffer_ = NULL;
user_buffer_size_ = 0;
// If the client hasn't called any function that takes a callback since
// the initial call to Open, or called ReadResponseBody and got a
// synchronous return, then the callback will be NULL.
if (TrackedCallback::IsPending(pending_callback_))
RunCallback(done_status_);
}
int32_t PPB_URLLoader_Impl::ValidateCallback(
scoped_refptr<TrackedCallback> callback) {
DCHECK(callback);
if (TrackedCallback::IsPending(pending_callback_))
return PP_ERROR_INPROGRESS;
return PP_OK;
}
void PPB_URLLoader_Impl::RegisterCallback(
scoped_refptr<TrackedCallback> callback) {
DCHECK(!TrackedCallback::IsPending(pending_callback_));
PluginModule* plugin_module = ResourceHelper::GetPluginModule(this);
if (!plugin_module)
return;
pending_callback_ = callback;
}
void PPB_URLLoader_Impl::RunCallback(int32_t result) {
// This may be null only when this is a main document loader.
if (!pending_callback_.get()) {
CHECK(main_document_loader_);
return;
}
// If |user_buffer_| was set as part of registering a callback, the paths
// which trigger that callack must have cleared it since the callback is now
// free to delete it.
DCHECK(!user_buffer_);
// As a second line of defense, clear the |user_buffer_| in case the
// callbacks get called in an unexpected order.
user_buffer_ = NULL;
user_buffer_size_ = 0;
pending_callback_->Run(result);
}
size_t PPB_URLLoader_Impl::FillUserBuffer() {
DCHECK(user_buffer_);
DCHECK(user_buffer_size_);
size_t bytes_to_copy = std::min(buffer_.size(), user_buffer_size_);
std::copy(buffer_.begin(), buffer_.begin() + bytes_to_copy, user_buffer_);
buffer_.erase(buffer_.begin(), buffer_.begin() + bytes_to_copy);
// If the buffer is getting too empty, resume asynchronous loading.
if (is_asynchronous_load_suspended_ &&
buffer_.size() <= static_cast<size_t>(
request_data_.prefetch_buffer_lower_threshold)) {
DVLOG(1) << "Resuming async load - buffer size: " << buffer_.size();
SetDefersLoading(false);
}
// Reset for next time.
user_buffer_ = NULL;
user_buffer_size_ = 0;
return bytes_to_copy;
}
void PPB_URLLoader_Impl::SaveResponse(const WebURLResponse& response) {
// DataFromWebURLResponse returns a file ref with one reference to it, which
// we take over via our ScopedPPResource.
response_info_.reset(new ::ppapi::URLResponseInfoData(
DataFromWebURLResponse(pp_instance(), response)));
response_info_file_ref_ = ::ppapi::ScopedPPResource(
::ppapi::ScopedPPResource::PassRef(),
response_info_->body_as_file_ref.resource.host_resource());
}
void PPB_URLLoader_Impl::UpdateStatus() {
if (status_callback_ &&
(RecordDownloadProgress() || RecordUploadProgress())) {
// Here we go through some effort to only send the exact information that
// the requestor wanted in the request flags. It would be just as
// efficient to send all of it, but we don't want people to rely on
// getting download progress when they happen to set the upload progress
// flag.
status_callback_(
pp_instance(), pp_resource(),
RecordUploadProgress() ? bytes_sent_ : -1,
RecordUploadProgress() ? total_bytes_to_be_sent_ : -1,
RecordDownloadProgress() ? bytes_received_ : -1,
RecordDownloadProgress() ? total_bytes_to_be_received_ : -1);
}
}
bool PPB_URLLoader_Impl::RecordDownloadProgress() const {
return request_data_.record_download_progress;
}
bool PPB_URLLoader_Impl::RecordUploadProgress() const {
return request_data_.record_upload_progress;
}
} // namespace ppapi
} // namespace webkit
| 33.72 | 81 | 0.732018 | [
"object"
] |
28a6e5476eca2a2f404a1cc0646281c36dde9f1f | 5,215 | hpp | C++ | cell_based/src/cell/srn/Goldbeter1991SrnModel.hpp | DGermano8/ChasteDom | 539a3a811698214c0938489b0cfdffd1abccf667 | [
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null | cell_based/src/cell/srn/Goldbeter1991SrnModel.hpp | DGermano8/ChasteDom | 539a3a811698214c0938489b0cfdffd1abccf667 | [
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null | cell_based/src/cell/srn/Goldbeter1991SrnModel.hpp | DGermano8/ChasteDom | 539a3a811698214c0938489b0cfdffd1abccf667 | [
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null | /*
Copyright (c) 2005-2018, University of Oxford.
All rights reserved.
University of Oxford means the Chancellor, Masters and Scholars of the
University of Oxford, having an administrative office at Wellington
Square, Oxford OX1 2JD, UK.
This file is part of Chaste.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the University of Oxford 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.
*/
#ifndef GOLDBETER1991SRNMODEL_HPP_
#define GOLDBETER1991SRNMODEL_HPP_
#include "ChasteSerialization.hpp"
#include <boost/serialization/base_object.hpp>
#include "Goldbeter1991OdeSystem.hpp"
#include "AbstractOdeSrnModel.hpp"
/**
* A Subcellular Reaction Network Model
* that includes a Goldbeter1991 ODE system in the sub-cellular reaction network.
*
* \todo #2752 give reference for this ODE system
*/
class Goldbeter1991SrnModel : public AbstractOdeSrnModel
{
private:
/** Needed for serialization. */
friend class boost::serialization::access;
/**
* Archive the SRN model and member variables.
*
* @param archive the archive
* @param version the current version of this class
*/
template<class Archive>
void serialize(Archive & archive, const unsigned int version)
{
archive & boost::serialization::base_object<AbstractOdeSrnModel>(*this);
}
protected:
/**
* Protected copy-constructor for use by CreateSrnModel(). The only way for external code to create a copy of a SRN model
* is by calling that method, to ensure that a model of the correct subclass is created.
* This copy-constructor helps subclasses to ensure that all member variables are correctly copied when this happens.
*
* This method is called by child classes to set member variables for a daughter cell upon cell division.
* Note that the parent SRN model will have had ResetForDivision() called just before CreateSrnModel() is called,
* so performing an exact copy of the parent is suitable behaviour. Any daughter-cell-specific initialisation
* can be done in InitialiseDaughterCell().
*
* @param rModel the SRN model to copy.
*/
Goldbeter1991SrnModel(const Goldbeter1991SrnModel& rModel);
public:
/**
* Default constructor calls base class.
*
* @param pOdeSolver An optional pointer to a cell-cycle model ODE solver object (allows the use of different ODE solvers)
*/
Goldbeter1991SrnModel(boost::shared_ptr<AbstractCellCycleModelOdeSolver> pOdeSolver = boost::shared_ptr<AbstractCellCycleModelOdeSolver>());
/**
* Overridden builder method to create new copies of
* this SRN model.
*
* @return Returns a copy of the current SRN model.
*/
AbstractSrnModel* CreateSrnModel();
/**
* Initialise the SRN model at the start of a simulation.
*
* This overridden method sets up a new Delta-Notch ODE system.
*/
void Initialise();
/**
* Overridden SimulateToTime() method for custom behaviour.
*
* \todo #2752 say what it does in this class
*/
void SimulateToCurrentTime();
/**
* Output SRN model parameters to file.
*
* @param rParamsFile the file stream to which the parameters are output
*/
void OutputSrnModelParameters(out_stream& rParamsFile);
/**
* @return the value of the state variable C in the ODE system.
*/
double GetC();
/**
* @return the value of the state variable M in the ODE system.
*/
double GetM();
/**
* @return the value of the state variable X in the ODE system.
*/
double GetX();
};
// Declare identifier for the serializer
#include "SerializationExportWrapper.hpp"
CHASTE_CLASS_EXPORT(Goldbeter1991SrnModel)
#include "CellCycleModelOdeSolverExportWrapper.hpp"
EXPORT_CELL_CYCLE_MODEL_ODE_SOLVER(Goldbeter1991SrnModel)
#endif /* GOLDBETER1991SRNMODEL_HPP_ */
| 35.965517 | 144 | 0.736337 | [
"object",
"model"
] |
28a90d1df82e4d1e2e0ace5140abb832f17305b2 | 6,067 | hpp | C++ | graphics/source/renderer/swapchain.hpp | HrvojeFER/irg-lab | 53f27430d39fa099dd605cfd632e38b55a392699 | [
"MIT"
] | null | null | null | graphics/source/renderer/swapchain.hpp | HrvojeFER/irg-lab | 53f27430d39fa099dd605cfd632e38b55a392699 | [
"MIT"
] | null | null | null | graphics/source/renderer/swapchain.hpp | HrvojeFER/irg-lab | 53f27430d39fa099dd605cfd632e38b55a392699 | [
"MIT"
] | null | null | null | #ifndef GRAPHICS_SWAPCHAIN_HPP
#define GRAPHICS_SWAPCHAIN_HPP
#include "../external/pch.hpp"
#include "../environment/device.hpp"
#include "env/window.hpp"
namespace il
{
struct swapchain
{
struct configuration
{
vk::Format format;
vk::PresentModeKHR present_mode;
vk::Extent2D extent;
vk::SurfaceTransformFlagBitsKHR transform_flag_bit;
vk::ColorSpaceKHR color_space;
unsigned int image_count;
};
explicit swapchain(const device& device, const window& window) :
swapchain_configuration_(select_swapchain_configuration(device, window)),
inner_(create_inner(device, window))
{
#if !defined(NDEBUG)
std::cout << std::endl << "-- Swapchain done --" << std::endl << std::endl;
#endif
}
[[nodiscard]] const vk::SwapchainKHR& operator *() const
{
return *inner_;
}
[[nodiscard]] configuration get_configuration() const
{
return swapchain_configuration_;
}
[[nodiscard]] const configuration& get_configuration_view() const
{
return swapchain_configuration_;
}
void reconstruct(const device& device, const window& window)
{
swapchain_configuration_ = select_swapchain_configuration(device, window);
inner_ = create_inner(device, window, *this->inner_);
#if !defined(NDEBUG)
std::cout << std::endl << "-- Swapchain reconstructed --" << std::endl << std::endl;
#endif
}
private:
configuration swapchain_configuration_;
vk::UniqueSwapchainKHR inner_;
[[nodiscard]] static configuration select_swapchain_configuration(
const device& device,
const window& window)
{
const auto& surface_info = device._query_surface_info(window);
const auto swap_surface = select_swap_surface_format(surface_info.formats);
auto image_count = surface_info.capabilities.minImageCount + 1;
// 0 means there is no maximum
if (surface_info.capabilities.maxImageCount > 0 &&
image_count > surface_info.capabilities.maxImageCount)
{
image_count = surface_info.capabilities.maxImageCount;
}
const configuration result
{
swap_surface.format,
select_swap_present_mode(surface_info.present_modes),
select_swap_extent(surface_info.capabilities, window),
surface_info.capabilities.currentTransform,
swap_surface.colorSpace,
image_count
};
#if !defined(NDEBUG)
std::cout << "Swapchain configuration selected" << std::endl;
#endif
return result;
}
[[nodiscard]] static vk::SurfaceFormatKHR select_swap_surface_format(
const std::vector<vk::SurfaceFormatKHR>& available_formats)
{
for (const auto& available_format : available_formats)
{
if (available_format.format == vk::Format::eB8G8R8A8Srgb &&
available_format.colorSpace == vk::ColorSpaceKHR::eSrgbNonlinear)
{
return available_format;
}
}
#if !defined(NDEBUG)
std::cerr
<< "Failed to find a desirable drawing_surface format. "
<< "The first available format will be selected instead."
<< std::endl;
#endif
return available_formats[0];
}
[[nodiscard]] static vk::PresentModeKHR select_swap_present_mode(
const std::vector<vk::PresentModeKHR>& available_present_modes) noexcept
{
for (const auto& available_present_mode : available_present_modes)
{
if (available_present_mode == vk::PresentModeKHR::eMailbox)
{
#if !defined(NDEBUG)
std::cout << "Triple buffering available" << std::endl;
#endif
return available_present_mode;
}
}
#if !defined(NDEBUG)
std::cerr
<< "Triple buffering unavailable -> "
<< "Using standard FIFO presentation mode (Vsync)"
<< std::endl;
#endif
return vk::PresentModeKHR::eFifo;
}
[[nodiscard]] static vk::Extent2D select_swap_extent(
const vk::SurfaceCapabilitiesKHR& capabilities,
const window& window) noexcept
{
if (capabilities.currentExtent.width != UINT32_MAX)
{
return capabilities.currentExtent;
}
auto actual_extent = window.query_extent();
// Clamps the extent to the capabilities of Vulkan.
actual_extent.width = max(capabilities.minImageExtent.width,
min(capabilities.maxImageExtent.width, actual_extent.width));
actual_extent.height = max(capabilities.minImageExtent.height,
min(capabilities.maxImageExtent.height, actual_extent.height));
return actual_extent;
}
[[nodiscard]] vk::UniqueSwapchainKHR create_inner(
const device& device,
const window& window,
const std::optional<vk::SwapchainKHR>& old = std::nullopt) const
{
vk::SwapchainCreateInfoKHR create_info =
{
{},
window.drawing_surface(),
swapchain_configuration_.image_count,
swapchain_configuration_.format,
swapchain_configuration_.color_space,
swapchain_configuration_.extent,
1,
vk::ImageUsageFlagBits::eColorAttachment,
vk::SharingMode::eExclusive,
0,
nullptr,
swapchain_configuration_.transform_flag_bit,
vk::CompositeAlphaFlagBitsKHR::eOpaque,
swapchain_configuration_.present_mode,
VK_TRUE,
old.has_value() ? old.value() : nullptr
};
const std::unordered_set<unsigned int> sharing_queue_family_indices_set
{
device.queue_family_indices.graphics_family.value(),
device.queue_family_indices.present_family.value()
};
if (sharing_queue_family_indices_set.size() > 1)
{
create_info.imageSharingMode = vk::SharingMode::eConcurrent;
const std::vector<unsigned int> sharing_queue_family_indices_array
{
sharing_queue_family_indices_set.begin(),
sharing_queue_family_indices_set.end()
};
create_info.queueFamilyIndexCount = static_cast<unsigned int>(
sharing_queue_family_indices_array.size());
}
auto result =
device->createSwapchainKHRUnique(create_info);
#if !defined(NDEBUG)
std::cout << "Swapchain created" << std::endl;
#endif
return result;
}
};
}
#endif
| 27.830275 | 94 | 0.691116 | [
"vector"
] |
28a9d2b3e3552eb8407fd7f4a918a486d6be9785 | 8,055 | cpp | C++ | DiffSamp/src/code/Main/MakeBlobs.cpp | 1iyiwei/noise | 0d1be2030518517199dff5c7e7514ee072037d59 | [
"MIT"
] | 24 | 2016-12-13T09:48:17.000Z | 2022-01-13T03:24:45.000Z | DiffSamp/src/code/Main/MakeBlobs.cpp | 1iyiwei/noise | 0d1be2030518517199dff5c7e7514ee072037d59 | [
"MIT"
] | 2 | 2019-03-29T06:44:41.000Z | 2019-11-12T03:14:25.000Z | RainbowNoise/src/Sain/MakeBlobs.cpp | 1iyiwei/noise | 0d1be2030518517199dff5c7e7514ee072037d59 | [
"MIT"
] | 8 | 2016-11-09T15:54:19.000Z | 2021-04-08T14:04:17.000Z | /*
MakeBlobs.cpp
splat a bunch of Gaussians onto a canvas
Li-Yi Wei
08/28/2008
*/
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
#include <math.h>
#include <stdlib.h>
#include "Exception.hpp"
#include "Sample.hpp"
#include "FrameBuffer.hpp"
#include "SequentialCounter.hpp"
class Blob
{
public:
Blob(void) : _scale(0) {};
Blob(const float scale, const Coordinate & mean, const Coordinate & std) : _scale(scale), _mean(mean), _std(std)
{
if(mean.Dimension() != std.Dimension()) throw Exception("mean.Dimension() != std.Dimension()");
};
int Dimension(void) const
{
return _mean.Dimension();
};
float Scale(void) const
{
return _scale;
};
const Coordinate & Mean(void) const
{
return _mean;
};
const Coordinate & Std(void) const
{
return _std;
};
float Evaluate(const Coordinate & query) const
{
if(query.Dimension() != _mean.Dimension())
{
// error
return 0;
}
else
{
float value = 0;
for(int i = 0; i < query.Dimension(); i++)
{
const float foo = (query[i] - _mean[i])/_std[i];
value += foo*foo;
}
return _scale*exp(-value);
}
};
protected:
float _scale;
Coordinate _mean, _std;
};
int WriteBlobs(const char * file_name, const vector<Blob> & blobs)
{
if(blobs.size() <= 0) return 0;
ofstream output(file_name);
if(! output)
{
return 0;
}
// number of blobs
output << blobs.size() << endl;
// dimension
output << blobs[0].Dimension() << endl;
for(unsigned int i = 0; i < blobs.size(); i++)
{
if(blobs[i].Dimension() != blobs[0].Dimension()) return 0;
// scale
output << blobs[i].Scale();
// mean
const Coordinate mean = blobs[i].Mean();
for(int j = 0; j < mean.Dimension(); j++)
{
output << " " << mean[j];
}
// std
const Coordinate std = blobs[i].Std();
for(int j = 0; j < std.Dimension(); j++)
{
output << " " << std[j];
}
output << endl;
}
// done
return 1;
}
string ReadBlobs(const char * file_name, vector<Blob> & blobs)
{
ifstream input(file_name);
if(! input)
{
return "cannot open input file";
}
// number of blobs
int num_blobs = 0;
input >> num_blobs;
if(num_blobs <= 0) return "num_blobs <= 0";
blobs.clear();
// dimension
int dimension = 0;
input >> dimension;
if(dimension <= 0) return "dimension <= 0";
float scale = 0;
Coordinate mean(dimension);
Coordinate std(dimension);
for(int i = 0; i < num_blobs; i++)
{
// scale
input >> scale;
// mean
for(int j = 0; j < mean.Dimension(); j++)
{
input >> mean[j];
}
// std
for(int j = 0; j < std.Dimension(); j++)
{
input >> std[j];
}
if(!input.good()) return "!input.good()";
blobs.push_back(Blob(scale, mean, std));
}
// done
return "";
}
int TileBlobs(const vector<float> & domain_size, const vector<Blob> & input, vector<Blob> & output)
{
const int dimension = domain_size.size();
SequentialCounter counter(dimension, -1, 1);
vector<Blob> result;
for(unsigned int i = 0; i < input.size(); i++)
{
if(input[i].Dimension() != dimension)
{
// cerr << input[i].Dimension() << "!=" << dimension << endl;
return 0;
}
const Coordinate & mean = input[i].Mean();
vector<int> index(dimension);
Coordinate new_mean = mean;
counter.Reset();
do
{
counter.Get(index);
for(int j = 0; j < new_mean.Dimension(); j++)
{
new_mean[j] = mean[j] + index[j]*domain_size[j];
}
result.push_back(Blob(input[i].Scale(), new_mean, input[i].Std()));
}
while(counter.Next());
}
output = result;
return 1;
}
int Main(int argc, char **argv)
{
const int min_argc = 5;
if(argc < min_argc)
{
cerr << "Usage: " << argv[0] << " input_file_name (ascii) output_file_name (pfm) output_size (pixels per unit domain size) boundary_condition (0 for none, 1 for toroidal) domain_size (optional, dimension numbers) color (optional, 3 floats in [0 1])" << endl;
return 1;
}
int argCtr = 0;
const char * input_file_name = argv[++argCtr];
const char * output_file_name = argv[++argCtr];
const int output_size_1d = atoi(argv[++argCtr]);
const int boundary_condition = atoi(argv[++argCtr]);
// read in blobs
vector<Blob> blobs;
const string message = ReadBlobs(input_file_name, blobs);
if(message != "")
{
cerr << "error in reading " << input_file_name << ", error message: " << message << endl;
return 1;
}
#if 0
// debug
if(! WriteBlobs(output_file_name, blobs))
{
cerr << "error in writing " << output_file_name << endl;
return 1;
}
else
{
cerr << "debug done" << endl;
return 0;
}
#endif
const int dimension = blobs[0].Dimension();
vector<float> domain_size(dimension, 1.0); // hardwired for now
if((argCtr + dimension) < argc)
{
for(unsigned int i = 0; i < domain_size.size(); i++)
{
domain_size[i] = atof(argv[++argCtr]);
}
cerr << "domain size:";
for(unsigned int i = 0; i < domain_size.size(); i++)
{
cerr << " " << domain_size[i];
}
cerr << endl;
}
FrameBuffer::PF color;
if((argCtr + 3) < argc)
{
color.r = atof(argv[++argCtr]);
color.g = atof(argv[++argCtr]);
color.b = atof(argv[++argCtr]);
}
else
{
color.r = color.g = color.b = 1.0;
}
if(boundary_condition == 1)
{
if(! TileBlobs(domain_size, blobs, blobs))
{
cerr << "cannot tile blobs" << endl;
return 1;
}
}
// write output image
vector<int> output_size(dimension, output_size_1d);
for(unsigned int i = 0; i < output_size.size(); i++)
{
output_size[i] = static_cast<int>(floor(output_size_1d*domain_size[i]+0.5));
}
Array<FrameBuffer::PF> output(output_size);
vector<int> output_size_minus_1(output_size);
for(unsigned int i = 0; i < output_size_minus_1.size(); i++)
{
output_size_minus_1[i] = output_size[i] - 1;
}
SequentialCounter counter(dimension, vector<int>(dimension, 0), output_size_minus_1);
counter.Reset();
vector<int> index(dimension);
Coordinate query(dimension);
FrameBuffer::PF pixel;
do
{
counter.Get(index);
for(int i = 0; i < query.Dimension(); i++)
{
query[i] = index[i]*domain_size[i]/output_size[i];
}
float value = 0;
for(unsigned int i = 0; i < blobs.size(); i++)
{
value += blobs[i].Evaluate(query);
}
pixel.r = value*color.r;
pixel.g = value*color.g;
pixel.b = value*color.b;
if(! output.Put(index, pixel) )
{
cerr << "cannot write output" << endl;
return 1;
}
}
while(counter.Next());
if(! FrameBuffer::WritePFM(output, output_file_name))
{
cerr << "cannot write " << output_file_name << endl;
return 1;
}
// done
return 0;
}
int main(int argc, char **argv)
{
try
{
return Main(argc, argv);
}
catch(Exception e)
{
cerr << "Error: " << e.Message() << endl;
return 1;
}
}
| 22.313019 | 266 | 0.513346 | [
"vector"
] |
28a9de195bf1229091cdca0d3f7e23a2106bc0e6 | 1,331 | cpp | C++ | Mathematical Challenges/Permutations.cpp | Ashwanigupta9125/code-DS-ALGO | 49f6cf7d0c682da669db23619aef3f80697b352b | [
"MIT"
] | 36 | 2019-12-27T08:23:08.000Z | 2022-01-24T20:35:47.000Z | Mathematical Challenges/Permutations.cpp | Ashwanigupta9125/code-DS-ALGO | 49f6cf7d0c682da669db23619aef3f80697b352b | [
"MIT"
] | 10 | 2019-11-13T02:55:18.000Z | 2021-10-13T23:28:09.000Z | Mathematical Challenges/Permutations.cpp | Ashwanigupta9125/code-DS-ALGO | 49f6cf7d0c682da669db23619aef3f80697b352b | [
"MIT"
] | 53 | 2020-08-15T11:08:40.000Z | 2021-10-09T15:51:38.000Z | #include<iostream>
using namespace std;
void swap(int *a,int *b)
{
int temp;
temp=*b;
*b=*a;
*a=temp;
return;
}
void permute(int *array,int i,int length) {
if (length == i){
for(int i=0;i<length;i++)
cout << array[i] <<" ";
cout << "\n";
return;
}
int j = i;
for (j = i; j < length; j++) {
swap(array+i,array+j);
permute(array,i+1,length);
swap(array+i,array+j);
}
return;
}
int main()
{
int n;
cin >> n;
int a[n];
int *p;
p=a;
for(int i=0;i<n;i++)
cin >> a[i];
permute(p,0,n);
}
//------------------------------------------------->
// #include <iostream>
// #include <vector>
// #include <algorithm>
// using namespace std;
// vector<vector<int>> allPermutations(vector<int> list)
// {
// vector<vector<int>> result;
// do
// {
// // push each permutation of list into result
// // used STL next_permutation func
// result.push_back(list);
// } while(next_permutation(list.begin(), list.end()));
// return result;
// }
// int main()
// {
// vector<int> list = {1, 2, 3, 4};
// vector<vector<int>> permutations = allPermutations(list);
// for (vector<int> permutation : permutations)
// {
// for (int i : permutation) cout << i << " ";
// cout << endl;
// }
// return 0;
// }
| 17.986486 | 64 | 0.510143 | [
"vector"
] |
28ac54f22ed66b8c8569a93bf61bad45eff7720d | 492 | cpp | C++ | Entrenamiento/CodeChef/ANUUND.cpp | snat-s/competitiva | a743f323e1bedec4709416ef684a0c6a15e42e00 | [
"MIT"
] | null | null | null | Entrenamiento/CodeChef/ANUUND.cpp | snat-s/competitiva | a743f323e1bedec4709416ef684a0c6a15e42e00 | [
"MIT"
] | null | null | null | Entrenamiento/CodeChef/ANUUND.cpp | snat-s/competitiva | a743f323e1bedec4709416ef684a0c6a15e42e00 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
int main(void) {
std::cin.tie(0);
std::ios_base::sync_with_stdio(0);
int t =0 ;
std::cin >> t;
while (t--) {
int n = 0;
std::cin >> n;
std::vector<int> arr(n);
for (int i = 0; i < n; ++i) {
std::cin >> arr[i];
}
std::sort(arr.begin(), arr.end());
for (int i = 1; i < n-1; ++i) {
std::swap(arr[i], arr[i+1]);
}
for (auto a : arr) {
std::cout << a << " ";
}
std::cout << "\n";
}
return 0;
}
| 18.222222 | 38 | 0.434959 | [
"vector"
] |
28b30011a52299c343e996b79aacadafa059d4c7 | 9,640 | cpp | C++ | winrt/test.external/CanvasFontFaceTests.cpp | r2d2rigo/Win2D | 3f06d4f19b7d16b67859a1b30ac770215ef3e52d | [
"MIT"
] | 1,002 | 2015-01-09T19:40:01.000Z | 2019-05-04T12:05:09.000Z | winrt/test.external/CanvasFontFaceTests.cpp | r2d2rigo/Win2D | 3f06d4f19b7d16b67859a1b30ac770215ef3e52d | [
"MIT"
] | 667 | 2015-01-02T19:04:11.000Z | 2019-05-03T14:43:51.000Z | winrt/test.external/CanvasFontFaceTests.cpp | SunburstApps/Win2D.WinUI | 75a33f8f4c0c785c2d1b478589fd4d3a9c5b53df | [
"MIT"
] | 258 | 2015-01-06T07:44:49.000Z | 2019-05-01T15:50:59.000Z | // Copyright (c) Microsoft Corporation. All rights reserved.
//
// Licensed under the MIT License. See LICENSE.txt in the project root for license information.
#include "pch.h"
using namespace Platform::Collections;
using namespace Microsoft::Graphics::Canvas;
using namespace Microsoft::Graphics::Canvas::Text;
#if WINVER > _WIN32_WINNT_WINBLUE
typedef Windows::Foundation::Numerics::float3x2 MatrixType;
typedef Windows::Foundation::Numerics::float2 Vector2Type;
#else
typedef Microsoft::Graphics::Canvas::Numerics::Matrix3x2 MatrixType;
typedef Microsoft::Graphics::Canvas::Numerics::Vector2 Vector2Type;
#endif
#if WINVER > _WIN32_WINNT_WINBLUE
typedef IDWriteFontFaceReference DWriteFontContainerType;
#else
typedef IDWriteFont DWriteFontContainerType;
#endif
ref class GlyphRun sealed
{
CanvasFontFace^ m_fontFace;
Platform::Array<CanvasGlyph>^ m_glyphs;
public:
GlyphRun(
CanvasFontFace^ fontFace,
Platform::Array<CanvasGlyph> const^ glyphs)
{
m_glyphs = ref new Platform::Array<CanvasGlyph>(glyphs);
m_fontFace = fontFace;
}
CanvasFontFace^ GetFontFace() { return m_fontFace; }
unsigned int GetGlyphCount() { return m_glyphs->Length; }
CanvasGlyph GetGlyph(unsigned int index) { return m_glyphs[index]; }
};
TEST_CLASS(CanvasFontFaceTests)
{
ref class GlyphRunListBuilder sealed : public ICanvasTextRenderer
{
Vector<GlyphRun^>^ m_list;
public:
GlyphRunListBuilder()
{
m_list = ref new Vector<GlyphRun^>();
}
virtual void DrawGlyphRun(
Vector2Type baselinePosition,
CanvasFontFace^ fontFace,
float fontSize,
Platform::Array<CanvasGlyph> const^ glyphs,
bool isSideways,
unsigned int bidiLevel,
Platform::Object^ brush,
CanvasTextMeasuringMode,
Platform::String^ locale,
Platform::String^ text,
Platform::Array<int> const^ clusterMap,
unsigned int characterIndex,
CanvasGlyphOrientation glyphOrientation)
{
GlyphRun^ glyphRun = ref new GlyphRun(fontFace, glyphs);
m_list->Append(glyphRun);
}
virtual void DrawStrikethrough(
Vector2Type baselineOrigin,
float width,
float thickness,
float offset,
CanvasTextDirection textDirection,
Platform::Object^ brush,
CanvasTextMeasuringMode measuringMode,
Platform::String^ locale,
CanvasGlyphOrientation glyphOrientation)
{
}
virtual void DrawUnderline(
Vector2Type baselineOrigin,
float width,
float thickness,
float offset,
float runHeight,
CanvasTextDirection textDirection,
Platform::Object^ brush,
CanvasTextMeasuringMode measuringMode,
Platform::String^ locale,
CanvasGlyphOrientation glyphOrientation)
{
}
virtual void DrawInlineObject(
Vector2Type baselineOrigin,
ICanvasTextInlineObject^ inlineObject,
bool isSideways,
bool isRightToLeft,
Platform::Object^ brush,
CanvasGlyphOrientation glyphOrientation)
{
}
virtual property float Dpi {float get() { return 96; }}
virtual property bool PixelSnappingDisabled {bool get() { return true; }}
virtual property MatrixType Transform {MatrixType get() { return{ 1, 0, 0, 1, 0, 0 }; }}
unsigned int GetGlyphRunCount() { return m_list->Size; }
GlyphRun^ GetGlyphRun(unsigned int index) { return m_list->GetAt(index); }
};
GlyphRunListBuilder^ GetSimpleGlyphRunList()
{
CanvasDevice^ device = ref new CanvasDevice();
CanvasTextFormat^ format = ref new CanvasTextFormat();
format->FontFamily = L"Arial";
auto layout = ref new CanvasTextLayout(device, L"123", format, 9999.0f, 0);
auto listBuilder = ref new GlyphRunListBuilder();
layout->DrawToTextRenderer(listBuilder, 0, 0);
Assert::AreEqual(1u, listBuilder->GetGlyphRunCount());
Assert::IsTrue(listBuilder->GetGlyphRun(0)->GetGlyphCount() > 0);
return listBuilder;
}
TEST_METHOD(CanvasFontFace_DefaultFontFace_Panose)
{
auto listBuilder = GetSimpleGlyphRunList();
auto panose = listBuilder->GetGlyphRun(0)->GetFontFace()->Panose;
Assert::AreEqual(10u, panose->Length);
//
// PANOSE values, which are decided by the font author, are very unlikely
// to change for a built-in font.
//
unsigned char expectedPanose[] = { 2, 11, 6, 4, 2, 2, 2, 2, 2, 4 };
for (unsigned int i = 0; i < 10; ++i)
Assert::AreEqual(panose[i], expectedPanose[i]);
}
ComPtr<DWriteFontContainerType> GetTestFont()
{
ComPtr<IDWriteFactory> factory;
ThrowIfFailed(DWriteCreateFactory(DWRITE_FACTORY_TYPE_SHARED, __uuidof(factory), &factory));
ComPtr<IDWriteFontCollection> dwriteSystemFontSet;
ThrowIfFailed(factory->GetSystemFontCollection(&dwriteSystemFontSet));
//
// While we could arbitrarily pick the Nth font in the system font collection,
// different environments could have malformed fonts or so forth,
// so we choose Arial here.
//
const uint32_t familyCount = dwriteSystemFontSet->GetFontFamilyCount();
for (uint32_t i = 0; i < familyCount; ++i)
{
ComPtr<IDWriteFontFamily> fontFamily;
ThrowIfFailed(dwriteSystemFontSet->GetFontFamily(i, &fontFamily));
ComPtr<IDWriteLocalizedStrings> localizedStrings;
ThrowIfFailed(fontFamily->GetFamilyNames(&localizedStrings));
uint32_t index;
BOOL exists;
ThrowIfFailed(localizedStrings->FindLocaleName(L"en-us", &index, &exists));
if (!exists) continue;
uint32_t familyNameLength;
ThrowIfFailed(localizedStrings->GetStringLength(index, &familyNameLength));
std::wstring familyName;
familyName.resize(familyNameLength + 1);
ThrowIfFailed(localizedStrings->GetString(index, &familyName[0], static_cast<uint32_t>(familyName.length())));
familyName.pop_back(); // Pop off the null term
if (familyName.compare(L"Arial") == 0)
{
ComPtr<IDWriteFont> font;
ThrowIfFailed(fontFamily->GetFirstMatchingFont(DWRITE_FONT_WEIGHT_REGULAR, DWRITE_FONT_STRETCH_NORMAL, DWRITE_FONT_STYLE_NORMAL, &font));
#if WINVER > _WIN32_WINNT_WINBLUE
ComPtr<IDWriteFontFaceReference> fontFaceReference;
ThrowIfFailed(As<IDWriteFont3>(font)->GetFontFaceReference(&fontFaceReference));
return fontFaceReference;
#else
return font;
#endif
}
}
Assert::Fail();
}
TEST_METHOD(CanvasFontFace_Interop)
{
auto font = GetTestFont();
auto wrapper = GetOrCreate<CanvasFontFace>(font.Get());
auto unwrapped = GetWrappedResource<DWriteFontContainerType>(wrapper);
Assert::AreEqual<void*>(font.Get(), unwrapped.Get());
}
TEST_METHOD(CanvasFontFace_GetTypographicGlyphSupport)
{
auto dwriteFont = GetTestFont();
auto font = GetOrCreate<CanvasFontFace>(dwriteFont.Get());
Platform::String^ testString = L"A";
auto textAnalyzer = ref new CanvasTextAnalyzer(testString, CanvasTextDirection::LeftToRightThenTopToBottom);
auto analyzedScript = textAnalyzer->GetScript();
auto script = analyzedScript->GetAt(0)->Value;
auto sourceCodePoints = ref new Platform::Array<unsigned int>(1) { testString->Data()[0] };
auto glyphIndices = font->GetGlyphIndices(sourceCodePoints);
auto glyphs = ref new Platform::Array<CanvasGlyph>(1);
glyphs[0].Index = glyphIndices[0];
glyphs[0].Advance = 0;
glyphs[0].AdvanceOffset = 0;
glyphs[0].AscenderOffset = 0;
struct TestCase
{
CanvasTypographyFeatureName FeatureName;
bool ExpectSupport;
} testCases[] =
{
{ CanvasTypographyFeatureName::Kerning, true },
{ CanvasTypographyFeatureName::StylisticSet20, false }
};
for (auto testCase : testCases)
{
Platform::Array<bool>^ support = font->GetTypographicFeatureGlyphSupport(
script,
testCase.FeatureName,
glyphs);
Assert::AreEqual(1u, support->Length);
Assert::AreEqual(testCase.ExpectSupport, support[0]);
}
}
#if WINVER > _WIN32_WINNT_WINBLUE
TEST_METHOD(CanvasFontFace_FontFacePassedToDrawGlyphRun_PresenceInSystemFontSet)
{
CanvasDevice^ device = ref new CanvasDevice();
CanvasTextFormat^ format = ref new CanvasTextFormat();
format->FontFamily = L"Arial";
auto layout = ref new CanvasTextLayout(device, L"123", format, 9999.0f, 0);
auto listBuilder = ref new GlyphRunListBuilder();
layout->DrawToTextRenderer(listBuilder, 0, 0);
auto fontFace = listBuilder->GetGlyphRun(0)->GetFontFace();
int index;
auto systemFonts = CanvasFontSet::GetSystemFontSet();
bool found = systemFonts->TryFindFontFace(fontFace, &index);
Assert::IsTrue(found);
}
#endif
};
| 33.58885 | 153 | 0.638278 | [
"object",
"vector",
"transform"
] |
28b7849fad9cd2dc892fa7a5b735e04bc0be0ca4 | 3,861 | cpp | C++ | src/Cosmos/Signer.cpp | yihuang/wallet-core | fd95099cacd2f2a03b1772592dc3b38bdfab09fe | [
"MIT"
] | 3 | 2019-10-15T16:55:04.000Z | 2020-03-14T06:52:22.000Z | src/Cosmos/Signer.cpp | yihuang/wallet-core | fd95099cacd2f2a03b1772592dc3b38bdfab09fe | [
"MIT"
] | 2 | 2019-08-31T22:56:54.000Z | 2021-08-10T12:07:44.000Z | src/Cosmos/Signer.cpp | yihuang/wallet-core | fd95099cacd2f2a03b1772592dc3b38bdfab09fe | [
"MIT"
] | 2 | 2019-08-03T19:56:11.000Z | 2019-12-20T08:49:19.000Z | // Copyright © 2017-2019 Trust Wallet.
//
// This file is part of Trust. The full Trust copyright notice, including
// terms governing use, modification, and redistribution, is contained in the
// file LICENSE at the root of the source code distribution tree.
#include "Signer.h"
#include "Serialization.h"
#include "../Hash.h"
#include "../HexCoding.h"
#include "../PrivateKey.h"
#include "../Data.h"
#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/io/zero_copy_stream_impl_lite.h>
#include <string>
using namespace TW;
using namespace TW::Cosmos;
using json = nlohmann::json;
Signer::Signer(Proto::SigningInput&& input) {
if (input.type_prefix().empty()) {
input.set_type_prefix(AMINO_PREFIX_SEND_COIN_MESSAGE);
}
if (input.has_send_coins_message()) {
auto message = input.send_coins_message();
if (message.type_prefix().empty()) {
message.set_type_prefix(AMINO_PREFIX_SEND_COIN_MESSAGE);
}
*input.mutable_send_coins_message() = message;
} else if (input.has_stake_message()) {
auto message = input.stake_message();
if (message.type_prefix().empty()) {
message.set_type_prefix(AMINO_PREFIX_STAKE_MESSAGE);
}
*input.mutable_stake_message() = message;
} else if(input.has_unstake_message()) {
auto message = input.unstake_message();
if (message.type_prefix().empty()) {
message.set_type_prefix(AMINO_PREFIX_UNSTAKE_MESSAGE);
}
*input.mutable_unstake_message() = message;
} else if(input.has_withdraw_stake_reward_message()) {
auto message = input.withdraw_stake_reward_message();
if (message.type_prefix().empty()) {
message.set_type_prefix(AMINO_PREFIX_WITHDRAW_STAKE_MESSAGE);
}
*input.mutable_withdraw_stake_reward_message() = message;
}
this->input = input;
}
std::vector<uint8_t> Signer::sign() const {
auto key = PrivateKey(input.private_key());
auto hash = Hash::sha256(signaturePreimage());
auto signature = key.sign(hash, TWCurveSECP256k1);
return std::vector<uint8_t>(signature.begin(), signature.end() - 1);
}
std::string Signer::signaturePreimage() const {
return signaturePreimageJSON(input).dump();
}
json Signer::buildTransactionJSON(const Data& signature) const {
auto sig = Cosmos::Proto::Signature();
sig.set_signature(signature.data(), signature.size());
auto privateKey = PrivateKey(input.private_key());
auto publicKey = privateKey.getPublicKey(TWPublicKeyTypeSECP256k1);
sig.set_public_key(publicKey.bytes.data(), publicKey.bytes.size());
auto transaction = Cosmos::Proto::Transaction();
*transaction.mutable_fee() = input.fee();
transaction.set_memo(input.memo());
if (input.has_send_coins_message()) {
*transaction.mutable_send_coins_message() = input.send_coins_message();
} else if (input.has_stake_message()) {
*transaction.mutable_stake_message() = input.stake_message();
} else if (input.has_unstake_message()) {
*transaction.mutable_unstake_message() = input.unstake_message();
} else if (input.has_withdraw_stake_reward_message()) {
*transaction.mutable_withdraw_stake_reward_message() = input.withdraw_stake_reward_message();
}
*transaction.mutable_signature() = sig;
return transactionJSON(transaction, input.type_prefix());
}
std::string Signer::buildTransaction() const {
auto signature = sign();
return buildTransactionJSON(signature).dump();
}
Proto::SigningOutput Signer::build() const {
auto output = Proto::SigningOutput();
auto signature = sign();
auto txJson = buildTransactionJSON(signature);
output.set_json(txJson.dump());
output.set_signature(signature.data(), signature.size());
return output;
}
| 35.1 | 101 | 0.694121 | [
"vector"
] |
28b84eabeff3e4ef7c91cab08fe8f50d22914b26 | 20,078 | cc | C++ | src/scanner.cc | lanza/tree-sitter-norg | 94040019ee1c621084f5083077b175339ea23f57 | [
"MIT"
] | null | null | null | src/scanner.cc | lanza/tree-sitter-norg | 94040019ee1c621084f5083077b175339ea23f57 | [
"MIT"
] | null | null | null | src/scanner.cc | lanza/tree-sitter-norg | 94040019ee1c621084f5083077b175339ea23f57 | [
"MIT"
] | null | null | null | #include "tree_sitter/parser.h"
#include <array>
#include <algorithm>
#include <locale>
#include <iostream>
#include <regex>
#include <string>
#include <cwctype>
enum TokenType
{
NONE,
SPACE,
WORD,
CAPITALIZED_WORD,
PARENTHESIZED_TEXT,
LINE_BREAK,
PARAGRAPH_BREAK,
ESCAPE_SEQUENCE,
HEADING1,
HEADING2,
HEADING3,
HEADING4,
HEADING5,
HEADING6,
QUOTE1,
QUOTE2,
QUOTE3,
QUOTE4,
QUOTE5,
QUOTE6,
UNORDERED_LIST1,
UNORDERED_LIST2,
UNORDERED_LIST3,
UNORDERED_LIST4,
UNORDERED_LIST5,
UNORDERED_LIST6,
ORDERED_LIST1,
ORDERED_LIST2,
ORDERED_LIST3,
ORDERED_LIST4,
ORDERED_LIST5,
ORDERED_LIST6,
MARKER,
TODO_ITEM_UNDONE,
TODO_ITEM_PENDING,
TODO_ITEM_DONE,
INSERTION,
UNORDERED_LINK1,
UNORDERED_LINK2,
UNORDERED_LINK3,
UNORDERED_LINK4,
UNORDERED_LINK5,
UNORDERED_LINK6,
ORDERED_LINK1,
ORDERED_LINK2,
ORDERED_LINK3,
ORDERED_LINK4,
ORDERED_LINK5,
ORDERED_LINK6,
STRONG_PARAGRAPH_DELIMITER,
WEAK_PARAGRAPH_DELIMITER,
HORIZONTAL_LINE,
LINK_BEGIN,
LINK_END_GENERIC,
LINK_END_URL,
LINK_END_HEADING1_REFERENCE,
LINK_END_HEADING2_REFERENCE,
LINK_END_HEADING3_REFERENCE,
LINK_END_HEADING4_REFERENCE,
LINK_END_HEADING5_REFERENCE,
LINK_END_HEADING6_REFERENCE,
LINK_END_MARKER_REFERENCE,
RANGED_TAG,
RANGED_TAG_END,
CARRYOVER_TAG,
SINGLE_DEFINITION,
MULTI_DEFINITION,
MULTI_DEFINITION_SUFFIX,
};
// Operator overloads for TokenTypes (allows for their chaining)
namespace
{
std::vector<TokenType> operator|(TokenType lhs, TokenType rhs)
{
return std::vector<TokenType>({ lhs, static_cast<TokenType>(rhs) });
}
std::vector<TokenType>&& operator|(std::vector<TokenType>&& lhs, TokenType rhs)
{
lhs.push_back(rhs);
return std::move(lhs);
}
}
class Scanner
{
public:
bool scan(TSLexer* lexer, const bool* valid_symbols)
{
lexer->result_symbol = NONE;
// Are we at the end of file? If so, bail
if (lexer->eof(lexer) || !lexer->lookahead)
{
advance(lexer);
return false;
}
// Check for an escape seqence (e.g. "\*")
if (m_TagStack.empty() && lexer->lookahead == '\\')
{
advance(lexer);
if (lexer->lookahead)
{
lexer->result_symbol = ESCAPE_SEQUENCE;
return true;
}
else
return false;
}
// If we are not in a tag and we have a square bracket opening then try matching
// either a todo item or beginning of a list
if (m_TagStack.empty() && lexer->lookahead == '[')
{
advance(lexer);
if (lexer->lookahead == ']')
{
lexer->result_symbol = WORD;
return true;
}
// Move over any whitespace
while (lexer->lookahead == ' ' || lexer->lookahead == '\t')
advance(lexer);
switch (lexer->lookahead)
{
// Did we encounter the end bracket? We've just dealt with an undone todo item
// ([ ])
case ']':
advance(lexer);
lexer->result_symbol = TODO_ITEM_UNDONE;
return true;
// We're dealing with a pending item ([*])
case '*':
lexer->result_symbol = TODO_ITEM_PENDING;
break;
// We're dealing with a done item ([x])
case 'x':
lexer->result_symbol = TODO_ITEM_DONE;
break;
case '\0':
advance(lexer);
return false;
}
// Move past the closing ] character
advance(lexer);
while (lexer->lookahead)
{
// If we've encountered an `]` check whether it has been escaped with a backslash
if (lexer->lookahead == ']' && m_Current != '\\')
{
advance(lexer);
return true;
}
else if (!std::iswspace(lexer->lookahead) || lexer->lookahead == '\n')
{
lexer->result_symbol = m_LastToken = LINK_BEGIN;
}
advance(lexer);
}
return lexer->lookahead != 0;
}
// Otherwise make sure to check for the existence of an opening link location
else if (m_TagStack.empty() && lexer->lookahead == '(' && m_Current == ']')
return check_link(lexer);
// Otherwise just check whether or not we're dealing with a newline and return STANDALONE_BREAK if we are
else if (lexer->lookahead == '\n')
{
advance(lexer);
lexer->result_symbol = LINE_BREAK;
if (lexer->eof(lexer) || !lexer->lookahead)
return false;
if (lexer->lookahead == '\n')
{
advance(lexer);
lexer->result_symbol = PARAGRAPH_BREAK;
}
return true;
}
// If we're at the beginning of a line check for all detached modifiers
if (lexer->get_column(lexer) == 0)
{
m_IndentationLevel = 0;
// Skip all leading whitespace
while (lexer->lookahead == ' ' || lexer->lookahead == '\t')
{
if (lexer->lookahead == '\t')
m_IndentationLevel += 4;
else
++m_IndentationLevel;
skip(lexer);
}
if (lexer->lookahead == '@')
{
advance(lexer);
lexer->mark_end(lexer);
if (lexer->lookahead == 'e')
{
advance(lexer);
if (lexer->lookahead == 'n')
{
advance(lexer);
if (lexer->lookahead == 'd')
{
advance(lexer);
if (std::iswspace(lexer->lookahead))
{
while (std::iswspace(lexer->lookahead) && lexer->lookahead != '\n' && lexer->lookahead)
advance(lexer);
if (std::iswspace(lexer->lookahead) && !m_TagStack.empty())
{
if (m_IndentationLevel != m_TagStack.back())
{
lexer->result_symbol = m_LastToken = WORD;
return true;
}
else
{
lexer->result_symbol = m_LastToken = RANGED_TAG_END;
m_TagStack.pop_back();
return true;
}
}
lexer->result_symbol = m_LastToken = WORD;
return true;
}
}
}
}
lexer->result_symbol = m_LastToken = RANGED_TAG;
m_TagStack.push_back(m_IndentationLevel);
return true;
}
else if (lexer->lookahead == '#')
{
advance(lexer);
lexer->result_symbol = CARRYOVER_TAG;
return true;
}
if (m_TagStack.empty())
{
if (check_detached(lexer, HEADING1 | HEADING2 | HEADING3 | HEADING4 | HEADING5 | HEADING6, { '*' }) != NONE)
return true;
if (check_detached(lexer, QUOTE1 | QUOTE2 | QUOTE3 | QUOTE4 | QUOTE5 | QUOTE6 | NONE, { '>' }) != NONE)
return true;
if (check_detached(lexer, UNORDERED_LIST1 | UNORDERED_LIST2 | UNORDERED_LIST3 | UNORDERED_LIST4 | UNORDERED_LIST5 | UNORDERED_LIST6 | NONE, { '-' },
{ '>', UNORDERED_LINK1 | UNORDERED_LINK2 | UNORDERED_LINK3 | UNORDERED_LINK4 | UNORDERED_LINK5 | UNORDERED_LINK6 | NONE }) != NONE)
{
return true;
}
else if (lexer->lookahead == '\n' && m_ParsedChars >= 3)
{
lexer->result_symbol = WEAK_PARAGRAPH_DELIMITER;
return true;
}
if (check_detached(lexer, ORDERED_LIST1 | ORDERED_LIST2 | ORDERED_LIST3 | ORDERED_LIST4 | ORDERED_LIST5 | ORDERED_LIST6 | NONE, { '~' },
{ '>', ORDERED_LINK1 | ORDERED_LINK2 | ORDERED_LINK3 | ORDERED_LINK4 | ORDERED_LINK5 | ORDERED_LINK6 | NONE }) != NONE)
return true;
if (check_detached(lexer, MARKER | NONE, { '|' }) != NONE)
return true;
if (check_detached(lexer, SINGLE_DEFINITION | MULTI_DEFINITION | NONE, { '$' }) != NONE)
return true;
else if (lexer->lookahead == '\n' && m_ParsedChars == 2)
{
lexer->result_symbol = MULTI_DEFINITION_SUFFIX;
return true;
}
if (check_detached(lexer, INSERTION, { '=' }) != NONE)
return true;
else if (lexer->lookahead == '\n')
{
if (m_ParsedChars >= 3)
{
lexer->result_symbol = STRONG_PARAGRAPH_DELIMITER;
return true;
}
else
{
advance(lexer);
lexer->result_symbol = WORD;
return true;
}
}
if (check_detached(lexer, NONE, { '_' }) != NONE)
return true;
else if (lexer->lookahead == '\n' && m_ParsedChars >= 3)
{
lexer->result_symbol = HORIZONTAL_LINE;
return true;
}
}
}
// Match paragraphs
return parse_text(lexer);
}
std::vector<size_t>& get_tag_stack() noexcept { return m_TagStack; }
private:
void skip(TSLexer* lexer)
{
m_Previous = m_Current;
m_Current = lexer->lookahead;
return lexer->advance(lexer, true);
}
void advance(TSLexer* lexer)
{
m_Previous = m_Current;
m_Current = lexer->lookahead;
return lexer->advance(lexer, false);
}
template <size_t Size = 1>
inline TokenType check_detached(TSLexer* lexer, TokenType result, const std::array<int32_t, Size>& expected, std::pair<char, TokenType> terminate_at = { 0, NONE })
{
return check_detached(lexer, result | NONE, expected, { terminate_at.first, terminate_at.second | NONE });
}
/*
* Checks for the existence of a detached modifier
* @param lexer - a pointer to the treesitter lexer
* @param results - a list of potential results repending on the amount of consecutive matches found
* @param expected - a list of expected modifiers to appear in the sequence
*/
template <size_t Size = 1>
[[nodiscard]]
TokenType check_detached(TSLexer* lexer, const std::vector<TokenType>& results, const std::array<int32_t, Size>& expected, std::pair<char, std::vector<TokenType>> terminate_at = { 0, NONE | NONE })
{
static_assert(Size > 0, "check_detached Size template must be greater than 0");
size_t i = m_ParsedChars = 0;
// Loop as long as the next character is a valid detached modifier
for (auto detached_modifier = std::find(s_DetachedModifiers.begin(), s_DetachedModifiers.end(), lexer->lookahead);
detached_modifier != s_DetachedModifiers.end();
detached_modifier = std::find(s_DetachedModifiers.begin(), s_DetachedModifiers.end(), lexer->lookahead), i++, m_ParsedChars++)
{
// If we've specified a termination character and we match then the token lexing prematurely
if (terminate_at.first != 0 && lexer->lookahead == terminate_at.first)
{
advance(lexer);
// Skip other potential whitespace
while (lexer->lookahead && (lexer->lookahead == ' ' || lexer->lookahead == '\t'))
advance(lexer);
TokenType result = terminate_at.second[clamp(i, size_t{}, terminate_at.second.size()) - 1];
lexer->result_symbol = result;
return result;
}
// If the next character is not one we expect then break
// We use clamp() here to prevent overflow and to make the last element of the expected array the fallback
if (lexer->lookahead != expected[clamp(i, size_t{}, Size - 1)])
break;
advance(lexer);
// If the next character is whitespace (which is the distinguishing factor between an attached/detached modifier)
if (std::iswspace(lexer->lookahead) && (lexer->lookahead != '\n'))
{
// Retrieve the correct result from the list of provided results depending on how many characters were matched.
// If we've exceeded the number of results then the clamp function will fall back to the last element
TokenType result = results[clamp(i, size_t{}, results.size() - 1)];
// Skip any other potential whitespace
while (lexer->lookahead && (lexer->lookahead == ' ' || lexer->lookahead == '\t'))
advance(lexer);
lexer->result_symbol = result;
m_LastToken = result;
return result;
}
}
return NONE;
}
/*
* Attempts to parse a link ([like](#this))
*/
bool check_link(TSLexer* lexer)
{
advance(lexer);
if (lexer->lookahead == ':')
{
while (lexer->lookahead && lexer->lookahead != '*' && lexer->lookahead != '#' && lexer->lookahead != '|' && lexer->lookahead != ')')
advance(lexer);
if (m_Current != ':')
return true;
}
advance(lexer);
// Is the current char an asterisk? We're dealing with a heading reference.
if (m_Current == '*')
{
size_t heading_level = 0;
// Keep capturing asterisks and increment the heading level accordingly
while (lexer->lookahead && lexer->lookahead == '*')
{
advance(lexer);
++heading_level;
}
// We use the clamp() here to make sure we don't overflow!
lexer->result_symbol = m_LastToken = static_cast<TokenType>(LINK_END_HEADING1_REFERENCE + clamp(heading_level, size_t{}, size_t{5}));
}
// We're dealing with a marker reference
else if (m_Current == '|')
{
lexer->result_symbol = m_LastToken = LINK_END_MARKER_REFERENCE;
}
// We're dealing with a generic (loose) link
else if (m_Current == '#')
lexer->result_symbol = m_LastToken = LINK_END_GENERIC;
// Until we don't hit the end of the link location keep advancing
while (lexer->lookahead && lexer->lookahead != ')')
{
if (lexer->lookahead == '\n' || !lexer->lookahead)
{
lexer->result_symbol = LINK_END_GENERIC;
break;
}
advance(lexer);
if (m_Current == '\\')
{
advance(lexer);
advance(lexer);
continue;
}
// This is our method of checking for a URL
// If there's a :// in the string we just assume that it's a URL and that's it
else if (m_Current == ':' && lexer->lookahead == '/' && lexer->result_symbol == NONE)
{
advance(lexer);
if (lexer->lookahead == '/')
lexer->result_symbol = m_LastToken = LINK_END_URL;
}
}
advance(lexer);
if (lexer->result_symbol == NONE)
lexer->result_symbol = m_LastToken = PARENTHESIZED_TEXT;
return true;
}
/*
* Simply parses any line (also called a paragraph segment)
*/
bool parse_text(TSLexer* lexer)
{
if (!m_TagStack.empty())
{
while (lexer->lookahead && lexer->lookahead != '\n')
advance(lexer);
lexer->result_symbol = m_LastToken = WORD;
return true;
}
if (lexer->lookahead == ' ' || lexer->lookahead == '\t')
{
do
advance(lexer);
while (lexer->lookahead && std::iswblank(lexer->lookahead));
lexer->result_symbol = m_LastToken = SPACE;
return true;
}
const TokenType resulting_symbol = (bool)std::iswupper(lexer->lookahead) ? CAPITALIZED_WORD : WORD;
do
{
if (lexer->lookahead == '~')
{
advance(lexer);
if (lexer->lookahead == '\n')
{
advance(lexer);
if (lexer->eof(lexer) || !lexer->lookahead)
return false;
}
}
else
advance(lexer);
}
while (lexer->lookahead && !std::iswspace(lexer->lookahead) && lexer->lookahead != '\\'); // TODO: Perform specific checks for attached modifiers
lexer->result_symbol = m_LastToken = resulting_symbol;
return true;
}
template<typename T, typename Comp>
T clamp(T value, Comp min, Comp max)
{
return value < min ? min : (value > max ? max : value);
}
private:
// Stores the current char rather than the next char
int32_t m_Previous = 0, m_Current = 0;
// The last matched token type (used to detect things like todo items
// which require an unordered list prefix beforehand)
TokenType m_LastToken = NONE;
// Used for lookback
size_t m_ParsedChars = 0, m_IndentationLevel = 0;
// Used for tags
std::vector<size_t> m_TagStack;
private:
const std::array<int32_t, 8> s_DetachedModifiers = { '*', '-', '>', '|', '=', '~', '$', '_' };
};
extern "C"
{
void* tree_sitter_norg_external_scanner_create()
{
return new Scanner();
}
void tree_sitter_norg_external_scanner_destroy(void* payload)
{
delete static_cast<Scanner*>(payload);
}
bool tree_sitter_norg_external_scanner_scan(void* payload, TSLexer* lexer, const bool* valid_symbols)
{
return static_cast<Scanner*>(payload)->scan(lexer, valid_symbols);
}
unsigned tree_sitter_norg_external_scanner_serialize(void* payload, char* buffer)
{
auto& tag_stack = static_cast<Scanner*>(payload)->get_tag_stack();
if (tag_stack.size() >= TREE_SITTER_SERIALIZATION_BUFFER_SIZE)
return 0;
std::copy(tag_stack.begin(), tag_stack.end(), buffer);
return tag_stack.size();
}
void tree_sitter_norg_external_scanner_deserialize(void* payload, const char* buffer, unsigned length)
{
auto& tag_stack = static_cast<Scanner*>(payload)->get_tag_stack();
tag_stack.clear();
tag_stack.resize(length);
std::copy_n(buffer, length, tag_stack.begin());
}
}
| 31.66877 | 201 | 0.511256 | [
"vector"
] |
28b854a859d2739673a3625cf6b1dcf381ab7b4e | 36,123 | cpp | C++ | userspace/libsinsp/chisel.cpp | mLavacca/sysdig | fd30d120651166c7efffd826769881988a41b7e8 | [
"Apache-2.0"
] | 1 | 2020-05-29T11:21:38.000Z | 2020-05-29T11:21:38.000Z | userspace/libsinsp/chisel.cpp | mLavacca/sysdig | fd30d120651166c7efffd826769881988a41b7e8 | [
"Apache-2.0"
] | null | null | null | userspace/libsinsp/chisel.cpp | mLavacca/sysdig | fd30d120651166c7efffd826769881988a41b7e8 | [
"Apache-2.0"
] | null | null | null | /*
Copyright (C) 2013-2018 Draios Inc dba Sysdig.
This file is part of sysdig.
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 <iostream>
#include <fstream>
#include <cctype>
#include <locale>
#ifdef _WIN32
#include <io.h>
#else
#include <limits.h>
#include <stdlib.h>
#include <unistd.h>
#endif
#include <third-party/tinydir.h>
#include <json/json.h>
#include "sinsp.h"
#include "sinsp_int.h"
#include "chisel.h"
#include "chisel_api.h"
#include "filter.h"
#include "filterchecks.h"
#include "table.h"
#ifdef HAS_CHISELS
#define HAS_LUA_CHISELS
#ifdef HAS_LUA_CHISELS
extern "C" {
#include "lua.h"
#include "lualib.h"
#include "lauxlib.h"
}
#endif
extern vector<chiseldir_info>* g_chisel_dirs;
extern sinsp_filter_check_list g_filterlist;
extern sinsp_evttables g_infotables;
///////////////////////////////////////////////////////////////////////////////
// For Lua debugging
///////////////////////////////////////////////////////////////////////////////
#ifdef HAS_LUA_CHISELS
void lua_stackdump(lua_State *L)
{
int i;
int top = lua_gettop(L);
for (i = 1; i <= top; i++)
{
int t = lua_type(L, i);
switch (t)
{
case LUA_TSTRING: // strings
printf("`%s'", lua_tostring(L, i));
break;
case LUA_TBOOLEAN: // booleans
printf(lua_toboolean(L, i) ? "true" : "false");
break;
case LUA_TNUMBER: // numbers
printf("%g", lua_tonumber(L, i));
break;
default: // other values
printf("%s", lua_typename(L, t));
break;
}
printf(" "); // put a separator
}
printf("\n"); // end the listing
}
#endif
///////////////////////////////////////////////////////////////////////////////
// Lua callbacks
///////////////////////////////////////////////////////////////////////////////
#ifdef HAS_LUA_CHISELS
const static struct luaL_reg ll_sysdig [] =
{
{"set_filter", &lua_cbacks::set_global_filter},
{"set_snaplen", &lua_cbacks::set_snaplen},
{"set_output_format", &lua_cbacks::set_output_format},
{"set_fatfile_dump_mode", &lua_cbacks::set_fatfile_dump_mode},
{"is_live", &lua_cbacks::is_live},
{"is_tty", &lua_cbacks::is_tty},
{"get_terminal_info", &lua_cbacks::get_terminal_info},
{"get_filter", &lua_cbacks::get_filter},
{"get_machine_info", &lua_cbacks::get_machine_info},
{"get_thread_table", &lua_cbacks::get_thread_table},
{"get_thread_table_nofds", &lua_cbacks::get_thread_table_nofds},
{"get_thread_table_barebone", &lua_cbacks::get_thread_table_barebone},
{"get_thread_table_barebone_nofds", &lua_cbacks::get_thread_table_barebone_nofds},
{"get_container_table", &lua_cbacks::get_container_table},
{"is_print_container_data", &lua_cbacks::is_print_container_data},
{"get_output_format", &lua_cbacks::get_output_format},
{"get_evtsource_name", &lua_cbacks::get_evtsource_name},
{"get_firstevent_ts", &lua_cbacks::get_firstevent_ts},
{"get_lastevent_ts", &lua_cbacks::get_lastevent_ts},
{"make_ts", &lua_cbacks::make_ts},
{"add_ts", &lua_cbacks::add_ts},
{"subtract_ts", &lua_cbacks::subtract_ts},
{"run_sysdig", &lua_cbacks::run_sysdig},
{"end_capture", &lua_cbacks::end_capture},
{"log", &lua_cbacks::log},
{"udp_setpeername", &lua_cbacks::udp_setpeername},
{"udp_send", &lua_cbacks::udp_send},
{"get_read_progress", &lua_cbacks::get_read_progress},
#ifdef HAS_ANALYZER
{"push_metric", &lua_cbacks::push_metric},
#endif
{NULL,NULL}
};
const static struct luaL_reg ll_chisel [] =
{
{"request_field", &lua_cbacks::request_field},
{"set_filter", &lua_cbacks::set_filter},
{"set_event_formatter", &lua_cbacks::set_event_formatter},
{"set_interval_ns", &lua_cbacks::set_interval_ns},
{"set_interval_s", &lua_cbacks::set_interval_s},
{"set_precise_interval_ns", &lua_cbacks::set_precise_interval_ns},
{"exec", &lua_cbacks::exec},
{NULL,NULL}
};
const static struct luaL_reg ll_evt [] =
{
{"field", &lua_cbacks::field},
{"get_num", &lua_cbacks::get_num},
{"get_ts", &lua_cbacks::get_ts},
{"get_type", &lua_cbacks::get_type},
{"get_cpuid", &lua_cbacks::get_cpuid},
{NULL,NULL}
};
#endif // HAS_LUA_CHISELS
///////////////////////////////////////////////////////////////////////////////
// chiselinfo implementation
///////////////////////////////////////////////////////////////////////////////
chiselinfo::chiselinfo(sinsp* inspector)
{
m_filter = NULL;
m_formatter = NULL;
m_dumper = NULL;
m_inspector = inspector;
m_has_nextrun_args = false;
m_end_capture = false;
#ifdef HAS_LUA_CHISELS
m_callback_interval = 0;
m_callback_precise_interval = 0;
#endif
}
chiselinfo::~chiselinfo()
{
if(m_filter)
{
delete m_filter;
}
if(m_formatter)
{
delete m_formatter;
}
if(m_dumper)
{
delete m_dumper;
}
}
void chiselinfo::init(string filterstr, string formatterstr)
{
set_filter(filterstr);
set_formatter(formatterstr);
}
void chiselinfo::set_filter(string filterstr)
{
sinsp_filter_compiler compiler(m_inspector, filterstr);
if(m_filter)
{
delete m_filter;
m_filter = NULL;
}
if(filterstr != "")
{
m_filter = compiler.compile();
}
}
void chiselinfo::set_formatter(string formatterstr)
{
if(m_formatter)
{
delete m_formatter;
m_formatter = NULL;
}
if(formatterstr == "" || formatterstr == "default")
{
m_formatter = new sinsp_evt_formatter(m_inspector, DEFAULT_OUTPUT_STR);
}
else
{
m_formatter = new sinsp_evt_formatter(m_inspector, formatterstr);
}
}
#ifdef HAS_LUA_CHISELS
void chiselinfo::set_callback_interval(uint64_t interval)
{
m_callback_interval = interval;
}
void chiselinfo::set_callback_precise_interval(uint64_t interval)
{
m_callback_precise_interval = interval;
}
#endif
///////////////////////////////////////////////////////////////////////////////
// chisel implementation
///////////////////////////////////////////////////////////////////////////////
sinsp_chisel::sinsp_chisel(sinsp* inspector, string filename)
{
m_inspector = inspector;
m_ls = NULL;
m_lua_has_handle_evt = false;
m_lua_is_first_evt = true;
m_lua_cinfo = NULL;
m_lua_last_interval_sample_time = 0;
m_lua_last_interval_ts = 0;
m_udp_socket = 0;
load(filename);
}
sinsp_chisel::~sinsp_chisel()
{
free_lua_chisel();
}
void sinsp_chisel::free_lua_chisel()
{
#ifdef HAS_LUA_CHISELS
if(m_ls)
{
lua_close(m_ls);
m_ls = NULL;
}
for(uint32_t j = 0; j < m_allocated_fltchecks.size(); j++)
{
delete m_allocated_fltchecks[j];
}
m_allocated_fltchecks.clear();
if(m_lua_cinfo != NULL)
{
delete m_lua_cinfo;
m_lua_cinfo = NULL;
}
m_lua_script_info.reset();
if(m_udp_socket > 0)
{
#ifdef _WIN32
closesocket(m_udp_socket);
#else
close(m_udp_socket);
#endif
m_udp_socket = 0;
}
#endif
}
#ifdef HAS_LUA_CHISELS
void parse_lua_chisel_arg(lua_State *ls, OUT chisel_desc* cd)
{
lua_pushnil(ls);
string name;
string type;
string desc;
bool optional = false;
while(lua_next(ls, -2) != 0)
{
if(lua_isstring(ls, -1))
{
if(string(lua_tostring(ls, -2)) == "name")
{
name = lua_tostring(ls, -1);
}
else if(string(lua_tostring(ls, -2)) == "argtype")
{
type = lua_tostring(ls, -1);
}
else if(string(lua_tostring(ls, -2)) == "description")
{
desc = lua_tostring(ls, -1);
}
}
else if(lua_isboolean(ls, -1))
{
if(string(lua_tostring(ls, -2)) == "optional")
{
optional = (lua_toboolean(ls, -1) != 0);
}
}
else
{
throw sinsp_exception(string(lua_tostring(ls, -2)) + " is not a string");
}
lua_pop(ls, 1);
}
cd->m_args.push_back(chiselarg_desc(name, type, desc, optional));
}
void parse_lua_chisel_args(lua_State *ls, OUT chisel_desc* cd)
{
lua_pushnil(ls);
while(lua_next(ls, -2) != 0)
{
if(lua_isstring(ls, -1))
{
printf("%s = %s\n", lua_tostring(ls, -2), lua_tostring(ls, -1));
cd->m_description = lua_tostring(ls, -1);
}
else if(lua_istable(ls, -1))
{
parse_lua_chisel_arg(ls, cd);
}
else
{
throw sinsp_exception(string(lua_tostring(ls, -2)) + " is not a string");
}
lua_pop(ls, 1);
}
}
void sinsp_chisel::add_lua_package_path(lua_State* ls, const char* path)
{
lua_getglobal(ls, "package");
lua_getfield(ls, -1, "path");
string cur_path = lua_tostring(ls, -1 );
cur_path += ';';
cur_path.append(path);
lua_pop(ls, 1);
lua_pushstring(ls, cur_path.c_str());
lua_setfield(ls, -2, "path");
lua_pop(ls, 1);
}
#endif
sinsp_field_aggregation sinsp_chisel::string_to_aggregation(string ag)
{
sinsp_field_aggregation res = A_NONE;
if(ag == "SUM")
{
res = A_SUM;
}
else if(ag == "AVG")
{
res = A_AVG;
}
else if(ag == "TIME_AVG")
{
res = A_TIME_AVG;
}
else if(ag == "MIN")
{
res = A_MIN;
}
else if(ag == "MAX")
{
res = A_MAX;
}
else
{
throw sinsp_exception("unknown view column aggregation " + ag);
}
return res;
}
void sinsp_chisel::parse_view_column(lua_State *ls, OUT chisel_desc* cd, OUT void* columns)
{
vector<sinsp_view_column_info>* cols = (vector<sinsp_view_column_info>*)columns;
lua_pushnil(ls);
string tmpstr;
string name;
string description;
string field;
string filterfield;
uint32_t colsize = 0xffffffff;
uint32_t flags = TEF_NONE;
sinsp_field_aggregation aggregation = A_NONE;
sinsp_field_aggregation groupby_aggregation = A_NONE;
vector<string> tags;
while(lua_next(ls, -2) != 0)
{
string fldname = lua_tostring(ls, -2);
if(fldname == "name")
{
name = lua_tostring(ls, -1);
}
else if(fldname == "description")
{
description = lua_tostring(ls, -1);
}
else if(fldname == "field")
{
field = lua_tostring(ls, -1);
}
else if(fldname == "filterfield")
{
filterfield = lua_tostring(ls, -1);
}
else if(fldname == "colsize")
{
if(lua_isnumber(ls, -1))
{
colsize = (uint32_t)lua_tonumber(ls, -1);
}
else
{
throw sinsp_exception(string(lua_tostring(ls, -2)) + " must be a number");
}
}
else if(fldname == "is_key")
{
if(lua_isboolean(ls, -1))
{
bool ik = (lua_toboolean(ls, -1) != 0);
if(ik)
{
flags |= TEF_IS_KEY;
}
}
else
{
throw sinsp_exception(string(lua_tostring(ls, -2)) + " must be a boolean value");
}
}
else if(fldname == "filter_in_child_only")
{
if(lua_isboolean(ls, -1))
{
bool ik = (lua_toboolean(ls, -1) != 0);
if(ik)
{
flags |= TEF_FILTER_IN_CHILD_ONLY;
}
}
else
{
throw sinsp_exception(string(lua_tostring(ls, -2)) + " must be a boolean value");
}
}
else if(fldname == "is_groupby_key")
{
if(lua_isboolean(ls, -1))
{
bool ik = (lua_toboolean(ls, -1) != 0);
if(ik)
{
flags |= TEF_IS_GROUPBY_KEY;
}
}
else
{
throw sinsp_exception(string(lua_tostring(ls, -2)) + " must be a boolean value");
}
}
else if(fldname == "is_sorting")
{
if(lua_isboolean(ls, -1))
{
bool ik = (lua_toboolean(ls, -1) != 0);
if(ik)
{
flags |= TEF_IS_SORT_COLUMN;
}
}
else
{
throw sinsp_exception(string(lua_tostring(ls, -2)) + " must be a boolean value");
}
}
else if(fldname == "aggregation")
{
if(lua_isstring(ls, -1))
{
string ag = lua_tostring(ls, -1);
aggregation = string_to_aggregation(ag);
}
}
else if(fldname == "groupby_aggregation")
{
if(lua_isstring(ls, -1))
{
string ag = lua_tostring(ls, -1);
groupby_aggregation = string_to_aggregation(ag);
}
}
else if(fldname == "tags")
{
if(lua_istable(ls, -1))
{
lua_pushnil(ls);
while(lua_next(ls, -2) != 0)
{
if(lua_isstring(ls, -1))
{
tmpstr = lua_tostring(ls, -1);
tags.push_back(tmpstr);
}
else
{
throw sinsp_exception("tags column entries must be strings");
}
lua_pop(ls, 1);
}
}
else
{
throw sinsp_exception(string(lua_tostring(ls, -2)) + " is not a table");
}
}
lua_pop(ls, 1);
}
if(filterfield != "" && ((flags & TEF_IS_KEY) == 0) && ((flags & TEF_IS_GROUPBY_KEY) == 0))
{
throw sinsp_exception("wrong view column syntax: filterfield specified for a non key column");
}
cols->push_back(sinsp_view_column_info(field,
name,
description,
colsize,
(uint32_t)flags,
aggregation,
groupby_aggregation,
tags,
filterfield));
}
void sinsp_chisel::parse_view_columns(lua_State *ls, OUT chisel_desc* cd, OUT void* columns)
{
string name;
string type;
string desc;
lua_pushnil(ls);
while(lua_next(ls, -2) != 0)
{
if(lua_istable(ls, -1))
{
parse_view_column(ls, cd, columns);
}
else
{
throw sinsp_exception("view_info column entries must be tables");
}
lua_pop(ls, 1);
}
}
void sinsp_chisel::parse_view_action(lua_State *ls, OUT chisel_desc* cd, OUT void* actions)
{
vector<sinsp_view_action_info>* keys = (vector<sinsp_view_action_info>*)actions;
lua_pushnil(ls);
char key = 0;
string command;
string description;
string tmpstr;
bool ask_confirmation = false;
bool waitfinish = true;
while(lua_next(ls, -2) != 0)
{
string fldname = lua_tostring(ls, -2);
if(fldname == "hotkey")
{
tmpstr = lua_tostring(ls, -1);
if(tmpstr.size() == 1)
{
key = tmpstr[0];
}
else
{
throw sinsp_exception("action 'key' field must be a single character string");
}
}
else if(fldname == "command")
{
command = lua_tostring(ls, -1);
}
else if(fldname == "description")
{
description = lua_tostring(ls, -1);
}
else if(fldname == "wait_finish")
{
int wf = lua_toboolean(ls, -1);
if(wf == 0)
{
waitfinish = false;
}
}
else if(fldname == "ask_confirmation")
{
int wf = lua_toboolean(ls, -1);
if(wf == 1)
{
ask_confirmation = true;
}
}
lua_pop(ls, 1);
}
if(key == 0)
{
throw sinsp_exception("action missing the 'key' value");
}
if(command == "")
{
throw sinsp_exception("action missing the 'command' value");
}
keys->push_back(sinsp_view_action_info(key,
command,
description,
ask_confirmation,
waitfinish));
}
void sinsp_chisel::parse_view_actions(lua_State *ls, OUT chisel_desc* cd, OUT void* actions)
{
string name;
string type;
string desc;
lua_pushnil(ls);
while(lua_next(ls, -2) != 0)
{
if(lua_istable(ls, -1))
{
parse_view_action(ls, cd, actions);
}
else
{
throw sinsp_exception("view_info action entries must be tables");
}
lua_pop(ls, 1);
}
}
bool sinsp_chisel::parse_view_info(lua_State *ls, OUT chisel_desc* cd)
{
lua_getglobal(ls, "view_info");
if(lua_isnoneornil(ls, -1))
{
lua_close(ls);
return false;
}
lua_pushnil(ls);
string tmpstr;
string id;
string name;
string description;
vector<string> applies_to;
string filter;
bool use_defaults = false;
sinsp_view_info::viewtype vt = sinsp_view_info::T_TABLE;
vector<sinsp_view_column_info> columns;
vector<sinsp_view_action_info> actions;
vector<string> tags;
vector<string> tips;
string drilldown_target;
string spectro_type;
bool drilldown_increase_depth = false;
bool is_root = false;
bool propagate_filter = true;
while(lua_next(ls, -2) != 0)
{
string fldname = lua_tostring(ls, -2);
if(fldname == "name")
{
name = lua_tostring(ls, -1);
}
else if(fldname == "id")
{
id = lua_tostring(ls, -1);
}
else if(fldname == "description")
{
description = lua_tostring(ls, -1);
}
else if(fldname == "tags")
{
if(lua_istable(ls, -1))
{
lua_pushnil(ls);
while(lua_next(ls, -2) != 0)
{
if(lua_isstring(ls, -1))
{
tmpstr = lua_tostring(ls, -1);
tags.push_back(tmpstr);
}
else
{
throw sinsp_exception("error in view " + cd->m_name + ": " + "tags entries must be strings");
}
lua_pop(ls, 1);
}
}
else
{
throw sinsp_exception("error in view " + cd->m_name + ": " + string(lua_tostring(ls, -2)) + " is not a table");
}
}
else if(fldname == "tips")
{
if(lua_istable(ls, -1))
{
lua_pushnil(ls);
while(lua_next(ls, -2) != 0)
{
if(lua_isstring(ls, -1))
{
tmpstr = lua_tostring(ls, -1);
tips.push_back(tmpstr);
}
else
{
throw sinsp_exception("error in view " + cd->m_name + ": " + "tips column entries must be strings");
}
lua_pop(ls, 1);
}
}
else
{
throw sinsp_exception("error in view " + cd->m_name + ": " + string(lua_tostring(ls, -2)) + " is not a table");
}
}
else if(fldname == "view_type")
{
tmpstr = lua_tostring(ls, -1);
if(tmpstr == "table")
{
vt = sinsp_view_info::T_TABLE;
}
else if(tmpstr == "list")
{
vt = sinsp_view_info::T_LIST;
}
else if(tmpstr == "spectrogram")
{
vt = sinsp_view_info::T_SPECTRO;
}
else
{
throw sinsp_exception("error in view " + cd->m_name + ": " + string(lua_tostring(ls, -2)) + " must be either 'table' or 'list'");
}
}
else if(fldname == "drilldown_target")
{
drilldown_target = lua_tostring(ls, -1);
}
else if(fldname == "spectro_type")
{
spectro_type = lua_tostring(ls, -1);
}
else if(fldname == "applies_to")
{
if(lua_istable(ls, -1))
{
lua_pushnil(ls);
while(lua_next(ls, -2) != 0)
{
if(lua_isstring(ls, -1))
{
tmpstr = lua_tostring(ls, -1);
applies_to.push_back(tmpstr);
}
else
{
throw sinsp_exception("error in view " + cd->m_name + ": " + "tips column entries must be strings");
}
lua_pop(ls, 1);
}
}
else
{
throw sinsp_exception("error in view " + cd->m_name + ": " + string(lua_tostring(ls, -2)) + " is not a table");
}
}
else if(fldname == "filter")
{
filter = lua_tostring(ls, -1);
}
else if(fldname == "use_defaults")
{
if(lua_isboolean(ls, -1))
{
use_defaults = (lua_toboolean(ls, -1) != 0);
}
else
{
throw sinsp_exception("error in view " + cd->m_name + ": " + string(lua_tostring(ls, -2)) + " must be a boolean");
}
}
else if(fldname == "is_root")
{
if(lua_isboolean(ls, -1))
{
is_root = (lua_toboolean(ls, -1) != 0);
}
else
{
throw sinsp_exception("error in view " + cd->m_name + ": " + string(lua_tostring(ls, -2)) + " must be a boolean");
}
}
else if(fldname == "columns")
{
if(lua_istable(ls, -1))
{
parse_view_columns(ls, cd, &columns);
}
else
{
throw sinsp_exception("error in view " + cd->m_name + ": " + string(lua_tostring(ls, -2)) + " is not a table");
}
}
else if(fldname == "actions")
{
if(lua_istable(ls, -1))
{
parse_view_actions(ls, cd, &actions);
}
else
{
throw sinsp_exception("error in view " + cd->m_name + ": " + string(lua_tostring(ls, -2)) + " is not a table");
}
}
else if(fldname == "drilldown_increase_depth")
{
if(lua_isboolean(ls, -1))
{
drilldown_increase_depth = (lua_toboolean(ls, -1) != 0);
}
else
{
throw sinsp_exception("error in view " + cd->m_name + ": " + string(lua_tostring(ls, -2)) + " must be a boolean");
}
}
else if(fldname == "propagate_filter")
{
if(lua_isboolean(ls, -1))
{
propagate_filter = (lua_toboolean(ls, -1) != 0);
}
else
{
throw sinsp_exception("error in view " + cd->m_name + ": " + string(lua_tostring(ls, -2)) + " must be a boolean");
}
}
lua_pop(ls, 1);
}
cd->m_viewinfo = sinsp_view_info(vt,
id,
name,
description,
tags,
tips,
columns,
applies_to,
filter,
drilldown_target,
use_defaults,
is_root,
actions,
drilldown_increase_depth,
spectro_type,
propagate_filter);
return true;
}
#ifdef HAS_LUA_CHISELS
// Initializes a lua chisel
bool sinsp_chisel::init_lua_chisel(chisel_desc &cd, string const &fpath)
{
lua_State* ls = lua_open();
if(ls == NULL)
{
return false;
}
luaL_openlibs(ls);
//
// Load our own lua libs
//
luaL_openlib(ls, "sysdig", ll_sysdig, 0);
luaL_openlib(ls, "chisel", ll_chisel, 0);
luaL_openlib(ls, "evt", ll_evt, 0);
//
// Add our chisel paths to package.path
//
for(vector<chiseldir_info>::const_iterator it = g_chisel_dirs->begin();
it != g_chisel_dirs->end(); ++it)
{
string path(it->m_dir);
path += "?.lua";
add_lua_package_path(ls, path.c_str());
}
//
// Load the script
//
if(luaL_loadfile(ls, fpath.c_str()) || lua_pcall(ls, 0, 0, 0))
{
goto failure;
}
//
// Extract the description
//
lua_getglobal(ls, "description");
if(!lua_isstring(ls, -1))
{
return parse_view_info(ls, &cd);
}
cd.m_description = lua_tostring(ls, -1);
//
// Extract the short description
//
lua_getglobal(ls, "short_description");
if(!lua_isstring(ls, -1))
{
goto failure;
}
cd.m_shortdesc = lua_tostring(ls, -1);
//
// Extract the category
//
cd.m_category = "";
lua_getglobal(ls, "category");
if(lua_isstring(ls, -1))
{
cd.m_category = lua_tostring(ls, -1);
}
//
// Extract the hidden flag and skip the chisel if it's set
//
lua_getglobal(ls, "hidden");
if(lua_isboolean(ls, -1))
{
int sares = lua_toboolean(ls, -1);
if(sares)
{
goto failure;
}
}
//
// Extract the args
//
lua_getglobal(ls, "args");
if(lua_isnoneornil(ls, -1))
{
goto failure;
}
try
{
parse_lua_chisel_args(ls, &cd);
}
catch(...)
{
goto failure;
}
return true;
failure:
lua_close(ls);
return false;
}
#endif
struct filename
{
bool valid;
string name;
string ext;
};
static filename split_filename(string const &fname)
{
filename res;
string::size_type idx = fname.rfind('.');
if(idx == std::string::npos)
{
res.valid = false;
}
else
{
res.valid = true;
res.name = fname.substr(0, idx);
res.ext = fname.substr(idx+1);
}
return res;
}
//
// 1. Iterates through the chisel files on disk (.sc and .lua)
// 2. Opens them and extracts the fields (name, description, etc)
// 3. Adds them to the chisel_descs vector.
//
void sinsp_chisel::get_chisel_list(vector<chisel_desc>* chisel_descs)
{
for(vector<chiseldir_info>::const_iterator it = g_chisel_dirs->begin();
it != g_chisel_dirs->end(); ++it)
{
if(string(it->m_dir).empty())
{
continue;
}
tinydir_dir dir = {};
tinydir_open(&dir, it->m_dir.c_str());
while(dir.has_next)
{
tinydir_file file;
tinydir_readfile(&dir, &file);
string fpath(file.path);
bool add_to_vector = false;
chisel_desc cd;
filename fn = split_filename(string(file.name));
if(fn.ext != "sc" && fn.ext != "lua")
{
goto next_file;
}
for(vector<chisel_desc>::const_iterator it_desc = chisel_descs->begin();
it_desc != chisel_descs->end(); ++it_desc)
{
if(fn.name == it_desc->m_name)
{
goto next_file;
}
}
cd.m_name = fn.name;
#ifdef HAS_LUA_CHISELS
if(fn.ext == "lua")
{
add_to_vector = init_lua_chisel(cd, fpath);
}
if(add_to_vector)
{
chisel_descs->push_back(cd);
}
#endif
next_file:
tinydir_next(&dir);
}
tinydir_close(&dir);
}
}
//
// If the function succeeds, is is initialized to point to the file.
// Otherwise, the return value is "false".
//
bool sinsp_chisel::openfile(string filename, OUT ifstream* is)
{
uint32_t j;
for(j = 0; j < g_chisel_dirs->size(); j++)
{
is->open(string(g_chisel_dirs->at(j).m_dir) + filename);
if(is->is_open())
{
return true;
}
}
return false;
}
void sinsp_chisel::load(string cmdstr)
{
m_filename = cmdstr;
trim(cmdstr);
ifstream is;
//
// Try to open the file with lua extension
//
if(!openfile(m_filename + ".lua", &is))
{
//
// Try to open the file as is
//
if(!openfile(m_filename, &is))
{
throw sinsp_exception("can't open file " + m_filename);
}
}
#ifdef HAS_LUA_CHISELS
//
// Load the file
//
std::istreambuf_iterator<char> eos;
std::string scriptstr(std::istreambuf_iterator<char>(is), eos);
//
// Open the script
//
m_ls = lua_open();
luaL_openlibs(m_ls);
//
// Load our own lua libs
//
luaL_openlib(m_ls, "sysdig", ll_sysdig, 0);
luaL_openlib(m_ls, "chisel", ll_chisel, 0);
luaL_openlib(m_ls, "evt", ll_evt, 0);
//
// Add our chisel paths to package.path
//
for(uint32_t j = 0; j < g_chisel_dirs->size(); j++)
{
string path(g_chisel_dirs->at(j).m_dir);
path += "?.lua";
add_lua_package_path(m_ls, path.c_str());
}
//
// Load the script
//
if(luaL_loadstring(m_ls, scriptstr.c_str()) || lua_pcall(m_ls, 0, 0, 0))
{
throw sinsp_exception("Failed to load chisel " +
m_filename + ": " + lua_tostring(m_ls, -1));
}
//
// Allocate the chisel context for the script
//
m_lua_cinfo = new chiselinfo(m_inspector);
//
// Set the context globals
//
lua_pushlightuserdata(m_ls, this);
lua_setglobal(m_ls, "sichisel");
//
// Extract the args
//
lua_getglobal(m_ls, "args");
if(!lua_istable(m_ls, -1))
{
throw sinsp_exception("Failed to load chisel " +
m_filename + ": args table missing");
}
try
{
parse_lua_chisel_args(m_ls, &m_lua_script_info);
}
catch(sinsp_exception& e)
{
throw e;
}
//
// Check if the script has an on_event
//
lua_getglobal(m_ls, "on_event");
if(lua_isfunction(m_ls, -1))
{
m_lua_has_handle_evt = true;
lua_pop(m_ls, 1);
}
#endif
is.close();
}
uint32_t sinsp_chisel::get_n_args()
{
ASSERT(m_ls);
#ifdef HAS_LUA_CHISELS
return (uint32_t)m_lua_script_info.m_args.size();
#else
return 0;
#endif
}
uint32_t sinsp_chisel::get_n_optional_args()
{
uint32_t j;
uint32_t res = 0;
for(j = 0; j < m_lua_script_info.m_args.size(); j++)
{
if(m_lua_script_info.m_args[j].m_optional)
{
res++;
}
}
return res;
}
uint32_t sinsp_chisel::get_n_required_args()
{
uint32_t j;
uint32_t res = 0;
for(j = 0; j < m_lua_script_info.m_args.size(); j++)
{
if(!m_lua_script_info.m_args[j].m_optional)
{
res++;
}
}
return res;
}
void sinsp_chisel::set_args(string args)
{
#ifdef HAS_LUA_CHISELS
uint32_t j;
uint32_t n_required_args = get_n_required_args();
uint32_t n_optional_args = get_n_optional_args();
ASSERT(m_ls);
//
// Split the argument string into tokens
//
uint32_t token_begin = 0;
bool inquotes = false;
uint32_t quote_correction = 0;
trim(args);
if(args.size() != 0)
{
for(j = 0; j < args.size(); j++)
{
if(args[j] == ' ' && !inquotes)
{
m_argvals.push_back(args.substr(token_begin, j - quote_correction - token_begin));
token_begin = j + 1;
quote_correction = 0;
}
else if(args[j] == '\'' || args[j] == '`')
{
if(inquotes)
{
quote_correction = 1;
inquotes = false;
}
else {
token_begin++;
inquotes = true;
}
}
}
if(inquotes)
{
throw sinsp_exception("corrupted parameters for chisel " + m_filename);
}
m_argvals.push_back(args.substr(token_begin, j - quote_correction - token_begin));
}
//
// Validate the arguments
//
if(m_argvals.size() < n_required_args)
{
throw sinsp_exception("wrong number of parameters for chisel " + m_filename +
", " + to_string((long long int)n_required_args) + " required, " +
to_string((long long int)m_argvals.size()) + " given");
}
else if(m_argvals.size() > n_optional_args + n_required_args)
{
throw sinsp_exception("too many parameters for chisel " + m_filename +
", " + to_string((long long int)(n_required_args)) + " required, " +
to_string((long long int)(n_optional_args)) + " optional, " +
to_string((long long int)m_argvals.size()) + " given");
}
//
// Create the arguments vector
//
vector<pair<string, string>> vargs;
for(j = 0; j < m_argvals.size(); j++)
{
vargs.push_back(pair<string, string>(m_lua_script_info.m_args[j].m_name,
m_argvals[j]));
}
set_args(vargs);
#endif
}
void sinsp_chisel::set_args(vector<pair<string, string>> args)
{
#ifdef HAS_LUA_CHISELS
uint32_t j;
uint32_t n_required_args = get_n_required_args();
uint32_t n_optional_args = get_n_optional_args();
ASSERT(m_ls);
//
// Validate the arguments
//
if(args.size() < n_required_args)
{
throw sinsp_exception("wrong number of parameters for chisel " + m_filename +
", " + to_string((long long int)n_required_args) + " required, " +
to_string((long long int)args.size()) + " given");
}
else if(args.size() > n_optional_args + n_required_args)
{
throw sinsp_exception("too many parameters for chisel " + m_filename +
", " + to_string((long long int)(n_required_args)) + " required, " +
to_string((long long int)(n_optional_args)) + " optional, " +
to_string((long long int)args.size()) + " given");
}
//
// Push the arguments
//
for(j = 0; j < args.size(); j++)
{
lua_getglobal(m_ls, "on_set_arg");
if(!lua_isfunction(m_ls, -1))
{
lua_pop(m_ls, 1);
throw sinsp_exception("chisel " + m_filename + " misses a set_arg() function.");
}
lua_pushstring(m_ls, args[j].first.c_str());
lua_pushstring(m_ls, args[j].second.c_str());
//
// call get_info()
//
if(lua_pcall(m_ls, 2, 1, 0) != 0)
{
throw sinsp_exception(m_filename + " chisel error: " + lua_tostring(m_ls, -1));
}
if(!lua_isboolean(m_ls, -1))
{
throw sinsp_exception(m_filename + " chisel error: wrong set_arg() return value.");
}
int sares = lua_toboolean(m_ls, -1);
if(!sares)
{
throw sinsp_exception("set_arg() for chisel " + m_filename + " failed.");
}
lua_pop(m_ls, 1);
}
#endif
}
void sinsp_chisel::on_init()
{
//
// Done with the arguments, call init()
//
lua_getglobal(m_ls, "on_init");
if(!lua_isfunction(m_ls, -1))
{
//
// No on_init.
// That's ok. Just return.
//
return;
}
if(lua_pcall(m_ls, 0, 1, 0) != 0)
{
//
// Exception running init
//
const char* lerr = lua_tostring(m_ls, -1);
string err = m_filename + ": error in init(): " + lerr;
throw sinsp_exception(err);
}
if(m_new_chisel_to_exec == "")
{
if(!lua_isboolean(m_ls, -1))
{
throw sinsp_exception(m_filename + " chisel error: wrong init() return value.");
}
if(!lua_toboolean(m_ls, -1))
{
throw sinsp_exception("init() for chisel " + m_filename + " failed.");
}
}
lua_pop(m_ls, 1);
//
// If the chisel called chisel.exec(), free this chisel and load the new one
//
if(m_new_chisel_to_exec != "")
{
free_lua_chisel();
load(m_new_chisel_to_exec);
m_new_chisel_to_exec = "";
string args;
for(uint32_t j = 0; j < m_argvals.size(); j++)
{
if(m_argvals[j].find(" ") == string::npos)
{
args += m_argvals[j];
}
else
{
args += string("'") + m_argvals[j] + "'";
}
if(j < m_argvals.size() - 1)
{
args += " ";
}
}
m_argvals.clear();
set_args(args);
on_init();
}
}
void sinsp_chisel::first_event_inits(sinsp_evt* evt)
{
uint64_t ts = evt->get_ts();
if(m_lua_cinfo->m_callback_interval != 0)
{
m_lua_last_interval_sample_time = ts - ts % m_lua_cinfo->m_callback_interval;
}
else if(m_lua_cinfo->m_callback_precise_interval != 0)
{
m_lua_last_interval_sample_time = ts;
}
m_lua_is_first_evt = false;
}
bool sinsp_chisel::run(sinsp_evt* evt)
{
#ifdef HAS_LUA_CHISELS
string line;
ASSERT(m_ls);
//
// Make the event available to the API
//
lua_pushlightuserdata(m_ls, evt);
lua_setglobal(m_ls, "sievt");
//
// If there is a timeout callback, see if it's time to call it
//
do_timeout(evt);
//
// If there is a filter, run it
//
if(m_lua_cinfo->m_filter != NULL)
{
if(!m_lua_cinfo->m_filter->run(evt))
{
return false;
}
}
//
// If the script has the on_event callback, call it
//
if(m_lua_has_handle_evt)
{
lua_getglobal(m_ls, "on_event");
if(lua_pcall(m_ls, 0, 1, 0) != 0)
{
throw sinsp_exception(m_filename + " chisel error: " + lua_tostring(m_ls, -1));
}
int oeres = lua_toboolean(m_ls, -1);
lua_pop(m_ls, 1);
if(m_lua_cinfo->m_end_capture == true)
{
throw sinsp_capture_interrupt_exception();
}
if(oeres == false)
{
return false;
}
}
//
// If the script has a formatter, run it
//
if(m_lua_cinfo->m_formatter != NULL)
{
if(m_lua_cinfo->m_formatter->tostring(evt, &line))
{
cout << line << endl;
}
}
return true;
#endif
}
void sinsp_chisel::do_timeout(sinsp_evt* evt)
{
if(m_lua_is_first_evt)
{
//
// If this is the first event, put the event pointer on the stack.
// We assume that the event pointer will never change.
//
if(m_lua_is_first_evt)
{
first_event_inits(evt);
}
return;
}
if(m_lua_cinfo->m_callback_interval != 0)
{
uint64_t ts = evt->get_ts();
uint64_t sample_time = ts - ts % m_lua_cinfo->m_callback_interval;
if(sample_time != m_lua_last_interval_sample_time)
{
int64_t delta = 0;
if(m_lua_last_interval_ts != 0)
{
delta = ts - m_lua_last_interval_ts;
if(delta == 0)
{
return;
}
}
lua_getglobal(m_ls, "on_interval");
lua_pushnumber(m_ls, (double)(ts / 1000000000));
lua_pushnumber(m_ls, (double)(ts % 1000000000));
lua_pushnumber(m_ls, (double)delta);
if(lua_pcall(m_ls, 3, 1, 0) != 0)
{
throw sinsp_exception(m_filename + " chisel error: calling on_interval() failed:" + lua_tostring(m_ls, -1));
}
int oeres = lua_toboolean(m_ls, -1);
lua_pop(m_ls, 1);
if(oeres == false)
{
throw sinsp_exception("execution terminated by the " + m_filename + " chisel");
}
m_lua_last_interval_sample_time = sample_time;
m_lua_last_interval_ts = ts;
}
}
else if(m_lua_cinfo->m_callback_precise_interval != 0)
{
uint64_t ts = evt->get_ts();
uint64_t interval = m_lua_cinfo->m_callback_precise_interval;
if(ts - m_lua_last_interval_sample_time >= interval)
{
uint64_t t;
for(t = m_lua_last_interval_sample_time; t <= ts - interval; t += interval)
{
lua_getglobal(m_ls, "on_interval");
lua_pushnumber(m_ls, (double)(t / 1000000000));
lua_pushnumber(m_ls, (double)(t % 1000000000));
lua_pushnumber(m_ls, (double)interval);
if(lua_pcall(m_ls, 3, 1, 0) != 0)
{
throw sinsp_exception(m_filename + " chisel error: calling on_interval() failed:" + lua_tostring(m_ls, -1));
}
int oeres = lua_toboolean(m_ls, -1);
lua_pop(m_ls, 1);
if(oeres == false)
{
throw sinsp_exception("execution terminated by the " + m_filename + " chisel");
}
}
m_lua_last_interval_sample_time = t;
}
}
}
void sinsp_chisel::do_end_of_sample()
{
#ifdef HAS_LUA_CHISELS
lua_getglobal(m_ls, "on_end_of_sample");
if(lua_pcall(m_ls, 0, 1, 0) != 0)
{
throw sinsp_exception(m_filename + " chisel error: calling on_end_of_sample() failed:" + lua_tostring(m_ls, -1));
}
int oeres = lua_toboolean(m_ls, -1);
lua_pop(m_ls, 1);
if(oeres == false)
{
throw sinsp_exception("execution terminated by the " + m_filename + " chisel");
}
#endif // HAS_LUA_CHISELS
}
void sinsp_chisel::on_capture_start()
{
#ifdef HAS_LUA_CHISELS
lua_getglobal(m_ls, "on_capture_start");
if(lua_isfunction(m_ls, -1))
{
if(lua_pcall(m_ls, 0, 1, 0) != 0)
{
throw sinsp_exception(m_filename + " chisel error: " + lua_tostring(m_ls, -1));
}
if(!lua_isboolean(m_ls, -1))
{
throw sinsp_exception(m_filename + " chisel error: wrong on_capture_start() return value. Boolean expected.");
}
if(!lua_toboolean(m_ls, -1))
{
throw sinsp_exception("init() for chisel " + m_filename + " failed.");
}
lua_pop(m_ls, 1);
}
#endif // HAS_LUA_CHISELS
}
void sinsp_chisel::on_capture_end()
{
#ifdef HAS_LUA_CHISELS
lua_getglobal(m_ls, "on_capture_end");
if(lua_isfunction(m_ls, -1))
{
uint64_t ts = m_inspector->m_firstevent_ts;
uint64_t te = m_inspector->m_lastevent_ts;
int64_t delta = te - ts;
lua_pushnumber(m_ls, (double)(te / 1000000000));
lua_pushnumber(m_ls, (double)(te % 1000000000));
lua_pushnumber(m_ls, (double)delta);
if(lua_pcall(m_ls, 3, 0, 0) != 0)
{
throw sinsp_exception(m_filename + " chisel error: " + lua_tostring(m_ls, -1));
}
lua_pop(m_ls, 1);
}
#endif // HAS_LUA_CHISELS
}
bool sinsp_chisel::get_nextrun_args(OUT string* args)
{
ASSERT(m_lua_cinfo != NULL);
*args = m_lua_cinfo->m_nextrun_args;
return m_lua_cinfo->m_has_nextrun_args;
}
#endif // HAS_CHISELS
| 20.001661 | 133 | 0.635191 | [
"vector"
] |
28bb8152353f2c3eee63370473f97a6c20032d5b | 1,676 | hpp | C++ | src/emu_core/include/emu_core/symbol_factory.hpp | pgrabas/emu6502 | 5b46d624cdbb3cffcfd76939d6cdda371f61ed6a | [
"MIT"
] | null | null | null | src/emu_core/include/emu_core/symbol_factory.hpp | pgrabas/emu6502 | 5b46d624cdbb3cffcfd76939d6cdda371f61ed6a | [
"MIT"
] | null | null | null | src/emu_core/include/emu_core/symbol_factory.hpp | pgrabas/emu6502 | 5b46d624cdbb3cffcfd76939d6cdda371f61ed6a | [
"MIT"
] | null | null | null | #pragma once
#include "memory_configuration_file.hpp"
#include "program.hpp"
#include <cstdint>
#include <memory>
#include <string_view>
#include <vector>
namespace emu {
struct SymbolDefinition {
std::string name;
SymbolAddress value;
std::optional<Segment> segment = std::nullopt;
};
using SymbolDefVector = std::vector<SymbolDefinition>;
SymbolAddress GetSymbolAddress(uint32_t v);
struct SymbolDefVectorBuilder {
SymbolDefVector entries;
const std::string device_name;
const std::string class_name;
SymbolDefVectorBuilder(const std::string &device_name, const std::string &class_name);
template <typename V, typename O = int>
void EmitSymbol(const std::string &name, V base, O offset = 0) {
entries.emplace_back(SymbolDefinition{
.name = fmt::format("{}_{}_{}", class_name, device_name, name),
.value = GetSymbolAddress(base + static_cast<V>(offset)),
.segment = Segment::AbsoluteAddress,
});
}
template <typename V, typename O = int>
void EmitAlias(const std::string &name, V base, O offset = 0) {
entries.emplace_back(SymbolDefinition{
.name = fmt::format("{}_{}_{}", class_name, device_name, name),
.value = GetSymbolAddress(base + static_cast<V>(offset)),
.segment = std::nullopt,
});
}
};
struct SymbolFactory {
virtual ~SymbolFactory() = default;
virtual SymbolDefVector
GetSymbols(const MemoryConfigEntry &entry,
const MemoryConfigEntry::MappedDevice &md) const = 0;
virtual SymbolDefVector GetSymbols(const MemoryConfig &memory_config) const;
};
} // namespace emu
| 28.896552 | 90 | 0.673031 | [
"vector"
] |
28be35bae71253bcbdd57cad4fe6bd272f5e9ddd | 1,208 | cpp | C++ | bin/KMP.cpp | potter1024/Hacktoberfest2020 | 5b02a6bded8628e540eb2cd760241bf3f837a007 | [
"MIT"
] | null | null | null | bin/KMP.cpp | potter1024/Hacktoberfest2020 | 5b02a6bded8628e540eb2cd760241bf3f837a007 | [
"MIT"
] | null | null | null | bin/KMP.cpp | potter1024/Hacktoberfest2020 | 5b02a6bded8628e540eb2cd760241bf3f837a007 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
vector<int> computelps(string str){
vector<int> lps(str.size());
lps[0]=0;
int j=0;
for(int i=1;i<str.size();i++){
while(j!=0 && str[j]!=str[i]){
j=lps[j-1];
}
if(str[j]==str[i]){
j++;
}
lps[i]=j;
}
return lps;
}
bool kmpsearch(string tofind,string text){
vector<int> lps = computelps(tofind);
cout<<endl;
int n = text.size(), m = tofind.size();
int i = 0, j = 0;
while( i < n ){
while( j < m && i < n && tofind[j] == text[i] ){
i++;
j++;
}
if( j == m && tofind[j-1] == text[i-1]){
return 1;
}
else if( i == n ){
return 0;
}
else{
if( j != 0){
j = lps[j-1];
}
else{
i++;
}
}
}
return 0;
}
int main(){
string text = "ABCDDBCEFGHIJJKLLMNOPQQRSTUVWXXXYZZ";
string tofind = "BCDD";
if(kmpsearch(tofind,text)){
cout<<"Found "<<tofind<<" in "<<text<<endl;
}
else{
cout<<"Not found "<<tofind<<" in "<<text<<endl;
}
}
| 20.474576 | 56 | 0.410596 | [
"vector"
] |
28be9588daa2845fdc5bdfef3ea69c968900782e | 2,060 | cpp | C++ | src/data/User.cpp | davidcorbin/mygcc-application | 9e978e4d6e4cd3d8534bbc73f38c45b205258cc9 | [
"MIT"
] | 2 | 2019-01-18T02:33:45.000Z | 2019-02-01T23:44:05.000Z | src/data/User.cpp | davidcorbin/mygcc-application | 9e978e4d6e4cd3d8534bbc73f38c45b205258cc9 | [
"MIT"
] | null | null | null | src/data/User.cpp | davidcorbin/mygcc-application | 9e978e4d6e4cd3d8534bbc73f38c45b205258cc9 | [
"MIT"
] | null | null | null | /**
* Copyright 2018 <David Corbin, Mitchell Harvey>
*/
#include <include/data/User.hpp>
#include <string>
#define USER_URL "http://localhost:8080/1/user/"
#define HTTP_CONTENT_TYPE "application/json"
User::User(Login *login) : login(login) {
userRetrieved = false;
connect(login, SIGNAL(authSuccessful()), this, SLOT(queueGetUser()));
}
void User::getUser(std::string *token) {
QNetworkRequest request(QUrl(USER_URL));
request.setHeader(QNetworkRequest::ContentTypeHeader, HTTP_CONTENT_TYPE);
request.setRawHeader("Authorization",
(QString::fromStdString(*token)).toUtf8());
auto *nam = new QNetworkAccessManager;
connect(nam, &QNetworkAccessManager::finished,
[=](QNetworkReply *reply) -> void {
if (reply->error()) {
// If credentials invalid
if (reply->error() ==
QNetworkReply::AuthenticationRequiredError) {
qDebug("Invalid credentials");
return;
}
qDebug() << "Unexpected error: " << reply->errorString();
return;
}
auto response = reply->readAll();
QJsonDocument loadDoc(QJsonDocument::fromJson(response));
// If invalid json object, reset file
if (!loadDoc.isObject()) {
qDebug("Invalid json response: expected json array");
return;
}
qDebug("Retrieved user");
parseUserJson(loadDoc.object());
});
nam->get(request);
}
void User::queueGetUser() {
auto *token = login->getApiToken();
getUser(token);
}
void User::parseUserJson(QJsonObject jsonObject) {
profile = new Profile(jsonObject);
userRetrieved = true;
emit userLoaded();
}
Profile *User::getProfile() const {
return profile;
}
void User::setProfile(Profile *profile) {
User::profile = profile;
}
bool User::isUserRetrieved() const {
return userRetrieved;
}
void User::setUserRetrieved(bool userRetrieved) {
User::userRetrieved = userRetrieved;
}
| 27.105263 | 75 | 0.619417 | [
"object"
] |
28bfb99c427b8f8009ae2af62e44d53b5772cda4 | 2,391 | cpp | C++ | Languages/C++/VerticalOrderTreePrint.cpp | saurabhcommand/Hacktoberfest | 77bcfebf6882d0481479c03503c8e024fb18f0c3 | [
"MIT"
] | 1 | 2020-10-03T03:17:03.000Z | 2020-10-03T03:17:03.000Z | Languages/C++/VerticalOrderTreePrint.cpp | saurabhcommand/Hacktoberfest | 77bcfebf6882d0481479c03503c8e024fb18f0c3 | [
"MIT"
] | 1 | 2020-10-13T06:01:45.000Z | 2020-10-13T06:01:45.000Z | Languages/C++/VerticalOrderTreePrint.cpp | saurabhcommand/Hacktoberfest | 77bcfebf6882d0481479c03503c8e024fb18f0c3 | [
"MIT"
] | 4 | 2020-10-07T14:58:50.000Z | 2020-10-24T10:13:17.000Z | #include<bits/stdc++.h>
using namespace std;
template <typename T>
class BinaryTreeNode {
public :
T data;
BinaryTreeNode<T> *left;
BinaryTreeNode<T> *right;
BinaryTreeNode(T data) {
this -> data = data;
left = NULL;
right = NULL;
}
};
BinaryTreeNode<int>* takeInputLevelWise() {
int data;
// cout << "Enter root : ";
cin >> data;
BinaryTreeNode<int> *root = new BinaryTreeNode<int>(data);
queue<BinaryTreeNode<int>* > pendingNodes;
pendingNodes.push(root);
while(!pendingNodes.empty()) {
BinaryTreeNode<int> *current = pendingNodes.front();
pendingNodes.pop();
int leftData, rightData;
// cout << "Enter left child of : " << current -> data << " : ";
cin >> leftData;
if(leftData != -1) {
BinaryTreeNode<int> *left = new BinaryTreeNode<int>(leftData);
current -> left = left;
pendingNodes.push(left);
}
// cout << "Enter right child of " << current -> data << " : ";
cin >> rightData;
if(rightData != -1) {
BinaryTreeNode<int> *right = new BinaryTreeNode<int>(rightData);
current -> right = right;
pendingNodes.push(right);
}
}
return root;
}
int main()
{
BinaryTreeNode<int> *root = takeInputLevelWise();
printBinaryTreeVerticalOrder(root);
return 0;
}
void verticalTraversal(BinaryTreeNode<int>* root,int order,map<int,vector<int>> &mp){
if(root == NULL)return;
mp[order].push_back(root->data);
verticalTraversal(root->left,order-1,mp);
verticalTraversal(root->right,order+1,mp);
}
void printBinaryTreeVerticalOrder(BinaryTreeNode<int>* root) {
// Following is the structure of the Binary Tree node class
/*
class BinaryTreeNode {
public :
T data;
BinaryTreeNode<T> *left;
BinaryTreeNode<T> *right;
BinaryTreeNode(T data) {
this -> data = data;
left = NULL;
right = NULL;
}
};
*/
map<int,vector<int>> mp;
int order = 0;
verticalTraversal(root,order,mp);
for(auto it = mp.begin();it!=mp.end();it++){
for(auto x:mp[it->first]){
cout<<x<<" ";
}
cout<<endl;
}
}
| 21.540541 | 86 | 0.54496 | [
"vector"
] |
28c1c885705cd4c5bcd329f6e6d745c16b180db5 | 3,024 | cpp | C++ | source/source/Finger/Finger02/src/LeapApp.cpp | LeapBookCpp/LeapBookCpp | 6c51c75693a69996bb7fb817b5108a7f72dc9b8c | [
"MIT"
] | 3 | 2016-06-16T00:16:03.000Z | 2020-12-07T03:12:10.000Z | source/source/Finger/Finger02/src/LeapApp.cpp | LeapBookCpp/LeapBookCpp | 6c51c75693a69996bb7fb817b5108a7f72dc9b8c | [
"MIT"
] | null | null | null | source/source/Finger/Finger02/src/LeapApp.cpp | LeapBookCpp/LeapBookCpp | 6c51c75693a69996bb7fb817b5108a7f72dc9b8c | [
"MIT"
] | 5 | 2015-06-04T08:48:14.000Z | 2021-07-26T14:27:58.000Z | #include "cinder/app/AppNative.h"
#include "cinder/gl/gl.h"
#include "cinder/gl/Texture.h"
#include "cinder/Text.h"
#include "cinder/MayaCamUI.h"
#include "Leap.h"
using namespace ci;
using namespace ci::app;
using namespace std;
class LeapApp : public AppNative {
public:
void setup()
{
// ウィンドウの位置とサイズを設定
setWindowPos( 50, 50 );
setWindowSize( 1280, 700 );
// 光源を追加する
glEnable( GL_LIGHTING );
glEnable( GL_LIGHT0 );
// 表示フォントと領域の設定
mFont = Font( "YuGothic", 20 );
// カメラ(視点)の設定
float y = 250;
mCam.setEyePoint( Vec3f( 0.0f, y, 500.0f ) );
mCam.lookAt( Vec3f( 0.0f, y, 0.0f ) );
mCam.setPerspective( 45.0f, getWindowAspectRatio(), 5.0f, 3000.0f );
mMayaCam.setCurrentCam(mCam);
// 描画時に奥行きの考慮を有効にする
gl::enableDepthRead();
// Leap Motion関連のセットアップ
setupLeapObject();
}
// マウスダウン
void mouseDown( MouseEvent event )
{
mMayaCam.mouseDown( event.getPos() );
}
// マウスのドラッグ
void mouseDrag( MouseEvent event )
{
mMayaCam.mouseDrag( event.getPos(), event.isLeftDown(),
event.isMiddleDown(), event.isRightDown() );
}
// 更新処理
void update()
{
// フレームの更新
mLastFrame = mCurrentFrame;
mCurrentFrame = mLeap.frame();
renderFrameParameter();
}
// 描画処理
void draw()
{
gl::clear( Color( 0, 0, 0 ) );
drawLeapObject();
drawTexture();
}
// Leap Motion関連のセットアップ
void setupLeapObject()
{
}
// フレーム情報の描画
void renderFrameParameter()
{
stringstream ss;
// 検出した指の数
ss << "Finger Count : "<< mCurrentFrame.fingers().count() << "\n";
// 指の座標を取得する
for ( auto finger : mCurrentFrame.fingers() ) {
ss << "Finger Position: " << finger.tipPosition().x << ", "
<< finger.tipPosition().y << ", "
<< finger.tipPosition().z << "\n";
}
// テキストボックスを作成する
auto tbox = TextBox()
.alignment( TextBox::LEFT )
.font( mFont )
.text ( ss.str() )
.color(Color( 1.0f, 1.0f, 1.0f ))
.backgroundColor( ColorA( 0, 0, 0, 0.5f ) );
mTextTexture = gl::Texture( tbox.render() );
}
// Leap Motion関連の描画
void drawLeapObject()
{
// 表示座標系の保持
gl::pushMatrices();
// カメラ位置を設定する
gl::setMatrices( mMayaCam.getCamera() );
// 指を表示する
for ( auto finger : mCurrentFrame.fingers() ) {
if ( finger.isExtended() ) {
gl::drawSphere( toVec3f( finger.tipPosition() ), 10 );
}
}
// 表示座標系を戻す
gl::popMatrices();
}
// テクスチャの描画
void drawTexture()
{
if( mTextTexture ) {
gl::draw( mTextTexture );
}
}
// Leap SDKのVectorをCinderのVec3fに変換する
Vec3f toVec3f( Leap::Vector vec )
{
return Vec3f( vec.x, vec.y, vec.z );
}
// カメラ
CameraPersp mCam;
MayaCamUI mMayaCam;
// パラメータ表示用のテクスチャ
gl::Texture mTextTexture;
Font mFont;
// Leap Motion
Leap::Controller mLeap;
Leap::Frame mCurrentFrame;
Leap::Frame mLastFrame;
};
CINDER_APP_NATIVE( LeapApp, RendererGl )
| 19.384615 | 72 | 0.588294 | [
"render",
"vector"
] |
28d35ba93f066cad36befef5b4305a992bd09390 | 2,460 | cpp | C++ | 01_Develop/libXMIrrlicht/Source/scene/loaders/CBSPMeshFileLoader.cpp | mcodegeeks/OpenKODE-Framework | d4382d781da7f488a0e7667362a89e8e389468dd | [
"MIT"
] | 2 | 2017-08-03T07:15:00.000Z | 2018-06-18T10:32:53.000Z | 01_Develop/libXMIrrlicht/Source/scene/loaders/CBSPMeshFileLoader.cpp | mcodegeeks/OpenKODE-Framework | d4382d781da7f488a0e7667362a89e8e389468dd | [
"MIT"
] | null | null | null | 01_Develop/libXMIrrlicht/Source/scene/loaders/CBSPMeshFileLoader.cpp | mcodegeeks/OpenKODE-Framework | d4382d781da7f488a0e7667362a89e8e389468dd | [
"MIT"
] | 2 | 2019-03-04T22:57:42.000Z | 2020-03-06T01:32:26.000Z | // Copyright (C) 2002-2011 Nikolaus Gebhardt
// This file is part of the "Irrlicht Engine".
// For conditions of distribution and use, see copyright notice in irrlicht.h
#include "IrrCompileConfig.h"
#ifdef _IRR_COMPILE_WITH_BSP_LOADER_
#include "CBSPMeshFileLoader.h"
#include "CQ3LevelMesh.h"
namespace irr
{
namespace scene
{
//! Constructor
CBSPMeshFileLoader::CBSPMeshFileLoader(scene::ISceneManager* smgr,
io::IFileSystem* fs)
: FileSystem(fs), SceneManager(smgr)
{
#ifdef _DEBUG
setDebugName("CBSPMeshFileLoader");
#endif
if (FileSystem)
FileSystem->grab();
}
//! destructor
CBSPMeshFileLoader::~CBSPMeshFileLoader()
{
if (FileSystem)
FileSystem->drop();
}
//! returns true if the file maybe is able to be loaded by this class
//! based on the file extension (e.g. ".bsp")
bool CBSPMeshFileLoader::isALoadableFileExtension(const io::path& filename) const
{
return core::hasFileExtension ( filename, "bsp", "shader", "cfg" );
}
//! creates/loads an animated mesh from the file.
//! \return Pointer to the created mesh. Returns 0 if loading failed.
//! If you no longer need the mesh, you should call IAnimatedMesh::drop().
//! See IReferenceCounted::drop() for more information.
IAnimatedMesh* CBSPMeshFileLoader::createMesh(io::IReadFile* file)
{
s32 type = core::isFileExtension ( file->getFileName(), "bsp", "shader", "cfg" );
CQ3LevelMesh* q = 0;
switch ( type )
{
case 1:
q = new CQ3LevelMesh(FileSystem, SceneManager, LoadParam);
// determine real shaders in LoadParam
if ( 0 == LoadParam.loadAllShaders )
{
q->getShader("scripts/common.shader");
q->getShader("scripts/sfx.shader");
q->getShader("scripts/gfx.shader");
q->getShader("scripts/liquid.shader");
q->getShader("scripts/models.shader");
q->getShader("scripts/walls.shader");
//q->getShader("scripts/sky.shader");
}
if ( q->loadFile(file) )
return q;
q->drop();
break;
case 2:
q = new CQ3LevelMesh(FileSystem, SceneManager,LoadParam);
q->getShader( file );
return q;
break;
case 3:
// load quake 3 loading parameter
if ( file->getFileName() == "levelparameter.cfg" )
{
file->read ( &LoadParam, sizeof ( LoadParam ) );
}
else
{
q = new CQ3LevelMesh(FileSystem, SceneManager,LoadParam);
q->getConfiguration( file );
return q;
}
break;
}
return 0;
}
} // end namespace scene
} // end namespace irr
#endif // _IRR_COMPILE_WITH_BSP_LOADER_
| 22.777778 | 82 | 0.689024 | [
"mesh"
] |
28d3c8cdc94af1aeed72e49e3188ae303b9aac03 | 2,823 | cpp | C++ | PhysBox2D/SOURCE/GRAPHICS/graphics_image_pixel_loader.cpp | consequencesunintended/TreeHundred | 8d3779d1071399a1f93cb5686d5c5e53bd6fde0a | [
"MIT"
] | 22 | 2021-07-24T17:54:23.000Z | 2021-10-20T16:35:12.000Z | PhysBox2D/SOURCE/GRAPHICS/graphics_image_pixel_loader.cpp | consequencesunintended/TreeHundred | 8d3779d1071399a1f93cb5686d5c5e53bd6fde0a | [
"MIT"
] | null | null | null | PhysBox2D/SOURCE/GRAPHICS/graphics_image_pixel_loader.cpp | consequencesunintended/TreeHundred | 8d3779d1071399a1f93cb5686d5c5e53bd6fde0a | [
"MIT"
] | 1 | 2021-08-04T09:24:10.000Z | 2021-08-04T09:24:10.000Z | #include "graphics_image_pixel_loader.h"
// -- LOCAL
// .. REFERENCES
#include "platform_file_reader.h"
// -- PUBLIC
// .. FUNCTIONS
void GRAPHICS_IMAGE_PIXEL_LOADER::LoadBMP( GRAPHICS_IMAGE_PIXEL_LOADER & image, const char * filename )
{
int dataOffset;
int headerSize;
int width;
int height;
int bytesPerRow;
int size;
char *pixels3;
char *pixels2;
int index_x;
int index_y;
int index_c;
PLATFORM_FILE_READER file_reader_engine;
file_reader_engine.LoadFile( filename );
file_reader_engine.SkipCharacters( 10 );
dataOffset = file_reader_engine.readInt();
headerSize = file_reader_engine.readInt();
switch( headerSize )
{
case 40:
width = file_reader_engine.readInt();
height = file_reader_engine.readInt();
break;
case 12:
width = file_reader_engine.readShort();
height = file_reader_engine.readShort();
break;
}
bytesPerRow = ((width * 3 + 3) / 4) * 4 - (width * 3 % 4);
size = bytesPerRow * height;
pixels3 = new char[ size ];
file_reader_engine.SeekInBeginning(dataOffset);
file_reader_engine.ReadCharacters( pixels3 , size);
pixels2 = new char[ width * height * 3 ];
for ( index_y = 0; index_y <= height - 1; index_y++ )
{
for ( index_x = 0; index_x <= width - 1; index_x++ )
{
for ( index_c = 0; index_c <= 2; index_c++ )
{
pixels2[ 3 * ( width * index_y + index_x ) + index_c ] = pixels3[ bytesPerRow * index_y + 3 * index_x + ( 2 - index_c ) ];
}
}
}
file_reader_engine.CloseTheFile();
image = GRAPHICS_IMAGE_PIXEL_LOADER( pixels2, width, height);
delete [] pixels2;
delete [] pixels3;
}
void GRAPHICS_IMAGE_PIXEL_LOADER::set_pixels( const char* other_pixels )
{
pixels = new char[ width * height * 3 ];
for ( int index_y = 0; index_y <= height - 1; index_y++ )
{
for ( int index_x = 0; index_x <= width - 1; index_x++ )
{
for ( int index_c = 0; index_c <= 2; index_c++ )
{
pixels[ 3 * (width * index_y + index_x) + index_c ] = other_pixels[ 3 * (width * index_y + index_x) + index_c ];
}
}
}
}
std::vector< MATH_POINT_2D > GRAPHICS_IMAGE_PIXEL_LOADER::GetPositions( const char* bitmap )
{
unsigned int width;
unsigned int height;
unsigned int colour;
GRAPHICS_IMAGE_PIXEL_LOADER image;
unsigned int index_x;
unsigned int index_y;
std::vector< MATH_POINT_2D > point_table;
GRAPHICS_IMAGE_PIXEL_LOADER::LoadBMP( image, bitmap );
width = image.GetWidth();
height = image.GetHeight();
for ( index_y = 0; index_y <= height - 1; index_y++ )
{
for ( index_x = 0; index_x <= width - 1; index_x++ )
{
colour = image.GetPixels()[ 3 * (index_y * width + index_x) ];
if ( colour != -1 )
{
point_table.push_back( MATH_POINT_2D( float( int( index_x - width / 2 ) ), float( int( index_y - height / 2 ) ) ) );
}
}
}
return point_table;
}
| 23.139344 | 126 | 0.657457 | [
"vector"
] |
28d3d249fbdb71fd3912ff2beea99fe21804646d | 4,064 | hpp | C++ | nxmodel/src/nexus.hpp | Intuity/nexus | 0d1414fa2ea518dae9f031930c40692ebac5d154 | [
"Apache-2.0"
] | 6 | 2021-06-28T05:52:15.000Z | 2022-03-27T20:45:28.000Z | nxmodel/src/nexus.hpp | Intuity/nexus | 0d1414fa2ea518dae9f031930c40692ebac5d154 | [
"Apache-2.0"
] | null | null | null | nxmodel/src/nexus.hpp | Intuity/nexus | 0d1414fa2ea518dae9f031930c40692ebac5d154 | [
"Apache-2.0"
] | null | null | null | // Copyright 2021, Peter Birch, mailto:peter@lightlogic.co.uk
//
// 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 <filesystem>
#include <iostream>
#include <list>
#include <map>
#include <memory>
#include <stdbool.h>
#include <stdint.h>
#include <tuple>
#include "nxmesh.hpp"
#include "nxmessagepipe.hpp"
#ifndef __NEXUS_HPP__
#define __NEXUS_HPP__
namespace NXModel {
class Nexus {
public:
// =====================================================================
// Data Structures
// =====================================================================
typedef std::tuple<uint32_t, uint32_t, uint32_t> output_key_t;
typedef std::map<output_key_t, bool> summary_t;
// =====================================================================
// Constructor
// =====================================================================
Nexus (
uint32_t rows,
uint32_t columns,
uint32_t node_inputs,
uint32_t node_outputs,
bool verbose = false
);
// =====================================================================
// Public Methods
// =====================================================================
/** Return the number of rows in the mesh
*
* @return integer number of rows
*/
uint32_t get_rows (void) { return m_rows; }
/** Return the number of columns in the mesh
*
* @return integer number of rows
*/
uint32_t get_columns (void) { return m_columns; }
/** Return a pointer to the mesh
*
* @return pointer to instance of NXMesh
*/
std::shared_ptr<NXMesh> get_mesh (void) { return m_mesh; }
/** Return a pointer to the ingress pipe
*
* @return pointer to instance of NXMessagePipe
*/
std::shared_ptr<NXMessagePipe> get_ingress (void) { return m_ingress; }
/** Return a pointer to the egress pipe
*
* @return pointer to instance of NXMessagePipe
*/
std::shared_ptr<NXMessagePipe> get_egress (void) { return m_egress; }
/** Run for a specified number of cycles
*
* @param cycles number of cycles to run for
*/
void run (uint32_t cycles);
/** Dump a VCD file
*
* @param path path to write the VCD to
*/
void dump_vcd (const std::string path);
/** Check if there are any output vectors available
*
* @return True if output is available, False otherwise
*/
bool is_output_available (void) { return !m_output.empty(); }
/** Pop the next output vector from the store
*
* @return pointer to an instance of summary_t
*/
summary_t * pop_output (void);
private:
// =====================================================================
// Private Members
// =====================================================================
// Sizing
uint32_t m_rows;
uint32_t m_columns;
// Verbosity
bool m_verbose;
// Mesh
std::shared_ptr<NXMesh> m_mesh;
// Ingress and egress pipes
std::shared_ptr<NXMessagePipe> m_ingress;
std::shared_ptr<NXMessagePipe> m_egress;
// Track output state
std::list<summary_t *> m_output;
};
}
#endif // __NEXUS_HPP__
| 28.822695 | 80 | 0.504921 | [
"mesh",
"vector"
] |
28d3d4da523b1c6c75aabf3f204bcbfbdc06b64f | 35,635 | hh | C++ | src/arch/arm/table_walker.hh | hyu-iot/gem5 | aeccc8bd8e9a86f96fc7a6f40d978f8494337fc5 | [
"BSD-3-Clause"
] | 765 | 2015-01-14T16:17:04.000Z | 2022-03-28T07:46:28.000Z | src/arch/arm/table_walker.hh | hyu-iot/gem5 | aeccc8bd8e9a86f96fc7a6f40d978f8494337fc5 | [
"BSD-3-Clause"
] | 30 | 2015-01-01T21:49:38.000Z | 2021-04-20T19:01:54.000Z | src/arch/arm/table_walker.hh | hyu-iot/gem5 | aeccc8bd8e9a86f96fc7a6f40d978f8494337fc5 | [
"BSD-3-Clause"
] | 807 | 2015-01-06T09:55:38.000Z | 2022-03-30T10:23:36.000Z | /*
* Copyright (c) 2010-2016, 2019, 2021 Arm Limited
* All rights reserved
*
* The license below extends only to copyright in the software and shall
* not be construed as granting a license to any other intellectual
* property including but not limited to intellectual property relating
* to a hardware implementation of the functionality of the software
* licensed hereunder. You may use the software subject to the license
* terms below provided that you ensure that this notice is replicated
* unmodified and in its entirety in all distributions of the software,
* modified or unmodified, in source code or in binary form.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders 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.
*/
#ifndef __ARCH_ARM_TABLE_WALKER_HH__
#define __ARCH_ARM_TABLE_WALKER_HH__
#include <list>
#include "arch/arm/faults.hh"
#include "arch/arm/mmu.hh"
#include "arch/arm/regs/misc.hh"
#include "arch/arm/system.hh"
#include "arch/arm/tlb.hh"
#include "arch/arm/types.hh"
#include "arch/generic/mmu.hh"
#include "mem/packet_queue.hh"
#include "mem/qport.hh"
#include "mem/request.hh"
#include "params/ArmTableWalker.hh"
#include "sim/clocked_object.hh"
#include "sim/eventq.hh"
namespace gem5
{
class ThreadContext;
namespace ArmISA {
class Translation;
class TLB;
class TableWalker : public ClockedObject
{
using LookupLevel = enums::ArmLookupLevel;
public:
class WalkerState;
class DescriptorBase
{
public:
DescriptorBase() : lookupLevel(LookupLevel::L0) {}
/** Current lookup level for this descriptor */
LookupLevel lookupLevel;
virtual Addr pfn() const = 0;
virtual TlbEntry::DomainType domain() const = 0;
virtual bool xn() const = 0;
virtual uint8_t ap() const = 0;
virtual bool global(WalkerState *currState) const = 0;
virtual uint8_t offsetBits() const = 0;
virtual bool secure(bool have_security, WalkerState *currState) const = 0;
virtual std::string dbgHeader() const = 0;
virtual uint64_t getRawData() const = 0;
virtual uint8_t texcb() const
{
panic("texcb() not implemented for this class\n");
}
virtual bool shareable() const
{
panic("shareable() not implemented for this class\n");
}
};
class L1Descriptor : public DescriptorBase
{
public:
/** Type of page table entry ARM DDI 0406B: B3-8*/
enum EntryType
{
Ignore,
PageTable,
Section,
Reserved
};
/** The raw bits of the entry */
uint32_t data;
/** This entry has been modified (access flag set) and needs to be
* written back to memory */
bool _dirty;
/** Default ctor */
L1Descriptor() : data(0), _dirty(false)
{
lookupLevel = LookupLevel::L1;
}
uint64_t
getRawData() const override
{
return (data);
}
std::string
dbgHeader() const override
{
return "Inserting Section Descriptor into TLB\n";
}
uint8_t
offsetBits() const override
{
return 20;
}
EntryType
type() const
{
return (EntryType)(data & 0x3);
}
/** Is the page a Supersection (16 MiB)?*/
bool
supersection() const
{
return bits(data, 18);
}
/** Return the physcal address of the entry, bits in position*/
Addr
paddr() const
{
if (supersection())
panic("Super sections not implemented\n");
return mbits(data, 31, 20);
}
/** Return the physcal address of the entry, bits in position*/
Addr
paddr(Addr va) const
{
if (supersection())
panic("Super sections not implemented\n");
return mbits(data, 31, 20) | mbits(va, 19, 0);
}
/** Return the physical frame, bits shifted right */
Addr
pfn() const override
{
if (supersection())
panic("Super sections not implemented\n");
return bits(data, 31, 20);
}
/** Is the translation global (no asid used)? */
bool
global(WalkerState *currState) const override
{
return !bits(data, 17);
}
/** Is the translation not allow execution? */
bool
xn() const override
{
return bits(data, 4);
}
/** Three bit access protection flags */
uint8_t
ap() const override
{
return (bits(data, 15) << 2) | bits(data, 11, 10);
}
/** Domain Client/Manager: ARM DDI 0406B: B3-31 */
TlbEntry::DomainType
domain() const override
{
return static_cast<TlbEntry::DomainType>(bits(data, 8, 5));
}
/** Address of L2 descriptor if it exists */
Addr
l2Addr() const
{
return mbits(data, 31, 10);
}
/** Memory region attributes: ARM DDI 0406B: B3-32.
* These bits are largly ignored by M5 and only used to
* provide the illusion that the memory system cares about
* anything but cachable vs. uncachable.
*/
uint8_t
texcb() const override
{
return bits(data, 2) | bits(data, 3) << 1 | bits(data, 14, 12) << 2;
}
/** If the section is shareable. See texcb() comment. */
bool
shareable() const override
{
return bits(data, 16);
}
/** Set access flag that this entry has been touched. Mark
* the entry as requiring a writeback, in the future.
*/
void
setAp0()
{
data |= 1 << 10;
_dirty = true;
}
/** This entry needs to be written back to memory */
bool
dirty() const
{
return _dirty;
}
/**
* Returns true if this entry targets the secure physical address
* map.
*/
bool
secure(bool have_security, WalkerState *currState) const override
{
if (have_security && currState->secureLookup) {
if (type() == PageTable)
return !bits(data, 3);
else
return !bits(data, 19);
}
return false;
}
};
/** Level 2 page table descriptor */
class L2Descriptor : public DescriptorBase
{
public:
/** The raw bits of the entry. */
uint32_t data;
L1Descriptor *l1Parent;
/** This entry has been modified (access flag set) and needs to be
* written back to memory */
bool _dirty;
/** Default ctor */
L2Descriptor() : data(0), l1Parent(nullptr), _dirty(false)
{
lookupLevel = LookupLevel::L2;
}
L2Descriptor(L1Descriptor &parent) : data(0), l1Parent(&parent),
_dirty(false)
{
lookupLevel = LookupLevel::L2;
}
uint64_t
getRawData() const override
{
return (data);
}
std::string
dbgHeader() const override
{
return "Inserting L2 Descriptor into TLB\n";
}
TlbEntry::DomainType
domain() const override
{
return l1Parent->domain();
}
bool
secure(bool have_security, WalkerState *currState) const override
{
return l1Parent->secure(have_security, currState);
}
uint8_t
offsetBits() const override
{
return large() ? 16 : 12;
}
/** Is the entry invalid */
bool
invalid() const
{
return bits(data, 1, 0) == 0;
}
/** What is the size of the mapping? */
bool
large() const
{
return bits(data, 1) == 0;
}
/** Is execution allowed on this mapping? */
bool
xn() const override
{
return large() ? bits(data, 15) : bits(data, 0);
}
/** Is the translation global (no asid used)? */
bool
global(WalkerState *currState) const override
{
return !bits(data, 11);
}
/** Three bit access protection flags */
uint8_t
ap() const override
{
return bits(data, 5, 4) | (bits(data, 9) << 2);
}
/** Memory region attributes: ARM DDI 0406B: B3-32 */
uint8_t
texcb() const override
{
return large() ?
(bits(data, 2) | (bits(data, 3) << 1) | (bits(data, 14, 12) << 2)) :
(bits(data, 2) | (bits(data, 3) << 1) | (bits(data, 8, 6) << 2));
}
/** Return the physical frame, bits shifted right */
Addr
pfn() const override
{
return large() ? bits(data, 31, 16) : bits(data, 31, 12);
}
/** Return complete physical address given a VA */
Addr
paddr(Addr va) const
{
if (large())
return mbits(data, 31, 16) | mbits(va, 15, 0);
else
return mbits(data, 31, 12) | mbits(va, 11, 0);
}
/** If the section is shareable. See texcb() comment. */
bool
shareable() const override
{
return bits(data, 10);
}
/** Set access flag that this entry has been touched. Mark
* the entry as requiring a writeback, in the future.
*/
void
setAp0()
{
data |= 1 << 4;
_dirty = true;
}
/** This entry needs to be written back to memory */
bool
dirty() const
{
return _dirty;
}
};
/** Long-descriptor format (LPAE) */
class LongDescriptor : public DescriptorBase
{
public:
/** Descriptor type */
enum EntryType
{
Invalid,
Table,
Block,
Page
};
LongDescriptor()
: data(0), _dirty(false), aarch64(false), grainSize(Grain4KB),
physAddrRange(0)
{}
/** The raw bits of the entry */
uint64_t data;
/** This entry has been modified (access flag set) and needs to be
* written back to memory */
bool _dirty;
/** True if the current lookup is performed in AArch64 state */
bool aarch64;
/** Width of the granule size in bits */
GrainSize grainSize;
uint8_t physAddrRange;
uint64_t
getRawData() const override
{
return (data);
}
std::string
dbgHeader() const override
{
switch (type()) {
case LongDescriptor::Page:
assert(lookupLevel == LookupLevel::L3);
return "Inserting Page descriptor into TLB\n";
case LongDescriptor::Block:
assert(lookupLevel < LookupLevel::L3);
return "Inserting Block descriptor into TLB\n";
case LongDescriptor::Table:
return "Inserting Table descriptor into TLB\n";
default:
panic("Trying to insert and invalid descriptor\n");
}
}
/**
* Returns true if this entry targets the secure physical address
* map.
*/
bool
secure(bool have_security, WalkerState *currState) const override
{
if (type() == Block || type() == Page) {
return have_security &&
(currState->secureLookup && !bits(data, 5));
} else {
return have_security && currState->secureLookup;
}
}
/** Return the descriptor type */
EntryType
type() const
{
switch (bits(data, 1, 0)) {
case 0x1:
// In AArch64 blocks are not allowed at L0 for the
// 4 KiB granule and at L1 for 16/64 KiB granules
switch (grainSize) {
case Grain4KB:
if (lookupLevel == LookupLevel::L0 ||
lookupLevel == LookupLevel::L3)
return Invalid;
else
return Block;
case Grain16KB:
if (lookupLevel == LookupLevel::L2)
return Block;
else
return Invalid;
case Grain64KB:
// With Armv8.2-LPA (52bit PA) L1 Block descriptors
// are allowed for 64KiB granule
if ((lookupLevel == LookupLevel::L1 && physAddrRange == 52) ||
lookupLevel == LookupLevel::L2)
return Block;
else
return Invalid;
default:
return Invalid;
}
case 0x3:
return lookupLevel == LookupLevel::L3 ? Page : Table;
default:
return Invalid;
}
}
/** Return the bit width of the page/block offset */
uint8_t
offsetBits() const override
{
if (type() == Block) {
switch (grainSize) {
case Grain4KB:
return lookupLevel == LookupLevel::L1 ?
30 /* 1 GiB */ : 21 /* 2 MiB */;
case Grain16KB:
return 25 /* 32 MiB */;
case Grain64KB:
return lookupLevel == LookupLevel::L1 ?
42 /* 4 TiB */ : 29 /* 512 MiB */;
default:
panic("Invalid AArch64 VM granule size\n");
}
} else if (type() == Page) {
switch (grainSize) {
case Grain4KB:
case Grain16KB:
case Grain64KB:
return grainSize; /* enum -> uint okay */
default:
panic("Invalid AArch64 VM granule size\n");
}
} else if (type() == Table) {
const auto* ptops = getPageTableOps(grainSize);
return ptops->walkBits(lookupLevel);
}
panic("AArch64 page table entry must be block or page\n");
}
/** Return the physical frame, bits shifted right */
Addr
pfn() const override
{
return paddr() >> offsetBits();
}
/** Return the physical address of the entry */
Addr
paddr() const
{
Addr addr = 0;
if (aarch64) {
addr = mbits(data, 47, offsetBits());
if (physAddrRange == 52 && grainSize == Grain64KB) {
addr |= bits(data, 15, 12) << 48;
}
} else {
addr = mbits(data, 39, offsetBits());
}
return addr;
}
/** Return the address of the next page table */
Addr
nextTableAddr() const
{
assert(type() == Table);
Addr table_address = 0;
if (aarch64) {
table_address = mbits(data, 47, grainSize);
// Using 52bit if Armv8.2-LPA is implemented
if (physAddrRange == 52 && grainSize == Grain64KB)
table_address |= bits(data, 15, 12) << 48;
} else {
table_address = mbits(data, 39, 12);
}
return table_address;
}
/** Return the address of the next descriptor */
Addr
nextDescAddr(Addr va) const
{
assert(type() == Table);
Addr pa = 0;
if (aarch64) {
int stride = grainSize - 3;
int va_lo = stride * (3 - (lookupLevel + 1)) + grainSize;
int va_hi = va_lo + stride - 1;
pa = nextTableAddr() | (bits(va, va_hi, va_lo) << 3);
} else {
if (lookupLevel == LookupLevel::L1)
pa = nextTableAddr() | (bits(va, 29, 21) << 3);
else // lookupLevel == L2
pa = nextTableAddr() | (bits(va, 20, 12) << 3);
}
return pa;
}
/** Is execution allowed on this mapping? */
bool
xn() const override
{
assert(type() == Block || type() == Page);
return bits(data, 54);
}
/** Is privileged execution allowed on this mapping? (LPAE only) */
bool
pxn() const
{
assert(type() == Block || type() == Page);
return bits(data, 53);
}
/** Contiguous hint bit. */
bool
contiguousHint() const
{
assert(type() == Block || type() == Page);
return bits(data, 52);
}
/** Is the translation global (no asid used)? */
bool
global(WalkerState *currState) const override
{
assert(currState && (type() == Block || type() == Page));
if (!currState->aarch64 && (currState->isSecure &&
!currState->secureLookup)) {
return false; // ARM ARM issue C B3.6.3
} else if (currState->aarch64) {
if (currState->el == EL2 || currState->el == EL3) {
return true; // By default translations are treated as global
// in AArch64 EL2 and EL3
} else if (currState->isSecure && !currState->secureLookup) {
return false;
}
}
return !bits(data, 11);
}
/** Returns true if the access flag (AF) is set. */
bool
af() const
{
assert(type() == Block || type() == Page);
return bits(data, 10);
}
/** 2-bit shareability field */
uint8_t
sh() const
{
assert(type() == Block || type() == Page);
return bits(data, 9, 8);
}
/** 2-bit access protection flags */
uint8_t
ap() const override
{
assert(type() == Block || type() == Page);
// Long descriptors only support the AP[2:1] scheme
return bits(data, 7, 6);
}
/** Read/write access protection flag */
bool
rw() const
{
assert(type() == Block || type() == Page);
return !bits(data, 7);
}
/** User/privileged level access protection flag */
bool
user() const
{
assert(type() == Block || type() == Page);
return bits(data, 6);
}
/** Return the AP bits as compatible with the AP[2:0] format. Utility
* function used to simplify the code in the TLB for performing
* permission checks. */
static uint8_t
ap(bool rw, bool user)
{
return ((!rw) << 2) | (user << 1);
}
TlbEntry::DomainType
domain() const override
{
// Long-desc. format only supports Client domain
return TlbEntry::DomainType::Client;
}
/** Attribute index */
uint8_t
attrIndx() const
{
assert(type() == Block || type() == Page);
return bits(data, 4, 2);
}
/** Memory attributes, only used by stage 2 translations */
uint8_t
memAttr() const
{
assert(type() == Block || type() == Page);
return bits(data, 5, 2);
}
/** Set access flag that this entry has been touched. Mark the entry as
* requiring a writeback, in the future. */
void
setAf()
{
data |= 1 << 10;
_dirty = true;
}
/** This entry needs to be written back to memory */
bool
dirty() const
{
return _dirty;
}
/** Whether the subsequent levels of lookup are secure */
bool
secureTable() const
{
assert(type() == Table);
return !bits(data, 63);
}
/** Two bit access protection flags for subsequent levels of lookup */
uint8_t
apTable() const
{
assert(type() == Table);
return bits(data, 62, 61);
}
/** R/W protection flag for subsequent levels of lookup */
uint8_t
rwTable() const
{
assert(type() == Table);
return !bits(data, 62);
}
/** User/privileged mode protection flag for subsequent levels of
* lookup */
uint8_t
userTable() const
{
assert(type() == Table);
return !bits(data, 61);
}
/** Is execution allowed on subsequent lookup levels? */
bool
xnTable() const
{
assert(type() == Table);
return bits(data, 60);
}
/** Is privileged execution allowed on subsequent lookup levels? */
bool
pxnTable() const
{
assert(type() == Table);
return bits(data, 59);
}
};
class WalkerState
{
public:
/** Thread context that we're doing the walk for */
ThreadContext *tc;
/** If the access is performed in AArch64 state */
bool aarch64;
/** Current exception level */
ExceptionLevel el;
/** Current physical address range in bits */
int physAddrRange;
/** Request that is currently being serviced */
RequestPtr req;
/** Initial walk entry allowing to skip lookup levels */
TlbEntry walkEntry;
/** ASID that we're servicing the request under */
uint16_t asid;
vmid_t vmid;
bool isHyp;
/** Translation state for delayed requests */
BaseMMU::Translation *transState;
/** The fault that we are going to return */
Fault fault;
/** The virtual address that is being translated with tagging removed.*/
Addr vaddr;
/** The virtual address that is being translated */
Addr vaddr_tainted;
/** Cached copy of the sctlr as it existed when translation began */
SCTLR sctlr;
/** Cached copy of the scr as it existed when translation began */
SCR scr;
/** Cached copy of the cpsr as it existed when translation began */
CPSR cpsr;
/** Cached copy of ttbcr/tcr as it existed when translation began */
union
{
TTBCR ttbcr; // AArch32 translations
TCR tcr; // AArch64 translations
};
/** Cached copy of the htcr as it existed when translation began. */
HTCR htcr;
/** Cached copy of the htcr as it existed when translation began. */
HCR hcr;
/** Cached copy of the vtcr as it existed when translation began. */
VTCR_t vtcr;
/** If the access is a write */
bool isWrite;
/** If the access is a fetch (for execution, and no-exec) must be checked?*/
bool isFetch;
/** If the access comes from the secure state. */
bool isSecure;
/** True if table walks are uncacheable (for table descriptors) */
bool isUncacheable;
/** Helper variables used to implement hierarchical access permissions
* when the long-desc. format is used (LPAE only) */
bool secureLookup;
bool rwTable;
bool userTable;
bool xnTable;
bool pxnTable;
/** Hierarchical access permission disable */
bool hpd;
/** Flag indicating if a second stage of lookup is required */
bool stage2Req;
/** A pointer to the stage 2 translation that's in progress */
BaseMMU::Translation *stage2Tran;
/** If the mode is timing or atomic */
bool timing;
/** If the atomic mode should be functional */
bool functional;
/** Save mode for use in delayed response */
BaseMMU::Mode mode;
/** The translation type that has been requested */
MMU::ArmTranslationType tranType;
/** Short-format descriptors */
L1Descriptor l1Desc;
L2Descriptor l2Desc;
/** Long-format descriptor (LPAE and AArch64) */
LongDescriptor longDesc;
/** Whether the response is delayed in timing mode due to additional
* lookups */
bool delayed;
TableWalker *tableWalker;
/** Timestamp for calculating elapsed time in service (for stats) */
Tick startTime;
/** Page entries walked during service (for stats) */
unsigned levels;
void doL1Descriptor();
void doL2Descriptor();
void doLongDescriptor();
WalkerState();
std::string name() const { return tableWalker->name(); }
};
class TableWalkerState : public Packet::SenderState
{
public:
Tick delay = 0;
Event *event = nullptr;
};
class Port : public QueuedRequestPort
{
public:
Port(TableWalker* _walker, RequestorID id);
void sendFunctionalReq(Addr desc_addr, int size,
uint8_t *data, Request::Flags flag);
void sendAtomicReq(Addr desc_addr, int size,
uint8_t *data, Request::Flags flag, Tick delay);
void sendTimingReq(Addr desc_addr, int size,
uint8_t *data, Request::Flags flag, Tick delay,
Event *event);
bool recvTimingResp(PacketPtr pkt) override;
private:
void handleRespPacket(PacketPtr pkt, Tick delay=0);
void handleResp(TableWalkerState *state, Addr addr,
Addr size, Tick delay=0);
PacketPtr createPacket(Addr desc_addr, int size,
uint8_t *data, Request::Flags flag,
Tick delay, Event *event);
private:
/** Packet queue used to store outgoing requests. */
ReqPacketQueue reqQueue;
/** Packet queue used to store outgoing snoop responses. */
SnoopRespPacketQueue snoopRespQueue;
/** Cached requestorId of the table walker */
RequestorID requestorId;
};
/** This translation class is used to trigger the data fetch once a timing
translation returns the translated physical address */
class Stage2Walk : public BaseMMU::Translation
{
private:
uint8_t *data;
int numBytes;
RequestPtr req;
Event *event;
TableWalker &parent;
Addr oVAddr;
BaseMMU::Mode mode;
MMU::ArmTranslationType tranType;
public:
Fault fault;
Stage2Walk(TableWalker &_parent, uint8_t *_data, Event *_event,
Addr vaddr, BaseMMU::Mode mode,
MMU::ArmTranslationType tran_type);
void markDelayed() {}
void finish(const Fault &fault, const RequestPtr &req,
ThreadContext *tc, BaseMMU::Mode mode);
void
setVirt(Addr vaddr, int size, Request::Flags flags,
int requestorId)
{
numBytes = size;
req->setVirt(vaddr, size, flags, requestorId, 0);
}
void translateTiming(ThreadContext *tc);
};
Fault readDataUntimed(ThreadContext *tc, Addr vaddr, Addr desc_addr,
uint8_t *data, int num_bytes, Request::Flags flags,
BaseMMU::Mode mode, MMU::ArmTranslationType tran_type,
bool functional);
void readDataTimed(ThreadContext *tc, Addr desc_addr,
Stage2Walk *translation, int num_bytes,
Request::Flags flags);
protected:
/** Queues of requests for all the different lookup levels */
std::list<WalkerState *> stateQueues[LookupLevel::Num_ArmLookupLevel];
/** Queue of requests that have passed are waiting because the walker is
* currently busy. */
std::list<WalkerState *> pendingQueue;
/** The MMU to forward second stage look upts to */
MMU *mmu;
/** Requestor id assigned by the MMU. */
RequestorID requestorId;
/** Port shared by the two table walkers. */
Port* port;
/** Indicates whether this table walker is part of the stage 2 mmu */
const bool isStage2;
/** TLB that is initiating these table walks */
TLB *tlb;
/** Cached copy of the sctlr as it existed when translation began */
SCTLR sctlr;
WalkerState *currState;
/** If a timing translation is currently in progress */
bool pending;
/** The number of walks belonging to squashed instructions that can be
* removed from the pendingQueue per cycle. */
unsigned numSquashable;
/** Cached copies of system-level properties */
const ArmRelease *release;
uint8_t _physAddrRange;
bool _haveLargeAsid64;
/** Statistics */
struct TableWalkerStats : public statistics::Group
{
TableWalkerStats(statistics::Group *parent);
statistics::Scalar walks;
statistics::Scalar walksShortDescriptor;
statistics::Scalar walksLongDescriptor;
statistics::Vector walksShortTerminatedAtLevel;
statistics::Vector walksLongTerminatedAtLevel;
statistics::Scalar squashedBefore;
statistics::Scalar squashedAfter;
statistics::Histogram walkWaitTime;
statistics::Histogram walkServiceTime;
// Essentially "L" of queueing theory
statistics::Histogram pendingWalks;
statistics::Vector pageSizes;
statistics::Vector2d requestOrigin;
} stats;
mutable unsigned pendingReqs;
mutable Tick pendingChangeTick;
static const unsigned REQUESTED = 0;
static const unsigned COMPLETED = 1;
public:
PARAMS(ArmTableWalker);
TableWalker(const Params &p);
virtual ~TableWalker();
bool haveLargeAsid64() const { return _haveLargeAsid64; }
uint8_t physAddrRange() const { return _physAddrRange; }
/** Checks if all state is cleared and if so, completes drain */
void completeDrain();
DrainState drain() override;
void drainResume() override;
gem5::Port &getPort(const std::string &if_name,
PortID idx=InvalidPortID) override;
Port &getTableWalkerPort();
Fault walk(const RequestPtr &req, ThreadContext *tc,
uint16_t asid, vmid_t _vmid,
bool hyp, BaseMMU::Mode mode, BaseMMU::Translation *_trans,
bool timing, bool functional, bool secure,
MMU::ArmTranslationType tran_type, bool stage2,
const TlbEntry *walk_entry);
void setMmu(MMU *_mmu);
void setTlb(TLB *_tlb) { tlb = _tlb; }
TLB* getTlb() { return tlb; }
void memAttrs(ThreadContext *tc, TlbEntry &te, SCTLR sctlr,
uint8_t texcb, bool s);
void memAttrsLPAE(ThreadContext *tc, TlbEntry &te,
LongDescriptor &lDescriptor);
void memAttrsAArch64(ThreadContext *tc, TlbEntry &te,
LongDescriptor &lDescriptor);
static LookupLevel toLookupLevel(uint8_t lookup_level_as_int);
private:
void doL1Descriptor();
void doL1DescriptorWrapper();
EventFunctionWrapper doL1DescEvent;
void doL2Descriptor();
void doL2DescriptorWrapper();
EventFunctionWrapper doL2DescEvent;
void doLongDescriptor();
void doL0LongDescriptorWrapper();
EventFunctionWrapper doL0LongDescEvent;
void doL1LongDescriptorWrapper();
EventFunctionWrapper doL1LongDescEvent;
void doL2LongDescriptorWrapper();
EventFunctionWrapper doL2LongDescEvent;
void doL3LongDescriptorWrapper();
EventFunctionWrapper doL3LongDescEvent;
void doLongDescriptorWrapper(LookupLevel curr_lookup_level);
Event* LongDescEventByLevel[4];
bool fetchDescriptor(Addr descAddr, uint8_t *data, int numBytes,
Request::Flags flags, int queueIndex, Event *event,
void (TableWalker::*doDescriptor)());
Fault generateLongDescFault(ArmFault::FaultSource src);
void insertTableEntry(DescriptorBase &descriptor, bool longDescriptor);
void insertPartialTableEntry(LongDescriptor &descriptor);
/** Returns a tuple made of:
* 1) The address of the first page table
* 2) The address of the first descriptor within the table
* 3) The page table level
*/
std::tuple<Addr, Addr, LookupLevel> walkAddresses(
Addr ttbr, GrainSize tg, int tsz, int pa_range);
Fault processWalk();
Fault processWalkLPAE();
bool checkVAddrSizeFaultAArch64(Addr addr, int top_bit,
GrainSize granule, int tsz, bool low_range);
/// Returns true if the address exceeds the range permitted by the
/// system-wide setting or by the TCR_ELx IPS/PS setting
bool checkAddrSizeFaultAArch64(Addr addr, int pa_range);
Fault processWalkAArch64();
void processWalkWrapper();
EventFunctionWrapper doProcessEvent;
void nextWalk(ThreadContext *tc);
void pendingChange();
static uint8_t pageSizeNtoStatBin(uint8_t N);
Fault testWalk(Addr pa, Addr size, TlbEntry::DomainType domain,
LookupLevel lookup_level, bool stage2);
};
} // namespace ArmISA
} // namespace gem5
#endif //__ARCH_ARM_TABLE_WALKER_HH__
| 29.945378 | 84 | 0.545026 | [
"vector"
] |
28db2b2f167b28a0bc479ff9ad14a9fa17c86296 | 10,573 | cpp | C++ | 3rdParty/iresearch/core/search/levenshtein_filter.cpp | Korov/arangodb | d1f8df028f8af60d1cd5708890f0d6ae75f9dd06 | [
"Apache-2.0"
] | 1 | 2020-07-30T23:33:02.000Z | 2020-07-30T23:33:02.000Z | 3rdParty/iresearch/core/search/levenshtein_filter.cpp | Korov/arangodb | d1f8df028f8af60d1cd5708890f0d6ae75f9dd06 | [
"Apache-2.0"
] | null | null | null | 3rdParty/iresearch/core/search/levenshtein_filter.cpp | Korov/arangodb | d1f8df028f8af60d1cd5708890f0d6ae75f9dd06 | [
"Apache-2.0"
] | 1 | 2020-10-01T08:49:12.000Z | 2020-10-01T08:49:12.000Z | ////////////////////////////////////////////////////////////////////////////////
/// DISCLAIMER
///
/// Copyright 2019 ArangoDB GmbH, Cologne, Germany
///
/// 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.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// @author Andrey Abramov
////////////////////////////////////////////////////////////////////////////////
#include "levenshtein_filter.hpp"
#include "shared.hpp"
#include "search/term_filter.hpp"
#include "search/limited_sample_collector.hpp"
#include "search/top_terms_collector.hpp"
#include "search/all_terms_collector.hpp"
#include "search/filter_visitor.hpp"
#include "search/multiterm_query.hpp"
#include "index/index_reader.hpp"
#include "utils/automaton_utils.hpp"
#include "utils/levenshtein_utils.hpp"
#include "utils/levenshtein_default_pdp.hpp"
#include "utils/hash_utils.hpp"
#include "utils/noncopyable.hpp"
#include "utils/utf8_utils.hpp"
#include "utils/std.hpp"
NS_LOCAL
using namespace irs;
////////////////////////////////////////////////////////////////////////////////
/// @returns levenshtein similarity
////////////////////////////////////////////////////////////////////////////////
FORCE_INLINE boost_t similarity(uint32_t distance, uint32_t size) noexcept {
assert(size);
static_assert(sizeof(boost_t) == sizeof(uint32_t),
"sizeof(boost_t) != sizeof(uint32_t)");
return 1.f - boost_t(distance) / size;
}
template<typename Invalid, typename Term, typename Levenshtein>
inline auto executeLevenshtein(byte_type max_distance,
by_edit_distance_options::pdp_f provider,
bool with_transpositions,
Invalid inv, Term t, Levenshtein lev) {
if (!provider) {
provider = &default_pdp;
}
if (0 == max_distance) {
return t();
}
assert(provider);
const auto& d = (*provider)(max_distance, with_transpositions);
if (!d) {
return inv();
}
return lev(d);
}
template<typename StatesType>
struct aggregated_stats_visitor : util::noncopyable {
aggregated_stats_visitor(
StatesType& states,
const term_collectors& term_stats) noexcept
: term_stats(term_stats),
states(states) {
}
void operator()(const irs::sub_reader& segment,
const irs::term_reader& field,
uint32_t docs_count) const {
it = field.iterator();
this->segment = &segment;
this->field = &field;
state = &states.insert(segment);
state->reader = &field;
state->scored_states_estimation += docs_count;
}
void operator()(seek_term_iterator::cookie_ptr& cookie) const {
assert(it);
if (!it->seek(irs::bytes_ref::NIL, *cookie)) {
return;
}
assert(segment);
assert(field);
term_stats.collect(*segment, *field, 0, *it);
state->scored_states.emplace_back(std::move(cookie), 0, boost);
}
const term_collectors& term_stats;
StatesType& states;
mutable seek_term_iterator::ptr it;
mutable typename StatesType::state_type* state{};
mutable const sub_reader* segment{};
mutable const term_reader* field{};
boost_t boost{ irs::no_boost() };
};
class top_terms_collector : public irs::top_terms_collector<top_term_state<boost_t>> {
public:
using base_type = irs::top_terms_collector<top_term_state<boost_t>>;
top_terms_collector(size_t size, field_collectors& field_stats)
: base_type(size),
field_stats_(field_stats) {
}
void prepare(const sub_reader& segment,
const term_reader& field,
const seek_term_iterator& terms) {
field_stats_.collect(segment, field);
base_type::prepare(segment, field, terms);
}
private:
field_collectors& field_stats_;
};
//////////////////////////////////////////////////////////////////////////////
/// @brief visitation logic for levenshtein filter
/// @param segment segment reader
/// @param field term reader
/// @param matcher input matcher
/// @param visitor visitor
//////////////////////////////////////////////////////////////////////////////
template<typename Visitor>
void visit(
const sub_reader& segment,
const term_reader& reader,
const byte_type no_distance,
const uint32_t utf8_target_size,
automaton_table_matcher& matcher,
Visitor& visitor) {
assert(fst::kError != matcher.Properties(0));
auto terms = reader.iterator(matcher);
if (IRS_UNLIKELY(!terms)) {
return;
}
if (terms->next()) {
auto* payload = irs::get<irs::payload>(*terms);
const byte_type* distance{&no_distance};
if (payload && !payload->value.empty()) {
distance = &payload->value.front();
}
visitor.prepare(segment, reader, *terms);
do {
terms->read();
const auto utf8_value_size = static_cast<uint32_t>(utf8_utils::utf8_length(terms->value()));
const auto boost = ::similarity(*distance, std::min(utf8_value_size, utf8_target_size));
visitor.visit(boost);
} while (terms->next());
}
}
template<typename Collector>
bool collect_terms(
const index_reader& index,
const string_ref& field,
const bytes_ref& term,
const parametric_description& d,
Collector& collector) {
const auto acceptor = make_levenshtein_automaton(d, term);
if (!validate(acceptor)) {
return false;
}
auto matcher = make_automaton_matcher(acceptor);
const uint32_t utf8_term_size = std::max(1U, uint32_t(utf8_utils::utf8_length(term)));
const byte_type max_distance = d.max_distance() + 1;
for (auto& segment : index) {
auto* reader = segment.field(field);
if (!reader) {
continue;
}
visit(segment, *reader, max_distance, utf8_term_size, matcher, collector);
}
return true;
}
filter::prepared::ptr prepare_levenshtein_filter(
const index_reader& index,
const order::prepared& order,
boost_t boost,
const string_ref& field,
const bytes_ref& term,
size_t terms_limit,
const parametric_description& d) {
field_collectors field_stats(order);
term_collectors term_stats(order, 1);
multiterm_query::states_t states(index.size());
if (!terms_limit) {
all_terms_collector<decltype(states)> term_collector(states, field_stats, term_stats);
term_collector.stat_index(0); // aggregate stats from different terms
if (!collect_terms(index, field, term, d, term_collector)) {
return filter::prepared::empty();
}
} else {
top_terms_collector term_collector(terms_limit, field_stats);
if (!collect_terms(index, field, term, d, term_collector)) {
return filter::prepared::empty();
}
aggregated_stats_visitor<decltype(states)> aggregate_stats(states, term_stats);
term_collector.visit([&aggregate_stats](top_term_state<boost_t>& state) {
aggregate_stats.boost = std::max(0.f, state.key);
state.visit(aggregate_stats);
});
}
std::vector<bstring> stats(1);
stats.back().resize(order.stats_size(), 0);
auto* stats_buf = const_cast<byte_type*>(stats[0].data());
term_stats.finish(stats_buf, 0, field_stats, index);
return memory::make_managed<multiterm_query>(
std::move(states), std::move(stats),
boost, sort::MergeType::MAX);
}
NS_END
NS_ROOT
// -----------------------------------------------------------------------------
// --SECTION-- by_edit_distance implementation
// -----------------------------------------------------------------------------
DEFINE_FACTORY_DEFAULT(by_edit_distance)
/*static*/ field_visitor by_edit_distance::visitor(const options_type::filter_options& opts) {
return executeLevenshtein(
opts.max_distance, opts.provider, opts.with_transpositions,
[]() -> field_visitor {
return [](const sub_reader&, const term_reader&, filter_visitor&){};
},
[&opts]() -> field_visitor {
// must copy term as it may point to temporary string
return [term = opts.term](
const sub_reader& segment,
const term_reader& field,
filter_visitor& visitor){
return by_term::visit(segment, field, term, visitor);
};
},
[&opts](const parametric_description& d) -> field_visitor {
struct automaton_context : util::noncopyable {
automaton_context(const parametric_description& d, const bytes_ref& term)
: acceptor(make_levenshtein_automaton(d, term)),
matcher(make_automaton_matcher(acceptor)) {
}
automaton acceptor;
automaton_table_matcher matcher;
};
// FIXME
auto ctx = memory::make_shared<automaton_context>(d, opts.term);
if (!validate(ctx->acceptor)) {
return [](const sub_reader&, const term_reader&, filter_visitor&){};
}
const uint32_t utf8_term_size = std::max(1U, uint32_t(utf8_utils::utf8_length(opts.term)));
const byte_type max_distance = d.max_distance() + 1;
return [ctx, utf8_term_size, max_distance](
const sub_reader& segment,
const term_reader& field,
filter_visitor& visitor) mutable {
return ::visit(segment, field, max_distance,
utf8_term_size, ctx->matcher, visitor);
};
}
);
}
/*static*/ filter::prepared::ptr by_edit_distance::prepare(
const index_reader& index,
const order::prepared& order,
boost_t boost,
const string_ref& field,
const bytes_ref& term,
size_t scored_terms_limit,
byte_type max_distance,
options_type::pdp_f provider,
bool with_transpositions) {
return executeLevenshtein(
max_distance, provider, with_transpositions,
[]() -> filter::prepared::ptr {
return prepared::empty();
},
[&index, &order, boost, &field, &term]() -> filter::prepared::ptr {
return by_term::prepare(index, order, boost, field, term);
},
[&field, &term, scored_terms_limit, &index, &order, boost](
const parametric_description& d) -> filter::prepared::ptr {
return prepare_levenshtein_filter(index, order, boost, field, term, scored_terms_limit, d);
}
);
}
NS_END
| 31.005865 | 98 | 0.639648 | [
"vector"
] |
28dbc55d4bdd602f5c2b306f67c118ce39a5bb00 | 430 | cpp | C++ | week5/FindContentChildren.cpp | AngelaJubeJudy/Algorithms | 3a6eef59fd2fcb54d80013c067273d73bc6e79b9 | [
"MIT"
] | null | null | null | week5/FindContentChildren.cpp | AngelaJubeJudy/Algorithms | 3a6eef59fd2fcb54d80013c067273d73bc6e79b9 | [
"MIT"
] | null | null | null | week5/FindContentChildren.cpp | AngelaJubeJudy/Algorithms | 3a6eef59fd2fcb54d80013c067273d73bc6e79b9 | [
"MIT"
] | null | null | null | class FindContentChildren {
public:
int findContentChildren(vector<int>& g, vector<int>& s) {
// 排序胃口
sort(g.begin(), g.end());
// 排序饼干
sort(s.begin(), s.end());
int j = 0;
int ans = 0;
for(int i = 0; i < g.size(); i++){
while(j < s.size() && s[j] < g[i]) j++;
if(j < s.size()) j++, ans++;
}
return ans;
}
}; | 25.294118 | 62 | 0.4 | [
"vector"
] |
28dc28634b8b01f2ef66b81a285870cfda72e002 | 11,194 | cpp | C++ | src/ast2ram/provenance/SubproofGenerator.cpp | sharon-wang/souffle | 64be3b32a29affed6f5f2cafee0071c599ad3be0 | [
"UPL-1.0"
] | null | null | null | src/ast2ram/provenance/SubproofGenerator.cpp | sharon-wang/souffle | 64be3b32a29affed6f5f2cafee0071c599ad3be0 | [
"UPL-1.0"
] | 1 | 2016-10-09T23:13:26.000Z | 2016-10-09T23:13:26.000Z | src/ast2ram/provenance/SubproofGenerator.cpp | sharon-wang/souffle | 64be3b32a29affed6f5f2cafee0071c599ad3be0 | [
"UPL-1.0"
] | 2 | 2021-04-02T05:44:53.000Z | 2021-04-21T05:07:22.000Z | /*
* Souffle - A Datalog Compiler
* Copyright (c) 2018 The Souffle Developers. All rights reserved
* Licensed under the Universal Permissive License v 1.0 as shown at:
* - https://opensource.org/licenses/UPL
* - <souffle root>/licenses/SOUFFLE-UPL.txt
*/
/************************************************************************
*
* @file SubproofGenerator.cpp
*
***********************************************************************/
#include "ast2ram/provenance/SubproofGenerator.h"
#include "ast/Atom.h"
#include "ast/BinaryConstraint.h"
#include "ast/BranchInit.h"
#include "ast/Clause.h"
#include "ast/Functor.h"
#include "ast/Negation.h"
#include "ast/RecordInit.h"
#include "ast/Variable.h"
#include "ast/utility/Utils.h"
#include "ast2ram/utility/TranslatorContext.h"
#include "ast2ram/utility/Utils.h"
#include "ast2ram/utility/ValueIndex.h"
#include "ram/Constraint.h"
#include "ram/Filter.h"
#include "ram/Negation.h"
#include "ram/ProvenanceExistenceCheck.h"
#include "ram/Query.h"
#include "ram/SignedConstant.h"
#include "ram/Statement.h"
#include "ram/SubroutineArgument.h"
#include "ram/SubroutineReturn.h"
#include "ram/UndefValue.h"
namespace souffle::ast2ram::provenance {
SubproofGenerator::SubproofGenerator(const TranslatorContext& context)
: ast2ram::provenance::ClauseTranslator(context) {}
SubproofGenerator::~SubproofGenerator() = default;
Own<ram::Operation> SubproofGenerator::addNegatedAtom(
Own<ram::Operation> op, const ast::Clause& /* clause */, const ast::Atom* atom) const {
// Add direct values
VecOwn<ram::Expression> values;
for (const auto* arg : atom->getArguments()) {
values.push_back(context.translateValue(*valueIndex, arg));
}
// Undefined value for rule number
values.push_back(mk<ram::UndefValue>());
// Height annotation for provenanceNotExists
// TODO (azreika): should height explicitly be here?
values.push_back(mk<ram::UndefValue>());
return mk<ram::Filter>(mk<ram::Negation>(mk<ram::ProvenanceExistenceCheck>(
getConcreteRelationName(atom->getQualifiedName()), std::move(values))),
std::move(op));
}
Own<ram::Statement> SubproofGenerator::createRamFactQuery(const ast::Clause& clause) const {
assert(isFact(clause) && "clause should be fact");
assert(!isRecursive() && "recursive clauses cannot have facts");
return mk<ram::Query>(generateReturnInstantiatedValues(clause));
}
Own<ram::Statement> SubproofGenerator::createRamRuleQuery(const ast::Clause& clause) {
assert(isRule(clause) && "clause should be rule");
// Index all variables and generators in the clause
valueIndex = mk<ValueIndex>();
indexClause(clause);
// Set up the RAM statement bottom-up
auto op = generateReturnInstantiatedValues(clause);
op = addVariableBindingConstraints(std::move(op));
op = addBodyLiteralConstraints(clause, std::move(op));
op = addGeneratorLevels(std::move(op), clause);
op = addVariableIntroductions(clause, std::move(op));
return mk<ram::Query>(std::move(op));
}
Own<ram::Operation> SubproofGenerator::addBodyLiteralConstraints(
const ast::Clause& clause, Own<ram::Operation> op) const {
// Add all non-constraints, and then constraints
std::vector<const ast::Constraint*> constraints;
for (const auto* lit : clause.getBodyLiterals()) {
if (const auto* constraint = as<ast::Constraint>(lit)) {
constraints.push_back(constraint);
continue;
}
if (auto condition = context.translateConstraint(*valueIndex, lit)) {
op = mk<ram::Filter>(std::move(condition), std::move(op));
}
}
for (const auto* constraint : constraints) {
if (auto condition = context.translateConstraint(*valueIndex, constraint)) {
op = mk<ram::Filter>(std::move(condition), std::move(op));
}
}
// index of level argument in argument list
const auto* head = clause.getHead();
const auto& headArgs = head->getArguments();
std::size_t levelIndex = clause.getHead()->getArguments().size();
for (std::size_t i = 0; i < head->getArity(); i++) {
auto arg = headArgs.at(i);
if (const auto* var = as<ast::Variable>(arg)) {
// FIXME: float equiv (`FEQ`)
auto lhs = context.translateValue(*valueIndex, var);
auto constraint = mk<ram::Constraint>(
BinaryConstraintOp::EQ, std::move(lhs), mk<ram::SubroutineArgument>(i));
op = mk<ram::Filter>(std::move(constraint), std::move(op));
} else if (const auto* func = as<ast::Functor>(arg)) {
TypeAttribute returnType = context.getFunctorReturnTypeAttribute(*func);
auto opEq = returnType == TypeAttribute::Float ? BinaryConstraintOp::FEQ : BinaryConstraintOp::EQ;
auto lhs = context.translateValue(*valueIndex, func);
auto constraint = mk<ram::Constraint>(opEq, std::move(lhs), mk<ram::SubroutineArgument>(i));
op = mk<ram::Filter>(std::move(constraint), std::move(op));
} else if (const auto* rec = as<ast::RecordInit>(arg)) {
auto lhs = context.translateValue(*valueIndex, rec);
auto constraint = mk<ram::Constraint>(
BinaryConstraintOp::EQ, std::move(lhs), mk<ram::SubroutineArgument>(i));
op = mk<ram::Filter>(std::move(constraint), std::move(op));
} else if (const auto* adt = as<ast::BranchInit>(arg)) {
// TODO (azreika): fill this out like record arguments
assert(false && adt && "unhandled");
}
}
// add constraint for each argument in head of atom
// add level constraints, i.e., that each body literal has height less than that of the head atom
for (const auto* lit : clause.getBodyLiterals()) {
if (const auto* atom = as<ast::Atom>(lit)) {
std::size_t levelNumber = 0;
while (getAtomOrdering(clause).at(levelNumber) != atom) {
levelNumber++;
assert(levelNumber < getAtomOrdering(clause).size());
}
auto varRepr = mk<ast::Variable>("@level_num_" + std::to_string(levelNumber));
auto valLHS = context.translateValue(*valueIndex, varRepr.get());
// add the constraint
auto constraint = mk<ram::Constraint>(
BinaryConstraintOp::LT, std::move(valLHS), mk<ram::SubroutineArgument>(levelIndex));
op = mk<ram::Filter>(std::move(constraint), std::move(op));
}
}
if (isRecursive()) {
if (clause.getHead()->getArity() > 0) {
// also negate the head
op = addNegatedAtom(std::move(op), clause, clause.getHead());
}
// also add in prev stuff
for (std::size_t i = version + 1; i < sccAtoms.size(); i++) {
op = addNegatedDeltaAtom(std::move(op), sccAtoms.at(i));
}
}
return op;
}
Own<ram::Operation> SubproofGenerator::generateReturnInstantiatedValues(const ast::Clause& clause) const {
VecOwn<ram::Expression> values;
// get all values in the body
for (const auto* lit : clause.getBodyLiterals()) {
if (const auto* atom = as<ast::Atom>(lit)) {
for (const auto* arg : atom->getArguments()) {
values.push_back(context.translateValue(*valueIndex, arg));
}
// TODO (azreika): put helper methods for these variables
std::size_t levelNumber = 0;
while (getAtomOrdering(clause).at(levelNumber) != atom) {
levelNumber++;
assert(levelNumber < getAtomOrdering(clause).size());
}
auto levelVarRepr = mk<ast::Variable>("@level_num_" + std::to_string(levelNumber));
auto ruleNumRepr = mk<ast::Variable>("@rule_num_" + std::to_string(levelNumber));
auto level = context.translateValue(*valueIndex, levelVarRepr.get());
auto ruleNum = context.translateValue(*valueIndex, ruleNumRepr.get());
values.push_back(std::move(ruleNum));
values.push_back(std::move(level));
} else if (const auto* neg = as<ast::Negation>(lit)) {
for (ast::Argument* arg : neg->getAtom()->getArguments()) {
values.push_back(context.translateValue(*valueIndex, arg));
}
values.push_back(mk<ram::UndefValue>());
values.push_back(mk<ram::UndefValue>());
}
}
for (const auto* constraint : ast::getBodyLiterals<const ast::BinaryConstraint>(clause)) {
values.push_back(context.translateValue(*valueIndex, constraint->getLHS()));
values.push_back(context.translateValue(*valueIndex, constraint->getRHS()));
}
// final provenance negation
if (isRecursive()) {
const auto* head = clause.getHead();
for (std::size_t i = 0; i < head->getArguments().size(); i++) {
auto arg = head->getArguments().at(i);
values.push_back(context.translateValue(*valueIndex, arg));
}
values.push_back(mk<ram::SignedConstant>(-1));
values.push_back(mk<ram::SignedConstant>(-1));
}
const auto* head = clause.getHead();
const auto& headArgs = head->getArguments();
std::size_t levelIndex = clause.getHead()->getArguments().size();
for (std::size_t i = 0; i < head->getArity(); i++) {
auto arg = headArgs.at(i);
if (const auto* var = as<ast::Variable>(arg)) {
values.push_back(context.translateValue(*valueIndex, var));
values.push_back(mk<ram::SubroutineArgument>(i));
} else if (const auto* func = as<ast::Functor>(arg)) {
values.push_back(context.translateValue(*valueIndex, func));
values.push_back(mk<ram::SubroutineArgument>(i));
} else if (const auto* rec = as<ast::RecordInit>(arg)) {
values.push_back(context.translateValue(*valueIndex, rec));
values.push_back(mk<ram::SubroutineArgument>(i));
} else if (const auto* adt = as<ast::BranchInit>(arg)) {
// TODO (azreika): fill this out like record arguments
assert(false && adt && "unhandled");
}
}
for (const auto* lit : clause.getBodyLiterals()) {
if (const auto* atom = as<ast::Atom>(lit)) {
std::size_t levelNumber = 0;
while (getAtomOrdering(clause).at(levelNumber) != atom) {
levelNumber++;
assert(levelNumber < getAtomOrdering(clause).size());
}
auto levelVarRepr = mk<ast::Variable>("@level_num_" + std::to_string(levelNumber));
auto ruleNumRepr = mk<ast::Variable>("@rule_num_" + std::to_string(levelNumber));
auto level = context.translateValue(*valueIndex, levelVarRepr.get());
auto ruleNum = context.translateValue(*valueIndex, ruleNumRepr.get());
values.push_back(std::move(level));
values.push_back(mk<ram::SubroutineArgument>(levelIndex));
}
}
return mk<ram::SubroutineReturn>(std::move(values));
}
} // namespace souffle::ast2ram::provenance
| 42.888889 | 110 | 0.617742 | [
"vector"
] |
28dc583ddd0e27644c39a1a5594e3ab4c184be60 | 8,589 | cpp | C++ | inference-engine/thirdparty/clDNN/kernel_selector/core/actual_kernels/convolution/convolution_kernel_fs_byx_fsv32_depthwise.cpp | Andruxin52rus/openvino | d824e371fe7dffb90e6d3d58e4e34adecfce4606 | [
"Apache-2.0"
] | 1 | 2022-01-19T15:36:45.000Z | 2022-01-19T15:36:45.000Z | inference-engine/thirdparty/clDNN/kernel_selector/core/actual_kernels/convolution/convolution_kernel_fs_byx_fsv32_depthwise.cpp | Andruxin52rus/openvino | d824e371fe7dffb90e6d3d58e4e34adecfce4606 | [
"Apache-2.0"
] | 22 | 2021-02-03T12:41:51.000Z | 2022-02-21T13:04:48.000Z | inference-engine/thirdparty/clDNN/kernel_selector/core/actual_kernels/convolution/convolution_kernel_fs_byx_fsv32_depthwise.cpp | mmakridi/openvino | 769bb7709597c14debdaa356dd60c5a78bdfa97e | [
"Apache-2.0"
] | 1 | 2021-07-28T17:30:46.000Z | 2021-07-28T17:30:46.000Z | // Copyright (c) 2019-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 "convolution_kernel_fs_byx_fsv32_depthwise.h"
#include <vector>
namespace kernel_selector {
static constexpr size_t subGroupSize = 16;
static constexpr size_t fsv = 32;
static constexpr size_t fsvPerThread = fsv / subGroupSize;
ConvolutionKernel_fs_byx_fsv32_depthwise::ConvolutionKernel_fs_byx_fsv32_depthwise()
: ConvolutionKernelBase("convolution_gpu_fs_byx_fsv32_depthwise") {
std::vector<size_t> blockWidths = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16};
std::vector<std::string> executionModes = ConvolutionKernelBase::autoTuneOptions;
for (auto w : blockWidths) {
for (auto exeMode : executionModes) {
autoTuneOptions.emplace_back(AutoTuneOption{w, exeMode});
}
}
}
ParamsKey ConvolutionKernel_fs_byx_fsv32_depthwise::GetSupportedKey() const {
ParamsKey k;
k.EnableInputDataType(Datatype::F16);
k.EnableOutputDataType(Datatype::F16);
k.EnableInputWeightsType(WeightsType::F16);
k.EnableInputLayout(DataLayout::fs_b_yx_fsv32);
k.EnableOutputLayout(DataLayout::fs_b_yx_fsv32);
k.EnableBiasPerFeature();
k.EnableBiasPerOutput();
k.EnableNonBiasTerm();
k.EnableBatching();
k.EnableDilation();
k.EnableTensorOffset();
k.EnableTensorPitches();
k.EnableDepthwiseSeparableOpt();
k.EnableGroupedConvolution();
k.EnableSubGroup();
k.EnableSubGroupShort();
return k;
}
size_t ConvolutionKernel_fs_byx_fsv32_depthwise::getInputWidth(const convolution_params& arg, size_t blockWidth) const {
return (blockWidth - 1) * arg.stride.x + (arg.filterSize.x - 1) * arg.dilation.x + 1;
}
size_t ConvolutionKernel_fs_byx_fsv32_depthwise::getMinRegisterUsage(const convolution_params& arg, size_t blockWidth) const {
size_t weightsRegisters = 2;
size_t outputRegisters = blockWidth * 2;
size_t inputRegisters = getInputWidth(arg, blockWidth) * 2;
return weightsRegisters + outputRegisters + inputRegisters;
}
ConvolutionKernel_fs_byx_fsv32_depthwise::AutoTuneOption ConvolutionKernel_fs_byx_fsv32_depthwise::GetAutoTuneOptions(
const Params& arg,
int autoTuneIndex) const {
if (autoTuneIndex >= 0 && autoTuneIndex < static_cast<int>(autoTuneOptions.size()))
return autoTuneOptions[autoTuneIndex];
const convolution_params& cp = static_cast<const convolution_params&>(arg);
const size_t regThreshold = 64;
std::vector<size_t> nonOptBlockWidths = {3, 2, 1}; // This will most likely be memory bound
std::vector<size_t> optBlockWidths = {8, 7, 6, 5, 4};
// Check if output can be evenly divided into large blocks
for (auto w : optBlockWidths) {
if (cp.output.X().v % w == 0 && getMinRegisterUsage(cp, w) < regThreshold)
return {w, AGE_BASED};
}
// Try to find large blocks with smallest offset
size_t minLeftover = static_cast<size_t>(-1);
size_t foundWidth = 0;
for (auto w : optBlockWidths) {
if (getMinRegisterUsage(cp, w) < regThreshold && Pad(cp.output.X().v, w) < minLeftover) {
minLeftover = Pad(cp.output.X().v, w);
foundWidth = w;
}
}
if (foundWidth != 0)
return {foundWidth, AGE_BASED};
// Check small and memory bound block sizes
for (auto w : nonOptBlockWidths) {
if (cp.output.X().v % w == 0 && getMinRegisterUsage(cp, w) < regThreshold)
return {w, AGE_BASED};
}
// This means all previous block sizes consumed too much registers, fallback to block width = 1
return {1, AGE_BASED};
}
ConvolutionKernelBase::DispatchData ConvolutionKernel_fs_byx_fsv32_depthwise::SetDefault(const convolution_params& arg,
int autoTuneIndex) const {
DispatchData dispatchData = ConvolutionKernelBase::SetDefault(arg);
AutoTuneOption option = GetAutoTuneOptions(arg, autoTuneIndex);
dispatchData.cldnnStyle.blockHeight = 1;
dispatchData.cldnnStyle.blockWidth = option.blockWidth;
dispatchData.cldnnStyle.inputBlockWidth = getInputWidth(arg, option.blockWidth);
dispatchData.lws[0] = 1;
dispatchData.lws[1] = 1;
dispatchData.lws[2] = 16;
dispatchData.gws[0] = CeilDiv(arg.output.X().v, option.blockWidth);
dispatchData.gws[1] = arg.output.Y().v;
dispatchData.gws[2] = CeilDiv(arg.output.Feature().v, 32) * 16 * arg.output.Batch().v;
return dispatchData;
}
KernelsPriority ConvolutionKernel_fs_byx_fsv32_depthwise::GetKernelsPriority(const Params& /*params*/, const optional_params& /*options*/) const {
return FORCE_PRIORITY_3;
}
bool ConvolutionKernel_fs_byx_fsv32_depthwise::Validate(const Params& p, const optional_params& o) const {
if (!ConvolutionKernelBase::Validate(p, o))
return false;
auto cp = static_cast<const convolution_params&>(p);
if (cp.groups < 16)
return false;
if (cp.inputs[0].Feature().v != cp.groups || cp.output.Feature().v != cp.groups)
return false;
// Output feature padding must be multiple of fsv to keep block alignment
if (cp.output.Feature().pad.before % fsv != 0)
return false;
// Input feature padding must be multiple of fsv to keep block alignment
if (cp.inputs[0].Feature().pad.before % fsv != 0)
return false;
return true;
}
JitConstants ConvolutionKernel_fs_byx_fsv32_depthwise::GetJitConstants(const convolution_params& params,
const DispatchData& dispatchData) const {
auto jit = ConvolutionKernelBase::GetJitConstants(params, dispatchData);
jit.AddConstant(MakeJitConstant("INPUT_BLOCK_WIDTH", dispatchData.cldnnStyle.inputBlockWidth));
jit.AddConstant(MakeJitConstant("OUTPUT_BLOCK_WIDTH", dispatchData.cldnnStyle.blockWidth));
jit.AddConstant(MakeJitConstant("FSV", fsv));
jit.AddConstant(MakeJitConstant("SUB_GROUP_SIZE", subGroupSize));
jit.AddConstant(MakeJitConstant("FSV_PER_THREAD", fsvPerThread));
if (!params.fused_ops.empty()) {
auto input_dt = GetUnitType(params);
FusedOpsConfiguration conf_vec_elem = {"_VEC_ELEM",
{"b", "(fs * FSV + sglid + out_f * SUB_GROUP_SIZE)", "or", "oc + out_x"},
"tmp_write[out_f]", input_dt, 1 };
FusedOpsConfiguration conf_scalar = {"_SCALAR",
{"b", "(fs * FSV + sglid + out_f * SUB_GROUP_SIZE)", "or", "oc + out_x"},
"out[out_idx]", input_dt, 1 };
jit.Merge(MakeFusedOpsJitConstants(params, {conf_vec_elem, conf_scalar}));
}
return jit;
}
KernelsData ConvolutionKernel_fs_byx_fsv32_depthwise::GetTunedKernelsDataByIndex(const Params& params,
const optional_params& options,
const int autoTuneIndex) const {
auto tuneOptions = GetAutoTuneOptions(params, autoTuneIndex);
return GetCommonKernelsData(params, options, tuneOptions.exeMode, autoTuneIndex);
}
KernelsData ConvolutionKernel_fs_byx_fsv32_depthwise::GetKernelsData(const Params& params, const optional_params& options) const {
return GetTunedKernelsDataByIndex(params, options);
}
KernelsData ConvolutionKernel_fs_byx_fsv32_depthwise::GetKernelsDataForAutoTune(const Params& params,
const optional_params& options) const {
if (!Validate(params, options)) {
return {};
}
KernelsData res = {};
for (size_t i = 0; i < autoTuneOptions.size(); i++) {
KernelsData kd = GetTunedKernelsDataByIndex(params, options, static_cast<int>(i));
if (!kd.empty()) {
res.emplace_back(kd[0]);
}
}
return res;
}
} // namespace kernel_selector
| 40.514151 | 146 | 0.666085 | [
"vector"
] |
28dca79c66a039b7f0e1b8d3f4dff5a997b3c36a | 2,443 | cpp | C++ | src/creature_group.cpp | jayheiland/Cartwright | 21e845e9b38a0670e943a58ff34c63ac04f42682 | [
"MIT"
] | null | null | null | src/creature_group.cpp | jayheiland/Cartwright | 21e845e9b38a0670e943a58ff34c63ac04f42682 | [
"MIT"
] | null | null | null | src/creature_group.cpp | jayheiland/Cartwright | 21e845e9b38a0670e943a58ff34c63ac04f42682 | [
"MIT"
] | null | null | null | #include "creature_group.h"
extern std::unordered_map<creatureCode, CreatureRule> crtRules;
void loadCreatureRules(std::string path){
CreatureRule crtRule;
creatureCode crtCode = 0;
std::string line;
int lineNum = 1;
std::ifstream infile;
//read creature rules
infile.open(path);
if(!infile.is_open()){
logError("Could not open creature rules file: '" + path + "'");
return;
}
while (std::getline(infile, line)){
if(line == "}"){
if(crtCode != 0){
crtRules.insert(std::make_pair(crtCode, crtRule));
crtCode = 0;
}
else{
logError("Could not process creature rules file: '" + path + "', at Line " + std::to_string(lineNum) + ". Parser creature code is " + std::to_string(crtCode));
}
}
else if(line.size() > 1){
std::vector<std::string> tokens;
splitString(&tokens, line, ':');
//parse string arg
tokens[0] = stripChar(tokens[0], ' ');
if(strContains(tokens[1], 2, '\'')){
if(tokens[0] == "speciesName"){
tokens[1] = stripCharAround(tokens[1], '\'');
crtRule.speciesName = tokens[1];
}
}
//parse creature code
else if(tokens[0] == "creatureCode"){
crtCode = std::stol(stripChar(tokens[1], ' '));
}
//parse body object code
else if(tokens[0] == "body"){
crtRule.bodyCode = std::stoi(stripChar(tokens[1], ' '));
}
else{
logError("Could not process creature rules file: '" + path + "', at Line " + std::to_string(lineNum));
}
}
else if(line == "{" || line == ""){
}
else{
logError("Could not process creature rules file: '" + path + "', at Line " + std::to_string(lineNum));
return;
}
lineNum++;
}
infile.close();
}
void addCreature(std::unordered_map<ID, Creature> *crtGroup, std::unordered_map<ID, Object> *objGroup, creatureCode crtCode, std::string name){
Creature crt;
crt.name = name;
crt.speciesName = crtRules[crtCode].speciesName;
crt.body = createObject(objGroup, crtRules[crtCode].bodyCode);
ID id = genID();
crtGroup->insert(std::make_pair(id, crt));
} | 35.405797 | 175 | 0.520262 | [
"object",
"vector"
] |
28e309c9b56c1cb289d2af910a29af2aefbb8dc7 | 10,383 | hxx | C++ | NxWidgets/libnxwidgets/include/ccallback.hxx | lanpinguo/Pikachu | d0ab1d36d2ac60c0c84f8f0e351225fc3f85ac7e | [
"Apache-2.0"
] | null | null | null | NxWidgets/libnxwidgets/include/ccallback.hxx | lanpinguo/Pikachu | d0ab1d36d2ac60c0c84f8f0e351225fc3f85ac7e | [
"Apache-2.0"
] | null | null | null | NxWidgets/libnxwidgets/include/ccallback.hxx | lanpinguo/Pikachu | d0ab1d36d2ac60c0c84f8f0e351225fc3f85ac7e | [
"Apache-2.0"
] | null | null | null | /****************************************************************************
* NxWidgets/libnxwidgets/include/ccallback.hxx
*
* Copyright (C) 2012 Gregory Nutt. All rights reserved.
* Author: Gregory Nutt <gnutt@nuttx.org>
*
* 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 NuttX, NxWidgets, nor the names of its contributors
* me 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.
*
****************************************************************************/
#ifndef __INCLUDE_CCALLBACK_HXX
#define __INCLUDE_CCALLBACK_HXX
/****************************************************************************
* Included Files
****************************************************************************/
#include <nuttx/config.h>
#include <sys/types.h>
#include <stdint.h>
#include <stdbool.h>
#include <nuttx/nx/nxglib.h>
#include <nuttx/nx/nx.h>
#ifdef CONFIG_NXTERM_NXKBDIN
# include <nuttx/nx/nxterm.h>
#endif
#include "crect.hxx"
/****************************************************************************
* Pre-Processor Definitions
****************************************************************************/
/****************************************************************************
* Implementation Classes
****************************************************************************/
#if defined(__cplusplus)
namespace NXWidgets
{
class CWidgetControl;
/**
* Callback function proxies. This class receives and dispatches callbacks
* from the NX server. This calls also manages a few lower-level details
* such as keeping track of the reported window handles and window positions
* and sizes.
*
* There are three instances that represent an NX window from the
* perspective of NXWidgets.
*
* - There is one widget control instance per NX window,
* - One CCallback instance per window,
* - One window instance.
*
* There a various kinds of of window instances, but each inherits
* (1) CCallback and dispatches the Windows callbacks and (2) INxWindow
* that describes the common window behavior.
*/
class CCallback
{
private:
CWidgetControl *m_widgetControl; /**< The widget control instance for this window */
struct nx_callback_s m_callbacks; /**< C-callable vtable of callback function pointers */
#ifdef CONFIG_NXTERM_NXKBDIN
NXTERM m_nxterm; /**< The NxTerm handle for redirection of keyboard input */
#endif
// Methods in the callback vtable
/**
* Re-Draw Callback. The redraw event is handled by CWidgetControl::redrawEvent.
*
* NOTE: This method runs in the context of the NX callback which may
* either be the context of the owning thread or, in the case of multi-
* user NX, the context of the NX event listener thread.
*
* @param hwnd Handle to a specific NX window.
* @param rect The rectangle that needs to be re-drawn (in window
* relative coordinates).
* @param bMore true: More re-draw requests will follow.
* @param arg User provided argument (see nx_openwindow, nx_requestbg,
* nxtk_openwindow, or nxtk_opentoolbar).
*/
static void redraw(NXHANDLE hwnd, FAR const struct nxgl_rect_s *rect,
bool bMore, FAR void *arg);
/**
* Position Callback. The new positional data is handled by
* CWidgetControl::geometryEvent.
*
* NOTE: This method runs in the context of the NX callback which may
* either be the context of the owning thread or, in the case of multi-
* user NX, the context of the NX event listener thread.
*
* @param hwnd Handle to a specific NX window.
* @param size The size of the window.
* @param pos The position of the upper left hand corner of the window on
* the overall display.
* @param bounds The bounding rectangle that describes the entire display.
* @param arg User provided argument (see nx_openwindow, nx_requestbg,
* nxtk_openwindow, or nxtk_opentoolbar).
*/
static void position(NXHANDLE hwnd, FAR const struct nxgl_size_s *size,
FAR const struct nxgl_point_s *pos,
FAR const struct nxgl_rect_s *bounds,
FAR void *arg);
/**
* New mouse data is available for the window. The new mouse
* data is handled by CWidgetControl::newMouseEvent.
*
* NOTE: This method runs in the context of the NX callback which may
* either be the context of the NX event listener thread (if multi-
* user NX), or possibly in the connects of device driver or even a
* device driver interrupt.
*
* The GUI thread is probably sleeping a semaphore, waiting to be
* awakened by a mouse or keyboard event.
*
* @param hwnd Handle to a specific NX window.
* @param pos The (x,y) position of the mouse.
* @param buttons See NX_MOUSE_* definitions.
* @param arg User provided argument (see nx_openwindow, nx_requestbg,
* nxtk_openwindow, or nxtk_opentoolbar).
*/
#ifdef CONFIG_NX_XYINPUT
static void newMouseEvent(NXHANDLE hwnd,
FAR const struct nxgl_point_s *pos,
uint8_t buttons, FAR void *arg);
#endif /* CONFIG_NX_XYINPUT */
/**
* New keyboard/keypad data is available for the window. The new
* keyboard data is handled by CWidgetControl::newKeyboardEvent.
*
* NOTE: This method runs in the context of the NX callback which may
* either be the context of the NX event listener thread (if multi-
* user NX), or possibly in the connects of device driver or even a
* device driver interrupt.
*
* The GUI thread is probably sleeping a semaphore, waiting to be
* awakened by a mouse or keyboard event.
*
* @param hwnd Handle to a specific NX window.
* @param nCh The number of characters that are available in str[].
* @param str The array of characters.
* @param arg User provided argument (see nx_openwindow, nx_requestbg,
* nxtk_openwindow, or nxtk_opentoolbar).
*/
#ifdef CONFIG_NX_KBD
static void newKeyboardEvent(NXHANDLE hwnd, uint8_t nCh,
FAR const uint8_t *str, FAR void *arg);
#endif // CONFIG_NX_KBD
/**
* This callback is the response from nx_block (or nxtk_block). Those
* blocking interfaces are used to assure that no further messages are
* directed to the window. Receipt of the blocked callback signifies
* that (1) there are no further pending callbacks and (2) that the
* window is now 'defunct' and will receive no further callbacks.
*
* This callback supports coordinated destruction of a window in multi-
* user mode. In multi-use mode, the client window logic must stay
* intact until all of the queued callbacks are processed. Then the
* window may be safely closed. Closing the window prior with pending
* callbacks can lead to bad behavior when the callback is executed.
*
* @param hwnd. Window handle of the blocked window
* @param arg1. User provided argument (see nx_openwindow, nx_requestbkgd,
* nxtk_openwindow, or nxtk_opentoolbar)
* @param arg2 - User provided argument (see nx_block or nxtk_block)
*/
static void windowBlocked(NXWINDOW hwnd, FAR void *arg1, FAR void *arg2);
public:
/**
* Constructor.
*
* @param widgetControl Control object associated with this window
*/
CCallback(CWidgetControl *widgetControl);
/**
* Destructor.
*/
inline ~CCallback(void) {}
/**
* Get the callback vtable. This is neeed only by the window
* instance that inherits this class. The window instance needs the
* C-callable vtable in order to create the NX window. Once the
* window is created, this class will begin to receive callbacks via
* the C-callable vtable methods.
*
* @return This method returns the C-callable vtable needed for
* NX window creation.
*/
inline FAR struct nx_callback_s *getCallbackVTable(void)
{
return &m_callbacks;
}
/**
* By default, NX keyboard input is given to the various widgets
* residing in the window. But NxTerm is a different usage model;
* In this case, keyboard input needs to be directed to the NxTerm
* character driver. This method can be used to enable (or disable)
* redirection of NX keyboard input from the window widgets to the
* NxTerm
*
* @param handle. The NXTERM handle. If non-NULL, NX keyboard
* input will be directed to the NxTerm driver using this
* handle; If NULL (the default), NX keyboard input will be
* directed to the widgets within the window.
*/
#ifdef CONFIG_NXTERM_NXKBDIN
inline void setNxTerm(NXTERM handle)
{
m_nxterm = handle;
}
#endif
};
}
#endif // __cplusplus
#endif // __INCLUDE_CCALLBACK_HXX
| 38.313653 | 101 | 0.644804 | [
"object",
"model"
] |
28e3b247dcf203f1bb52f030233dd96a5c332aee | 27,306 | cpp | C++ | Source/GmmLib/TranslationTable/GmmPageTableMgr.cpp | heitbaum/gmmlib | 143d0d928c302d27964e40a71952037396bb768f | [
"MIT"
] | null | null | null | Source/GmmLib/TranslationTable/GmmPageTableMgr.cpp | heitbaum/gmmlib | 143d0d928c302d27964e40a71952037396bb768f | [
"MIT"
] | null | null | null | Source/GmmLib/TranslationTable/GmmPageTableMgr.cpp | heitbaum/gmmlib | 143d0d928c302d27964e40a71952037396bb768f | [
"MIT"
] | null | null | null | /*==============================================================================
Copyright(c) 2019 Intel Corporation
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files(the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and / or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
Description: UMD-TT manager (manages both TR-TT and AUX-TT in user mode space)
============================================================================*/
#include "Internal/Common/GmmLibInc.h"
#include "External/Common/GmmPageTableMgr.h"
#include "../TranslationTable/GmmUmdTranslationTable.h"
#include "External/Common/GmmClientContext.h"
#if defined(__linux__)
#include "Internal/Linux/GmmResourceInfoLinInt.h"
#endif
#define ENTER_CRITICAL_SECTION \
if(AuxTTObj) \
{ \
EnterCriticalSection(&PoolLock); \
}
#define EXIT_CRITICAL_SECTION \
if(AuxTTObj) \
{ \
LeaveCriticalSection(&PoolLock); \
}
extern GMM_MA_LIB_CONTEXT *pGmmMALibContext;
#if defined(__linux__)
GMM_STATUS GmmLib::__GmmDeviceAlloc(GmmClientContext * pClientContext,
GMM_DEVICE_CALLBACKS_INT *pDeviceCbInt,
GMM_DEVICE_ALLOC * pAlloc)
{
GMM_CLIENT ClientType;
GMM_DDI_ALLOCATE Alloc = {0};
int err;
GET_GMM_CLIENT_TYPE(pClientContext, ClientType);
__GMM_ASSERTPTR(GmmCheckForNullDevCbPfn(ClientType, pDeviceCbInt, GMM_DEV_CB_ALLOC), GMM_INVALIDPARAM);
if(GmmCheckForNullDevCbPfn(ClientType, pDeviceCbInt, GMM_DEV_CB_ALLOC))
{
Alloc.size = pAlloc->Size;
Alloc.alignment = pAlloc->Alignment;
err = GmmDeviceCallback(ClientType, pDeviceCbInt, &Alloc);
if(err)
{
return GMM_OUT_OF_MEMORY;
}
pAlloc->GfxVA = Alloc.gfxAddr;
pAlloc->CPUVA = (GMM_GFX_ADDRESS) Alloc.cpuAddr;
pAlloc->Handle = (HANDLE)Alloc.bo;
}
return GMM_SUCCESS;
}
GMM_STATUS GmmLib::__GmmDeviceDealloc(GMM_CLIENT ClientType,
GMM_DEVICE_CALLBACKS_INT *DeviceCb,
GMM_DEVICE_DEALLOC * pDealloc,
GmmClientContext * pClientContext)
{
GMM_DDI_DEALLOCATE DeAlloc = {0};
int err = 0;
__GMM_ASSERTPTR(GmmCheckForNullDevCbPfn(ClientType, DeviceCb, GMM_DEV_CB_DEALLOC), GMM_INVALIDPARAM);
if(GmmCheckForNullDevCbPfn(ClientType, DeviceCb, GMM_DEV_CB_DEALLOC))
{
DeAlloc.bo = pDealloc->Handle;
err = GmmDeviceCallback(ClientType, DeviceCb, &DeAlloc);
}
return (err == 0) ? GMM_SUCCESS : GMM_ERROR;
}
#endif
//=============================================================================
//
// Function: __AllocateNodePool
//
// Desc: Allocates (always resident SVM) memory for new Pool node, and updates PageTableMgr object
//
// Parameters:
// AddrAlignment: Pool allocation address alignment
//
// Returns:
// S_OK on success,
//-----------------------------------------------------------------------------
GmmLib::GMM_PAGETABLEPool *GmmLib::GmmPageTableMgr::__AllocateNodePool(uint32_t AddrAlignment, GmmLib::POOL_TYPE Type)
{
GMM_STATUS Status = GMM_SUCCESS;
GMM_RESOURCE_INFO *pGmmResInfo = NULL;
GMM_PAGETABLEPool *pTTPool = NULL;
HANDLE PoolHnd = 0;
GMM_CLIENT ClientType;
GMM_DEVICE_ALLOC Alloc = {0};
ENTER_CRITICAL_SECTION
//Allocate pool, sized PAGETABLE_POOL_MAX_NODES pages, assignable to TR/Aux L1/L2 tables
//SVM allocation, always resident
Alloc.Size = PAGETABLE_POOL_SIZE;
Alloc.Alignment = AddrAlignment;
Alloc.hCsr = hCsr;
Status = __GmmDeviceAlloc(pClientContext, &DeviceCbInt, &Alloc);
if(Status != GMM_SUCCESS)
{
__GMM_ASSERT(0);
EXIT_CRITICAL_SECTION
return NULL;
}
PoolHnd = Alloc.Handle;
pGmmResInfo = (GMM_RESOURCE_INFO *)Alloc.Priv;
pTTPool = new GMM_PAGETABLEPool(PoolHnd, pGmmResInfo, Alloc.GfxVA, Alloc.CPUVA, Type);
if(pTTPool)
{
if(pPool)
{
NumNodePoolElements++;
if(Type == POOL_TYPE_TRTTL2) // TRTT-L2 not 1st node in Pool LinkedList, place it at beginning
{
pPool = pPool->InsertInListAtBegin(pTTPool);
}
else
{
pTTPool = pPool->InsertInList(pTTPool);
}
}
else
{
NumNodePoolElements = 1;
pPool = pTTPool;
}
}
else
{
__GMM_ASSERT(0);
Status = GMM_OUT_OF_MEMORY;
}
EXIT_CRITICAL_SECTION
return (Status == GMM_SUCCESS) ? pTTPool : NULL;
}
//=============================================================================
//
// Function: __ReleaseUnusedPool
//
// Desc: Frees up unused PageTablePools once residency limit is hit
//
// Parameters:
// UmdContext: pointer to caller thread's context (containing BBHandle/Fence info)
//
//-----------------------------------------------------------------------------
void GmmLib::GmmPageTableMgr::__ReleaseUnusedPool(GMM_UMD_SYNCCONTEXT *UmdContext)
{
GMM_STATUS Status = GMM_SUCCESS;
GMM_GFX_SIZE_T PoolSizeToFree = {0};
GMM_GFX_SIZE_T FreedSize = {0};
GmmLib::GMM_PAGETABLEPool *Pool = NULL, *PrevPool = NULL;
uint32_t i = 0;
GMM_CLIENT ClientType;
GMM_DEVICE_DEALLOC Dealloc;
GET_GMM_CLIENT_TYPE(pClientContext, ClientType);
ENTER_CRITICAL_SECTION
if(pPool->__IsUnusedTRTTPoolOverLimit(&PoolSizeToFree))
{
for(i = 0; i < NumNodePoolElements && FreedSize < PoolSizeToFree; i++)
{
Pool = (PrevPool) ? PrevPool->GetNextPool() : pPool;
if(Pool->IsPoolInUse(UmdContext ? SyncInfo(UmdContext->BBFenceObj, UmdContext->BBLastFence) : SyncInfo()))
{
PrevPool = Pool;
continue;
}
if(GmmCheckForNullDevCbPfn(ClientType, &DeviceCbInt, GMM_DEV_CB_WAIT_FROM_CPU))
{
GMM_DDI_WAITFORSYNCHRONIZATIONOBJECTFROMCPU Wait = {0};
Wait.bo = Pool->GetPoolHandle();
GmmDeviceCallback(ClientType, &DeviceCbInt, &Wait);
}
Dealloc.Handle = Pool->GetPoolHandle();
Dealloc.GfxVA = Pool->GetGfxAddress();
Dealloc.Priv = Pool->GetGmmResInfo();
Dealloc.hCsr = hCsr;
Status = __GmmDeviceDealloc(ClientType, &DeviceCbInt, &Dealloc, pClientContext);
__GMM_ASSERT(GMM_SUCCESS == Status);
if(PrevPool)
{
PrevPool->GetNextPool() = Pool->GetNextPool();
}
else
{
pPool = Pool->GetNextPool();
}
delete Pool;
FreedSize += PAGETABLE_POOL_SIZE;
}
}
EXIT_CRITICAL_SECTION
}
//=============================================================================
//
// Function: __GetFreePoolNode
//
// Desc: Finds free node within existing PageTablePool(s), if no such node found,
// allocates new PageTablePool. Caller should update Pool Node usage
//
// Parameters:
// FreePoolNodeIdx: pointer to return Pool's free Node index
// PoolType: AuxTT_L1/L2 pool
//
// Returns:
// PageTablePool element and FreePoolNodeIdx that should be used for L2/L1 assignment
// NULL, if no free node exists and new pool allocation failed
//-----------------------------------------------------------------------------
GmmLib::GMM_PAGETABLEPool *GmmLib::GmmPageTableMgr::__GetFreePoolNode(uint32_t *FreePoolNodeIdx, POOL_TYPE PoolType)
{
uint32_t PoolNode = -1, i = 0, j = 0, DWdivisor = 1, IdxMultiplier = 1;
bool PoolNodeFound = false, TRTTPool = false;
ENTER_CRITICAL_SECTION
GmmLib::GMM_PAGETABLEPool *Pool = pPool;
Pool = (PoolType == POOL_TYPE_TRTTL2) ? Pool : //1st pool reserved for TRTT-L2, since TRTT-L2 pruning not supported yet,
(Pool ? Pool->GetNextPool() : NULL); //other pools can be TR-L1/Aux-L1/Aux-L2 (and support dynamic pruning)
TRTTPool = (PoolType == POOL_TYPE_TRTTL2 || PoolType == POOL_TYPE_TRTTL1) ? true : false;
DWdivisor = TRTTPool ? 8 * sizeof(uint32_t) : (PoolType == POOL_TYPE_AUXTTL2) ? 8 * sizeof(uint32_t) * AUX_L2TABLE_SIZE_IN_POOLNODES : 8 * sizeof(uint32_t) * AUX_L1TABLE_SIZE_IN_POOLNODES;
IdxMultiplier = TRTTPool ? 1 : (PoolType == POOL_TYPE_AUXTTL2) ? AUX_L2TABLE_SIZE_IN_POOLNODES : AUX_L1TABLE_SIZE_IN_POOLNODES;
//Scan existing PageTablePools for free pool node
for(i = (PoolType == POOL_TYPE_TRTTL2) ? 0 : 1; Pool && i < NumNodePoolElements; i++)
{
if(Pool->GetNumFreeNode() > 0 && Pool->GetPoolType() == PoolType)
{
PoolNodeFound = true;
*FreePoolNodeIdx = 0;
for(; j < PAGETABLE_POOL_MAX_NODES / DWdivisor; j++)
{
if(_BitScanForward((uint32_t *)&PoolNode, (uint32_t) ~(Pool->GetNodeUsageAtIndex(j)))) // Get LSB that has value 0
{
*FreePoolNodeIdx += PoolNode * IdxMultiplier;
PoolNodeFound = true;
break;
}
PoolNodeFound = false;
*FreePoolNodeIdx += DWdivisor; //DWORD size in bits
}
}
if(PoolNodeFound)
{
__GMM_ASSERT(Pool->GetPoolType() == PoolType);
EXIT_CRITICAL_SECTION
return Pool;
}
Pool = Pool->GetNextPool();
}
//No free pool node, allocate new
if(!PoolNodeFound)
{
GMM_PAGETABLEPool *Pool = NULL;
if(Pool = __AllocateNodePool(IdxMultiplier * PAGE_SIZE, PoolType))
{
__GMM_ASSERT(Pool->GetPoolType() == PoolType);
*FreePoolNodeIdx = 0;
EXIT_CRITICAL_SECTION
return Pool;
}
}
EXIT_CRITICAL_SECTION
return NULL;
}
/**********************************************************************************
** Class GmmPageTableMgr functions **
***********************************************************************************/
/////////////////////////////////////////////////////////////////////////////////////
/// Instantiates GmmPageTableMgr, allocating memory for root-tables, copies provided
/// device-callback function pointers
///
/// @param[in] DeviceCb: pointer sharing device-callback function pointers
/// @param[in] TTFlags: Flags specifying which PageTables are required by client
/// @return GmmPageTableMgr*
/////////////////////////////////////////////////////////////////////////////////////
GmmLib::GmmPageTableMgr::GmmPageTableMgr(GMM_DEVICE_CALLBACKS_INT *DeviceCB, uint32_t TTFlags, GmmClientContext *pClientContextIn)
: GmmPageTableMgr()
{
GMM_PAGETABLE_MGR *ptr = NULL;
GMM_STATUS status = GMM_SUCCESS;
GMM_CLIENT ClientType;
if(pClientContextIn)
{
ClientType = pClientContextIn->GetClientType();
}
else
{
goto ERROR_CASE;
}
// this is needed if there is an error case and destructor gets called on ptr
this->pClientContext = pClientContextIn;
// Currently coping the code below to GMMOldAPi.cpp for backward compatible.
// Any changes here should be copied there.
//Initialize PageTableMgr further, only if PageTable creation succeeded
try
{
ptr = new GmmPageTableMgr();
ptr->pClientContext = pClientContextIn;
memcpy(&ptr->DeviceCbInt, DeviceCB, sizeof(GMM_DEVICE_CALLBACKS_INT));
if(pClientContextIn->GetSkuTable().FtrE2ECompression &&
!pClientContextIn->GetSkuTable().FtrFlatPhysCCS)
{
__GMM_ASSERT(TTFlags & AUXTT); //Aux-TT is mandatory
ptr->AuxTTObj = new AuxTable();
if(!ptr->AuxTTObj)
{
goto ERROR_CASE;
}
ptr->AuxTTObj->PageTableMgr = ptr;
ptr->AuxTTObj->pClientContext = pClientContextIn;
status = ptr->AuxTTObj->AllocateL3Table(8 * PAGE_SIZE, 8 * PAGE_SIZE);
if(status != GMM_SUCCESS)
{
InitializeCriticalSection(&(ptr->PoolLock));
goto ERROR_CASE;
}
}
}
catch(...)
{
__GMM_ASSERT(false);
if(ptr && (AuxTTObj))
{
InitializeCriticalSection(&(ptr->PoolLock));
}
goto ERROR_CASE;
}
if(status == GMM_SUCCESS && !(AuxTTObj))
{
if(ptr->AuxTTObj)
{
ptr->AuxTTObj->PageTableMgr = this;
}
*this = *ptr;
//Don't initialize PoolLock until any of AuxTable object created
if(ptr->AuxTTObj )
{
InitializeCriticalSection(&PoolLock);
}
//Delete temporary ptr, but don't release allocated PageTable Obj.
ptr->AuxTTObj = NULL;
}
ERROR_CASE:
delete ptr;
ptr = NULL;
}
/////////////////////////////////////////////////////////////////////////////////////
/// Returns Root-table address for Aux-table
///
/// @return GMM_GFX_ADDRESS if Aux-Table was created; NULL otherwise
/////////////////////////////////////////////////////////////////////////////////////
GMM_GFX_ADDRESS GmmLib::GmmPageTableMgr::GetAuxL3TableAddr()
{
return AuxTTObj ? AuxTTObj->GetL3Address() : 0ULL;
}
/////////////////////////////////////////////////////////////////////////////////////
/// Queues commands to initialize Aux-Table registers in the HW context image
///
/// @param[in] initialBBHandle: pointer to BatchBuffer for queuing commands
/// @param[in] engType: specifes engine on which the context would run
/// @return GMM_SUCCESS if queuing succeeded; GMM_ERROR otherwise
/////////////////////////////////////////////////////////////////////////////////////
GMM_STATUS GmmLib::GmmPageTableMgr::InitContextAuxTableRegister(HANDLE CmdQHandle, GMM_ENGINE_TYPE engType)
{
GMM_GFX_ADDRESS MaskedL3GfxAddress = 0ULL;
GMM_UNREFERENCED_PARAMETER(engType);
//Check FtrE2ECompression = 1
if(GetLibContext()->GetSkuTable().FtrE2ECompression && AuxTTObj != NULL)
{
EnterCriticalSection(&AuxTTObj->TTLock);
if(CmdQHandle)
{
//engType = ENGINE_TYPE_RCS; //use correct offset based on engType (once per-eng offsets known)
uint64_t RegOffset = 0, L3AdrReg = 0;
GET_L3ADROFFSET(0, L3AdrReg, GetLibContext());
RegOffset = (L3AdrReg + sizeof(uint32_t));
RegOffset = L3AdrReg | (RegOffset << 0x20);
MaskedL3GfxAddress = AuxTTObj->GetL3Address();
//TTCb.pfPrologTranslationTable(CmdQHandle); //MI_FLUSH, TLBInv not required since its called during context-init
TTCb.pfWriteL3Adr(CmdQHandle, MaskedL3GfxAddress, RegOffset);
GMM_DPF(GFXDBG_NORMAL, "AuxTT Map Address: GPUVA=0x%016llX\n", MaskedL3GfxAddress);
//TTCb.pfEpilogTranslationTable(CmdQHandle, 0);
AuxTTObj->GetRegisterStatus() = 0;
}
else
{
__GMM_ASSERT(false);
LeaveCriticalSection(&AuxTTObj->TTLock);
return GMM_INVALIDPARAM;
}
LeaveCriticalSection(&AuxTTObj->TTLock);
}
return GMM_SUCCESS;
}
/////////////////////////////////////////////////////////////////////////////////////
/// Updates the Aux-PageTables, for given base resource, with appropriate mappings
///
/// @param[in] Details of AuxTable update request
/// @return GMM_STATUS
/////////////////////////////////////////////////////////////////////////////////////
GMM_STATUS GmmLib::GmmPageTableMgr::UpdateAuxTable(const GMM_DDI_UPDATEAUXTABLE *UpdateReq)
{
if(GetAuxL3TableAddr() == 0ULL)
{
GMM_ASSERTDPF(0, "Invalid AuxTable update request, AuxTable is not initialized");
return GMM_INVALIDPARAM;
}
if(!((UpdateReq->BaseResInfo->GetResFlags().Info.RenderCompressed ||
UpdateReq->BaseResInfo->GetResFlags().Info.MediaCompressed) &&
((!UpdateReq->AuxResInfo && UpdateReq->BaseResInfo->GetResFlags().Gpu.UnifiedAuxSurface) ||
(UpdateReq->AuxResInfo && UpdateReq->AuxResInfo->GetResFlags().Gpu.CCS))))
/*(UpdateReq->BaseResInfo->GetResFlags().Gpu.TiledResource ||
UpdateReq->BaseResInfo->GetResFlags().Gpu.Depth) */
//Allow Separate Aux for Depth/TR/MSAA/others?
{
GMM_ASSERTDPF(0, "Invalid AuxTable update request");
return GMM_INVALIDPARAM;
}
if(UpdateReq->Map && !(!UpdateReq->BaseResInfo->GetResFlags().Gpu.TiledResource || (UpdateReq->BaseResInfo->GetResFlags().Gpu.TiledResource && UpdateReq->UmdContext && UpdateReq->UmdContext->pCommandQueueHandle)))
{
//GMM_DPF_CRITICAL("TiledResources must Gpu-update AuxTable, proceeding with CPU-update...");
//Allowing CPU-update if requested so..
if(!UpdateReq->DoNotWait)
{
return GMM_INVALIDPARAM;
}
}
ENTER_CRITICAL_SECTION
if(UpdateReq->Map)
{
//Get AuxL1e data (other than CCS-adr) from main surface
uint64_t PartialL1e = AuxTTObj->CreateAuxL1Data(UpdateReq->BaseResInfo).Value;
GMM_STATUS Status = GMM_SUCCESS;
if(UpdateReq->BaseResInfo->GetResFlags().Gpu.TiledResource)
{
//Aux-TT is sparsely updated, for TRs, upon change in mapping state ie
// null->non-null must be mapped
// non-null->null invalidated on AuxTT
uint8_t CpuUpdate = UpdateReq->DoNotWait || !(UpdateReq->UmdContext && UpdateReq->UmdContext->pCommandQueueHandle);
GMM_GFX_ADDRESS AuxVA = UpdateReq->AuxSurfVA;
if(UpdateReq->BaseResInfo->GetResFlags().Gpu.UnifiedAuxSurface)
{
GMM_UNIFIED_AUX_TYPE AuxType = GMM_AUX_CCS;
AuxType = (UpdateReq->BaseResInfo->GetResFlags().Gpu.Depth && UpdateReq->BaseResInfo->GetResFlags().Gpu.CCS) ? GMM_AUX_ZCS : AuxType;
AuxVA = UpdateReq->BaseGpuVA + GmmResGetAuxSurfaceOffset(UpdateReq->BaseResInfo, AuxType);
}
}
else
{
GMM_GFX_ADDRESS AuxVA = {0};
GMM_GFX_ADDRESS UVAuxVA = {0};
GMM_GFX_SIZE_T YPlaneSize = 0;
uint32_t MaxPlanes = 1;
if(!UpdateReq->AuxResInfo && UpdateReq->BaseResInfo->GetResFlags().Gpu.UnifiedAuxSurface)
{
GMM_UNIFIED_AUX_TYPE AuxType = GMM_AUX_CCS;
AuxType = (UpdateReq->BaseResInfo->GetResFlags().Gpu.Depth &&
UpdateReq->BaseResInfo->GetResFlags().Gpu.CCS) ?
GMM_AUX_ZCS :
AuxType;
AuxVA = UpdateReq->BaseGpuVA + GmmResGetAuxSurfaceOffset(UpdateReq->BaseResInfo, AuxType);
//For UV Packed, Gen12 e2e compr supported formats have 2 planes per surface
//Each has distinct Aux surface, Y-plane/UV-plane must be mapped to respective Y/UV Aux surface
if(GmmIsPlanar(UpdateReq->BaseResInfo->GetResourceFormat()))
{
GMM_REQ_OFFSET_INFO ReqInfo = {0};
ReqInfo.Plane = GMM_PLANE_U;
ReqInfo.ReqRender = 1;
MaxPlanes = 2;
UpdateReq->BaseResInfo->GetOffset(ReqInfo);
YPlaneSize = ReqInfo.Render.Offset64;
UVAuxVA = UpdateReq->BaseGpuVA + GmmResGetAuxSurfaceOffset(UpdateReq->BaseResInfo, GMM_AUX_UV_CCS);
}
}
//Per-plane Aux-TT map called with per-plane base/Aux address/size
for(uint32_t i = 0; i < MaxPlanes; i++)
{
GMM_GFX_SIZE_T SurfSize = (MaxPlanes > 1 && UpdateReq->BaseResInfo->GetArraySize() > 1) ?
(UpdateReq->BaseResInfo->GetQPitchPlanar(GMM_NO_PLANE) * UpdateReq->BaseResInfo->GetRenderPitch()) :
UpdateReq->BaseResInfo->GetSizeMainSurface();
GMM_GFX_SIZE_T MapSize = (i == 0) ? ((MaxPlanes > 1) ? YPlaneSize : SurfSize) : SurfSize - YPlaneSize;
GMM_GFX_ADDRESS BaseSurfVA = (UpdateReq->AuxResInfo || i == 0) ? UpdateReq->BaseGpuVA :
UpdateReq->BaseGpuVA + YPlaneSize;
GMM_GFX_ADDRESS AuxSurfVA = (UpdateReq->AuxResInfo) ? UpdateReq->AuxSurfVA : (i > 0 ? UVAuxVA : AuxVA);
//Luma plane reset LumaChroma bit
((GMM_AUXTTL1e *)&PartialL1e)->LumaChroma = (i == 0) ? 0 : 1;
uint32_t ArrayEle = GFX_MAX(((MaxPlanes > 1) ?
UpdateReq->BaseResInfo->GetArraySize() :
1),
1);
for(uint32_t j = 0; j < ArrayEle; j++)
{
BaseSurfVA += ((j > 0) ? (UpdateReq->BaseResInfo->GetQPitchPlanar(GMM_PLANE_Y) * UpdateReq->BaseResInfo->GetRenderPitch()) : 0);
AuxSurfVA += (UpdateReq->AuxResInfo ?
((j > 0) ? (UpdateReq->AuxResInfo->GetQPitchPlanar(GMM_PLANE_Y) * UpdateReq->BaseResInfo->GetRenderPitch()) : 0) :
((j > 0) ? UpdateReq->BaseResInfo->GetAuxQPitch() : 0));
//(Flat mapping): Remove main/aux resInfo from params
Status = AuxTTObj->MapValidEntry(UpdateReq->UmdContext, BaseSurfVA, MapSize, UpdateReq->BaseResInfo,
AuxSurfVA, UpdateReq->AuxResInfo, PartialL1e, 1);
if(Status != GMM_SUCCESS)
{
GMM_ASSERTDPF(0, "Insufficient memory, free resources and try again");
EXIT_CRITICAL_SECTION
return Status;
}
}
}
}
}
else
{
//Invalidate all mappings for given main surface
AuxTTObj->InvalidateTable(UpdateReq->UmdContext, UpdateReq->BaseGpuVA, UpdateReq->BaseResInfo->GetSizeMainSurface(), UpdateReq->DoNotWait);
}
EXIT_CRITICAL_SECTION
return GMM_SUCCESS;
}
#if defined(__linux__) && !_WIN32
/////////////////////////////////////////////////////////////////////////////////////
/// Gets size of PageTable buffer object (BOs) list
///
/// @param[in] TTFlags: Flags specifying PageTable-type for which BO-count required
/// @return non-zero if BO list is created. Zero otherwise.
/////////////////////////////////////////////////////////////////////////////////////
int GmmLib::GmmPageTableMgr::GetNumOfPageTableBOs(uint8_t TTFlags)
{
int NumBO = 0;
__GMM_ASSERTPTR(TTFlags & AUXTT, 0);
ENTER_CRITICAL_SECTION
if(AuxTTObj && AuxTTObj->GetL3Handle())
NumBO++;
NumBO += NumNodePoolElements;
EXIT_CRITICAL_SECTION
return NumBO;
}
/////////////////////////////////////////////////////////////////////////////////////
/// Gets size of PageTable buffer object (BOs) list
///
/// @param[in] TTFlags: Flags specifying PageTable-type for which BO-count required
/// @param[in][out] BOList: pointer to memory where PageTable BO*(s) must be sent
/// @return non-zero if BO list is created. Zero otherwise.
/////////////////////////////////////////////////////////////////////////////////////
int GmmLib::GmmPageTableMgr::GetPageTableBOList(uint8_t TTFlags, void *BOList)
{
int NumBO = GetNumOfPageTableBOs(TTFlags);
HANDLE * Handles = (HANDLE *)BOList;
GmmLib::GMM_PAGETABLEPool *Pool;
__GMM_ASSERTPTR(TTFlags & AUXTT, 0);
__GMM_ASSERTPTR(BOList, 0);
__GMM_ASSERTPTR(NumBO, 0);
ENTER_CRITICAL_SECTION
if(AuxTTObj && AuxTTObj->GetL3Handle())
Handles[0] = AuxTTObj->GetL3Handle();
Pool = pPool;
for(int i = 0; i < NumNodePoolElements; i++)
{
if(Pool)
{
Handles[i + 1] = Pool->GetPoolHandle();
Pool = Pool->GetNextPool();
}
}
EXIT_CRITICAL_SECTION
return NumBO;
}
#endif
/////////////////////////////////////////////////////////////////////////////////////
/// Releases GmmPageTableMgr, deleting root-tables and existing page-table pools
/////////////////////////////////////////////////////////////////////////////////////
GmmLib::GmmPageTableMgr::~GmmPageTableMgr()
{
GMM_CLIENT ClientType;
GET_GMM_CLIENT_TYPE(pClientContext, ClientType);
if(pPool)
{
ENTER_CRITICAL_SECTION
pPool->__DestroyPageTablePool(&DeviceCbInt, hCsr);
NumNodePoolElements = 0;
EXIT_CRITICAL_SECTION
}
if(AuxTTObj)
{
DeleteCriticalSection(&PoolLock);
if(AuxTTObj)
{
if(AuxTTObj->NullL1Table)
{
delete AuxTTObj->NullL1Table;
}
if(AuxTTObj->NullL2Table)
{
delete AuxTTObj->NullL2Table;
}
AuxTTObj->DestroyL3Table();
delete AuxTTObj;
AuxTTObj = NULL;
}
}
}
/////////////////////////////////////////////////////////////////////////////////////
/// Instantiates and zeroes out GmmPageTableMgr
///
/// @return GmmPageTableMgr*
/////////////////////////////////////////////////////////////////////////////////////
GmmLib::GmmPageTableMgr::GmmPageTableMgr()
{
this->AuxTTObj = NULL;
this->pPool = NULL;
this->NumNodePoolElements = 0;
this->pClientContext = NULL;
this->hCsr = NULL;
memset(&DeviceCb, 0, sizeof(GMM_DEVICE_CALLBACKS));
memset(&DeviceCbInt, 0, sizeof(GMM_DEVICE_CALLBACKS_INT));
}
| 37.201635 | 217 | 0.554823 | [
"render",
"object"
] |
28e623bcce64fedfb91ba4488f8c95949477d57a | 3,352 | cpp | C++ | homework/Aladushkin/06/calculator.cpp | nkotelevskii/msu_cpp_spring_2018 | b5d84447f9b8c7f3615b421c51cf4192f1b90342 | [
"MIT"
] | 12 | 2018-02-20T15:25:12.000Z | 2022-02-15T03:31:55.000Z | homework/Aladushkin/06/calculator.cpp | nkotelevskii/msu_cpp_spring_2018 | b5d84447f9b8c7f3615b421c51cf4192f1b90342 | [
"MIT"
] | 1 | 2018-02-26T12:40:47.000Z | 2018-02-26T12:40:47.000Z | homework/Aladushkin/06/calculator.cpp | nkotelevskii/msu_cpp_spring_2018 | b5d84447f9b8c7f3615b421c51cf4192f1b90342 | [
"MIT"
] | 33 | 2018-02-20T15:25:11.000Z | 2019-02-13T22:33:36.000Z | #include <string>
#include <vector>
#include <cmath>
#include <cctype>
#include <cstring>
#include <stdexcept>
struct Expression
{
public:
Expression(const std::string& token) : token(token) {}
Expression(const std::string& token, const Expression& a) : token(token), args{ a } {}
Expression(const std::string& token, const Expression& a, const Expression& b) : token(token), args{ a, b } {}
std::string token;
std::vector<Expression> args;
};
template<typename T>
T cast(const std::string& str);
template<> int cast<int>(const std::string& str) { return std::stoi(str); }
template <typename T>
class Calculator
{
public:
explicit Calculator(const char* input) : input(input) {}
Expression parse();
T eval(const Expression& e);
private:
std::string parse_token();
Expression parse_simple_expression();
Expression parse_binary_expression(int min_priority);
const char* input;
};
template<typename T>
std::string Calculator<T>::parse_token()
{
while (std::isspace(*input))
++input;
if (std::isdigit(*input))
{
std::string number;
while (std::isdigit(*input) || *input == '.') number.push_back(*input++);
return number;
}
static const std::string tokens[] = { "+", "-", "*", "/" };
for (auto& t : tokens)
{
if (std::strncmp(input, t.c_str(), t.size()) == 0)
{
input += t.size();
return t;
}
}
return "";
}
template<typename T>
Expression Calculator<T>::parse_simple_expression() {
auto token = parse_token();
if (token.empty())
throw std::runtime_error("Invalid input");
if (std::isdigit(token[0]))
return Expression(token);
return Expression(token, parse_simple_expression());
}
int get_priority(const std::string& binary_op) {
if (binary_op == "+") return 1;
if (binary_op == "-") return 1;
if (binary_op == "*") return 2;
if (binary_op == "/") return 2;
return 0;
}
template<typename T>
Expression Calculator<T>::parse_binary_expression(int min_priority)
{
auto left_expr = parse_simple_expression();
for (;;)
{
auto op = parse_token();
auto priority = get_priority(op);
if (priority <= min_priority)
{
input -= op.size();
return left_expr;
}
auto right_expr = parse_binary_expression(priority);
left_expr = Expression(op, left_expr, right_expr);
}
}
template<typename T>
Expression Calculator<T>::parse()
{
return parse_binary_expression(0);
}
template <typename T>
T Calculator<T>::eval(const Expression& e)
{
switch (e.args.size())
{
case 2:
{
auto a = eval(e.args[0]);
auto b = eval(e.args[1]);
if (e.token == "+") return a + b;
if (e.token == "-") return a - b;
if (e.token == "*") return a * b;
if (e.token == "/")
{
if (b == 0)
throw std::runtime_error("Division by zero");
return a / b;
}
throw std::runtime_error("Unknown binary operator");
}
case 1:
{
auto a = eval(e.args[0]);
if (e.token == "+") return +a;
if (e.token == "-") return -a;
throw std::runtime_error("Unknown unary operator");
}
case 0:
return cast<T>(e.token);
}
throw std::runtime_error("Unknown expression type");
}
#include <iostream>
int main(int argc, char* argv[])
{
try
{
if (argc != 2)
throw std::runtime_error("Invalid input");
else
{
Calculator<int> p(argv[1]);
auto result = p.eval(p.parse());
std::cout << result;
}
}
catch (...)
{
std::cout << "error";
return 1;
}
return 0;
}
| 19.488372 | 111 | 0.6429 | [
"vector"
] |
28e63419242911d1f0c9ddea7de2848e58f0a64c | 60,331 | cpp | C++ | src/mongo/db/pipeline/document_value_test.cpp | pengliu2/rtree_mongo | 0b90913f75de5281a96d1383c319843ea84a90d2 | [
"Apache-2.0"
] | 29 | 2015-01-13T02:34:23.000Z | 2022-01-30T16:57:10.000Z | src/mongo/db/pipeline/document_value_test.cpp | pengliu2/rtree_mongo | 0b90913f75de5281a96d1383c319843ea84a90d2 | [
"Apache-2.0"
] | null | null | null | src/mongo/db/pipeline/document_value_test.cpp | pengliu2/rtree_mongo | 0b90913f75de5281a96d1383c319843ea84a90d2 | [
"Apache-2.0"
] | 12 | 2015-01-24T08:40:28.000Z | 2017-10-04T17:23:39.000Z | // documenttests.cpp : Unit tests for Document, Value, and related classes.
/**
* Copyright (C) 2012 10gen Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* This program 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* As a special exception, the copyright holders give permission to link the
* code of portions of this program with the OpenSSL library under certain
* conditions as described in each individual source file and distribute
* linked combinations including the program with the OpenSSL library. You
* must comply with the GNU Affero General Public License in all respects
* for all of the code used other than as permitted herein. If you modify
* file(s) with this exception, you may extend this exception to your
* version of the file(s), but you are not obligated to do so. If you do not
* wish to do so, delete this exception statement from your version. If you
* delete this exception statement from all source files in the program,
* then also delete it in the license file.
*/
#include "mongo/platform/basic.h"
#include "mongo/db/pipeline/document.h"
#include "mongo/db/pipeline/field_path.h"
#include "mongo/db/pipeline/value.h"
#include "mongo/dbtests/dbtests.h"
#include "mongo/util/print.h"
namespace DocumentTests {
using std::endl;
using std::numeric_limits;
using std::string;
using std::vector;
mongo::Document::FieldPair getNthField(mongo::Document doc, size_t index) {
mongo::FieldIterator it (doc);
while (index--) // advance index times
it.next();
return it.next();
}
namespace Document {
using mongo::Document;
BSONObj toBson( const Document& document ) {
return document.toBson();
}
Document fromBson( BSONObj obj ) {
return Document(obj);
}
void assertRoundTrips( const Document& document1 ) {
BSONObj obj1 = toBson( document1 );
Document document2 = fromBson( obj1 );
BSONObj obj2 = toBson( document2 );
ASSERT_EQUALS( obj1, obj2 );
ASSERT_EQUALS( document1, document2 );
}
/** Create a Document. */
class Create {
public:
void run() {
Document document;
ASSERT_EQUALS( 0U, document.size() );
assertRoundTrips( document );
}
};
/** Create a Document from a BSONObj. */
class CreateFromBsonObj {
public:
void run() {
Document document = fromBson( BSONObj() );
ASSERT_EQUALS( 0U, document.size() );
document = fromBson( BSON( "a" << 1 << "b" << "q" ) );
ASSERT_EQUALS( 2U, document.size() );
ASSERT_EQUALS( "a", getNthField(document, 0).first.toString() );
ASSERT_EQUALS( 1, getNthField(document, 0).second.getInt() );
ASSERT_EQUALS( "b", getNthField(document, 1).first.toString() );
ASSERT_EQUALS( "q", getNthField(document, 1).second.getString() );
assertRoundTrips( document );
}
};
/** Add Document fields. */
class AddField {
public:
void run() {
MutableDocument md;
md.addField( "foo", Value( 1 ) );
ASSERT_EQUALS( 1U, md.peek().size() );
ASSERT_EQUALS( 1, md.peek()["foo"].getInt() );
md.addField( "bar", Value( 99 ) );
ASSERT_EQUALS( 2U, md.peek().size() );
ASSERT_EQUALS( 99, md.peek()["bar"].getInt() );
// No assertion is triggered by a duplicate field name.
md.addField( "a", Value( 5 ) );
Document final = md.freeze();
ASSERT_EQUALS( 3U, final.size() );
assertRoundTrips( final );
}
};
/** Get Document values. */
class GetValue {
public:
void run() {
Document document = fromBson( BSON( "a" << 1 << "b" << 2.2 ) );
ASSERT_EQUALS( 1, document["a"].getInt() );
ASSERT_EQUALS( 1, document["a"].getInt() );
ASSERT_EQUALS( 2.2, document["b"].getDouble() );
ASSERT_EQUALS( 2.2, document["b"].getDouble() );
// Missing field.
ASSERT( document["c"].missing() );
ASSERT( document["c"].missing() );
assertRoundTrips( document );
}
};
/** Get Document fields. */
class SetField {
public:
void run() {
Document original = fromBson(BSON("a" << 1 << "b" << 2.2 << "c" << 99));
// Initial positions. Used at end of function to make sure nothing moved
const Position apos = original.positionOf("a");
const Position bpos = original.positionOf("c");
const Position cpos = original.positionOf("c");
MutableDocument md (original);
// Set the first field.
md.setField( "a" , Value( "foo" ) );
ASSERT_EQUALS( 3U, md.peek().size() );
ASSERT_EQUALS( "foo", md.peek()["a"].getString() );
ASSERT_EQUALS( "foo", getNthField(md.peek(), 0).second.getString() );
assertRoundTrips( md.peek() );
// Set the second field.
md["b"] = Value("bar");
ASSERT_EQUALS( 3U, md.peek().size() );
ASSERT_EQUALS( "bar", md.peek()["b"].getString() );
ASSERT_EQUALS( "bar", getNthField(md.peek(), 1).second.getString() );
assertRoundTrips( md.peek() );
// Remove the second field.
md.setField("b", Value());
PRINT(md.peek().toString());
ASSERT_EQUALS( 2U, md.peek().size() );
ASSERT( md.peek()["b"].missing() );
ASSERT_EQUALS( "a", getNthField(md.peek(), 0 ).first.toString() );
ASSERT_EQUALS( "c", getNthField(md.peek(), 1 ).first.toString() );
ASSERT_EQUALS( 99, md.peek()["c"].getInt() );
assertRoundTrips( md.peek() );
// Remove the first field.
md["a"] = Value();
ASSERT_EQUALS( 1U, md.peek().size() );
ASSERT( md.peek()["a"].missing() );
ASSERT_EQUALS( "c", getNthField(md.peek(), 0 ).first.toString() );
ASSERT_EQUALS( 99, md.peek()["c"].getInt() );
assertRoundTrips( md.peek() );
// Remove the final field. Verify document is empty.
md.remove("c");
ASSERT( md.peek().empty() );
ASSERT_EQUALS( 0U, md.peek().size() );
ASSERT_EQUALS( md.peek(), Document() );
ASSERT( !FieldIterator(md.peek()).more() );
ASSERT( md.peek()["c"].missing() );
assertRoundTrips( md.peek() );
// Set a nested field using []
md["x"]["y"]["z"] = Value("nested");
ASSERT_EQUALS(md.peek()["x"]["y"]["z"], Value("nested"));
// Set a nested field using setNestedField
FieldPath xxyyzz = string("xx.yy.zz");
md.setNestedField(xxyyzz, Value("nested"));
ASSERT_EQUALS(md.peek().getNestedField(xxyyzz), Value("nested") );
// Set a nested fields through an existing empty document
md["xxx"] = Value(Document());
md["xxx"]["yyy"] = Value(Document());
FieldPath xxxyyyzzz = string("xxx.yyy.zzz");
md.setNestedField(xxxyyyzzz, Value("nested"));
ASSERT_EQUALS(md.peek().getNestedField(xxxyyyzzz), Value("nested") );
// Make sure nothing moved
ASSERT_EQUALS(apos, md.peek().positionOf("a"));
ASSERT_EQUALS(bpos, md.peek().positionOf("c"));
ASSERT_EQUALS(cpos, md.peek().positionOf("c"));
ASSERT_EQUALS(Position(), md.peek().positionOf("d"));
}
};
/** Document comparator. */
class Compare {
public:
void run() {
assertComparison( 0, BSONObj(), BSONObj() );
assertComparison( 0, BSON( "a" << 1 ), BSON( "a" << 1 ) );
assertComparison( -1, BSONObj(), BSON( "a" << 1 ) );
assertComparison( -1, BSON( "a" << 1 ), BSON( "c" << 1 ) );
assertComparison( 0, BSON( "a" << 1 << "r" << 2 ), BSON( "a" << 1 << "r" << 2 ) );
assertComparison( -1, BSON( "a" << 1 ), BSON( "a" << 1 << "r" << 2 ) );
assertComparison( 0, BSON( "a" << 2 ), BSON( "a" << 2 ) );
assertComparison( -1, BSON( "a" << 1 ), BSON( "a" << 2 ) );
assertComparison( -1, BSON( "a" << 1 << "b" << 1 ), BSON( "a" << 1 << "b" << 2 ) );
// numbers sort before strings
assertComparison( -1, BSON( "a" << 1 ), BSON( "a" << "foo" ) );
// numbers sort before strings, even if keys compare otherwise
assertComparison( -1, BSON( "b" << 1 ), BSON( "a" << "foo" ) );
// null before number, even if keys compare otherwise
assertComparison( -1, BSON( "z" << BSONNULL ), BSON( "a" << 1 ) );
}
public:
int cmp( const BSONObj& a, const BSONObj& b ) {
int result = Document::compare( fromBson( a ), fromBson( b ) );
return // sign
result < 0 ? -1 :
result > 0 ? 1 :
0;
}
void assertComparison( int expectedResult, const BSONObj& a, const BSONObj& b ) {
ASSERT_EQUALS( expectedResult, cmp( a, b ) );
ASSERT_EQUALS( -expectedResult, cmp( b, a ) );
if ( expectedResult == 0 ) {
ASSERT_EQUALS( hash( a ), hash( b ) );
}
}
size_t hash( const BSONObj& obj ) {
size_t seed = 0x106e1e1;
Document(obj).hash_combine(seed);
return seed;
}
};
/** Shallow copy clone of a single field Document. */
class Clone {
public:
void run() {
const Document document = fromBson( BSON( "a" << BSON( "b" << 1 ) ) );
MutableDocument cloneOnDemand (document);
// Check equality.
ASSERT_EQUALS(document, cloneOnDemand.peek());
// Check pointer equality of sub document.
ASSERT_EQUALS( document["a"].getDocument().getPtr(),
cloneOnDemand.peek()["a"].getDocument().getPtr() );
// Change field in clone and ensure the original document's field is unchanged.
cloneOnDemand.setField( StringData("a"), Value(2) );
ASSERT_EQUALS( Value(1), document.getNestedField(FieldPath("a.b")) );
// setNestedField and ensure the original document is unchanged.
cloneOnDemand.reset(document);
vector<Position> path;
ASSERT_EQUALS( Value(1), document.getNestedField(FieldPath("a.b"), &path) );
cloneOnDemand.setNestedField(path, Value(2));
ASSERT_EQUALS( Value(1), document.getNestedField(FieldPath("a.b")) );
ASSERT_EQUALS( Value(2), cloneOnDemand.peek().getNestedField(FieldPath("a.b")) );
ASSERT_EQUALS( DOC( "a" << DOC( "b" << 1 ) ), document );
ASSERT_EQUALS( DOC( "a" << DOC( "b" << 2 ) ), cloneOnDemand.freeze() );
}
};
/** Shallow copy clone of a multi field Document. */
class CloneMultipleFields {
public:
void run() {
Document document =
fromBson( fromjson( "{a:1,b:['ra',4],c:{z:1},d:'lal'}" ) );
Document clonedDocument = document.clone();
ASSERT_EQUALS(document, clonedDocument);
}
};
/** FieldIterator for an empty Document. */
class FieldIteratorEmpty {
public:
void run() {
FieldIterator iterator ( (Document()) );
ASSERT( !iterator.more() );
}
};
/** FieldIterator for a single field Document. */
class FieldIteratorSingle {
public:
void run() {
FieldIterator iterator (fromBson( BSON( "a" << 1 ) ));
ASSERT( iterator.more() );
Document::FieldPair field = iterator.next();
ASSERT_EQUALS( "a", field.first.toString() );
ASSERT_EQUALS( 1, field.second.getInt() );
ASSERT( !iterator.more() );
}
};
/** FieldIterator for a multiple field Document. */
class FieldIteratorMultiple {
public:
void run() {
FieldIterator iterator (fromBson( BSON( "a" << 1 << "b" << 5.6 << "c" << "z" )));
ASSERT( iterator.more() );
Document::FieldPair field = iterator.next();
ASSERT_EQUALS( "a", field.first.toString() );
ASSERT_EQUALS( 1, field.second.getInt() );
ASSERT( iterator.more() );
Document::FieldPair field2 = iterator.next();
ASSERT_EQUALS( "b", field2.first.toString() );
ASSERT_EQUALS( 5.6, field2.second.getDouble() );
ASSERT( iterator.more() );
Document::FieldPair field3 = iterator.next();
ASSERT_EQUALS( "c", field3.first.toString() );
ASSERT_EQUALS( "z", field3.second.getString() );
ASSERT( !iterator.more() );
}
};
class AllTypesDoc {
public:
void run() {
// These are listed in order of BSONType with some duplicates
append("minkey", MINKEY);
// EOO not valid in middle of BSONObj
append("double", 1.0);
append("c-string", "string\0after NUL"); // after NULL is ignored
append("c++", StringData("string\0after NUL", StringData::LiteralTag()).toString());
append("StringData", StringData("string\0after NUL", StringData::LiteralTag()));
append("emptyObj", BSONObj());
append("filledObj", BSON("a" << 1));
append("emptyArray", BSON("" << BSONArray()).firstElement());
append("filledArray", BSON("" << BSON_ARRAY(1 << "a")).firstElement());
append("binData", BSONBinData("a\0b", 3, BinDataGeneral));
append("binDataCustom", BSONBinData("a\0b", 3, bdtCustom));
append("binDataUUID", BSONBinData("123456789\0abcdef", 16, bdtUUID));
append("undefined", BSONUndefined);
append("oid", OID());
append("true", true);
append("false", false);
append("date", jsTime());
append("null", BSONNULL);
append("regex", BSONRegEx(".*"));
append("regexFlags", BSONRegEx(".*", "i"));
append("regexEmpty", BSONRegEx("", ""));
append("dbref", BSONDBRef("foo", OID()));
append("code", BSONCode("function() {}"));
append("codeNul", BSONCode(StringData("var nul = '\0'", StringData::LiteralTag())));
append("symbol", BSONSymbol("foo"));
append("symbolNul", BSONSymbol(StringData("f\0o", StringData::LiteralTag())));
append("codeWScope", BSONCodeWScope("asdf", BSONObj()));
append("codeWScopeWScope", BSONCodeWScope("asdf", BSON("one" << 1)));
append("int", 1);
append("timestamp", OpTime());
append("long", 1LL);
append("very long", 1LL << 40);
append("maxkey", MAXKEY);
const BSONArray arr = arrBuilder.arr();
// can't use append any more since arrBuilder is done
objBuilder << "mega array" << arr;
docBuilder["mega array"] = mongo::Value(values);
const BSONObj obj = objBuilder.obj();
const Document doc = docBuilder.freeze();
const BSONObj obj2 = toBson(doc);
const Document doc2 = fromBson(obj);
// logical equality
ASSERT_EQUALS(obj, obj2);
ASSERT_EQUALS(doc, doc2);
// binary equality
ASSERT_EQUALS(obj.objsize(), obj2.objsize());
ASSERT_EQUALS(memcmp(obj.objdata(), obj2.objdata(), obj.objsize()), 0);
// ensure sorter serialization round-trips correctly
BufBuilder bb;
doc.serializeForSorter(bb);
BufReader reader(bb.buf(), bb.len());
const Document doc3 = Document::deserializeForSorter(
reader, Document::SorterDeserializeSettings());
BSONObj obj3 = toBson(doc3);
ASSERT_EQUALS(obj.objsize(), obj3.objsize());
ASSERT_EQUALS(memcmp(obj.objdata(), obj3.objdata(), obj.objsize()), 0);
}
template <typename T>
void append(const char* name, const T& thing) {
objBuilder << name << thing;
arrBuilder << thing;
docBuilder[name] = mongo::Value(thing);
values.push_back(mongo::Value(thing));
}
vector<mongo::Value> values;
MutableDocument docBuilder;
BSONObjBuilder objBuilder;
BSONArrayBuilder arrBuilder;
};
} // namespace Document
namespace Value {
using mongo::Value;
BSONObj toBson( const Value& value ) {
if (value.missing())
return BSONObj(); // EOO
BSONObjBuilder bob;
value.addToBsonObj( &bob, "" );
return bob.obj();
}
Value fromBson( const BSONObj& obj ) {
BSONElement element = obj.firstElement();
return Value( element );
}
void assertRoundTrips( const Value& value1 ) {
BSONObj obj1 = toBson( value1 );
Value value2 = fromBson( obj1 );
BSONObj obj2 = toBson( value2 );
ASSERT_EQUALS( obj1, obj2 );
ASSERT_EQUALS(value1, value2);
ASSERT_EQUALS(value1.getType(), value2.getType());
}
class BSONArrayTest {
public:
void run() {
ASSERT_EQUALS(Value(BSON_ARRAY(1 << 2 << 3)), DOC_ARRAY(1 << 2 << 3));
ASSERT_EQUALS(Value(BSONArray()), Value(vector<Value>()));
}
};
/** Int type. */
class Int {
public:
void run() {
Value value = Value( 5 );
ASSERT_EQUALS( 5, value.getInt() );
ASSERT_EQUALS( 5, value.getLong() );
ASSERT_EQUALS( 5, value.getDouble() );
ASSERT_EQUALS( NumberInt, value.getType() );
assertRoundTrips( value );
}
};
/** Long type. */
class Long {
public:
void run() {
Value value = Value( 99LL );
ASSERT_EQUALS( 99, value.getLong() );
ASSERT_EQUALS( 99, value.getDouble() );
ASSERT_EQUALS( NumberLong, value.getType() );
assertRoundTrips( value );
}
};
/** Double type. */
class Double {
public:
void run() {
Value value = Value( 5.5 );
ASSERT_EQUALS( 5.5, value.getDouble() );
ASSERT_EQUALS( NumberDouble, value.getType() );
assertRoundTrips( value );
}
};
/** String type. */
class String {
public:
void run() {
Value value = Value( "foo" );
ASSERT_EQUALS( "foo", value.getString() );
ASSERT_EQUALS( mongo::String, value.getType() );
assertRoundTrips( value );
}
};
/** String with a null character. */
class StringWithNull {
public:
void run() {
string withNull( "a\0b", 3 );
BSONObj objWithNull = BSON( "" << withNull );
ASSERT_EQUALS( withNull, objWithNull[ "" ].str() );
Value value = fromBson( objWithNull );
ASSERT_EQUALS( withNull, value.getString() );
assertRoundTrips( value );
}
};
/** Date type. */
class Date {
public:
void run() {
Value value = Value(Date_t(999));
ASSERT_EQUALS( 999, value.getDate() );
ASSERT_EQUALS( mongo::Date, value.getType() );
assertRoundTrips( value );
}
};
/** Timestamp type. */
class Timestamp {
public:
void run() {
Value value = Value( OpTime( 777 ) );
ASSERT( OpTime( 777 ) == value.getTimestamp() );
ASSERT_EQUALS( mongo::Timestamp, value.getType() );
assertRoundTrips( value );
}
};
/** Document with no fields. */
class EmptyDocument {
public:
void run() {
mongo::Document document = mongo::Document();
Value value = Value( document );
ASSERT_EQUALS( document.getPtr(), value.getDocument().getPtr() );
ASSERT_EQUALS( Object, value.getType() );
assertRoundTrips( value );
}
};
/** Document type. */
class Document {
public:
void run() {
mongo::MutableDocument md;
md.addField( "a", Value( 5 ) );
md.addField( "apple", Value( "rrr" ) );
md.addField( "banana", Value( -.3 ) );
mongo::Document document = md.freeze();
Value value = Value( document );
// Check document pointers are equal.
ASSERT_EQUALS( document.getPtr(), value.getDocument().getPtr() );
// Check document contents.
ASSERT_EQUALS( 5, document["a"].getInt() );
ASSERT_EQUALS( "rrr", document["apple"].getString() );
ASSERT_EQUALS( -.3, document["banana"].getDouble() );
ASSERT_EQUALS( Object, value.getType() );
assertRoundTrips( value );
}
};
/** Array with no elements. */
class EmptyArray {
public:
void run() {
vector<Value> array;
Value value (array);
const vector<Value>& array2 = value.getArray();
ASSERT( array2.empty() );
ASSERT_EQUALS( Array, value.getType() );
ASSERT_EQUALS( 0U, value.getArrayLength() );
assertRoundTrips( value );
}
};
/** Array type. */
class Array {
public:
void run() {
vector<Value> array;
array.push_back( Value( 5 ) );
array.push_back( Value( "lala" ) );
array.push_back( Value( 3.14 ) );
Value value = Value( array );
const vector<Value>& array2 = value.getArray();
ASSERT( !array2.empty() );
ASSERT_EQUALS( array2.size(), 3U);
ASSERT_EQUALS( 5, array2[0].getInt() );
ASSERT_EQUALS( "lala", array2[1].getString() );
ASSERT_EQUALS( 3.14, array2[2].getDouble() );
ASSERT_EQUALS( mongo::Array, value.getType() );
ASSERT_EQUALS( 3U, value.getArrayLength() );
assertRoundTrips( value );
}
};
/** Oid type. */
class Oid {
public:
void run() {
Value value =
fromBson( BSON( "" << OID( "abcdefabcdefabcdefabcdef" ) ) );
ASSERT_EQUALS( OID( "abcdefabcdefabcdefabcdef" ), value.getOid() );
ASSERT_EQUALS( jstOID, value.getType() );
assertRoundTrips( value );
}
};
/** Bool type. */
class Bool {
public:
void run() {
Value value = fromBson( BSON( "" << true ) );
ASSERT_EQUALS( true, value.getBool() );
ASSERT_EQUALS( mongo::Bool, value.getType() );
assertRoundTrips( value );
}
};
/** Regex type. */
class Regex {
public:
void run() {
Value value = fromBson( fromjson( "{'':/abc/}" ) );
ASSERT_EQUALS( string("abc"), value.getRegex() );
ASSERT_EQUALS( RegEx, value.getType() );
assertRoundTrips( value );
}
};
/** Symbol type (currently unsupported). */
class Symbol {
public:
void run() {
Value value (BSONSymbol("FOOBAR"));
ASSERT_EQUALS( "FOOBAR", value.getSymbol() );
ASSERT_EQUALS( mongo::Symbol, value.getType() );
assertRoundTrips( value );
}
};
/** Undefined type. */
class Undefined {
public:
void run() {
Value value = Value(BSONUndefined);
ASSERT_EQUALS( mongo::Undefined, value.getType() );
assertRoundTrips( value );
}
};
/** Null type. */
class Null {
public:
void run() {
Value value = Value(BSONNULL);
ASSERT_EQUALS( jstNULL, value.getType() );
assertRoundTrips( value );
}
};
/** True value. */
class True {
public:
void run() {
Value value = Value(true);
ASSERT_EQUALS( true, value.getBool() );
ASSERT_EQUALS( mongo::Bool, value.getType() );
assertRoundTrips( value );
}
};
/** False value. */
class False {
public:
void run() {
Value value = Value(false);
ASSERT_EQUALS( false, value.getBool() );
ASSERT_EQUALS( mongo::Bool, value.getType() );
assertRoundTrips( value );
}
};
/** -1 value. */
class MinusOne {
public:
void run() {
Value value = Value(-1);
ASSERT_EQUALS( -1, value.getInt() );
ASSERT_EQUALS( NumberInt, value.getType() );
assertRoundTrips( value );
}
};
/** 0 value. */
class Zero {
public:
void run() {
Value value = Value(0);
ASSERT_EQUALS( 0, value.getInt() );
ASSERT_EQUALS( NumberInt, value.getType() );
assertRoundTrips( value );
}
};
/** 1 value. */
class One {
public:
void run() {
Value value = Value(1);
ASSERT_EQUALS( 1, value.getInt() );
ASSERT_EQUALS( NumberInt, value.getType() );
assertRoundTrips( value );
}
};
namespace Coerce {
class ToBoolBase {
public:
virtual ~ToBoolBase() {
}
void run() {
ASSERT_EQUALS( expected(), value().coerceToBool() );
}
protected:
virtual Value value() = 0;
virtual bool expected() = 0;
};
class ToBoolTrue : public ToBoolBase {
bool expected() { return true; }
};
class ToBoolFalse : public ToBoolBase {
bool expected() { return false; }
};
/** Coerce 0 to bool. */
class ZeroIntToBool : public ToBoolFalse {
Value value() { return Value( 0 ); }
};
/** Coerce -1 to bool. */
class NonZeroIntToBool : public ToBoolTrue {
Value value() { return Value( -1 ); }
};
/** Coerce 0LL to bool. */
class ZeroLongToBool : public ToBoolFalse {
Value value() { return Value( 0LL ); }
};
/** Coerce 5LL to bool. */
class NonZeroLongToBool : public ToBoolTrue {
Value value() { return Value( 5LL ); }
};
/** Coerce 0.0 to bool. */
class ZeroDoubleToBool : public ToBoolFalse {
Value value() { return Value( 0 ); }
};
/** Coerce -1.3 to bool. */
class NonZeroDoubleToBool : public ToBoolTrue {
Value value() { return Value( -1.3 ); }
};
/** Coerce "" to bool. */
class StringToBool : public ToBoolTrue {
Value value() { return Value( "" ); }
};
/** Coerce {} to bool. */
class ObjectToBool : public ToBoolTrue {
Value value() {
return Value( mongo::Document() );
}
};
/** Coerce [] to bool. */
class ArrayToBool : public ToBoolTrue {
Value value() {
return Value( vector<Value>() );
}
};
/** Coerce Date(0) to bool. */
class DateToBool : public ToBoolTrue {
Value value() { return Value(Date_t(0)); }
};
/** Coerce js literal regex to bool. */
class RegexToBool : public ToBoolTrue {
Value value() { return fromBson( fromjson( "{''://}" ) ); }
};
/** Coerce true to bool. */
class TrueToBool : public ToBoolTrue {
Value value() { return fromBson( BSON( "" << true ) ); }
};
/** Coerce false to bool. */
class FalseToBool : public ToBoolFalse {
Value value() { return fromBson( BSON( "" << false ) ); }
};
/** Coerce null to bool. */
class NullToBool : public ToBoolFalse {
Value value() { return Value(BSONNULL); }
};
/** Coerce undefined to bool. */
class UndefinedToBool : public ToBoolFalse {
Value value() { return Value(BSONUndefined); }
};
class ToIntBase {
public:
virtual ~ToIntBase() {
}
void run() {
if (asserts())
ASSERT_THROWS( value().coerceToInt(), UserException );
else
ASSERT_EQUALS( expected(), value().coerceToInt() );
}
protected:
virtual Value value() = 0;
virtual int expected() { return 0; }
virtual bool asserts() { return false; }
};
/** Coerce -5 to int. */
class IntToInt : public ToIntBase {
Value value() { return Value( -5 ); }
int expected() { return -5; }
};
/** Coerce long to int. */
class LongToInt : public ToIntBase {
Value value() { return Value( 0xff00000007LL ); }
int expected() { return 7; }
};
/** Coerce 9.8 to int. */
class DoubleToInt : public ToIntBase {
Value value() { return Value( 9.8 ); }
int expected() { return 9; }
};
/** Coerce null to int. */
class NullToInt : public ToIntBase {
Value value() { return Value(BSONNULL); }
bool asserts() { return true; }
};
/** Coerce undefined to int. */
class UndefinedToInt : public ToIntBase {
Value value() { return Value(BSONUndefined); }
bool asserts() { return true; }
};
/** Coerce "" to int unsupported. */
class StringToInt {
public:
void run() {
ASSERT_THROWS( Value( "" ).coerceToInt(), UserException );
}
};
class ToLongBase {
public:
virtual ~ToLongBase() {
}
void run() {
if (asserts())
ASSERT_THROWS( value().coerceToLong(), UserException );
else
ASSERT_EQUALS( expected(), value().coerceToLong() );
}
protected:
virtual Value value() = 0;
virtual long long expected() { return 0; }
virtual bool asserts() { return false; }
};
/** Coerce -5 to long. */
class IntToLong : public ToLongBase {
Value value() { return Value( -5 ); }
long long expected() { return -5; }
};
/** Coerce long to long. */
class LongToLong : public ToLongBase {
Value value() { return Value( 0xff00000007LL ); }
long long expected() { return 0xff00000007LL; }
};
/** Coerce 9.8 to long. */
class DoubleToLong : public ToLongBase {
Value value() { return Value( 9.8 ); }
long long expected() { return 9; }
};
/** Coerce null to long. */
class NullToLong : public ToLongBase {
Value value() { return Value(BSONNULL); }
bool asserts() { return true; }
};
/** Coerce undefined to long. */
class UndefinedToLong : public ToLongBase {
Value value() { return Value(BSONUndefined); }
bool asserts() { return true; }
};
/** Coerce string to long unsupported. */
class StringToLong {
public:
void run() {
ASSERT_THROWS( Value( "" ).coerceToLong(), UserException );
}
};
class ToDoubleBase {
public:
virtual ~ToDoubleBase() {
}
void run() {
if (asserts())
ASSERT_THROWS( value().coerceToDouble(), UserException );
else
ASSERT_EQUALS( expected(), value().coerceToDouble() );
}
protected:
virtual Value value() = 0;
virtual double expected() { return 0; }
virtual bool asserts() { return false; }
};
/** Coerce -5 to double. */
class IntToDouble : public ToDoubleBase {
Value value() { return Value( -5 ); }
double expected() { return -5; }
};
/** Coerce long to double. */
class LongToDouble : public ToDoubleBase {
Value value() {
// A long that cannot be exactly represented as a double.
return Value( static_cast<double>( 0x8fffffffffffffffLL ) );
}
double expected() { return static_cast<double>( 0x8fffffffffffffffLL ); }
};
/** Coerce double to double. */
class DoubleToDouble : public ToDoubleBase {
Value value() { return Value( 9.8 ); }
double expected() { return 9.8; }
};
/** Coerce null to double. */
class NullToDouble : public ToDoubleBase {
Value value() { return Value(BSONNULL); }
bool asserts() { return true; }
};
/** Coerce undefined to double. */
class UndefinedToDouble : public ToDoubleBase {
Value value() { return Value(BSONUndefined); }
bool asserts() { return true; }
};
/** Coerce string to double unsupported. */
class StringToDouble {
public:
void run() {
ASSERT_THROWS( Value( "" ).coerceToDouble(), UserException );
}
};
class ToDateBase {
public:
virtual ~ToDateBase() {
}
void run() {
ASSERT_EQUALS( expected(), value().coerceToDate() );
}
protected:
virtual Value value() = 0;
virtual long long expected() = 0;
};
/** Coerce date to date. */
class DateToDate : public ToDateBase {
Value value() { return Value(Date_t(888)); }
long long expected() { return 888; }
};
/**
* Convert timestamp to date. This extracts the time portion of the timestamp, which
* is different from BSON behavior of interpreting all bytes as a date.
*/
class TimestampToDate : public ToDateBase {
Value value() {
return Value( OpTime( 777, 666 ) );
}
long long expected() { return 777 * 1000; }
};
/** Coerce string to date unsupported. */
class StringToDate {
public:
void run() {
ASSERT_THROWS( Value( "" ).coerceToDate(), UserException );
}
};
class ToStringBase {
public:
virtual ~ToStringBase() {
}
void run() {
ASSERT_EQUALS( expected(), value().coerceToString() );
}
protected:
virtual Value value() = 0;
virtual string expected() { return ""; }
};
/** Coerce -0.2 to string. */
class DoubleToString : public ToStringBase {
Value value() { return Value( -0.2 ); }
string expected() { return "-0.2"; }
};
/** Coerce -4 to string. */
class IntToString : public ToStringBase {
Value value() { return Value( -4 ); }
string expected() { return "-4"; }
};
/** Coerce 10000LL to string. */
class LongToString : public ToStringBase {
Value value() { return Value( 10000LL ); }
string expected() { return "10000"; }
};
/** Coerce string to string. */
class StringToString : public ToStringBase {
Value value() { return Value( "fO_o" ); }
string expected() { return "fO_o"; }
};
/** Coerce timestamp to string. */
class TimestampToString : public ToStringBase {
Value value() {
return Value( OpTime( 1, 2 ) );
}
string expected() { return OpTime( 1, 2 ).toStringPretty(); }
};
/** Coerce date to string. */
class DateToString : public ToStringBase {
Value value() { return Value(Date_t(1234567890LL*1000)); }
string expected() { return "2009-02-13T23:31:30"; } // from js
};
/** Coerce null to string. */
class NullToString : public ToStringBase {
Value value() { return Value(BSONNULL); }
};
/** Coerce undefined to string. */
class UndefinedToString : public ToStringBase {
Value value() { return Value(BSONUndefined); }
};
/** Coerce document to string unsupported. */
class DocumentToString {
public:
void run() {
ASSERT_THROWS( Value
( mongo::Document() ).coerceToString(),
UserException );
}
};
/** Coerce timestamp to timestamp. */
class TimestampToTimestamp {
public:
void run() {
Value value = Value( OpTime( 1010 ) );
ASSERT( OpTime( 1010 ) == value.coerceToTimestamp() );
}
};
/** Coerce date to timestamp unsupported. */
class DateToTimestamp {
public:
void run() {
ASSERT_THROWS( Value(Date_t(1010)).coerceToTimestamp(),
UserException );
}
};
} // namespace Coerce
/** Get the "widest" of two numeric types. */
class GetWidestNumeric {
public:
void run() {
using mongo::Undefined;
// Numeric types.
assertWidest( NumberInt, NumberInt, NumberInt );
assertWidest( NumberLong, NumberInt, NumberLong );
assertWidest( NumberDouble, NumberInt, NumberDouble );
assertWidest( NumberLong, NumberLong, NumberLong );
assertWidest( NumberDouble, NumberLong, NumberDouble );
assertWidest( NumberDouble, NumberDouble, NumberDouble );
// Missing value and numeric types (result Undefined).
assertWidest( Undefined, NumberInt, Undefined );
assertWidest( Undefined, NumberInt, Undefined );
assertWidest( Undefined, NumberLong, jstNULL );
assertWidest( Undefined, NumberLong, Undefined );
assertWidest( Undefined, NumberDouble, jstNULL );
assertWidest( Undefined, NumberDouble, Undefined );
// Missing value types (result Undefined).
assertWidest( Undefined, jstNULL, jstNULL );
assertWidest( Undefined, jstNULL, Undefined );
assertWidest( Undefined, Undefined, Undefined );
// Other types (result Undefined).
assertWidest( Undefined, NumberInt, mongo::Bool );
assertWidest( Undefined, mongo::String, NumberDouble );
}
private:
void assertWidest( BSONType expectedWidest, BSONType a, BSONType b ) {
ASSERT_EQUALS( expectedWidest, Value::getWidestNumeric( a, b ) );
ASSERT_EQUALS( expectedWidest, Value::getWidestNumeric( b, a ) );
}
};
/** Add a Value to a BSONObj. */
class AddToBsonObj {
public:
void run() {
BSONObjBuilder bob;
Value( 4.4 ).addToBsonObj( &bob, "a" );
Value( 22 ).addToBsonObj( &bob, "b" );
Value( "astring" ).addToBsonObj( &bob, "c" );
ASSERT_EQUALS( BSON( "a" << 4.4 << "b" << 22 << "c" << "astring" ), bob.obj() );
}
};
/** Add a Value to a BSONArray. */
class AddToBsonArray {
public:
void run() {
BSONArrayBuilder bab;
Value( 4.4 ).addToBsonArray( &bab );
Value( 22 ).addToBsonArray( &bab );
Value( "astring" ).addToBsonArray( &bab );
ASSERT_EQUALS( BSON_ARRAY( 4.4 << 22 << "astring" ), bab.arr() );
}
};
/** Value comparator. */
class Compare {
public:
void run() {
BSONObjBuilder undefinedBuilder;
undefinedBuilder.appendUndefined( "" );
BSONObj undefined = undefinedBuilder.obj();
// Undefined / null.
assertComparison( 0, undefined, undefined );
assertComparison( -1, undefined, BSON( "" << BSONNULL ) );
assertComparison( 0, BSON( "" << BSONNULL ), BSON( "" << BSONNULL ) );
// Undefined / null with other types.
assertComparison( -1, undefined, BSON( "" << 1 ) );
assertComparison( -1, undefined, BSON( "" << "bar" ) );
assertComparison( -1, BSON( "" << BSONNULL ), BSON( "" << -1 ) );
assertComparison( -1, BSON( "" << BSONNULL ), BSON( "" << "bar" ) );
// Numeric types.
assertComparison( 0, 5, 5LL );
assertComparison( 0, -2, -2.0 );
assertComparison( 0, 90LL, 90.0 );
assertComparison( -1, 5, 6LL );
assertComparison( -1, -2, 2.1 );
assertComparison( 1, 90LL, 89.999 );
assertComparison( -1, 90, 90.1 );
assertComparison( 0, numeric_limits<double>::quiet_NaN(),
numeric_limits<double>::signaling_NaN() );
assertComparison( -1, numeric_limits<double>::quiet_NaN(), 5 );
// strings compare between numbers and objects
assertComparison( 1, "abc", 90 );
assertComparison( -1, "abc", BSON( "a" << "b" ) );
// String comparison.
assertComparison( -1, "", "a" );
assertComparison( 0, "a", "a" );
assertComparison( -1, "a", "b" );
assertComparison( -1, "aa", "b" );
assertComparison( 1, "bb", "b" );
assertComparison( 1, "bb", "b" );
assertComparison( 1, "b-", "b" );
assertComparison( -1, "b-", "ba" );
// With a null character.
assertComparison( 1, string( "a\0", 2 ), "a" );
// Object.
assertComparison( 0, fromjson( "{'':{}}" ), fromjson( "{'':{}}" ) );
assertComparison( 0, fromjson( "{'':{x:1}}" ), fromjson( "{'':{x:1}}" ) );
assertComparison( -1, fromjson( "{'':{}}" ), fromjson( "{'':{x:1}}" ) );
assertComparison( -1, fromjson( "{'':{'z': 1}}" ), fromjson( "{'':{'a': 'a'}}") );
// Array.
assertComparison( 0, fromjson( "{'':[]}" ), fromjson( "{'':[]}" ) );
assertComparison( -1, fromjson( "{'':[0]}" ), fromjson( "{'':[1]}" ) );
assertComparison( -1, fromjson( "{'':[0,0]}" ), fromjson( "{'':[1]}" ) );
assertComparison( -1, fromjson( "{'':[0]}" ), fromjson( "{'':[0,0]}" ) );
assertComparison( -1, fromjson( "{'':[0]}" ), fromjson( "{'':['']}" ) );
// OID.
assertComparison( 0, OID( "abcdefabcdefabcdefabcdef" ),
OID( "abcdefabcdefabcdefabcdef" ) );
assertComparison( 1, OID( "abcdefabcdefabcdefabcdef" ),
OID( "010101010101010101010101" ) );
// Bool.
assertComparison( 0, true, true );
assertComparison( 0, false, false );
assertComparison( 1, true, false );
// Date.
assertComparison( 0, Date_t( 555 ), Date_t( 555 ) );
assertComparison( 1, Date_t( 555 ), Date_t( 554 ) );
// Negative date.
assertComparison( 1, Date_t( 0 ), Date_t( -1 ) );
// Regex.
assertComparison( 0, fromjson( "{'':/a/}" ), fromjson( "{'':/a/}" ) );
assertComparison( -1, fromjson( "{'':/a/}" ), fromjson( "{'':/a/i}" ) );
assertComparison( -1, fromjson( "{'':/a/}" ), fromjson( "{'':/aa/}" ) );
// Timestamp.
assertComparison( 0, OpTime( 1234 ), OpTime( 1234 ) );
assertComparison( -1, OpTime( 4 ), OpTime( 1234 ) );
// Cross-type comparisons. Listed in order of canonical types.
assertComparison(-1, Value(mongo::MINKEY), Value());
assertComparison(0, Value(), Value());
assertComparison(0, Value(), Value(BSONUndefined));
assertComparison(-1, Value(BSONUndefined), Value(BSONNULL));
assertComparison(-1, Value(BSONNULL), Value(1));
assertComparison(0, Value(1), Value(1LL));
assertComparison(0, Value(1), Value(1.0));
assertComparison(-1, Value(1), Value("string"));
assertComparison(0, Value("string"), Value(BSONSymbol("string")));
assertComparison(-1, Value("string"), Value(mongo::Document()));
assertComparison(-1, Value(mongo::Document()), Value(vector<Value>()));
assertComparison(-1, Value(vector<Value>()), Value(BSONBinData("", 0, MD5Type)));
assertComparison(-1, Value(BSONBinData("", 0, MD5Type)), Value(mongo::OID()));
assertComparison(-1, Value(mongo::OID()), Value(false));
assertComparison(-1, Value(false), Value(Date_t(0)));
assertComparison(-1, Value(Date_t(0)), Value(OpTime()));
assertComparison(-1, Value(OpTime()), Value(BSONRegEx("")));
assertComparison(-1, Value(BSONRegEx("")), Value(BSONDBRef("", mongo::OID())));
assertComparison(-1, Value(BSONDBRef("", mongo::OID())), Value(BSONCode("")));
assertComparison(-1, Value(BSONCode("")), Value(BSONCodeWScope("", BSONObj())));
assertComparison(-1, Value(BSONCodeWScope("", BSONObj())), Value(mongo::MAXKEY));
}
private:
template<class T,class U>
void assertComparison( int expectedResult, const T& a, const U& b ) {
assertComparison( expectedResult, BSON( "" << a ), BSON( "" << b ) );
}
void assertComparison( int expectedResult, const OpTime& a, const OpTime& b ) {
BSONObjBuilder first;
first.appendTimestamp( "", a.asDate() );
BSONObjBuilder second;
second.appendTimestamp( "", b.asDate() );
assertComparison( expectedResult, first.obj(), second.obj() );
}
int sign(int cmp) {
if (cmp == 0) return 0;
else if (cmp < 0) return -1;
else return 1;
}
int cmp( const Value& a, const Value& b ) {
return sign(Value::compare(a, b));
}
void assertComparison( int expectedResult, const BSONObj& a, const BSONObj& b ) {
assertComparison(expectedResult, fromBson(a), fromBson(b));
}
void assertComparison(int expectedResult, const Value& a, const Value& b) {
mongo::unittest::log() <<
"testing " << a.toString() << " and " << b.toString() << endl;
// reflexivity
ASSERT_EQUALS(0, cmp(a, a));
ASSERT_EQUALS(0, cmp(b, b));
// symmetry
ASSERT_EQUALS( expectedResult, cmp( a, b ) );
ASSERT_EQUALS( -expectedResult, cmp( b, a ) );
if ( expectedResult == 0 ) {
// equal values must hash equally.
ASSERT_EQUALS( hash( a ), hash( b ) );
}
else {
// unequal values must hash unequally.
// (not true in general but we should error if it fails in any of these cases)
ASSERT_NOT_EQUALS( hash( a ), hash( b ) );
}
// same as BSON
ASSERT_EQUALS(expectedResult, sign(toBson(a).firstElement().woCompare(
toBson(b).firstElement())));
}
size_t hash(const Value& v) {
size_t seed = 0xf00ba6;
v.hash_combine( seed );
return seed;
}
};
class SubFields {
public:
void run() {
const Value val = fromBson(fromjson(
"{'': {a: [{x:1, b:[1, {y:1, c:1234, z:1}, 1]}]}}"));
// ^ this outer object is removed by fromBson
ASSERT(val.getType() == mongo::Object);
ASSERT(val[999].missing());
ASSERT(val["missing"].missing());
ASSERT(val["a"].getType() == mongo::Array);
ASSERT(val["a"][999].missing());
ASSERT(val["a"]["missing"].missing());
ASSERT(val["a"][0].getType() == mongo::Object);
ASSERT(val["a"][0][999].missing());
ASSERT(val["a"][0]["missing"].missing());
ASSERT(val["a"][0]["b"].getType() == mongo::Array);
ASSERT(val["a"][0]["b"][999].missing());
ASSERT(val["a"][0]["b"]["missing"].missing());
ASSERT(val["a"][0]["b"][1].getType() == mongo::Object);
ASSERT(val["a"][0]["b"][1][999].missing());
ASSERT(val["a"][0]["b"][1]["missing"].missing());
ASSERT(val["a"][0]["b"][1]["c"].getType() == mongo::NumberInt);
ASSERT_EQUALS(val["a"][0]["b"][1]["c"].getInt(), 1234);
}
};
class SerializationOfMissingForSorter {
// Can't be tested in AllTypesDoc since missing values are omitted when adding to BSON.
public:
void run() {
const Value missing;
const Value arrayOfMissing = Value(vector<Value>(10));
BufBuilder bb;
missing.serializeForSorter(bb);
arrayOfMissing.serializeForSorter(bb);
BufReader reader(bb.buf(), bb.len());
ASSERT_EQUALS(
missing,
Value::deserializeForSorter(reader, Value::SorterDeserializeSettings()));
ASSERT_EQUALS(
arrayOfMissing,
Value::deserializeForSorter(reader, Value::SorterDeserializeSettings()));
}
};
} // namespace Value
class All : public Suite {
public:
All() : Suite( "document" ) {
}
void setupTests() {
add<Document::Create>();
add<Document::CreateFromBsonObj>();
add<Document::AddField>();
add<Document::GetValue>();
add<Document::SetField>();
add<Document::Compare>();
add<Document::Clone>();
add<Document::CloneMultipleFields>();
add<Document::FieldIteratorEmpty>();
add<Document::FieldIteratorSingle>();
add<Document::FieldIteratorMultiple>();
add<Document::AllTypesDoc>();
add<Value::BSONArrayTest>();
add<Value::Int>();
add<Value::Long>();
add<Value::Double>();
add<Value::String>();
add<Value::StringWithNull>();
add<Value::Date>();
add<Value::Timestamp>();
add<Value::EmptyDocument>();
add<Value::EmptyArray>();
add<Value::Array>();
add<Value::Oid>();
add<Value::Bool>();
add<Value::Regex>();
add<Value::Symbol>();
add<Value::Undefined>();
add<Value::Null>();
add<Value::True>();
add<Value::False>();
add<Value::MinusOne>();
add<Value::Zero>();
add<Value::One>();
add<Value::Coerce::ZeroIntToBool>();
add<Value::Coerce::NonZeroIntToBool>();
add<Value::Coerce::ZeroLongToBool>();
add<Value::Coerce::NonZeroLongToBool>();
add<Value::Coerce::ZeroDoubleToBool>();
add<Value::Coerce::NonZeroDoubleToBool>();
add<Value::Coerce::StringToBool>();
add<Value::Coerce::ObjectToBool>();
add<Value::Coerce::ArrayToBool>();
add<Value::Coerce::DateToBool>();
add<Value::Coerce::RegexToBool>();
add<Value::Coerce::TrueToBool>();
add<Value::Coerce::FalseToBool>();
add<Value::Coerce::NullToBool>();
add<Value::Coerce::UndefinedToBool>();
add<Value::Coerce::IntToInt>();
add<Value::Coerce::LongToInt>();
add<Value::Coerce::DoubleToInt>();
add<Value::Coerce::NullToInt>();
add<Value::Coerce::UndefinedToInt>();
add<Value::Coerce::StringToInt>();
add<Value::Coerce::IntToLong>();
add<Value::Coerce::LongToLong>();
add<Value::Coerce::DoubleToLong>();
add<Value::Coerce::NullToLong>();
add<Value::Coerce::UndefinedToLong>();
add<Value::Coerce::StringToLong>();
add<Value::Coerce::IntToDouble>();
add<Value::Coerce::LongToDouble>();
add<Value::Coerce::DoubleToDouble>();
add<Value::Coerce::NullToDouble>();
add<Value::Coerce::UndefinedToDouble>();
add<Value::Coerce::StringToDouble>();
add<Value::Coerce::DateToDate>();
add<Value::Coerce::TimestampToDate>();
add<Value::Coerce::StringToDate>();
add<Value::Coerce::DoubleToString>();
add<Value::Coerce::IntToString>();
add<Value::Coerce::LongToString>();
add<Value::Coerce::StringToString>();
add<Value::Coerce::TimestampToString>();
add<Value::Coerce::DateToString>();
add<Value::Coerce::NullToString>();
add<Value::Coerce::UndefinedToString>();
add<Value::Coerce::DocumentToString>();
add<Value::Coerce::TimestampToTimestamp>();
add<Value::Coerce::DateToTimestamp>();
add<Value::GetWidestNumeric>();
add<Value::AddToBsonObj>();
add<Value::AddToBsonArray>();
add<Value::Compare>();
add<Value::SubFields>();
add<Value::SerializationOfMissingForSorter>();
}
};
SuiteInstance<All> myall;
} // namespace DocumentTests
| 39.901455 | 100 | 0.469526 | [
"object",
"vector"
] |
28ec3f9954576d78153e9d0f57e22a240e950639 | 13,763 | cpp | C++ | src/tests/containerizer/nvidia_gpu_isolator_tests.cpp | prateek-s/mesos | 4b81147797e4d9a45e0b2f5e5634d4a214dbc4e8 | [
"Apache-2.0"
] | 2 | 2019-02-08T21:29:57.000Z | 2021-07-27T06:59:19.000Z | src/tests/containerizer/nvidia_gpu_isolator_tests.cpp | prateek-s/mesos | 4b81147797e4d9a45e0b2f5e5634d4a214dbc4e8 | [
"Apache-2.0"
] | null | null | null | src/tests/containerizer/nvidia_gpu_isolator_tests.cpp | prateek-s/mesos | 4b81147797e4d9a45e0b2f5e5634d4a214dbc4e8 | [
"Apache-2.0"
] | null | null | null | // 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 <set>
#include <vector>
#include <gmock/gmock.h>
#include <mesos/resources.hpp>
#include <mesos/scheduler.hpp>
#include <mesos/master/detector.hpp>
#include <process/future.hpp>
#include <process/gtest.hpp>
#include <process/owned.hpp>
#include <stout/jsonify.hpp>
#include "master/master.hpp"
#include "slave/slave.hpp"
#include "slave/containerizer/containerizer.hpp"
#include "slave/containerizer/fetcher.hpp"
#include "slave/containerizer/mesos/isolators/gpu/allocator.hpp"
#include "slave/containerizer/mesos/isolators/gpu/nvml.hpp"
#include "tests/mesos.hpp"
using mesos::internal::master::Master;
using mesos::internal::slave::Containerizer;
using mesos::internal::slave::Fetcher;
using mesos::internal::slave::Gpu;
using mesos::internal::slave::MesosContainerizer;
using mesos::internal::slave::MesosContainerizerProcess;
using mesos::internal::slave::NvidiaGpuAllocator;
using mesos::internal::slave::Slave;
using mesos::master::detector::MasterDetector;
using process::Future;
using process::Owned;
using std::set;
using std::vector;
using testing::_;
using testing::Eq;
using testing::Return;
namespace mesos {
namespace internal {
namespace tests {
class NvidiaGpuTest : public MesosTest {};
// This test verifies that we are able to enable the Nvidia GPU
// isolator and launch tasks with restricted access to GPUs. We
// first launch a task with access to 0 GPUs and verify that a
// call to `nvidia-smi` fails. We then launch a task with 1 GPU
// and verify that a call to `nvidia-smi` both succeeds and
// reports exactly 1 GPU available.
TEST_F(NvidiaGpuTest, ROOT_CGROUPS_NVIDIA_GPU_VerifyDeviceAccess)
{
Try<Owned<cluster::Master>> master = StartMaster();
ASSERT_SOME(master);
// Turn on Nvidia GPU isolation.
// Assume at least one GPU is available for isolation.
slave::Flags flags = CreateSlaveFlags();
flags.isolation = "cgroups/devices,gpu/nvidia";
flags.nvidia_gpu_devices = vector<unsigned int>({0u});
flags.resources = "gpus:1";
Owned<MasterDetector> detector = master.get()->createDetector();
Try<Owned<cluster::Slave>> slave = StartSlave(detector.get(), flags);
ASSERT_SOME(slave);
MockScheduler sched;
FrameworkInfo frameworkInfo = DEFAULT_FRAMEWORK_INFO;
frameworkInfo.add_capabilities()->set_type(
FrameworkInfo::Capability::GPU_RESOURCES);
MesosSchedulerDriver driver(
&sched, frameworkInfo, master.get()->pid, DEFAULT_CREDENTIAL);
Future<Nothing> schedRegistered;
EXPECT_CALL(sched, registered(_, _, _))
.WillOnce(FutureSatisfy(&schedRegistered));
Future<vector<Offer>> offers1, offers2;
EXPECT_CALL(sched, resourceOffers(_, _))
.WillOnce(FutureArg<1>(&offers1))
.WillOnce(FutureArg<1>(&offers2))
.WillRepeatedly(Return()); // Ignore subsequent offers.
driver.start();
AWAIT_READY(schedRegistered);
// Launch a task requesting no GPUs and
// verify that running `nvidia-smi` fails.
AWAIT_READY(offers1);
EXPECT_EQ(1u, offers1->size());
TaskInfo task1 = createTask(
offers1.get()[0].slave_id(),
Resources::parse("cpus:0.1;mem:128;").get(),
"nvidia-smi");
Future<TaskStatus> statusRunning1, statusFailed1;
EXPECT_CALL(sched, statusUpdate(_, _))
.WillOnce(FutureArg<1>(&statusRunning1))
.WillOnce(FutureArg<1>(&statusFailed1));
driver.launchTasks(offers1.get()[0].id(), {task1});
AWAIT_READY(statusRunning1);
ASSERT_EQ(TASK_RUNNING, statusRunning1->state());
AWAIT_READY(statusFailed1);
ASSERT_EQ(TASK_FAILED, statusFailed1->state());
// Launch a task requesting 1 GPU and verify
// that `nvidia-smi` lists exactly one GPU.
AWAIT_READY(offers2);
EXPECT_EQ(1u, offers2->size());
TaskInfo task2 = createTask(
offers1.get()[0].slave_id(),
Resources::parse("cpus:0.1;mem:128;gpus:1").get(),
"NUM_GPUS=`nvidia-smi --list-gpus | wc -l`;\n"
"if [ \"$NUM_GPUS\" != \"1\" ]; then\n"
" exit 1;\n"
"fi");
Future<TaskStatus> statusRunning2, statusFinished2;
EXPECT_CALL(sched, statusUpdate(_, _))
.WillOnce(FutureArg<1>(&statusRunning2))
.WillOnce(FutureArg<1>(&statusFinished2));
driver.launchTasks(offers2.get()[0].id(), {task2});
AWAIT_READY(statusRunning2);
ASSERT_EQ(TASK_RUNNING, statusRunning2->state());
AWAIT_READY(statusFinished2);
ASSERT_EQ(TASK_FINISHED, statusFinished2->state());
driver.stop();
driver.join();
}
// This test verifies correct failure semantics when
// a task requests a fractional number of GPUs.
TEST_F(NvidiaGpuTest, ROOT_CGROUPS_NVIDIA_GPU_FractionalResources)
{
Try<Owned<cluster::Master>> master = StartMaster();
ASSERT_SOME(master);
// Turn on Nvidia GPU isolation.
// Assume at least one GPU is available for isolation.
slave::Flags flags = CreateSlaveFlags();
flags.isolation = "cgroups/devices,gpu/nvidia";
flags.nvidia_gpu_devices = vector<unsigned int>({0u});
flags.resources = "gpus:1";
Owned<MasterDetector> detector = master.get()->createDetector();
Try<Owned<cluster::Slave>> slave = StartSlave(detector.get(), flags);
ASSERT_SOME(slave);
MockScheduler sched;
FrameworkInfo frameworkInfo = DEFAULT_FRAMEWORK_INFO;
frameworkInfo.add_capabilities()->set_type(
FrameworkInfo::Capability::GPU_RESOURCES);
MesosSchedulerDriver driver(
&sched, frameworkInfo, master.get()->pid, DEFAULT_CREDENTIAL);
Future<Nothing> schedRegistered;
EXPECT_CALL(sched, registered(_, _, _))
.WillOnce(FutureSatisfy(&schedRegistered));
Future<vector<Offer>> offers;
EXPECT_CALL(sched, resourceOffers(_, _))
.WillOnce(FutureArg<1>(&offers))
.WillRepeatedly(Return()); // Ignore subsequent offers.
driver.start();
AWAIT_READY(schedRegistered);
// Launch a task requesting a fractional number
// of GPUs and verify that it fails as expected.
AWAIT_READY(offers);
EXPECT_EQ(1u, offers->size());
TaskInfo task = createTask(
offers.get()[0].slave_id(),
Resources::parse("cpus:0.1;mem:128;gpus:0.1").get(),
"true");
Future<TaskStatus> status;
EXPECT_CALL(sched, statusUpdate(_, _))
.WillOnce(FutureArg<1>(&status));
driver.launchTasks(offers.get()[0].id(), {task});
AWAIT_READY(status);
EXPECT_EQ(TASK_ERROR, status->state());
EXPECT_EQ(TaskStatus::REASON_TASK_INVALID, status->reason());
EXPECT_TRUE(strings::contains(
status->message(),
"The 'gpus' resource must be an unsigned integer"));
driver.stop();
driver.join();
}
// Ensures that GPUs can be auto-discovered.
TEST_F(NvidiaGpuTest, NVIDIA_GPU_Discovery)
{
ASSERT_TRUE(nvml::isAvailable());
ASSERT_SOME(nvml::initialize());
Try<unsigned int> gpus = nvml::deviceGetCount();
ASSERT_SOME(gpus);
slave::Flags flags = CreateSlaveFlags();
flags.resources = "cpus:1"; // To override the default with gpus:0.
flags.isolation = "gpu/nvidia";
Try<Resources> resources = Containerizer::resources(flags);
ASSERT_SOME(resources);
ASSERT_SOME(resources->gpus());
ASSERT_EQ(gpus.get(), resources->gpus().get());
}
// Ensures that the --resources and --nvidia_gpu_devices
// flags are correctly validated.
TEST_F(NvidiaGpuTest, ROOT_CGROUPS_NVIDIA_GPU_FlagValidation)
{
ASSERT_TRUE(nvml::isAvailable());
ASSERT_SOME(nvml::initialize());
Try<unsigned int> gpus = nvml::deviceGetCount();
ASSERT_SOME(gpus);
// Not setting the `gpu/nvidia` isolation flag
// should not trigger-autodiscovery!
slave::Flags flags = CreateSlaveFlags();
Try<Resources> resources = NvidiaGpuAllocator::resources(flags);
ASSERT_SOME(resources);
ASSERT_NONE(resources->gpus());
// Setting `--nvidia_gpu_devices` without the `gpu/nvidia`
// isolation flag should trigger an error.
flags = CreateSlaveFlags();
flags.nvidia_gpu_devices = vector<unsigned int>({0u});
flags.resources = "gpus:1";
resources = Containerizer::resources(flags);
ASSERT_ERROR(resources);
// Setting GPUs without the `gpu/nvidia` isolation
// flag should just pass them through without an error.
flags = CreateSlaveFlags();
flags.resources = "gpus:100";
resources = Containerizer::resources(flags);
ASSERT_SOME(resources);
ASSERT_SOME(resources->gpus());
ASSERT_EQ(100u, resources->gpus().get());
// Setting the `gpu/nvidia` isolation
// flag should trigger autodiscovery.
flags = CreateSlaveFlags();
flags.resources = "cpus:1"; // To override the default with gpus:0.
flags.isolation = "gpu/nvidia";
resources = NvidiaGpuAllocator::resources(flags);
ASSERT_SOME(resources);
ASSERT_SOME(resources->gpus());
ASSERT_EQ(gpus.get(), resources->gpus().get());
// Setting the GPUs to 0 should not trigger auto-discovery!
flags = CreateSlaveFlags();
flags.resources = "gpus:0";
flags.isolation = "gpu/nvidia";
resources = Containerizer::resources(flags);
ASSERT_SOME(resources);
ASSERT_NONE(resources->gpus());
// --nvidia_gpu_devices and --resources agree on the number of GPUs.
flags = CreateSlaveFlags();
flags.nvidia_gpu_devices = vector<unsigned int>({0u});
flags.resources = "gpus:1";
flags.isolation = "gpu/nvidia";
resources = NvidiaGpuAllocator::resources(flags);
ASSERT_SOME(resources);
ASSERT_SOME(resources->gpus());
ASSERT_EQ(1u, resources->gpus().get());
// Both --resources and --nvidia_gpu_devices must be specified!
flags = CreateSlaveFlags();
flags.nvidia_gpu_devices = vector<unsigned int>({0u});
flags.resources = "cpus:1"; // To override the default with gpus:0.
flags.isolation = "gpu/nvidia";
resources = NvidiaGpuAllocator::resources(flags);
ASSERT_ERROR(resources);
flags = CreateSlaveFlags();
flags.resources = "gpus:" + stringify(gpus.get());
flags.isolation = "gpu/nvidia";
resources = NvidiaGpuAllocator::resources(flags);
ASSERT_ERROR(resources);
// --nvidia_gpu_devices and --resources do not match!
flags = CreateSlaveFlags();
flags.nvidia_gpu_devices = vector<unsigned int>({0u});
flags.resources = "gpus:2";
flags.isolation = "gpu/nvidia";
resources = NvidiaGpuAllocator::resources(flags);
ASSERT_ERROR(resources);
flags = CreateSlaveFlags();
flags.nvidia_gpu_devices = vector<unsigned int>({0u});
flags.resources = "gpus:0";
flags.isolation = "gpu/nvidia";
resources = NvidiaGpuAllocator::resources(flags);
ASSERT_ERROR(resources);
// More than available on the machine!
flags = CreateSlaveFlags();
flags.nvidia_gpu_devices = vector<unsigned int>();
flags.resources = "gpus:" + stringify(2 * gpus.get());
flags.isolation = "gpu/nvidia";
for (size_t i = 0; i < 2 * gpus.get(); ++i) {
flags.nvidia_gpu_devices->push_back(i);
}
resources = NvidiaGpuAllocator::resources(flags);
ASSERT_ERROR(resources);
// Set `nvidia_gpu_devices` to contain duplicates.
flags = CreateSlaveFlags();
flags.nvidia_gpu_devices = vector<unsigned int>({0u, 0u});
flags.resources = "cpus:1;gpus:1";
flags.isolation = "gpu/nvidia";
resources = NvidiaGpuAllocator::resources(flags);
ASSERT_ERROR(resources);
}
// Test proper allocation / deallocation of GPU devices.
TEST_F(NvidiaGpuTest, NVIDIA_GPU_Allocator)
{
ASSERT_TRUE(nvml::isAvailable());
ASSERT_SOME(nvml::initialize());
slave::Flags flags = CreateSlaveFlags();
flags.resources = "cpus:1"; // To override the default with gpus:0.
flags.isolation = "gpu/nvidia";
Try<Resources> resources = NvidiaGpuAllocator::resources(flags);
ASSERT_SOME(resources);
Try<NvidiaGpuAllocator> allocator =
NvidiaGpuAllocator::create(flags, resources.get());
ASSERT_SOME(allocator);
Try<unsigned int> total = nvml::deviceGetCount();
ASSERT_SOME(total);
ASSERT_GE(total.get(), 1u);
ASSERT_EQ(total.get(), allocator->total().size());
// Allocate all GPUs at once.
Future<set<Gpu>> gpus = allocator->allocate(total.get());
AWAIT_READY(gpus);
ASSERT_EQ(total.get(), gpus->size());
// Make sure there are no GPUs left to allocate.
AWAIT_FAILED(allocator->allocate(1));
// Free all GPUs at once and reallocate them by reference.
AWAIT_READY(allocator->deallocate(gpus.get()));
AWAIT_READY(allocator->allocate(gpus.get()));
// Free 1 GPU back and reallocate it. Make sure they are the same.
AWAIT_READY(allocator->deallocate({ *gpus->begin() }));
Future<set<Gpu>> gpu = allocator->allocate(1);
AWAIT_READY(gpu);
ASSERT_EQ(*gpus->begin(), *gpu->begin());
// Attempt to free the same GPU twice.
AWAIT_READY(allocator->deallocate({ *gpus->begin() }));
AWAIT_FAILED(allocator->deallocate({ *gpus->begin() }));
// Allocate a specific GPU by reference.
AWAIT_READY(allocator->allocate({ *gpus->begin() }));
// Attempt to free a bogus GPU.
Gpu bogus;
bogus.major = 999;
bogus.minor = 999;
AWAIT_FAILED(allocator->deallocate({ bogus }));
// Free all GPUs.
AWAIT_READY(allocator->deallocate(gpus.get()));
// Attempt to allocate a bogus GPU.
AWAIT_FAILED(allocator->allocate({ bogus }));
}
} // namespace tests {
} // namespace internal {
} // namespace mesos {
| 29.40812 | 75 | 0.716196 | [
"vector"
] |
28edb86df0390251252a5385685afe3b857953c3 | 5,269 | cc | C++ | chrome/browser/ui/webui/sync_internals_message_handler.cc | anirudhSK/chromium | a8f23c87e656ab9ba49de9ccccbc53f614cdcb41 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | chrome/browser/ui/webui/sync_internals_message_handler.cc | anirudhSK/chromium | a8f23c87e656ab9ba49de9ccccbc53f614cdcb41 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | chrome/browser/ui/webui/sync_internals_message_handler.cc | anirudhSK/chromium | a8f23c87e656ab9ba49de9ccccbc53f614cdcb41 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 2 | 2015-04-17T13:19:09.000Z | 2021-10-21T12:55:15.000Z | // Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/ui/webui/sync_internals_message_handler.h"
#include <vector>
#include "base/logging.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/sync/about_sync_util.h"
#include "chrome/browser/sync/profile_sync_service.h"
#include "chrome/browser/sync/profile_sync_service_factory.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/web_ui.h"
#include "sync/internal_api/public/util/weak_handle.h"
#include "sync/js/js_arg_list.h"
#include "sync/js/js_event_details.h"
using syncer::JsArgList;
using syncer::JsEventDetails;
using syncer::JsReplyHandler;
using syncer::ModelTypeSet;
using syncer::WeakHandle;
SyncInternalsMessageHandler::SyncInternalsMessageHandler()
: scoped_observer_(this),
weak_ptr_factory_(this) {}
SyncInternalsMessageHandler::~SyncInternalsMessageHandler() {
if (js_controller_)
js_controller_->RemoveJsEventHandler(this);
}
void SyncInternalsMessageHandler::RegisterMessages() {
DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));
// Register for ProfileSyncService events.
ProfileSyncService* service = GetProfileSyncService();
if (service) {
scoped_observer_.Add(service);
js_controller_ = service->GetJsController();
js_controller_->AddJsEventHandler(this);
}
web_ui()->RegisterMessageCallback(
"requestUpdatedAboutInfo",
base::Bind(&SyncInternalsMessageHandler::HandleRequestUpdatedAboutInfo,
base::Unretained(this)));
web_ui()->RegisterMessageCallback(
"requestListOfTypes",
base::Bind(&SyncInternalsMessageHandler::HandleRequestListOfTypes,
base::Unretained(this)));
RegisterJsControllerCallback("getNotificationState");
RegisterJsControllerCallback("getNotificationInfo");
RegisterJsControllerCallback("getAllNodes");
RegisterJsControllerCallback("getClientServerTraffic");
}
void SyncInternalsMessageHandler::HandleRequestUpdatedAboutInfo(
const base::ListValue* args) {
DCHECK(args->empty());
SendAboutInfo();
}
void SyncInternalsMessageHandler::HandleRequestListOfTypes(
const base::ListValue* args) {
DCHECK(args->empty());
base::DictionaryValue event_details;
scoped_ptr<base::ListValue> type_list(new base::ListValue());
ModelTypeSet protocol_types = syncer::ProtocolTypes();
for (ModelTypeSet::Iterator it = protocol_types.First();
it.Good(); it.Inc()) {
type_list->Append(new base::StringValue(ModelTypeToString(it.Get())));
}
event_details.Set("types", type_list.release());
web_ui()->CallJavascriptFunction(
"chrome.sync.dispatchEvent",
base::StringValue("onReceivedListOfTypes"),
event_details);
}
void SyncInternalsMessageHandler::HandleJsReply(
const std::string& name, const JsArgList& args) {
DVLOG(1) << "Handling reply for " << name << " message"
<< " with args " << args.ToString();
const std::string& reply_handler = "chrome.sync." + name + ".handleReply";
std::vector<const base::Value*> arg_list(args.Get().begin(),
args.Get().end());
web_ui()->CallJavascriptFunction(reply_handler, arg_list);
}
void SyncInternalsMessageHandler::OnStateChanged() {
SendAboutInfo();
}
void SyncInternalsMessageHandler::HandleJsEvent(
const std::string& name,
const JsEventDetails& details) {
DVLOG(1) << "Handling event: " << name
<< " with details " << details.ToString();
web_ui()->CallJavascriptFunction("chrome.sync.dispatchEvent",
base::StringValue(name),
details.Get());
}
void SyncInternalsMessageHandler::RegisterJsControllerCallback(
const std::string& name) {
web_ui()->RegisterMessageCallback(
name,
base::Bind(&SyncInternalsMessageHandler::ForwardToJsController,
base::Unretained(this),
name));
}
void SyncInternalsMessageHandler::SendAboutInfo() {
scoped_ptr<base::DictionaryValue> value =
sync_ui_util::ConstructAboutInformation(GetProfileSyncService());
web_ui()->CallJavascriptFunction(
"chrome.sync.dispatchEvent",
base::StringValue("onAboutInfoUpdated"),
*value);
}
void SyncInternalsMessageHandler::ForwardToJsController(
const std::string& name,
const base::ListValue* args) {
if (js_controller_) {
scoped_ptr<base::ListValue> args_copy(args->DeepCopy());
JsArgList js_arg_list(args_copy.get());
js_controller_->ProcessJsMessage(
name, js_arg_list,
MakeWeakHandle(weak_ptr_factory_.GetWeakPtr()));
} else {
DLOG(WARNING) << "No sync service; dropping message " << name;
}
}
// Gets the ProfileSyncService of the underlying original profile.
// May return NULL (e.g., if sync is disabled on the command line).
ProfileSyncService* SyncInternalsMessageHandler::GetProfileSyncService() {
Profile* profile = Profile::FromWebUI(web_ui());
ProfileSyncServiceFactory* factory = ProfileSyncServiceFactory::GetInstance();
return factory->GetForProfile(profile->GetOriginalProfile());
}
| 35.362416 | 80 | 0.722338 | [
"vector"
] |
28ef39ce912d5a73f7efab9212d0926b8073224a | 1,106 | cpp | C++ | main.cpp | Fastbee1/ModernTechLab | 1c096a66cb3f445219ef1ff10eb74a79770bba27 | [
"MIT"
] | null | null | null | main.cpp | Fastbee1/ModernTechLab | 1c096a66cb3f445219ef1ff10eb74a79770bba27 | [
"MIT"
] | null | null | null | main.cpp | Fastbee1/ModernTechLab | 1c096a66cb3f445219ef1ff10eb74a79770bba27 | [
"MIT"
] | null | null | null | #include <vector>
#include "ExpressionParser.h"
#include <iterator>
#include <ostream>
void DrawPlotWithPython(const std::pair<std::vector<double>, std::vector<double>>& x_y_out) {
const std::string separator = ",";
auto make_list = [&separator] (const std::vector<double>& values) {
std::ostringstream out;
std::copy(std::begin(values), std::end(values), std::ostream_iterator<double>(out, separator.c_str()));
// removing extra separator in the end
std::string result = std::move(out.str());
result.pop_back();
return result;
};
const std::string call_python = "python ../plotting.py";
const std::string syscall = call_python + ' ' + make_list(x_y_out.first) + ' ' + make_list(x_y_out.second);
std::cout << syscall << std::endl;
// python sys call to draw function plot
system(syscall.c_str());
}
int main(int argc, char** argv) {
ExpressionParser expr_parser;
auto tokens = std::vector<ExpressionParser::Token>(argv + 1, argv + argc);
DrawPlotWithPython(expr_parser.evaluate(0.0, 6.5, 0.01, tokens));
}
| 32.529412 | 111 | 0.654611 | [
"vector"
] |
28f0f821a7f5f46898986820ff91118bfd37da7f | 1,583 | cpp | C++ | Week_2/10 Programming Assignment/Example.cpp | Animart/basics-of-c-plus-plus-development-white-belt | 9ad0aec57a54e505955ad4a93a0636903ba92822 | [
"Unlicense"
] | 1 | 2018-11-22T17:33:45.000Z | 2018-11-22T17:33:45.000Z | Week_2/10 Programming Assignment/Example.cpp | Animart/basics-of-c-plus-plus-development-white-belt | 9ad0aec57a54e505955ad4a93a0636903ba92822 | [
"Unlicense"
] | null | null | null | Week_2/10 Programming Assignment/Example.cpp | Animart/basics-of-c-plus-plus-development-white-belt | 9ad0aec57a54e505955ad4a93a0636903ba92822 | [
"Unlicense"
] | 1 | 2021-03-09T05:26:37.000Z | 2021-03-09T05:26:37.000Z | #include <iostream>
#include <string>
#include <vector>
using namespace std;
int main()
{
int m = 0;
vector<int> days_in_months = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
int q;
cin >> q;
vector<vector<string>> v(31, vector<string>());
for (int i = 0; i < q; ++i)
{
string operation_code;
cin >> operation_code;
if (operation_code == "ADD")
{
string s;
int i;
cin >> i;
cin >> s;
v[i-1].push_back(s);
}
else
if (operation_code == "DUMP")
{
int i;
cin >> i;
cout << v[i-1].size();
for (string s: v[i-1])
{
cout << " " << s;
}
cout << endl;
}
else
if (operation_code == "NEXT")
{
m += 1;
if (m == 12)
{
m = 0;
}
if (m == 0)
{
}
else
{
if (days_in_months[m] == 28)
{
v[27].insert(end(v[27]), begin(v[28]), end(v[28]));
v[28].clear();
v[27].insert(end(v[27]), begin(v[29]), end(v[29]));
v[29].clear();
v[27].insert(end(v[27]), begin(v[30]), end(v[30]));
v[30].clear();
}
else
if (days_in_months[m] == 30)
{
v[29].insert(end(v[29]), begin(v[30]), end(v[30]));
v[30].clear();
}
}
}
}
return 0;
} | 21.986111 | 82 | 0.356286 | [
"vector"
] |
28f58fc49cd7d1b12bba53a62c2305199672c4b6 | 7,663 | cc | C++ | patchpanel/minijailed_process_runner.cc | Toromino/chromiumos-platform2 | 97e6ba18f0e5ab6723f3448a66f82c1a07538d87 | [
"BSD-3-Clause"
] | null | null | null | patchpanel/minijailed_process_runner.cc | Toromino/chromiumos-platform2 | 97e6ba18f0e5ab6723f3448a66f82c1a07538d87 | [
"BSD-3-Clause"
] | null | null | null | patchpanel/minijailed_process_runner.cc | Toromino/chromiumos-platform2 | 97e6ba18f0e5ab6723f3448a66f82c1a07538d87 | [
"BSD-3-Clause"
] | null | null | null | // Copyright 2019 The Chromium OS 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 "patchpanel/minijailed_process_runner.h"
#include <linux/capability.h>
#include <utility>
#include <base/check.h>
#include <base/files/scoped_file.h>
#include <base/logging.h>
#include <base/posix/eintr_wrapper.h>
#include <base/strings/string_number_conversions.h>
#include <base/strings/string_util.h>
#include <brillo/process/process.h>
#include "patchpanel/net_util.h"
namespace patchpanel {
namespace {
constexpr char kUnprivilegedUser[] = "nobody";
constexpr char kNetworkUnprivilegedUser[] = "patchpaneld";
constexpr uint64_t kModprobeCapMask = CAP_TO_MASK(CAP_SYS_MODULE);
constexpr uint64_t kNetRawCapMask = CAP_TO_MASK(CAP_NET_RAW);
constexpr uint64_t kNetRawAdminCapMask =
CAP_TO_MASK(CAP_NET_ADMIN) | CAP_TO_MASK(CAP_NET_RAW);
// These match what is used in iptables.cc in firewalld.
constexpr char kIpPath[] = "/bin/ip";
constexpr char kIptablesPath[] = "/sbin/iptables";
constexpr char kIp6tablesPath[] = "/sbin/ip6tables";
constexpr char kModprobePath[] = "/sbin/modprobe";
// An empty string will be returned if read fails.
std::string ReadBlockingFDToStringAndClose(base::ScopedFD fd) {
if (!fd.is_valid()) {
LOG(ERROR) << "Invalid fd";
return "";
}
static constexpr int kBufSize = 2048;
char buf[kBufSize] = {0};
std::string output;
while (true) {
ssize_t cnt = HANDLE_EINTR(read(fd.get(), buf, kBufSize));
if (cnt == -1) {
PLOG(ERROR) << __func__ << " failed";
return "";
}
if (cnt == 0) {
return output;
}
output.append({buf, static_cast<size_t>(cnt)});
}
}
} // namespace
int MinijailedProcessRunner::RunSyncDestroy(
const std::vector<std::string>& argv,
brillo::Minijail* mj,
minijail* jail,
bool log_failures,
std::string* output) {
std::vector<char*> args;
for (const auto& arg : argv) {
args.push_back(const_cast<char*>(arg.c_str()));
}
args.push_back(nullptr);
pid_t pid;
int fd_stdout = -1;
int* stdout_p = output ? &fd_stdout : nullptr;
bool ran = mj->RunPipesAndDestroy(jail, args, &pid, nullptr /*stdin*/,
stdout_p, nullptr /*stderr*/);
if (output) {
*output = ReadBlockingFDToStringAndClose(base::ScopedFD(fd_stdout));
}
int status = 0;
if (ran) {
ran = system_->WaitPid(pid, &status) == pid;
}
if (!ran) {
LOG(ERROR) << "Could not execute '" << base::JoinString(argv, " ") << "'";
} else if (log_failures && (!WIFEXITED(status) || WEXITSTATUS(status) != 0)) {
if (WIFEXITED(status)) {
LOG(WARNING) << "Subprocess '" << base::JoinString(argv, " ")
<< "' exited with code " << WEXITSTATUS(status);
} else if (WIFSIGNALED(status)) {
LOG(WARNING) << "Subprocess '" << base::JoinString(argv, " ")
<< "' exited with signal " << WTERMSIG(status);
} else {
LOG(WARNING) << "Subprocess '" << base::JoinString(argv, " ")
<< "' exited with unknown status " << status;
}
}
return ran && WIFEXITED(status) ? WEXITSTATUS(status) : -1;
}
int MinijailedProcessRunner::RunSync(const std::vector<std::string>& argv,
bool log_failures,
std::string* output) {
return RunSyncDestroy(argv, mj_, mj_->New(), log_failures, output);
}
void EnterChildProcessJail() {
brillo::Minijail* m = brillo::Minijail::GetInstance();
struct minijail* jail = m->New();
// Most of these return void, but DropRoot() can fail if the user/group
// does not exist.
CHECK(m->DropRoot(jail, kNetworkUnprivilegedUser, kNetworkUnprivilegedUser))
<< "Could not drop root privileges";
m->UseCapabilities(jail, kNetRawCapMask);
m->Enter(jail);
m->Destroy(jail);
}
MinijailedProcessRunner::MinijailedProcessRunner(brillo::Minijail* mj)
: MinijailedProcessRunner(mj ? mj : brillo::Minijail::GetInstance(),
std::make_unique<System>()) {}
MinijailedProcessRunner::MinijailedProcessRunner(brillo::Minijail* mj,
std::unique_ptr<System> system)
: mj_(mj), system_(std::move(system)) {}
int MinijailedProcessRunner::Run(const std::vector<std::string>& argv,
bool log_failures) {
minijail* jail = mj_->New();
CHECK(mj_->DropRoot(jail, kUnprivilegedUser, kUnprivilegedUser));
mj_->UseCapabilities(jail, kNetRawAdminCapMask);
return RunSyncDestroy(argv, mj_, jail, log_failures, nullptr);
}
int MinijailedProcessRunner::ip(const std::string& obj,
const std::string& cmd,
const std::vector<std::string>& argv,
bool log_failures) {
std::vector<std::string> args = {kIpPath, obj, cmd};
args.insert(args.end(), argv.begin(), argv.end());
return Run(args, log_failures);
}
int MinijailedProcessRunner::ip6(const std::string& obj,
const std::string& cmd,
const std::vector<std::string>& argv,
bool log_failures) {
std::vector<std::string> args = {kIpPath, "-6", obj, cmd};
args.insert(args.end(), argv.begin(), argv.end());
return Run(args, log_failures);
}
int MinijailedProcessRunner::iptables(const std::string& table,
const std::vector<std::string>& argv,
bool log_failures,
std::string* output) {
std::vector<std::string> args = {kIptablesPath, "-t", table};
args.insert(args.end(), argv.begin(), argv.end());
return RunSync(args, log_failures, output);
}
int MinijailedProcessRunner::ip6tables(const std::string& table,
const std::vector<std::string>& argv,
bool log_failures,
std::string* output) {
std::vector<std::string> args = {kIp6tablesPath, "-t", table};
args.insert(args.end(), argv.begin(), argv.end());
return RunSync(args, log_failures, output);
}
int MinijailedProcessRunner::modprobe_all(
const std::vector<std::string>& modules, bool log_failures) {
minijail* jail = mj_->New();
CHECK(mj_->DropRoot(jail, kUnprivilegedUser, kUnprivilegedUser));
mj_->UseCapabilities(jail, kModprobeCapMask);
std::vector<std::string> args = {kModprobePath, "-a"};
args.insert(args.end(), modules.begin(), modules.end());
return RunSyncDestroy(args, mj_, jail, log_failures, nullptr);
}
int MinijailedProcessRunner::ip_netns_add(const std::string& netns_name,
bool log_failures) {
std::vector<std::string> args = {kIpPath, "netns", "add", netns_name};
return RunSync(args, log_failures, nullptr);
}
int MinijailedProcessRunner::ip_netns_attach(const std::string& netns_name,
pid_t netns_pid,
bool log_failures) {
std::vector<std::string> args = {kIpPath, "netns", "attach", netns_name,
std::to_string(netns_pid)};
return RunSync(args, log_failures, nullptr);
}
int MinijailedProcessRunner::ip_netns_delete(const std::string& netns_name,
bool log_failures) {
std::vector<std::string> args = {kIpPath, "netns", "delete", netns_name};
return RunSync(args, log_failures, nullptr);
}
} // namespace patchpanel
| 36.665072 | 80 | 0.616208 | [
"vector"
] |
28fd0b0b8f2025e3ab02a2e838cb05061de43266 | 15,732 | cpp | C++ | src/main.cpp | stritti/kostal-pv-monitor | 90ecc7351e75ba3dfe6ff710e75d0383520220f5 | [
"MIT"
] | null | null | null | src/main.cpp | stritti/kostal-pv-monitor | 90ecc7351e75ba3dfe6ff710e75d0383520220f5 | [
"MIT"
] | 1 | 2022-02-22T20:02:49.000Z | 2022-03-06T14:33:18.000Z | src/main.cpp | stritti/kostal-pv-monitor | 90ecc7351e75ba3dfe6ff710e75d0383520220f5 | [
"MIT"
] | null | null | null | /**
Kostal Plenticore DC/DC converter Monitor:
*/
#if !(defined(ESP32))
#error This code is intended to run on the ESP32 platform!
#endif
#define TTGO_T5_1_2 1 // see defines in board_def.h
//#define TTGO_T5_2_3 1 // see defines in board_def.h
#include "board_def.h"
#include "ntp_localtime.h"
#include "kostal_modbus.h"
#include "u8g2_display.h"
#include <Arduino.h>
#include <WiFi.h>
#include <AsyncTCP.h>
#include <SPIFFS.h>
#include <WiFiSettings.h>
const String hostname = "kostal-monitor";
const int32_t DATA_UPDATE_DELAY_SECONDS = 60; // Show result every second
#define uS_TO_S_FACTOR 1000000 // Conversion factor for micro seconds to seconds
RTC_DATA_ATTR int wakeUpCounter = 0; // RTC counter variable
#define MODEM_POWER_ON 23
#define LED_BUILTIN 2 // built-in LED on TTGO-T5
WiFiClient theClient; // Set up a client for the WiFi connection
IPAddress remote; // Address of Modbus Slave device
ModbusIP mb; //ModbusTCP object
String kostal_hostname; // hostname of the Modbus TCP server
uint16_t kostal_modbus_port; // port of the Modbus TCP server
uint32_t modbus_query_last = 0;
/**
* @brief reconstruct the float from 2 unsigned integers
*
*/
float f_2uint_float(unsigned int uint1, unsigned int uint2) {
union f_2uint {
float f;
uint16_t i[2];
};
union f_2uint f_number;
f_number.i[0] = uint1;
f_number.i[1] = uint2;
return f_number.f;
}
/**
* @brief Callback og Modbus TCP connection.
*
* @param event
* @param transactionId
* @param data
* @return true
* @return false
*/
bool cb(Modbus::ResultCode event, uint16_t transactionId, void* data) { // Callback to monitor errors
if (event == Modbus::EX_TIMEOUT) { // If Transaction timeout took place
mb.disconnect(remote); // Close connection to slave and
mb.dropTransactions(); // Cancel all waiting transactions
}
if (event != Modbus::EX_SUCCESS) {
Serial.print("Request result: 0x");
Serial.println(event, HEX);
}
return true;
}
/**
* @brief Get the float object
*
* @param reg
* @return float
*/
float get_float(uint16_t reg) { // get the float from the Modbus register
uint16_t numregs = 2;
uint16_t value[numregs];
while (millis() - modbus_query_last < MODBUS_QUERY_DELAY) {
if (mb.isConnected(remote)) { // Check if connection to Modbus Slave is established
mb.task();
delay(10);
}
}
if (!mb.isConnected(remote)) { // Check if connection to Modbus Slave is established
mb.connect(remote, kostal_modbus_port); // Try to connect if no connection
}
uint16_t trans = mb.readHreg(remote, reg, value, numregs, cb, KOSTAL_MODBUS_SLAVE_ID); // Initiate Read Hreg from Modbus Server
while (mb.isTransaction(trans)) { // Check if transaction is active
mb.task();
delay(10);
}
float float_reconstructed = f_2uint_float(value[0], value[1]);
return float_reconstructed;
}
/**
* @brief Get the uint16 object
*
* @param reg
* @return uint16_t
*/
uint16_t get_uint16(uint16_t reg) { // get the int16 from the Modbus register
uint16_t res;
while (millis() - modbus_query_last < MODBUS_QUERY_DELAY) {
if (mb.isConnected(remote)) { // Check if connection to Modbus Slave is established
mb.task();
delay(10);
}
}
if (!mb.isConnected(remote)) { // Check if connection to Modbus Slave is established
mb.connect(remote, kostal_modbus_port); // Try to connect if no connection
}
uint16_t trans = mb.readHreg(remote, reg, &res, 1, cb, KOSTAL_MODBUS_SLAVE_ID); // Initiate Read Hreg from Modbus Server
while (mb.isTransaction(trans)) { // Check if transaction is active
mb.task();
delay(10);
}
return res;
}
/**
* @brief Get the Power String object
*
* @param value
* @return String
*/
String getPowerString(float value) {
char buffer[50];
if (value < 0) {
value *= -1; //remove the minus sign
}
if (value < 1) {
sprintf(buffer, " 0 W");
} else if (value < 1000) {
sprintf(buffer, "%3.0d W", (int)value);
} else {
sprintf(buffer, "%2.1f kW", value / 1000);
}
return String(buffer);
}
/**
* @brief draw battery icon
*
* @param SoC of battery in percent (0 - 100)
*/
void drawBattery(uint16_t percent, uint16_t y) {
char buffer[50];
if (percent > 100) {
percent = 100;
} else if (percent < 0) {
percent = 0;
}
sprintf(buffer, "%d", (percent + 5) / 20);
u8g2_for_adafruit_gfx.setFontMode(0);
u8g2_for_adafruit_gfx.setForegroundColor(0);
u8g2_for_adafruit_gfx.setBackgroundColor(1);
u8g2_for_adafruit_gfx.setFont(u8g2_font_battery19_tn);
u8g2_for_adafruit_gfx.drawStr(12, y, buffer);
}
/**
* @brief draw smiley
*
*/
void drawSmiley(float own_consumption_grid, float own_consumption_pv, float own_consumption_batt) {
uint8_t smiley;
if (own_consumption_grid > (own_consumption_pv + own_consumption_batt)) {
smiley = 0x0026; /* hex 26 sad man */
} else if (own_consumption_pv > (own_consumption_batt + own_consumption_grid)) {
smiley = 0x0036; /* hex 36 sunglass smily man */
} else {
smiley = 0x0021; /* hex 21 smily man */
}
u8g2_for_adafruit_gfx.setFontMode(0);
u8g2_for_adafruit_gfx.setForegroundColor(0);
u8g2_for_adafruit_gfx.setBackgroundColor(1);
u8g2_for_adafruit_gfx.setFont(u8g2_font_emoticons21_tr);
u8g2_for_adafruit_gfx.drawGlyph(display.width() / 2 - 11, 75, smiley);
}
/**
* @brief
*
*/
void writeOwnConsumption() {
// get data from modbus
uint16_t battery_soc = get_uint16(KOSTAL_MODBUS_REG_BATTERY_SOC);
float own_consumption_grid = get_float(KOSTAL_MODBUS_REG_OWN_CONSUMPTION_GRID);
float own_consumption_pv = get_float(KOSTAL_MODBUS_REG_OWN_CONSUMPTION_PV);
float own_consumption_batt = get_float(KOSTAL_MODBUS_REG_OWN_CONSUMPTION_BATTERY);
float power_dc1 = get_float(KOSTAL_MODBUS_REG_POWER_DC1);
float power_dc2 = get_float(KOSTAL_MODBUS_REG_POWER_DC2);
float home_consumption_rate = get_float(KOSTAL_MODBUS_REG_TOTAL_HOME_CONSUMTION_RATE);
Serial.printf("Eigenverbrauch: %.1f %%\n", home_consumption_rate);
float home_consumption = get_float(KOSTAL_MODBUS_REG_TOTAL_HOME_CONSUMPTION);
Serial.printf("Hausverbrauch: %.1f Wh\n", home_consumption);
float power_wallbox = 0; // TODO
int16_t power_battery = (int16_t)get_uint16(KOSTAL_MODBUS_REG_BATTERY_POWER_CHARGE);
float power_house = own_consumption_grid + own_consumption_pv + own_consumption_batt;
float power_pv = power_dc1 + power_dc2;
float power_grid = power_pv + power_battery + power_wallbox - power_house;
display.setFont(&FreeSans9pt7b);
displayText("Kostal Monitor", 18, GxEPD_ALIGN_CENTER);
// draw icons
u8g2_for_adafruit_gfx.setFontMode(0);
u8g2_for_adafruit_gfx.setForegroundColor(0);
u8g2_for_adafruit_gfx.setBackgroundColor(1);
u8g2_for_adafruit_gfx.setFont(u8g2_font_streamline_ecology_t);
u8g2_for_adafruit_gfx.drawGlyph(4, 50, 0x003E); /* hex 3E solar panel */
drawBattery(battery_soc, 115);
u8g2_for_adafruit_gfx.setFont(u8g2_font_streamline_interface_essential_wifi_t);
u8g2_for_adafruit_gfx.drawGlyph(display.width() - 23, 50, 0x0031); /* hex 30 Grid */
u8g2_for_adafruit_gfx.setFont(u8g2_font_streamline_ecology_t);
u8g2_for_adafruit_gfx.drawGlyph(display.width() - 23, 87, 0x0034); /* hex 34 e-car */
u8g2_for_adafruit_gfx.setFont(u8g2_font_streamline_interface_essential_home_menu_t);
u8g2_for_adafruit_gfx.drawGlyph(display.width() - 23, 122, 0x0030); /* hex 30 house */
int16_t offset = display.width() / 2 + 38;
displayText(getPowerString(power_pv).c_str(), 50, GxEPD_ALIGN_RIGHT, offset); // PV power production
displayText(getPowerString(power_battery).c_str(), 102, GxEPD_ALIGN_RIGHT, offset); // battery power production
char buffer_soc[10];
sprintf(buffer_soc, "%3.0d %%", battery_soc);
displayText(buffer_soc, 120, GxEPD_ALIGN_RIGHT, offset); // battery SoC
displayText(getPowerString(power_grid).c_str(), 50, GxEPD_ALIGN_RIGHT, 28); // grid consumption grid
displayText(getPowerString(power_wallbox).c_str(), 85, GxEPD_ALIGN_RIGHT, 28); // wallbox consumption grid
displayText(getPowerString(power_house).c_str(), 120, GxEPD_ALIGN_RIGHT, 28);
/*
char buffer_hcr[10];
sprintf(buffer_hcr, "%3.0d %%", (int)home_consumption_rate);
displayText(buffer_hcr, 120, GxEPD_ALIGN_CENTER);
*/
int8_t arrow_offset_left = 38;
int8_t arrow_offset_right = 21;
int8_t display_center = display.width() / 2;
// draw centered inverter with smiley in center
drawSmiley(own_consumption_grid, own_consumption_pv, own_consumption_batt);
display.drawRect(display_center - 22, 40, 43, 65, GxEPD_BLACK);
display.drawLine(display_center - 17, 40, display_center - 15, 105, GxEPD_BLACK);
display.drawLine(display_center + 16, 40, display_center + 14, 105, GxEPD_BLACK);
// draw arrows
u8g2_for_adafruit_gfx.setFont(u8g2_font_unifont_t_86);
if (power_pv > 0) {
u8g2_for_adafruit_gfx.drawGlyph(display_center - arrow_offset_left, 55, 0x2b0a); /* ↘ */
} else if (power_pv < 0) {
u8g2_for_adafruit_gfx.drawGlyph(display_center - arrow_offset_left, 55, 0x2b09); /* ↖ */
}
if (power_battery > 0) {
u8g2_for_adafruit_gfx.drawGlyph(display_center - arrow_offset_left, 105, 0x2b08); /* ↗ */
} else if (power_battery < 0) {
u8g2_for_adafruit_gfx.drawGlyph(display_center - arrow_offset_left, 105, 0x2b0b); /* ↙ */
}
if (power_grid < 0) {
u8g2_for_adafruit_gfx.drawGlyph(display_center + arrow_offset_right, 55, 0x2b0b); /* ↙ */
} else if (power_grid > 0) {
u8g2_for_adafruit_gfx.drawGlyph(display_center + arrow_offset_right, 55, 0x2b08); /* ↗ */
}
if (power_wallbox > 0) {
u8g2_for_adafruit_gfx.drawGlyph(display_center + arrow_offset_right, 85, 0x2b6c); /* → */
} else if (power_wallbox < 0) {
u8g2_for_adafruit_gfx.drawGlyph(display_center + arrow_offset_right, 85, 0x2b69); /* ← */
}
if (power_house > 0) {
u8g2_for_adafruit_gfx.drawGlyph(display_center + arrow_offset_right, 105, 0x2b0a); /* ↘ */
}
display.setFont(&FreeMono9pt7b);
displayText(getCurrentTime().c_str(), 18, GxEPD_ALIGN_RIGHT);
display.update();
}
void showSetupScreen() {
Serial.println("setup device");
display.fillScreen(GxEPD_WHITE);
display.setFont(&FreeSans9pt7b);
displayText("Kostal Monitor", 18, GxEPD_ALIGN_LEFT);
displayText("*** Setup ***", 50, GxEPD_ALIGN_CENTER);
displayText("Connect to WiFi & add data:", 80, GxEPD_ALIGN_CENTER);
displayText(hostname.c_str(), 110, GxEPD_ALIGN_CENTER);
display.update();
}
void showWiFiConnectionFailedScreen() {
display.fillScreen(GxEPD_WHITE);
display.setFont(&FreeSans9pt7b);
displayText("Kostal Monitor", 18, GxEPD_ALIGN_LEFT);
displayText("*** Error ***", 60, GxEPD_ALIGN_CENTER);
displayText("WiFi connection failed", 90, GxEPD_ALIGN_LEFT);
display.update();
}
void showWiFiConnectedScreen() {
WiFi.waitForConnectResult();
IPAddress wIP = WiFi.localIP();
Serial.printf("WiFi IP address: %u.%u.%u.%u\n", wIP[0], wIP[1], wIP[2], wIP[3]);
Serial.printf("Connecting to %s\n", kostal_hostname.c_str());
WiFi.hostByName(kostal_hostname.c_str(), remote);
if (remote != INADDR_NONE) {
Serial.printf("Connecting to kostal converter: %s (IP: %u.%u.%u.%u)\n", kostal_hostname.c_str(), remote[0], remote[1],
remote[2], remote[3]);
mb.connect(remote, kostal_modbus_port);
} else {
Serial.printf("Could not resolve hostname: %s\n", kostal_hostname.c_str());
}
}
/*
Method to print the reason by which ESP32
has been awaken from sleep
*/
void print_wakeup_reason() {
esp_sleep_wakeup_cause_t wakeup_reason;
wakeup_reason = esp_sleep_get_wakeup_cause();
switch (wakeup_reason) {
case ESP_SLEEP_WAKEUP_EXT0:
Serial.println("Wakeup caused by external signal using RTC_IO");
break;
case ESP_SLEEP_WAKEUP_EXT1:
Serial.println("Wakeup caused by external signal using RTC_CNTL");
break;
case ESP_SLEEP_WAKEUP_TIMER:
Serial.println("Wakeup caused by timer");
break;
case ESP_SLEEP_WAKEUP_TOUCHPAD:
Serial.println("Wakeup caused by touchpad");
break;
case ESP_SLEEP_WAKEUP_ULP:
Serial.println("Wakeup caused by ULP program");
break;
default:
Serial.printf("Wakeup was not caused by deep sleep: %d\n", wakeup_reason);
wakeUpCounter = 0;
break;
}
}
/**
* @brief
*
*/
void setup() {
Serial.begin(SERIAL_SPEED);
while (!Serial) {
}
Serial.println(F(".-----------------------------------------------."));
Serial.println(F("| Kostal Plenticore DC/DC converter Monitor |"));
Serial.println(F("| https://stritti.github.io/kostal-pv-monitor/ |"));
Serial.println(F(" ------------------------------------------------"));
Serial.println(" wake up counter " + String(++wakeUpCounter));
//Print the wakeup reason for ESP32
print_wakeup_reason();
SPIFFS.begin(true); // Will format on the first run after failing to mount
// Set up the display
display.init(SERIAL_SPEED);
display.setRotation(3);
display.setTextColor(GxEPD_BLACK);
u8g2_for_adafruit_gfx.begin(display);
if (ESP_SLEEP_WAKEUP_TIMER != esp_sleep_get_wakeup_cause()) {
display.fillScreen(GxEPD_WHITE);
}
WiFiSettings.hostname = hostname.c_str();
WiFiSettings.onPortal = []() { showSetupScreen(); };
WiFiSettings.onSuccess = []() { showWiFiConnectedScreen(); };
WiFiSettings.onFailure = []() { showWiFiConnectionFailedScreen(); };
// Define custom settings saved by WifiSettings
// These will return the default if nothing was set before
kostal_hostname = WiFiSettings.string("kostal_hostname", "hostname", "KOSTAL Hostname");
kostal_modbus_port = WiFiSettings.integer("kostal_modbus_port", 1, 65535, 1502, "KOSTAL Modbus Port");
// Connect to WiFi with a timeout of 30 seconds
// Launches the portal if the connection failed
WiFiSettings.connect(true, 30);
// Initialize a NTPClient to get time
timeClient.begin();
// Set up ModbusTCP connection
mb.client();
// TODO: Show Warning if level X is reached
Serial.print(F("Battery Temp: "));
Serial.print(get_float(214));
Serial.println(F("\u00B0C"));
writeOwnConsumption();
mb.disconnect(remote); // Close connection and
mb.dropTransactions(); // Cancel all waiting transactions
while (mb.isConnected(remote)) { // Check if connection to Modbus Slave is established and wait until it is closed
mb.task();
delay(10);
}
WiFi.disconnect();
Serial.printf("Going to sleep now for %d sec.\n", (DATA_UPDATE_DELAY_SECONDS));
esp_sleep_enable_timer_wakeup(DATA_UPDATE_DELAY_SECONDS * uS_TO_S_FACTOR);
pinMode(MODEM_POWER_ON, OUTPUT);
digitalWrite(MODEM_POWER_ON, LOW);
/*
Next we decide what all peripherals to shut down/keep on
By default, ESP32 will automatically power down the peripherals
not needed by the wakeup source, but if you want to be a poweruser
this is for you. Read in detail at the API docs
http://esp-idf.readthedocs.io/en/latest/api-reference/system/deep_sleep.html
Left the line commented as an example of how to configure peripherals.
The line below turns off all RTC peripherals in deep sleep.
*/
esp_sleep_pd_config(ESP_PD_DOMAIN_RTC_PERIPH, ESP_PD_OPTION_OFF);
esp_sleep_pd_config(ESP_PD_DOMAIN_RTC_FAST_MEM, ESP_PD_OPTION_OFF);
esp_sleep_pd_config(ESP_PD_DOMAIN_RTC_SLOW_MEM, ESP_PD_OPTION_OFF);
pinMode(LED_BUILTIN, OUTPUT);
esp_deep_sleep_start();
Serial.println("This will never be printed");
}
/**
* @brief
*
*/
void loop() {}
| 33.189873 | 130 | 0.703344 | [
"object"
] |
e900d34f767b8f2b984ffb9c368fea1889478065 | 10,236 | cpp | C++ | franka_interface/src/motion_controller_interface.cpp | StanfordVL/franka_ros_interface | 48067aecfff479572f375d6351c069b47ddc2be3 | [
"Apache-2.0"
] | 1 | 2020-11-12T11:47:39.000Z | 2020-11-12T11:47:39.000Z | franka_interface/src/motion_controller_interface.cpp | StanfordVL/franka_ros_interface | 48067aecfff479572f375d6351c069b47ddc2be3 | [
"Apache-2.0"
] | null | null | null | franka_interface/src/motion_controller_interface.cpp | StanfordVL/franka_ros_interface | 48067aecfff479572f375d6351c069b47ddc2be3 | [
"Apache-2.0"
] | 1 | 2020-07-22T03:22:38.000Z | 2020-07-22T03:22:38.000Z | /***************************************************************************
* Adapted from arm_controller_interface.cpp (sawyer_simulator package)
*
* @package: franka_interface
* @metapackage: franka_ros_interface
* @author: Saif Sidhik <sxs1412@bham.ac.uk>
*
**************************************************************************/
/***************************************************************************
* Copyright (c) 2019, Saif Sidhik
* Copyright (c) 2013-2018, Rethink Robotics 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.
**************************************************************************/
#include <franka_interface/motion_controller_interface.h>
#include <controller_manager_msgs/SwitchController.h>
namespace franka_interface {
void MotionControllerInterface::init(ros::NodeHandle& nh,
boost::shared_ptr<controller_manager::ControllerManager> controller_manager) {
current_mode_ = -1;
if (!nh.getParam("/controllers_config/position_controller", position_controller_name_)) {
position_controller_name_ = "position_joint_position_controller";
}
if (!nh.getParam("/controllers_config/torque_controller", torque_controller_name_)) {
torque_controller_name_ = "effort_joint_torque_controller";
}
if (!nh.getParam("/controllers_config/impedance_controller", impedance_controller_name_)) {
impedance_controller_name_ = "effort_joint_impedance_controller";
}
if (!nh.getParam("/controllers_config/velocity_controller", velocity_controller_name_)) {
velocity_controller_name_ = "velocity_joint_velocity_controller";
}
if (!nh.getParam("/controllers_config/trajectory_controller", trajectory_controller_name_)) {
trajectory_controller_name_ = "position_joint_trajectory_controller";
}
if (!nh.getParam("/controllers_config/default_controller", default_controller_name_)) {
default_controller_name_ = "position_joint_trajectory_controller";
}
current_controller_name_ = default_controller_name_;
all_controllers_.clear();
all_controllers_.push_back(position_controller_name_);
all_controllers_.push_back(torque_controller_name_);
all_controllers_.push_back(impedance_controller_name_);
all_controllers_.push_back(velocity_controller_name_);
all_controllers_.push_back(trajectory_controller_name_);
bool default_defined = false;
for (size_t i = 0; i < all_controllers_.size(); ++i){
if (all_controllers_[i] == default_controller_name_){
default_defined = true;
break;
}
}
controller_name_to_mode_map_[position_controller_name_] = franka_core_msgs::JointCommand::POSITION_MODE;
controller_name_to_mode_map_[torque_controller_name_] = franka_core_msgs::JointCommand::TORQUE_MODE;
controller_name_to_mode_map_[impedance_controller_name_] = franka_core_msgs::JointCommand::IMPEDANCE_MODE;
controller_name_to_mode_map_[velocity_controller_name_] = franka_core_msgs::JointCommand::VELOCITY_MODE;
controller_name_to_mode_map_[trajectory_controller_name_] = -1;
if (! default_defined){
ROS_ERROR_STREAM_NAMED("MotionControllerInterface", "Default controller not present in the provided controllers!");
}
controller_manager_ = controller_manager;
joint_command_sub_ = nh.subscribe("/franka_ros_interface/motion_controller/arm/joint_commands", 1,
&MotionControllerInterface::jointCommandCallback, this);
// Command Timeout
joint_command_timeout_sub_ = nh.subscribe("/franka_ros_interface/motion_controller/arm/joint_command_timeout", 1,
&MotionControllerInterface::jointCommandTimeoutCallback, this);
double command_timeout_default;
nh.param<double>("command_timeout", command_timeout_default, 0.2);
auto p_cmd_timeout_length = std::make_shared<ros::Duration>(std::min(1.0,
std::max(0.0, command_timeout_default)));
box_timeout_length_.set(p_cmd_timeout_length);
ROS_INFO_STREAM("MotionControllerInterface Initialised");
// Update at 100Hz
cmd_timeout_timer_ = nh.createTimer(100, &MotionControllerInterface::commandTimeoutCheck, this);
}
void MotionControllerInterface::commandTimeoutCheck(const ros::TimerEvent& e) {
// lock out other thread(s) which are getting called back via ros.
std::lock_guard<std::mutex> guard(mtx_);
// Check Command Timeout
std::shared_ptr<const ros::Duration> p_timeout_length;
box_timeout_length_.get(p_timeout_length);
std::shared_ptr<const ros::Time> p_cmd_msg_time;
box_cmd_timeout_.get(p_cmd_msg_time);
bool command_timeout = (p_cmd_msg_time && p_timeout_length &&
((ros::Time::now() - *p_cmd_msg_time.get()) > (*p_timeout_length.get())));
if(command_timeout && (current_controller_name_ != default_controller_name_)) {
// Timeout violated, force robot back to Default Controller Mode
ROS_WARN_STREAM("MotionControllerInterface: Command timeout violated: Switching to Default control mode." << default_controller_name_);
switchToDefaultController();
}
}
bool MotionControllerInterface::switchToDefaultController() {
std::vector<std::string> start_controllers;
std::vector<std::string> stop_controllers;
for (size_t i = 0; i < all_controllers_.size(); ++i) {
if (all_controllers_[i] == default_controller_name_)
start_controllers.push_back(all_controllers_[i]);
else stop_controllers.push_back(all_controllers_[i]);
}
if (!controller_manager_->switchController(start_controllers, stop_controllers,
controller_manager_msgs::SwitchController::Request::BEST_EFFORT))
{
ROS_ERROR_STREAM_NAMED("MotionControllerInterface", "Failed to switch controllers");
return false;
}
current_controller_name_ = start_controllers[0];
current_mode_ = controller_name_to_mode_map_[current_controller_name_];
ROS_INFO_STREAM("MotionControllerInterface: Controller " << start_controllers[0]
<< " started; Controllers " << stop_controllers[0] <<
", " << stop_controllers[1] <<
", " << stop_controllers[2] <<
", " << stop_controllers[3] << " stopped.");
return true;
}
void MotionControllerInterface::jointCommandTimeoutCallback(const std_msgs::Float64 msg) {
ROS_INFO_STREAM("MotionControllerInterface: Joint command timeout: " << msg.data);
auto p_cmd_timeout_length = std::make_shared<ros::Duration>(
std::min(1.0, std::max(0.0, double(msg.data))));
box_timeout_length_.set(p_cmd_timeout_length);
}
bool MotionControllerInterface::switchControllers(int control_mode) {
std::vector<std::string> start_controllers;
std::vector<std::string> stop_controllers;
if(current_mode_ != control_mode)
{
switch (control_mode)
{
case franka_core_msgs::JointCommand::POSITION_MODE:
start_controllers.push_back(position_controller_name_);
stop_controllers.push_back(impedance_controller_name_);
stop_controllers.push_back(torque_controller_name_);
stop_controllers.push_back(velocity_controller_name_);
stop_controllers.push_back(trajectory_controller_name_);
break;
case franka_core_msgs::JointCommand::IMPEDANCE_MODE:
start_controllers.push_back(impedance_controller_name_);
stop_controllers.push_back(position_controller_name_);
stop_controllers.push_back(torque_controller_name_);
stop_controllers.push_back(velocity_controller_name_);
stop_controllers.push_back(trajectory_controller_name_);
break;
case franka_core_msgs::JointCommand::TORQUE_MODE:
start_controllers.push_back(torque_controller_name_);
stop_controllers.push_back(position_controller_name_);
stop_controllers.push_back(impedance_controller_name_);
stop_controllers.push_back(velocity_controller_name_);
stop_controllers.push_back(trajectory_controller_name_);
break;
case franka_core_msgs::JointCommand::VELOCITY_MODE:
start_controllers.push_back(velocity_controller_name_);
stop_controllers.push_back(position_controller_name_);
stop_controllers.push_back(impedance_controller_name_);
stop_controllers.push_back(torque_controller_name_);
stop_controllers.push_back(trajectory_controller_name_);
break;
default:
ROS_ERROR_STREAM_NAMED("MotionControllerInterface", "Unknown JointCommand mode "
<< control_mode << ". Ignoring command.");
return false;
}
if (!controller_manager_->switchController(start_controllers, stop_controllers,
controller_manager_msgs::SwitchController::Request::BEST_EFFORT))
{
ROS_ERROR_STREAM_NAMED("MotionControllerInterface", "Failed to switch controllers");
return false;
}
current_mode_ = control_mode;
current_controller_name_ = start_controllers[0];
ROS_INFO_STREAM("MotionControllerInterface: Controller " << start_controllers[0]
<< " started; Controllers " << stop_controllers[0] <<
", " << stop_controllers[1] <<
", " << stop_controllers[2] <<
", " << stop_controllers[3] << " stopped.");
}
return true;
}
void MotionControllerInterface::jointCommandCallback(const franka_core_msgs::JointCommandConstPtr& msg) {
// lock out other thread(s) which are getting called back via ros.
std::lock_guard<std::mutex> guard(mtx_);
if(switchControllers(msg->mode)) {
auto p_cmd_msg_time = std::make_shared<ros::Time>(ros::Time::now());
box_cmd_timeout_.set(p_cmd_msg_time);
}
}
}
| 45.493333 | 139 | 0.712974 | [
"vector"
] |
e90439fab2d0731f73e8b683e433eb03297601a9 | 8,541 | hpp | C++ | include/VROSC/UIScrollableContainerInput.hpp | v0idp/virtuoso-codegen | 6f560f04822c67f092d438a3f484249072c1d21d | [
"Unlicense"
] | null | null | null | include/VROSC/UIScrollableContainerInput.hpp | v0idp/virtuoso-codegen | 6f560f04822c67f092d438a3f484249072c1d21d | [
"Unlicense"
] | null | null | null | include/VROSC/UIScrollableContainerInput.hpp | v0idp/virtuoso-codegen | 6f560f04822c67f092d438a3f484249072c1d21d | [
"Unlicense"
] | 1 | 2022-03-30T21:07:35.000Z | 2022-03-30T21:07:35.000Z | // Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
// Begin includes
#include "beatsaber-hook/shared/utils/typedefs.h"
#include "beatsaber-hook/shared/utils/byref.hpp"
// Including type: VROSC.UIInteractable
#include "VROSC/UIInteractable.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp"
#include "beatsaber-hook/shared/utils/utils.h"
// Completed includes
// Begin forward declares
// Forward declaring namespace: VROSC
namespace VROSC {
// Forward declaring type: UIScrollableContainer
class UIScrollableContainer;
// Forward declaring type: ClickData
class ClickData;
}
// Forward declaring namespace: System
namespace System {
// Forward declaring type: Action`1<T>
template<typename T>
class Action_1;
}
// Forward declaring namespace: UnityEngine
namespace UnityEngine {
// Skipping declaration: Vector3 because it is already included!
}
// Completed forward declares
// Type namespace: VROSC
namespace VROSC {
// Forward declaring type: UIScrollableContainerInput
class UIScrollableContainerInput;
}
#include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp"
NEED_NO_BOX(::VROSC::UIScrollableContainerInput);
DEFINE_IL2CPP_ARG_TYPE(::VROSC::UIScrollableContainerInput*, "VROSC", "UIScrollableContainerInput");
// Type namespace: VROSC
namespace VROSC {
// Size: 0xA0
#pragma pack(push, 1)
// Autogenerated type: VROSC.UIScrollableContainerInput
// [TokenAttribute] Offset: FFFFFFFF
class UIScrollableContainerInput : public ::VROSC::UIInteractable {
public:
public:
// private VROSC.UIScrollableContainer _scrollableContainer
// Size: 0x8
// Offset: 0x88
::VROSC::UIScrollableContainer* scrollableContainer;
// Field size check
static_assert(sizeof(::VROSC::UIScrollableContainer*) == 0x8);
// public System.Action`1<System.Int32> OnItemClicked
// Size: 0x8
// Offset: 0x90
::System::Action_1<int>* OnItemClicked;
// Field size check
static_assert(sizeof(::System::Action_1<int>*) == 0x8);
// public System.Action`1<System.Int32> OnItemHoverChanged
// Size: 0x8
// Offset: 0x98
::System::Action_1<int>* OnItemHoverChanged;
// Field size check
static_assert(sizeof(::System::Action_1<int>*) == 0x8);
public:
// Get instance field reference: private VROSC.UIScrollableContainer _scrollableContainer
[[deprecated("Use field access instead!")]] ::VROSC::UIScrollableContainer*& dyn__scrollableContainer();
// Get instance field reference: public System.Action`1<System.Int32> OnItemClicked
[[deprecated("Use field access instead!")]] ::System::Action_1<int>*& dyn_OnItemClicked();
// Get instance field reference: public System.Action`1<System.Int32> OnItemHoverChanged
[[deprecated("Use field access instead!")]] ::System::Action_1<int>*& dyn_OnItemHoverChanged();
// private System.Void OnEnable()
// Offset: 0x1914F4C
void OnEnable();
// private System.Void HoverStayChanged()
// Offset: 0x19151B4
void HoverStayChanged();
// private System.Void ItemWasPressed(VROSC.ClickData clickData)
// Offset: 0x19153AC
void ItemWasPressed(::VROSC::ClickData* clickData);
// private System.Int32 GetItemByPosition(UnityEngine.Vector3 worldPosition)
// Offset: 0x1915228
int GetItemByPosition(::UnityEngine::Vector3 worldPosition);
// public override System.Boolean get_InteractionStopsLaser()
// Offset: 0x1914F44
// Implemented from: VROSC.UIInteractable
// Base method: System.Boolean UIInteractable::get_InteractionStopsLaser()
bool get_InteractionStopsLaser();
// public System.Void .ctor()
// Offset: 0x1915438
// Implemented from: VROSC.UIInteractable
// Base method: System.Void UIInteractable::.ctor()
// Base method: System.Void Clickable::.ctor()
// Base method: System.Void Interactable::.ctor()
template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary>
static UIScrollableContainerInput* New_ctor() {
static auto ___internal__logger = ::Logger::get().WithContext("::VROSC::UIScrollableContainerInput::.ctor");
return THROW_UNLESS((::il2cpp_utils::New<UIScrollableContainerInput*, creationType>()));
}
// protected override System.Void OnDisable()
// Offset: 0x191507C
// Implemented from: VROSC.Interactable
// Base method: System.Void Interactable::OnDisable()
void OnDisable();
}; // VROSC.UIScrollableContainerInput
#pragma pack(pop)
static check_size<sizeof(UIScrollableContainerInput), 152 + sizeof(::System::Action_1<int>*)> __VROSC_UIScrollableContainerInputSizeCheck;
static_assert(sizeof(UIScrollableContainerInput) == 0xA0);
}
#include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
// Writing MetadataGetter for method: VROSC::UIScrollableContainerInput::OnEnable
// Il2CppName: OnEnable
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (VROSC::UIScrollableContainerInput::*)()>(&VROSC::UIScrollableContainerInput::OnEnable)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(VROSC::UIScrollableContainerInput*), "OnEnable", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: VROSC::UIScrollableContainerInput::HoverStayChanged
// Il2CppName: HoverStayChanged
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (VROSC::UIScrollableContainerInput::*)()>(&VROSC::UIScrollableContainerInput::HoverStayChanged)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(VROSC::UIScrollableContainerInput*), "HoverStayChanged", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: VROSC::UIScrollableContainerInput::ItemWasPressed
// Il2CppName: ItemWasPressed
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (VROSC::UIScrollableContainerInput::*)(::VROSC::ClickData*)>(&VROSC::UIScrollableContainerInput::ItemWasPressed)> {
static const MethodInfo* get() {
static auto* clickData = &::il2cpp_utils::GetClassFromName("VROSC", "ClickData")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(VROSC::UIScrollableContainerInput*), "ItemWasPressed", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{clickData});
}
};
// Writing MetadataGetter for method: VROSC::UIScrollableContainerInput::GetItemByPosition
// Il2CppName: GetItemByPosition
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<int (VROSC::UIScrollableContainerInput::*)(::UnityEngine::Vector3)>(&VROSC::UIScrollableContainerInput::GetItemByPosition)> {
static const MethodInfo* get() {
static auto* worldPosition = &::il2cpp_utils::GetClassFromName("UnityEngine", "Vector3")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(VROSC::UIScrollableContainerInput*), "GetItemByPosition", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{worldPosition});
}
};
// Writing MetadataGetter for method: VROSC::UIScrollableContainerInput::get_InteractionStopsLaser
// Il2CppName: get_InteractionStopsLaser
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (VROSC::UIScrollableContainerInput::*)()>(&VROSC::UIScrollableContainerInput::get_InteractionStopsLaser)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(VROSC::UIScrollableContainerInput*), "get_InteractionStopsLaser", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: VROSC::UIScrollableContainerInput::New_ctor
// Il2CppName: .ctor
// Cannot get method pointer of value based method overload from template for constructor!
// Try using FindMethod instead!
// Writing MetadataGetter for method: VROSC::UIScrollableContainerInput::OnDisable
// Il2CppName: OnDisable
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (VROSC::UIScrollableContainerInput::*)()>(&VROSC::UIScrollableContainerInput::OnDisable)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(VROSC::UIScrollableContainerInput*), "OnDisable", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
| 50.538462 | 194 | 0.749678 | [
"vector"
] |
e905798d67d1679094f91365c929403aeee48a43 | 164,891 | cc | C++ | components/autofill/core/browser/credit_card_save_manager_unittest.cc | zipated/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 2,151 | 2020-04-18T07:31:17.000Z | 2022-03-31T08:39:18.000Z | components/autofill/core/browser/credit_card_save_manager_unittest.cc | cangulcan/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 395 | 2020-04-18T08:22:18.000Z | 2021-12-08T13:04:49.000Z | components/autofill/core/browser/credit_card_save_manager_unittest.cc | cangulcan/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 338 | 2020-04-18T08:03:10.000Z | 2022-03-29T12:33:22.000Z | // Copyright 2017 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 "components/autofill/core/browser/credit_card_save_manager.h"
#include <stddef.h>
#include <algorithm>
#include <list>
#include <map>
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include "base/guid.h"
#include "base/metrics/metrics_hashes.h"
#include "base/test/metrics/histogram_tester.h"
#include "base/test/scoped_feature_list.h"
#include "base/test/scoped_task_environment.h"
#include "base/threading/thread_task_runner_handle.h"
#include "base/time/time.h"
#include "build/build_config.h"
#include "components/autofill/core/browser/autofill_experiments.h"
#include "components/autofill/core/browser/autofill_metrics.h"
#include "components/autofill/core/browser/autofill_profile.h"
#include "components/autofill/core/browser/autofill_test_utils.h"
#include "components/autofill/core/browser/credit_card.h"
#include "components/autofill/core/browser/payments/test_payments_client.h"
#include "components/autofill/core/browser/personal_data_manager.h"
#include "components/autofill/core/browser/test_autofill_client.h"
#include "components/autofill/core/browser/test_autofill_clock.h"
#include "components/autofill/core/browser/test_autofill_driver.h"
#include "components/autofill/core/browser/test_autofill_manager.h"
#include "components/autofill/core/browser/test_credit_card_save_manager.h"
#include "components/autofill/core/browser/test_personal_data_manager.h"
#include "components/autofill/core/browser/test_sync_service.h"
#include "components/autofill/core/browser/validation.h"
#include "components/autofill/core/browser/webdata/autofill_webdata_service.h"
#include "components/autofill/core/common/autofill_clock.h"
#include "components/autofill/core/common/form_data.h"
#include "components/autofill/core/common/form_field_data.h"
#include "components/prefs/pref_service.h"
#include "components/ukm/test_ukm_recorder.h"
#include "components/ukm/ukm_source.h"
#include "net/url_request/url_request_context_getter.h"
#include "net/url_request/url_request_test_util.h"
#include "services/metrics/public/cpp/ukm_builders.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "url/gurl.h"
using base::ASCIIToUTF16;
using testing::_;
using testing::AtLeast;
using testing::Return;
using testing::SaveArg;
using testing::UnorderedElementsAre;
namespace autofill {
namespace {
using UkmCardUploadDecisionType = ukm::builders::Autofill_CardUploadDecision;
using UkmDeveloperEngagementType = ukm::builders::Autofill_DeveloperEngagement;
const base::Time kArbitraryTime = base::Time::FromDoubleT(25);
const base::Time kMuchLaterTime = base::Time::FromDoubleT(5000);
std::string NextYear() {
base::Time::Exploded now;
base::Time::Now().LocalExplode(&now);
return std::to_string(now.year + 1);
}
class MockAutofillClient : public TestAutofillClient {
public:
MockAutofillClient() {}
~MockAutofillClient() override {}
MOCK_METHOD2(ConfirmSaveCreditCardLocally,
void(const CreditCard& card, const base::Closure& callback));
private:
DISALLOW_COPY_AND_ASSIGN(MockAutofillClient);
};
} // anonymous namespace
class CreditCardSaveManagerTest : public testing::Test {
public:
void SetUp() override {
autofill_client_.SetPrefs(test::PrefServiceForTesting());
personal_data_.set_database(autofill_client_.GetDatabase());
personal_data_.SetPrefService(autofill_client_.GetPrefs());
personal_data_.SetSyncServiceForTest(&sync_service_);
autofill_driver_.reset(new TestAutofillDriver());
request_context_ = new net::TestURLRequestContextGetter(
base::ThreadTaskRunnerHandle::Get());
autofill_driver_->SetURLRequestContext(request_context_.get());
payments_client_ = new payments::TestPaymentsClient(
autofill_driver_->GetURLRequestContext(), autofill_client_.GetPrefs(),
autofill_client_.GetIdentityManager(),
/*unmask_delegate=*/nullptr,
// Will be set by CreditCardSaveManager's ctor
/*save_delegate=*/nullptr);
credit_card_save_manager_ =
new TestCreditCardSaveManager(autofill_driver_.get(), &autofill_client_,
payments_client_, &personal_data_);
autofill_manager_.reset(new TestAutofillManager(
autofill_driver_.get(), &autofill_client_, &personal_data_,
std::unique_ptr<CreditCardSaveManager>(credit_card_save_manager_),
payments_client_));
autofill_manager_->SetExpectedObservedSubmission(true);
}
void TearDown() override {
// Order of destruction is important as AutofillManager relies on
// PersonalDataManager to be around when it gets destroyed.
autofill_manager_.reset();
autofill_driver_.reset();
// Remove the AutofillWebDataService so TestPersonalDataManager does not
// need to care about removing self as an observer in destruction.
personal_data_.set_database(scoped_refptr<AutofillWebDataService>(nullptr));
personal_data_.SetPrefService(nullptr);
personal_data_.ClearCreditCards();
request_context_ = nullptr;
}
void DisableAutofillUpstreamSendDetectedValuesExperiment() {
scoped_feature_list_.InitAndDisableFeature(
kAutofillUpstreamSendDetectedValues);
}
void EnableAutofillUpstreamSendDetectedValuesExperiment() {
scoped_feature_list_.InitAndEnableFeature(
kAutofillUpstreamSendDetectedValues);
}
void EnableAutofillUpstreamSendPanFirstSixExperiment() {
scoped_feature_list_.InitAndEnableFeature(kAutofillUpstreamSendPanFirstSix);
}
void EnableAutofillUpstreamUpdatePromptExplanationExperiment() {
scoped_feature_list_.InitAndEnableFeature(
kAutofillUpstreamUpdatePromptExplanation);
}
void FormsSeen(const std::vector<FormData>& forms) {
autofill_manager_->OnFormsSeen(forms, base::TimeTicks());
}
void FormSubmitted(const FormData& form) {
autofill_manager_->OnFormSubmitted(
form, false, SubmissionSource::FORM_SUBMISSION, base::TimeTicks::Now());
}
// Populates |form| with data corresponding to a simple credit card form.
// Note that this actually appends fields to the form data, which can be
// useful for building up more complex test forms.
void CreateTestCreditCardFormData(FormData* form,
bool is_https,
bool use_month_type) {
form->name = ASCIIToUTF16("MyForm");
if (is_https) {
form->origin = GURL("https://myform.com/form.html");
form->action = GURL("https://myform.com/submit.html");
form->main_frame_origin =
url::Origin::Create(GURL("https://myform_root.com/form.html"));
} else {
form->origin = GURL("http://myform.com/form.html");
form->action = GURL("http://myform.com/submit.html");
form->main_frame_origin =
url::Origin::Create(GURL("http://myform_root.com/form.html"));
}
FormFieldData field;
test::CreateTestFormField("Name on Card", "nameoncard", "", "text", &field);
form->fields.push_back(field);
test::CreateTestFormField("Card Number", "cardnumber", "", "text", &field);
form->fields.push_back(field);
if (use_month_type) {
test::CreateTestFormField("Expiration Date", "ccmonth", "", "month",
&field);
form->fields.push_back(field);
} else {
test::CreateTestFormField("Expiration Date", "ccmonth", "", "text",
&field);
form->fields.push_back(field);
test::CreateTestFormField("", "ccyear", "", "text", &field);
form->fields.push_back(field);
}
test::CreateTestFormField("CVC", "cvc", "", "text", &field);
form->fields.push_back(field);
}
// Fills the fields in |form| with test data.
void ManuallyFillAddressForm(const char* first_name,
const char* last_name,
const char* zip_code,
const char* country,
FormData* form) {
for (FormFieldData& field : form->fields) {
if (base::EqualsASCII(field.name, "firstname"))
field.value = ASCIIToUTF16(first_name);
else if (base::EqualsASCII(field.name, "lastname"))
field.value = ASCIIToUTF16(last_name);
else if (base::EqualsASCII(field.name, "addr1"))
field.value = ASCIIToUTF16("123 Maple");
else if (base::EqualsASCII(field.name, "city"))
field.value = ASCIIToUTF16("Dallas");
else if (base::EqualsASCII(field.name, "state"))
field.value = ASCIIToUTF16("Texas");
else if (base::EqualsASCII(field.name, "zipcode"))
field.value = ASCIIToUTF16(zip_code);
else if (base::EqualsASCII(field.name, "country"))
field.value = ASCIIToUTF16(country);
}
}
// Tests if credit card data gets saved.
void TestSaveCreditCards(bool is_https) {
// Set up our form data.
FormData form;
CreateTestCreditCardFormData(&form, is_https, false);
std::vector<FormData> forms(1, form);
FormsSeen(forms);
// Edit the data, and submit.
form.fields[1].value = ASCIIToUTF16("4111111111111111");
form.fields[2].value = ASCIIToUTF16("11");
form.fields[3].value = ASCIIToUTF16(NextYear());
EXPECT_CALL(autofill_client_, ConfirmSaveCreditCardLocally(_, _));
FormSubmitted(form);
}
void ExpectUniqueFillableFormParsedUkm() {
auto entries = test_ukm_recorder_.GetEntriesByName(
UkmDeveloperEngagementType::kEntryName);
EXPECT_EQ(1u, entries.size());
for (const auto* const entry : entries) {
test_ukm_recorder_.ExpectEntryMetric(
entry, UkmDeveloperEngagementType::kDeveloperEngagementName,
1 << AutofillMetrics::FILLABLE_FORM_PARSED_WITHOUT_TYPE_HINTS);
}
}
void ExpectUniqueCardUploadDecision(
const base::HistogramTester& histogram_tester,
AutofillMetrics::CardUploadDecisionMetric metric) {
histogram_tester.ExpectUniqueSample("Autofill.CardUploadDecisionMetric",
ToHistogramSample(metric), 1);
}
void ExpectCardUploadDecision(
const base::HistogramTester& histogram_tester,
AutofillMetrics::CardUploadDecisionMetric metric) {
histogram_tester.ExpectBucketCount("Autofill.CardUploadDecisionMetric",
ToHistogramSample(metric), 1);
}
void ExpectCardUploadDecisionUkm(int expected_metric_value) {
ExpectMetric(UkmCardUploadDecisionType::kUploadDecisionName,
UkmCardUploadDecisionType::kEntryName, expected_metric_value,
1 /* expected_num_matching_entries */);
}
void ExpectFillableFormParsedUkm(int num_fillable_forms_parsed) {
ExpectMetric(UkmDeveloperEngagementType::kDeveloperEngagementName,
UkmDeveloperEngagementType::kEntryName,
1 << AutofillMetrics::FILLABLE_FORM_PARSED_WITHOUT_TYPE_HINTS,
num_fillable_forms_parsed);
}
void ExpectMetric(const char* metric_name,
const char* entry_name,
int expected_metric_value,
size_t expected_num_matching_entries) {
auto entries = test_ukm_recorder_.GetEntriesByName(entry_name);
EXPECT_EQ(expected_num_matching_entries, entries.size());
for (const auto* const entry : entries) {
test_ukm_recorder_.ExpectEntryMetric(entry, metric_name,
expected_metric_value);
}
}
protected:
base::test::ScopedTaskEnvironment scoped_task_environment_;
ukm::TestAutoSetUkmRecorder test_ukm_recorder_;
MockAutofillClient autofill_client_;
std::unique_ptr<TestAutofillDriver> autofill_driver_;
std::unique_ptr<TestAutofillManager> autofill_manager_;
scoped_refptr<net::TestURLRequestContextGetter> request_context_;
TestPersonalDataManager personal_data_;
TestSyncService sync_service_;
base::test::ScopedFeatureList scoped_feature_list_;
// Ends up getting owned (and destroyed) by TestFormDataImporter:
TestCreditCardSaveManager* credit_card_save_manager_;
// Ends up getting owned (and destroyed) by TestAutofillManager:
payments::TestPaymentsClient* payments_client_;
private:
int ToHistogramSample(AutofillMetrics::CardUploadDecisionMetric metric) {
for (int sample = 0; sample < metric + 1; ++sample)
if (metric & (1 << sample))
return sample;
NOTREACHED();
return 0;
}
};
// Tests that credit card data are saved for forms on https
// TODO(crbug.com/666704): Flaky on android_n5x_swarming_rel bot.
#if defined(OS_ANDROID)
#define MAYBE_ImportFormDataCreditCardHTTPS \
DISABLED_ImportFormDataCreditCardHTTPS
#else
#define MAYBE_ImportFormDataCreditCardHTTPS ImportFormDataCreditCardHTTPS
#endif
TEST_F(CreditCardSaveManagerTest, MAYBE_ImportFormDataCreditCardHTTPS) {
TestSaveCreditCards(true);
}
// Tests that credit card data are saved for forms on http
// TODO(crbug.com/666704): Flaky on android_n5x_swarming_rel bot.
#if defined(OS_ANDROID)
#define MAYBE_ImportFormDataCreditCardHTTP DISABLED_ImportFormDataCreditCardHTTP
#else
#define MAYBE_ImportFormDataCreditCardHTTP ImportFormDataCreditCardHTTP
#endif
TEST_F(CreditCardSaveManagerTest, MAYBE_ImportFormDataCreditCardHTTP) {
TestSaveCreditCards(false);
}
// Tests that credit card data are saved when autocomplete=off for CC field.
// TODO(crbug.com/666704): Flaky on android_n5x_swarming_rel bot.
#if defined(OS_ANDROID)
#define MAYBE_CreditCardSavedWhenAutocompleteOff \
DISABLED_CreditCardSavedWhenAutocompleteOff
#else
#define MAYBE_CreditCardSavedWhenAutocompleteOff \
CreditCardSavedWhenAutocompleteOff
#endif
TEST_F(CreditCardSaveManagerTest, MAYBE_CreditCardSavedWhenAutocompleteOff) {
// Set up our form data.
FormData form;
CreateTestCreditCardFormData(&form, false, false);
// Set "autocomplete=off" for cardnumber field.
form.fields[1].should_autocomplete = false;
std::vector<FormData> forms(1, form);
FormsSeen(forms);
// Edit the data, and submit.
form.fields[1].value = ASCIIToUTF16("4111111111111111");
form.fields[2].value = ASCIIToUTF16("11");
form.fields[3].value = ASCIIToUTF16(NextYear());
EXPECT_CALL(autofill_client_, ConfirmSaveCreditCardLocally(_, _));
FormSubmitted(form);
}
// Tests that credit card data are not saved when CC number does not pass the
// Luhn test.
TEST_F(CreditCardSaveManagerTest, InvalidCreditCardNumberIsNotSaved) {
// Set up our form data.
FormData form;
CreateTestCreditCardFormData(&form, true, false);
std::vector<FormData> forms(1, form);
FormsSeen(forms);
// Edit the data, and submit.
std::string card("4408041234567890");
ASSERT_FALSE(autofill::IsValidCreditCardNumber(ASCIIToUTF16(card)));
form.fields[1].value = ASCIIToUTF16(card);
form.fields[2].value = ASCIIToUTF16("11");
form.fields[3].value = ASCIIToUTF16(NextYear());
EXPECT_CALL(autofill_client_, ConfirmSaveCreditCardLocally(_, _)).Times(0);
FormSubmitted(form);
}
TEST_F(CreditCardSaveManagerTest, CreditCardDisabledDoesNotSave) {
personal_data_.ClearProfiles();
autofill_manager_->SetCreditCardEnabled(false);
// Create, fill and submit an address form in order to establish a recent
// profile which can be selected for the upload request.
FormData address_form;
test::CreateTestAddressFormData(&address_form);
FormsSeen(std::vector<FormData>(1, address_form));
ManuallyFillAddressForm("Flo", "Master", "77401", "US", &address_form);
FormSubmitted(address_form);
// Set up our credit card form data.
FormData credit_card_form;
CreateTestCreditCardFormData(&credit_card_form, true, false);
FormsSeen(std::vector<FormData>(1, credit_card_form));
// Edit the data, and submit.
credit_card_form.fields[0].value = ASCIIToUTF16("Flo Master");
credit_card_form.fields[1].value = ASCIIToUTF16("4111111111111111");
credit_card_form.fields[2].value = ASCIIToUTF16("11");
credit_card_form.fields[3].value = ASCIIToUTF16(NextYear());
credit_card_form.fields[4].value = ASCIIToUTF16("123");
base::HistogramTester histogram_tester;
// The credit card should neither be saved locally or uploaded.
EXPECT_CALL(autofill_client_, ConfirmSaveCreditCardLocally(_, _)).Times(0);
FormSubmitted(credit_card_form);
EXPECT_FALSE(credit_card_save_manager_->CreditCardWasUploaded());
// Verify that no histogram entry was logged.
histogram_tester.ExpectTotalCount("Autofill.CardUploadDecisionMetric", 0);
}
TEST_F(CreditCardSaveManagerTest, UploadCreditCard) {
personal_data_.ClearCreditCards();
personal_data_.ClearProfiles();
credit_card_save_manager_->SetCreditCardUploadEnabled(true);
// Create, fill and submit an address form in order to establish a recent
// profile which can be selected for the upload request.
FormData address_form;
test::CreateTestAddressFormData(&address_form);
FormsSeen(std::vector<FormData>(1, address_form));
ExpectUniqueFillableFormParsedUkm();
ManuallyFillAddressForm("Flo", "Master", "77401", "US", &address_form);
FormSubmitted(address_form);
// Set up our credit card form data.
FormData credit_card_form;
CreateTestCreditCardFormData(&credit_card_form, true, false);
FormsSeen(std::vector<FormData>(1, credit_card_form));
ExpectFillableFormParsedUkm(2 /* num_fillable_forms_parsed */);
// Edit the data, and submit.
credit_card_form.fields[0].value = ASCIIToUTF16("Flo Master");
credit_card_form.fields[1].value = ASCIIToUTF16("4111111111111111");
credit_card_form.fields[2].value = ASCIIToUTF16("11");
credit_card_form.fields[3].value = ASCIIToUTF16(NextYear());
credit_card_form.fields[4].value = ASCIIToUTF16("123");
base::HistogramTester histogram_tester;
EXPECT_CALL(autofill_client_, ConfirmSaveCreditCardLocally(_, _)).Times(0);
FormSubmitted(credit_card_form);
EXPECT_TRUE(credit_card_save_manager_->CreditCardWasUploaded());
EXPECT_THAT(payments_client_->GetActiveExperimentsSetInRequest(),
UnorderedElementsAre(kAutofillUpstreamSendDetectedValues.name));
// Server did not send a server_id, expect copy of card is not stored.
EXPECT_TRUE(personal_data_.GetCreditCards().empty());
// Verify that the correct histogram entry (and only that) was logged.
ExpectUniqueCardUploadDecision(histogram_tester,
AutofillMetrics::UPLOAD_OFFERED);
// Verify that the correct UKM was logged.
ExpectCardUploadDecisionUkm(AutofillMetrics::UPLOAD_OFFERED);
// Verify the histogram entry for recent profile modification.
histogram_tester.ExpectUniqueSample(
"Autofill.HasModifiedProfile.CreditCardFormSubmission", true, 1);
// Verify that UMA for "DaysSincePreviousUse" was not logged because we
// modified the profile.
histogram_tester.ExpectTotalCount(
"Autofill.DaysSincePreviousUseAtSubmission.Profile", 0);
}
TEST_F(CreditCardSaveManagerTest, UploadCreditCardAndSaveCopy) {
personal_data_.ClearCreditCards();
personal_data_.ClearProfiles();
credit_card_save_manager_->SetCreditCardUploadEnabled(true);
const char* const server_id = "InstrumentData:1234";
payments_client_->SetServerIdForCardUpload(server_id);
// Create, fill and submit an address form in order to establish a recent
// profile which can be selected for the upload request.
FormData address_form;
test::CreateTestAddressFormData(&address_form);
FormsSeen(std::vector<FormData>(1, address_form));
ManuallyFillAddressForm("Flo", "Master", "77401", "US", &address_form);
FormSubmitted(address_form);
// Set up our credit card form data.
FormData credit_card_form;
CreateTestCreditCardFormData(&credit_card_form, true, false);
FormsSeen(std::vector<FormData>(1, credit_card_form));
// Edit the data, and submit.
const char* const card_number = "4111111111111111";
credit_card_form.fields[0].value = ASCIIToUTF16("Flo Master");
credit_card_form.fields[1].value = ASCIIToUTF16(card_number);
credit_card_form.fields[2].value = ASCIIToUTF16("11");
credit_card_form.fields[3].value = ASCIIToUTF16(NextYear());
credit_card_form.fields[4].value = ASCIIToUTF16("123");
FormSubmitted(credit_card_form);
EXPECT_TRUE(credit_card_save_manager_->CreditCardWasUploaded());
EXPECT_TRUE(personal_data_.GetLocalCreditCards().empty());
#if defined(OS_LINUX) && !defined(OS_CHROMEOS)
// See |OfferStoreUnmaskedCards|
EXPECT_TRUE(personal_data_.GetCreditCards().empty());
#else
ASSERT_EQ(1U, personal_data_.GetCreditCards().size());
const CreditCard* const saved_card = personal_data_.GetCreditCards()[0];
EXPECT_EQ(CreditCard::OK, saved_card->GetServerStatus());
EXPECT_EQ(base::ASCIIToUTF16("1111"), saved_card->LastFourDigits());
EXPECT_EQ(kVisaCard, saved_card->network());
EXPECT_EQ(11, saved_card->expiration_month());
EXPECT_EQ(std::stoi(NextYear()), saved_card->expiration_year());
EXPECT_EQ(server_id, saved_card->server_id());
EXPECT_EQ(CreditCard::FULL_SERVER_CARD, saved_card->record_type());
EXPECT_EQ(base::ASCIIToUTF16(card_number), saved_card->number());
#endif
}
TEST_F(CreditCardSaveManagerTest, UploadCreditCard_FeatureNotEnabled) {
personal_data_.ClearProfiles();
credit_card_save_manager_->SetCreditCardUploadEnabled(false);
// Create, fill and submit an address form in order to establish a recent
// profile which can be selected for the upload request.
FormData address_form;
test::CreateTestAddressFormData(&address_form);
FormsSeen(std::vector<FormData>(1, address_form));
ManuallyFillAddressForm("Flo", "Master", "77401", "US", &address_form);
FormSubmitted(address_form);
// Set up our credit card form data.
FormData credit_card_form;
CreateTestCreditCardFormData(&credit_card_form, true, false);
FormsSeen(std::vector<FormData>(1, credit_card_form));
// Edit the data, and submit.
credit_card_form.fields[0].value = ASCIIToUTF16("Flo Master");
credit_card_form.fields[1].value = ASCIIToUTF16("4111111111111111");
credit_card_form.fields[2].value = ASCIIToUTF16("11");
credit_card_form.fields[3].value = ASCIIToUTF16(NextYear());
credit_card_form.fields[4].value = ASCIIToUTF16("123");
base::HistogramTester histogram_tester;
// The save prompt should be shown instead of doing an upload.
EXPECT_CALL(autofill_client_, ConfirmSaveCreditCardLocally(_, _));
FormSubmitted(credit_card_form);
EXPECT_FALSE(credit_card_save_manager_->CreditCardWasUploaded());
// Verify that no histogram entry was logged.
histogram_tester.ExpectTotalCount("Autofill.CardUploadDecisionMetric", 0);
}
TEST_F(CreditCardSaveManagerTest, UploadCreditCard_CvcUnavailable) {
EnableAutofillUpstreamSendDetectedValuesExperiment();
personal_data_.ClearProfiles();
credit_card_save_manager_->SetCreditCardUploadEnabled(true);
// Create, fill and submit an address form in order to establish a recent
// profile which can be selected for the upload request.
FormData address_form;
test::CreateTestAddressFormData(&address_form);
FormsSeen(std::vector<FormData>(1, address_form));
ExpectUniqueFillableFormParsedUkm();
ManuallyFillAddressForm("Flo", "Master", "77401", "US", &address_form);
FormSubmitted(address_form);
// Set up our credit card form data.
FormData credit_card_form;
CreateTestCreditCardFormData(&credit_card_form, true, false);
FormsSeen(std::vector<FormData>(1, credit_card_form));
ExpectFillableFormParsedUkm(2 /* num_fillable_forms_parsed */);
// Edit the data, and submit.
credit_card_form.fields[0].value = ASCIIToUTF16("Flo Master");
credit_card_form.fields[1].value = ASCIIToUTF16("4111111111111111");
credit_card_form.fields[2].value = ASCIIToUTF16("11");
credit_card_form.fields[3].value = ASCIIToUTF16(NextYear());
credit_card_form.fields[4].value = ASCIIToUTF16(""); // CVC MISSING
base::HistogramTester histogram_tester;
// With the offer-to-save decision deferred to Google Payments, Payments can
// still decide to allow saving despite the missing CVC value.
EXPECT_CALL(autofill_client_, ConfirmSaveCreditCardLocally(_, _)).Times(0);
FormSubmitted(credit_card_form);
EXPECT_TRUE(credit_card_save_manager_->CreditCardWasUploaded());
// Verify that the correct histogram entries were logged.
ExpectCardUploadDecision(histogram_tester, AutofillMetrics::UPLOAD_OFFERED);
ExpectCardUploadDecision(histogram_tester,
AutofillMetrics::CVC_VALUE_NOT_FOUND);
// Verify that the correct UKM was logged.
ExpectCardUploadDecisionUkm(AutofillMetrics::UPLOAD_OFFERED |
AutofillMetrics::CVC_VALUE_NOT_FOUND);
}
TEST_F(CreditCardSaveManagerTest,
UploadCreditCard_CvcUnavailable_DetectedValuesOff) {
DisableAutofillUpstreamSendDetectedValuesExperiment();
personal_data_.ClearProfiles();
credit_card_save_manager_->SetCreditCardUploadEnabled(true);
// Create, fill and submit an address form in order to establish a recent
// profile which can be selected for the upload request.
FormData address_form;
test::CreateTestAddressFormData(&address_form);
FormsSeen(std::vector<FormData>(1, address_form));
ExpectUniqueFillableFormParsedUkm();
ManuallyFillAddressForm("Flo", "Master", "77401", "US", &address_form);
FormSubmitted(address_form);
// Set up our credit card form data.
FormData credit_card_form;
CreateTestCreditCardFormData(&credit_card_form, true, false);
FormsSeen(std::vector<FormData>(1, credit_card_form));
ExpectFillableFormParsedUkm(2 /* num_fillable_forms_parsed */);
// Edit the data, and submit.
credit_card_form.fields[0].value = ASCIIToUTF16("Flo Master");
credit_card_form.fields[1].value = ASCIIToUTF16("4111111111111111");
credit_card_form.fields[2].value = ASCIIToUTF16("11");
credit_card_form.fields[3].value = ASCIIToUTF16(NextYear());
credit_card_form.fields[4].value = ASCIIToUTF16(""); // CVC MISSING
base::HistogramTester histogram_tester;
// Neither a local save nor an upload should happen in this case.
EXPECT_CALL(autofill_client_, ConfirmSaveCreditCardLocally(_, _)).Times(0);
FormSubmitted(credit_card_form);
EXPECT_FALSE(credit_card_save_manager_->CreditCardWasUploaded());
// Verify that the correct histogram entry (and only that) was logged.
ExpectUniqueCardUploadDecision(histogram_tester,
AutofillMetrics::CVC_VALUE_NOT_FOUND);
// Verify that the correct UKM was logged.
ExpectCardUploadDecisionUkm(AutofillMetrics::CVC_VALUE_NOT_FOUND);
}
TEST_F(CreditCardSaveManagerTest, UploadCreditCard_CvcInvalidLength) {
personal_data_.ClearProfiles();
credit_card_save_manager_->SetCreditCardUploadEnabled(true);
// Create, fill and submit an address form in order to establish a recent
// profile which can be selected for the upload request.
FormData address_form;
test::CreateTestAddressFormData(&address_form);
FormsSeen(std::vector<FormData>(1, address_form));
ManuallyFillAddressForm("Flo", "Master", "77401", "US", &address_form);
FormSubmitted(address_form);
// Set up our credit card form data.
FormData credit_card_form;
CreateTestCreditCardFormData(&credit_card_form, true, false);
FormsSeen(std::vector<FormData>(1, credit_card_form));
// Edit the data, and submit.
credit_card_form.fields[0].value = ASCIIToUTF16("Flo Master");
credit_card_form.fields[1].value = ASCIIToUTF16("4111111111111111");
credit_card_form.fields[2].value = ASCIIToUTF16("11");
credit_card_form.fields[3].value = ASCIIToUTF16(NextYear());
credit_card_form.fields[4].value = ASCIIToUTF16("1234");
base::HistogramTester histogram_tester;
// With the offer-to-save decision deferred to Google Payments, Payments can
// still decide to allow saving despite the invalid CVC value.
EXPECT_CALL(autofill_client_, ConfirmSaveCreditCardLocally(_, _)).Times(0);
FormSubmitted(credit_card_form);
EXPECT_TRUE(credit_card_save_manager_->CreditCardWasUploaded());
// Verify that the correct histogram entries were logged.
ExpectCardUploadDecision(histogram_tester, AutofillMetrics::UPLOAD_OFFERED);
ExpectCardUploadDecision(histogram_tester,
AutofillMetrics::INVALID_CVC_VALUE);
// Verify that the correct UKM was logged.
ExpectCardUploadDecisionUkm(AutofillMetrics::UPLOAD_OFFERED |
AutofillMetrics::INVALID_CVC_VALUE);
}
TEST_F(CreditCardSaveManagerTest,
UploadCreditCard_CvcInvalidLength_DetectedValuesOff) {
DisableAutofillUpstreamSendDetectedValuesExperiment();
personal_data_.ClearProfiles();
credit_card_save_manager_->SetCreditCardUploadEnabled(true);
// Create, fill and submit an address form in order to establish a recent
// profile which can be selected for the upload request.
FormData address_form;
test::CreateTestAddressFormData(&address_form);
FormsSeen(std::vector<FormData>(1, address_form));
ManuallyFillAddressForm("Flo", "Master", "77401", "US", &address_form);
FormSubmitted(address_form);
// Set up our credit card form data.
FormData credit_card_form;
CreateTestCreditCardFormData(&credit_card_form, true, false);
FormsSeen(std::vector<FormData>(1, credit_card_form));
// Edit the data, and submit.
credit_card_form.fields[0].value = ASCIIToUTF16("Flo Master");
credit_card_form.fields[1].value = ASCIIToUTF16("4111111111111111");
credit_card_form.fields[2].value = ASCIIToUTF16("11");
credit_card_form.fields[3].value = ASCIIToUTF16(NextYear());
credit_card_form.fields[4].value = ASCIIToUTF16("1234");
base::HistogramTester histogram_tester;
// Neither a local save nor an upload should happen in this case.
EXPECT_CALL(autofill_client_, ConfirmSaveCreditCardLocally(_, _)).Times(0);
FormSubmitted(credit_card_form);
EXPECT_FALSE(credit_card_save_manager_->CreditCardWasUploaded());
// Verify that the correct histogram entry (and only that) was logged.
ExpectUniqueCardUploadDecision(histogram_tester,
AutofillMetrics::INVALID_CVC_VALUE);
// Verify that the correct UKM was logged.
ExpectCardUploadDecisionUkm(AutofillMetrics::INVALID_CVC_VALUE);
}
TEST_F(CreditCardSaveManagerTest, UploadCreditCard_MultipleCvcFields) {
credit_card_save_manager_->SetCreditCardUploadEnabled(true);
// Remove the profiles that were created in the TestPersonalDataManager
// constructor because they would result in conflicting names that would
// prevent the upload.
personal_data_.ClearProfiles();
// Create, fill and submit an address form in order to establish a recent
// profile which can be selected for the upload request.
FormData address_form;
test::CreateTestAddressFormData(&address_form);
FormsSeen(std::vector<FormData>(1, address_form));
ManuallyFillAddressForm("Flo", "Master", "77401", "US", &address_form);
FormSubmitted(address_form);
// Set up our credit card form data.
FormData credit_card_form;
credit_card_form.name = ASCIIToUTF16("MyForm");
credit_card_form.origin = GURL("https://myform.com/form.html");
credit_card_form.action = GURL("https://myform.com/submit.html");
credit_card_form.main_frame_origin =
url::Origin::Create(GURL("http://myform_root.com/form.html"));
FormFieldData field;
test::CreateTestFormField("Card Name", "cardname", "", "text", &field);
credit_card_form.fields.push_back(field);
test::CreateTestFormField("Card Number", "cardnumber", "", "text", &field);
credit_card_form.fields.push_back(field);
test::CreateTestFormField("Expiration Month", "ccmonth", "", "text", &field);
credit_card_form.fields.push_back(field);
test::CreateTestFormField("Expiration Year", "ccyear", "", "text", &field);
credit_card_form.fields.push_back(field);
test::CreateTestFormField("CVC (hidden)", "cvc1", "", "text", &field);
credit_card_form.fields.push_back(field);
test::CreateTestFormField("CVC", "cvc2", "", "text", &field);
credit_card_form.fields.push_back(field);
FormsSeen(std::vector<FormData>(1, credit_card_form));
// Edit the data, and submit.
credit_card_form.fields[0].value = ASCIIToUTF16("Flo Master");
credit_card_form.fields[1].value = ASCIIToUTF16("4111111111111111");
credit_card_form.fields[2].value = ASCIIToUTF16("11");
credit_card_form.fields[3].value = ASCIIToUTF16(NextYear());
credit_card_form.fields[4].value = ASCIIToUTF16(""); // CVC MISSING
credit_card_form.fields[5].value = ASCIIToUTF16("123");
base::HistogramTester histogram_tester;
// A CVC value appeared in one of the two CVC fields, upload should happen.
EXPECT_CALL(autofill_client_, ConfirmSaveCreditCardLocally(_, _)).Times(0);
FormSubmitted(credit_card_form);
EXPECT_TRUE(credit_card_save_manager_->CreditCardWasUploaded());
// Verify that the correct histogram entry (and only that) was logged.
ExpectUniqueCardUploadDecision(histogram_tester,
AutofillMetrics::UPLOAD_OFFERED);
// Verify that the correct UKM was logged.
ExpectCardUploadDecisionUkm(AutofillMetrics::UPLOAD_OFFERED);
}
TEST_F(CreditCardSaveManagerTest, UploadCreditCard_NoCvcFieldOnForm) {
credit_card_save_manager_->SetCreditCardUploadEnabled(true);
// Remove the profiles that were created in the TestPersonalDataManager
// constructor because they would result in conflicting names that would
// prevent the upload.
personal_data_.ClearProfiles();
// Create, fill and submit an address form in order to establish a recent
// profile which can be selected for the upload request.
FormData address_form;
test::CreateTestAddressFormData(&address_form);
FormsSeen(std::vector<FormData>(1, address_form));
ManuallyFillAddressForm("Flo", "Master", "77401", "US", &address_form);
FormSubmitted(address_form);
// Set up our credit card form data. Note that CVC field is missing.
FormData credit_card_form;
credit_card_form.name = ASCIIToUTF16("MyForm");
credit_card_form.origin = GURL("https://myform.com/form.html");
credit_card_form.action = GURL("https://myform.com/submit.html");
credit_card_form.main_frame_origin =
url::Origin::Create(GURL("http://myform_root.com/form.html"));
FormFieldData field;
test::CreateTestFormField("Card Name", "cardname", "", "text", &field);
credit_card_form.fields.push_back(field);
test::CreateTestFormField("Card Number", "cardnumber", "", "text", &field);
credit_card_form.fields.push_back(field);
test::CreateTestFormField("Expiration Month", "ccmonth", "", "text", &field);
credit_card_form.fields.push_back(field);
test::CreateTestFormField("Expiration Year", "ccyear", "", "text", &field);
credit_card_form.fields.push_back(field);
FormsSeen(std::vector<FormData>(1, credit_card_form));
// Edit the data, and submit.
credit_card_form.fields[0].value = ASCIIToUTF16("Flo Master");
credit_card_form.fields[1].value = ASCIIToUTF16("4111111111111111");
credit_card_form.fields[2].value = ASCIIToUTF16("11");
credit_card_form.fields[3].value = ASCIIToUTF16(NextYear());
base::HistogramTester histogram_tester;
// With the offer-to-save decision deferred to Google Payments, Payments can
// still decide to allow saving despite the missing CVC value.
EXPECT_CALL(autofill_client_, ConfirmSaveCreditCardLocally(_, _)).Times(0);
FormSubmitted(credit_card_form);
EXPECT_TRUE(credit_card_save_manager_->CreditCardWasUploaded());
// Verify that the correct histogram entries were logged.
ExpectCardUploadDecision(histogram_tester, AutofillMetrics::UPLOAD_OFFERED);
ExpectCardUploadDecision(histogram_tester,
AutofillMetrics::CVC_FIELD_NOT_FOUND);
// Verify that the correct UKM was logged.
ExpectCardUploadDecisionUkm(AutofillMetrics::UPLOAD_OFFERED |
AutofillMetrics::CVC_FIELD_NOT_FOUND);
}
TEST_F(CreditCardSaveManagerTest,
UploadCreditCard_NoCvcFieldOnForm_DetectedValuesOff) {
DisableAutofillUpstreamSendDetectedValuesExperiment();
credit_card_save_manager_->SetCreditCardUploadEnabled(true);
// Remove the profiles that were created in the TestPersonalDataManager
// constructor because they would result in conflicting names that would
// prevent the upload.
personal_data_.ClearProfiles();
// Create, fill and submit an address form in order to establish a recent
// profile which can be selected for the upload request.
FormData address_form;
test::CreateTestAddressFormData(&address_form);
FormsSeen(std::vector<FormData>(1, address_form));
ManuallyFillAddressForm("Flo", "Master", "77401", "US", &address_form);
FormSubmitted(address_form);
// Set up our credit card form data. Note that CVC field is missing.
FormData credit_card_form;
credit_card_form.name = ASCIIToUTF16("MyForm");
credit_card_form.origin = GURL("https://myform.com/form.html");
credit_card_form.action = GURL("https://myform.com/submit.html");
credit_card_form.main_frame_origin =
url::Origin::Create(GURL("http://myform_root.com/form.html"));
FormFieldData field;
test::CreateTestFormField("Card Name", "cardname", "", "text", &field);
credit_card_form.fields.push_back(field);
test::CreateTestFormField("Card Number", "cardnumber", "", "text", &field);
credit_card_form.fields.push_back(field);
test::CreateTestFormField("Expiration Month", "ccmonth", "", "text", &field);
credit_card_form.fields.push_back(field);
test::CreateTestFormField("Expiration Year", "ccyear", "", "text", &field);
credit_card_form.fields.push_back(field);
FormsSeen(std::vector<FormData>(1, credit_card_form));
// Edit the data, and submit.
credit_card_form.fields[0].value = ASCIIToUTF16("Flo Master");
credit_card_form.fields[1].value = ASCIIToUTF16("4111111111111111");
credit_card_form.fields[2].value = ASCIIToUTF16("11");
credit_card_form.fields[3].value = ASCIIToUTF16(NextYear());
base::HistogramTester histogram_tester;
// Upload should not happen because CVC field was not found.
EXPECT_CALL(autofill_client_, ConfirmSaveCreditCardLocally(_, _)).Times(0);
FormSubmitted(credit_card_form);
EXPECT_FALSE(credit_card_save_manager_->CreditCardWasUploaded());
// Verify that the correct histogram entry (and only that) was logged.
ExpectUniqueCardUploadDecision(histogram_tester,
AutofillMetrics::CVC_FIELD_NOT_FOUND);
// Verify that the correct UKM was logged.
ExpectCardUploadDecisionUkm(AutofillMetrics::CVC_FIELD_NOT_FOUND);
}
TEST_F(CreditCardSaveManagerTest,
UploadCreditCard_NoCvcFieldOnForm_InvalidCvcInNonCvcField) {
credit_card_save_manager_->SetCreditCardUploadEnabled(true);
// Remove the profiles that were created in the TestPersonalDataManager
// constructor because they would result in conflicting names that would
// prevent the upload.
personal_data_.ClearProfiles();
// Create, fill and submit an address form in order to establish a recent
// profile which can be selected for the upload request.
FormData address_form;
test::CreateTestAddressFormData(&address_form);
FormsSeen({address_form});
ManuallyFillAddressForm("Flo", "Master", "77401", "US", &address_form);
FormSubmitted(address_form);
// Set up our credit card form data. Note that CVC field is missing.
FormData credit_card_form;
credit_card_form.name = ASCIIToUTF16("MyForm");
credit_card_form.origin = GURL("https://myform.com/form.html");
credit_card_form.action = GURL("https://myform.com/submit.html");
credit_card_form.main_frame_origin =
url::Origin::Create(GURL("http://myform_root.com/form.html"));
FormFieldData field;
test::CreateTestFormField("Card Name", "cardname", "", "text", &field);
credit_card_form.fields.push_back(field);
test::CreateTestFormField("Card Number", "cardnumber", "", "text", &field);
credit_card_form.fields.push_back(field);
test::CreateTestFormField("Expiration Month", "ccmonth", "", "text", &field);
credit_card_form.fields.push_back(field);
test::CreateTestFormField("Expiration Year", "ccyear", "", "text", &field);
credit_card_form.fields.push_back(field);
test::CreateTestFormField("Random Field", "random", "", "text", &field);
credit_card_form.fields.push_back(field);
FormsSeen({credit_card_form});
// Enter an invalid cvc in "Random Field" and submit.
credit_card_form.fields[0].value = ASCIIToUTF16("Flo Master");
credit_card_form.fields[1].value = ASCIIToUTF16("4111111111111111");
credit_card_form.fields[2].value = ASCIIToUTF16("11");
credit_card_form.fields[3].value = ASCIIToUTF16(NextYear());
credit_card_form.fields[4].value = ASCIIToUTF16("1234");
base::HistogramTester histogram_tester;
// With the offer-to-save decision deferred to Google Payments, Payments can
// still decide to allow saving despite the invalid CVC value.
EXPECT_CALL(autofill_client_, ConfirmSaveCreditCardLocally(_, _)).Times(0);
FormSubmitted(credit_card_form);
EXPECT_TRUE(credit_card_save_manager_->CreditCardWasUploaded());
// Verify that the correct histogram entries were logged.
ExpectCardUploadDecision(histogram_tester, AutofillMetrics::UPLOAD_OFFERED);
ExpectCardUploadDecision(histogram_tester,
AutofillMetrics::CVC_FIELD_NOT_FOUND);
// Verify that the correct UKM was logged.
ExpectCardUploadDecisionUkm(AutofillMetrics::UPLOAD_OFFERED |
AutofillMetrics::CVC_FIELD_NOT_FOUND);
}
TEST_F(
CreditCardSaveManagerTest,
UploadCreditCard_NoCvcFieldOnForm_InvalidCvcInNonCvcField_DetectedValuesOff) {
DisableAutofillUpstreamSendDetectedValuesExperiment();
credit_card_save_manager_->SetCreditCardUploadEnabled(true);
// Remove the profiles that were created in the TestPersonalDataManager
// constructor because they would result in conflicting names that would
// prevent the upload.
personal_data_.ClearProfiles();
// Create, fill and submit an address form in order to establish a recent
// profile which can be selected for the upload request.
FormData address_form;
test::CreateTestAddressFormData(&address_form);
FormsSeen({address_form});
ManuallyFillAddressForm("Flo", "Master", "77401", "US", &address_form);
FormSubmitted(address_form);
// Set up our credit card form data. Note that CVC field is missing.
FormData credit_card_form;
credit_card_form.name = ASCIIToUTF16("MyForm");
credit_card_form.origin = GURL("https://myform.com/form.html");
credit_card_form.action = GURL("https://myform.com/submit.html");
credit_card_form.main_frame_origin =
url::Origin::Create(GURL("http://myform_root.com/form.html"));
FormFieldData field;
test::CreateTestFormField("Card Name", "cardname", "", "text", &field);
credit_card_form.fields.push_back(field);
test::CreateTestFormField("Card Number", "cardnumber", "", "text", &field);
credit_card_form.fields.push_back(field);
test::CreateTestFormField("Expiration Month", "ccmonth", "", "text", &field);
credit_card_form.fields.push_back(field);
test::CreateTestFormField("Expiration Year", "ccyear", "", "text", &field);
credit_card_form.fields.push_back(field);
test::CreateTestFormField("Random Field", "random", "", "text", &field);
credit_card_form.fields.push_back(field);
FormsSeen({credit_card_form});
// Enter an invalid cvc in "Random Field" and submit.
credit_card_form.fields[0].value = ASCIIToUTF16("Flo Master");
credit_card_form.fields[1].value = ASCIIToUTF16("4111111111111111");
credit_card_form.fields[2].value = ASCIIToUTF16("11");
credit_card_form.fields[3].value = ASCIIToUTF16(NextYear());
credit_card_form.fields[4].value = ASCIIToUTF16("1234");
base::HistogramTester histogram_tester;
// Upload should not happen because CVC field was not found.
EXPECT_CALL(autofill_client_, ConfirmSaveCreditCardLocally(_, _)).Times(0);
FormSubmitted(credit_card_form);
EXPECT_FALSE(credit_card_save_manager_->CreditCardWasUploaded());
// Verify that the correct histogram entry (and only that) was logged.
ExpectUniqueCardUploadDecision(histogram_tester,
AutofillMetrics::CVC_FIELD_NOT_FOUND);
// Verify that the correct UKM was logged.
ExpectCardUploadDecisionUkm(AutofillMetrics::CVC_FIELD_NOT_FOUND);
}
TEST_F(CreditCardSaveManagerTest,
UploadCreditCard_NoCvcFieldOnForm_CvcInNonCvcField) {
credit_card_save_manager_->SetCreditCardUploadEnabled(true);
// Remove the profiles that were created in the TestPersonalDataManager
// constructor because they would result in conflicting names that would
// prevent the upload.
personal_data_.ClearProfiles();
// Create, fill and submit an address form in order to establish a recent
// profile which can be selected for the upload request.
FormData address_form;
test::CreateTestAddressFormData(&address_form);
FormsSeen({address_form});
ManuallyFillAddressForm("Flo", "Master", "77401", "US", &address_form);
FormSubmitted(address_form);
// Set up our credit card form data. Note that CVC field is missing.
FormData credit_card_form;
credit_card_form.name = ASCIIToUTF16("MyForm");
credit_card_form.origin = GURL("https://myform.com/form.html");
credit_card_form.action = GURL("https://myform.com/submit.html");
credit_card_form.main_frame_origin =
url::Origin::Create(GURL("http://myform_root.com/form.html"));
FormFieldData field;
test::CreateTestFormField("Card Name", "cardname", "", "text", &field);
credit_card_form.fields.push_back(field);
test::CreateTestFormField("Card Number", "cardnumber", "", "text", &field);
credit_card_form.fields.push_back(field);
test::CreateTestFormField("Expiration Month", "ccmonth", "", "text", &field);
credit_card_form.fields.push_back(field);
test::CreateTestFormField("Expiration Year", "ccyear", "", "text", &field);
credit_card_form.fields.push_back(field);
test::CreateTestFormField("Random Field", "random", "", "text", &field);
credit_card_form.fields.push_back(field);
FormsSeen({credit_card_form});
// Enter a valid cvc in "Random Field" and submit.
credit_card_form.fields[0].value = ASCIIToUTF16("Flo Master");
credit_card_form.fields[1].value = ASCIIToUTF16("4111111111111111");
credit_card_form.fields[2].value = ASCIIToUTF16("11");
credit_card_form.fields[3].value = ASCIIToUTF16(NextYear());
credit_card_form.fields[4].value = ASCIIToUTF16("123");
base::HistogramTester histogram_tester;
// With the offer-to-save decision deferred to Google Payments, Payments can
// still decide to allow saving despite the missing CVC value.
EXPECT_CALL(autofill_client_, ConfirmSaveCreditCardLocally(_, _)).Times(0);
FormSubmitted(credit_card_form);
EXPECT_TRUE(credit_card_save_manager_->CreditCardWasUploaded());
// Verify that the correct histogram entries were logged.
ExpectCardUploadDecision(histogram_tester, AutofillMetrics::UPLOAD_OFFERED);
ExpectCardUploadDecision(
histogram_tester,
AutofillMetrics::FOUND_POSSIBLE_CVC_VALUE_IN_NON_CVC_FIELD);
// Verify that the correct UKM was logged.
ExpectCardUploadDecisionUkm(
AutofillMetrics::UPLOAD_OFFERED |
AutofillMetrics::FOUND_POSSIBLE_CVC_VALUE_IN_NON_CVC_FIELD);
}
TEST_F(CreditCardSaveManagerTest,
UploadCreditCard_NoCvcFieldOnForm_CvcInNonCvcField_DetectedValuesOff) {
DisableAutofillUpstreamSendDetectedValuesExperiment();
credit_card_save_manager_->SetCreditCardUploadEnabled(true);
// Remove the profiles that were created in the TestPersonalDataManager
// constructor because they would result in conflicting names that would
// prevent the upload.
personal_data_.ClearProfiles();
// Create, fill and submit an address form in order to establish a recent
// profile which can be selected for the upload request.
FormData address_form;
test::CreateTestAddressFormData(&address_form);
FormsSeen({address_form});
ManuallyFillAddressForm("Flo", "Master", "77401", "US", &address_form);
FormSubmitted(address_form);
// Set up our credit card form data. Note that CVC field is missing.
FormData credit_card_form;
credit_card_form.name = ASCIIToUTF16("MyForm");
credit_card_form.origin = GURL("https://myform.com/form.html");
credit_card_form.action = GURL("https://myform.com/submit.html");
credit_card_form.main_frame_origin =
url::Origin::Create(GURL("http://myform_root.com/form.html"));
FormFieldData field;
test::CreateTestFormField("Card Name", "cardname", "", "text", &field);
credit_card_form.fields.push_back(field);
test::CreateTestFormField("Card Number", "cardnumber", "", "text", &field);
credit_card_form.fields.push_back(field);
test::CreateTestFormField("Expiration Month", "ccmonth", "", "text", &field);
credit_card_form.fields.push_back(field);
test::CreateTestFormField("Expiration Year", "ccyear", "", "text", &field);
credit_card_form.fields.push_back(field);
test::CreateTestFormField("Random Field", "random", "", "text", &field);
credit_card_form.fields.push_back(field);
FormsSeen({credit_card_form});
// Enter a valid cvc in "Random Field" and submit.
credit_card_form.fields[0].value = ASCIIToUTF16("Flo Master");
credit_card_form.fields[1].value = ASCIIToUTF16("4111111111111111");
credit_card_form.fields[2].value = ASCIIToUTF16("11");
credit_card_form.fields[3].value = ASCIIToUTF16(NextYear());
credit_card_form.fields[4].value = ASCIIToUTF16("123");
base::HistogramTester histogram_tester;
// Upload should not happen because CVC field was not found.
EXPECT_CALL(autofill_client_, ConfirmSaveCreditCardLocally(_, _)).Times(0);
FormSubmitted(credit_card_form);
EXPECT_FALSE(credit_card_save_manager_->CreditCardWasUploaded());
// Verify that the correct histogram entry (and only that) was logged.
ExpectUniqueCardUploadDecision(
histogram_tester,
AutofillMetrics::FOUND_POSSIBLE_CVC_VALUE_IN_NON_CVC_FIELD);
// Verify that the correct UKM was logged.
ExpectCardUploadDecisionUkm(
AutofillMetrics::FOUND_POSSIBLE_CVC_VALUE_IN_NON_CVC_FIELD);
}
TEST_F(CreditCardSaveManagerTest,
UploadCreditCard_NoCvcFieldOnForm_CvcInAddressField) {
credit_card_save_manager_->SetCreditCardUploadEnabled(true);
// Remove the profiles that were created in the TestPersonalDataManager
// constructor because they would result in conflicting names that would
// prevent the upload.
personal_data_.ClearProfiles();
// Create, fill and submit an address form in order to establish a recent
// profile which can be selected for the upload request.
FormData address_form;
test::CreateTestAddressFormData(&address_form);
FormsSeen({address_form});
ManuallyFillAddressForm("Flo", "Master", "77401", "US", &address_form);
FormSubmitted(address_form);
// Set up our credit card form data. Note that CVC field is missing.
FormData credit_card_form;
credit_card_form.name = ASCIIToUTF16("MyForm");
credit_card_form.origin = GURL("https://myform.com/form.html");
credit_card_form.action = GURL("https://myform.com/submit.html");
credit_card_form.main_frame_origin =
url::Origin::Create(GURL("http://myform_root.com/form.html"));
FormFieldData field;
test::CreateTestFormField("Card Name", "cardname", "", "text", &field);
credit_card_form.fields.push_back(field);
test::CreateTestFormField("Card Number", "cardnumber", "", "text", &field);
credit_card_form.fields.push_back(field);
test::CreateTestFormField("Expiration Month", "ccmonth", "", "text", &field);
credit_card_form.fields.push_back(field);
test::CreateTestFormField("Expiration Year", "ccyear", "", "text", &field);
credit_card_form.fields.push_back(field);
test::CreateTestFormField("Address Line 1", "addr1", "", "text", &field);
credit_card_form.fields.push_back(field);
FormsSeen({credit_card_form});
// Enter a valid cvc in "Random Field" and submit.
credit_card_form.fields[0].value = ASCIIToUTF16("Flo Master");
credit_card_form.fields[1].value = ASCIIToUTF16("4111111111111111");
credit_card_form.fields[2].value = ASCIIToUTF16("11");
credit_card_form.fields[3].value = ASCIIToUTF16(NextYear());
credit_card_form.fields[4].value = ASCIIToUTF16("123");
base::HistogramTester histogram_tester;
// With the offer-to-save decision deferred to Google Payments, Payments can
// still decide to allow saving despite the missing CVC value.
EXPECT_CALL(autofill_client_, ConfirmSaveCreditCardLocally(_, _)).Times(0);
FormSubmitted(credit_card_form);
EXPECT_TRUE(credit_card_save_manager_->CreditCardWasUploaded());
// Verify that the correct histogram entries were logged.
ExpectCardUploadDecision(histogram_tester, AutofillMetrics::UPLOAD_OFFERED);
ExpectCardUploadDecision(histogram_tester,
AutofillMetrics::CVC_FIELD_NOT_FOUND);
// Verify that the correct UKM was logged.
ExpectCardUploadDecisionUkm(AutofillMetrics::UPLOAD_OFFERED |
AutofillMetrics::CVC_FIELD_NOT_FOUND);
}
TEST_F(CreditCardSaveManagerTest,
UploadCreditCard_NoCvcFieldOnForm_CvcInAddressField_DetectedValuesOff) {
DisableAutofillUpstreamSendDetectedValuesExperiment();
credit_card_save_manager_->SetCreditCardUploadEnabled(true);
// Remove the profiles that were created in the TestPersonalDataManager
// constructor because they would result in conflicting names that would
// prevent the upload.
personal_data_.ClearProfiles();
// Create, fill and submit an address form in order to establish a recent
// profile which can be selected for the upload request.
FormData address_form;
test::CreateTestAddressFormData(&address_form);
FormsSeen({address_form});
ManuallyFillAddressForm("Flo", "Master", "77401", "US", &address_form);
FormSubmitted(address_form);
// Set up our credit card form data. Note that CVC field is missing.
FormData credit_card_form;
credit_card_form.name = ASCIIToUTF16("MyForm");
credit_card_form.origin = GURL("https://myform.com/form.html");
credit_card_form.action = GURL("https://myform.com/submit.html");
credit_card_form.main_frame_origin =
url::Origin::Create(GURL("http://myform_root.com/form.html"));
FormFieldData field;
test::CreateTestFormField("Card Name", "cardname", "", "text", &field);
credit_card_form.fields.push_back(field);
test::CreateTestFormField("Card Number", "cardnumber", "", "text", &field);
credit_card_form.fields.push_back(field);
test::CreateTestFormField("Expiration Month", "ccmonth", "", "text", &field);
credit_card_form.fields.push_back(field);
test::CreateTestFormField("Expiration Year", "ccyear", "", "text", &field);
credit_card_form.fields.push_back(field);
test::CreateTestFormField("Address Line 1", "addr1", "", "text", &field);
credit_card_form.fields.push_back(field);
FormsSeen({credit_card_form});
// Enter a valid cvc in "Random Field" and submit.
credit_card_form.fields[0].value = ASCIIToUTF16("Flo Master");
credit_card_form.fields[1].value = ASCIIToUTF16("4111111111111111");
credit_card_form.fields[2].value = ASCIIToUTF16("11");
credit_card_form.fields[3].value = ASCIIToUTF16(NextYear());
credit_card_form.fields[4].value = ASCIIToUTF16("123");
base::HistogramTester histogram_tester;
// Upload should not happen because CVC field was not found.
EXPECT_CALL(autofill_client_, ConfirmSaveCreditCardLocally(_, _)).Times(0);
FormSubmitted(credit_card_form);
EXPECT_FALSE(credit_card_save_manager_->CreditCardWasUploaded());
// Verify that the correct histogram entry (and only that) was logged.
ExpectUniqueCardUploadDecision(histogram_tester,
AutofillMetrics::CVC_FIELD_NOT_FOUND);
// Verify that the correct UKM was logged.
ExpectCardUploadDecisionUkm(AutofillMetrics::CVC_FIELD_NOT_FOUND);
}
TEST_F(CreditCardSaveManagerTest, UploadCreditCard_NoProfileAvailable) {
personal_data_.ClearProfiles();
credit_card_save_manager_->SetCreditCardUploadEnabled(true);
// Don't fill or submit an address form.
// Set up our credit card form data.
FormData credit_card_form;
CreateTestCreditCardFormData(&credit_card_form, true, false);
FormsSeen(std::vector<FormData>(1, credit_card_form));
// Edit the data, and submit.
credit_card_form.fields[0].value = ASCIIToUTF16("Bob Master");
credit_card_form.fields[1].value = ASCIIToUTF16("4111111111111111");
credit_card_form.fields[2].value = ASCIIToUTF16("11");
credit_card_form.fields[3].value = ASCIIToUTF16(NextYear());
credit_card_form.fields[4].value = ASCIIToUTF16("123");
base::HistogramTester histogram_tester;
// With the offer-to-save decision deferred to Google Payments, Payments can
// still decide to allow saving despite the missing name/address.
EXPECT_CALL(autofill_client_, ConfirmSaveCreditCardLocally(_, _)).Times(0);
FormSubmitted(credit_card_form);
EXPECT_TRUE(credit_card_save_manager_->CreditCardWasUploaded());
// Verify that the correct histogram entries were logged.
ExpectCardUploadDecision(histogram_tester, AutofillMetrics::UPLOAD_OFFERED);
ExpectCardUploadDecision(
histogram_tester, AutofillMetrics::UPLOAD_NOT_OFFERED_NO_ADDRESS_PROFILE);
// Verify that the correct UKM was logged.
ExpectCardUploadDecisionUkm(
AutofillMetrics::UPLOAD_OFFERED |
AutofillMetrics::UPLOAD_NOT_OFFERED_NO_ADDRESS_PROFILE);
}
TEST_F(CreditCardSaveManagerTest,
UploadCreditCard_NoProfileAvailable_DetectedValuesOff) {
DisableAutofillUpstreamSendDetectedValuesExperiment();
personal_data_.ClearProfiles();
credit_card_save_manager_->SetCreditCardUploadEnabled(true);
// Don't fill or submit an address form.
// Set up our credit card form data.
FormData credit_card_form;
CreateTestCreditCardFormData(&credit_card_form, true, false);
FormsSeen(std::vector<FormData>(1, credit_card_form));
// Edit the data, and submit.
credit_card_form.fields[0].value = ASCIIToUTF16("Bob Master");
credit_card_form.fields[1].value = ASCIIToUTF16("4111111111111111");
credit_card_form.fields[2].value = ASCIIToUTF16("11");
credit_card_form.fields[3].value = ASCIIToUTF16(NextYear());
credit_card_form.fields[4].value = ASCIIToUTF16("123");
base::HistogramTester histogram_tester;
// Neither a local save nor an upload should happen in this case.
EXPECT_CALL(autofill_client_, ConfirmSaveCreditCardLocally(_, _)).Times(0);
FormSubmitted(credit_card_form);
EXPECT_FALSE(credit_card_save_manager_->CreditCardWasUploaded());
// Verify that the correct histogram entries are logged.
ExpectUniqueCardUploadDecision(
histogram_tester, AutofillMetrics::UPLOAD_NOT_OFFERED_NO_ADDRESS_PROFILE);
// Verify that the correct UKM was logged.
ExpectCardUploadDecisionUkm(
AutofillMetrics::UPLOAD_NOT_OFFERED_NO_ADDRESS_PROFILE);
}
TEST_F(CreditCardSaveManagerTest, UploadCreditCard_NoRecentlyUsedProfile) {
// Create the test clock and set the time to a specific value.
TestAutofillClock test_clock;
test_clock.SetNow(kArbitraryTime);
personal_data_.ClearProfiles();
credit_card_save_manager_->SetCreditCardUploadEnabled(true);
// Create, fill and submit an address form in order to establish a profile.
FormData address_form;
test::CreateTestAddressFormData(&address_form);
FormsSeen({address_form});
ManuallyFillAddressForm("Flo", "Master", "77401", "US", &address_form);
FormSubmitted(address_form);
// Set the current time to another value.
test_clock.SetNow(kMuchLaterTime);
// Set up our credit card form data.
FormData credit_card_form;
CreateTestCreditCardFormData(&credit_card_form, true, false);
FormsSeen(std::vector<FormData>(1, credit_card_form));
// Edit the data, and submit.
credit_card_form.fields[0].value = ASCIIToUTF16("Flo Master");
credit_card_form.fields[1].value = ASCIIToUTF16("4111111111111111");
credit_card_form.fields[2].value = ASCIIToUTF16("11");
credit_card_form.fields[3].value = ASCIIToUTF16(NextYear());
credit_card_form.fields[4].value = ASCIIToUTF16("123");
base::HistogramTester histogram_tester;
// With the offer-to-save decision deferred to Google Payments, Payments can
// still decide to allow saving despite the missing name/address.
EXPECT_CALL(autofill_client_, ConfirmSaveCreditCardLocally(_, _)).Times(0);
FormSubmitted(credit_card_form);
EXPECT_TRUE(credit_card_save_manager_->CreditCardWasUploaded());
// Verify that the correct histogram entries were logged.
ExpectCardUploadDecision(histogram_tester, AutofillMetrics::UPLOAD_OFFERED);
ExpectCardUploadDecision(
histogram_tester,
AutofillMetrics::UPLOAD_NOT_OFFERED_NO_RECENTLY_USED_ADDRESS);
// Verify that the correct UKM was logged.
ExpectCardUploadDecisionUkm(
AutofillMetrics::UPLOAD_OFFERED |
AutofillMetrics::UPLOAD_NOT_OFFERED_NO_RECENTLY_USED_ADDRESS);
// Verify the histogram entry for recent profile modification.
histogram_tester.ExpectUniqueSample(
"Autofill.HasModifiedProfile.CreditCardFormSubmission", false, 1);
}
TEST_F(CreditCardSaveManagerTest,
UploadCreditCard_NoRecentlyUsedProfile_DetectedValuesOff) {
DisableAutofillUpstreamSendDetectedValuesExperiment();
// Create the test clock and set the time to a specific value.
TestAutofillClock test_clock;
test_clock.SetNow(kArbitraryTime);
personal_data_.ClearProfiles();
credit_card_save_manager_->SetCreditCardUploadEnabled(true);
// Create, fill and submit an address form in order to establish a profile.
FormData address_form;
test::CreateTestAddressFormData(&address_form);
FormsSeen({address_form});
ManuallyFillAddressForm("Flo", "Master", "77401", "US", &address_form);
FormSubmitted(address_form);
// Set the current time to another value.
test_clock.SetNow(kMuchLaterTime);
// Set up our credit card form data.
FormData credit_card_form;
CreateTestCreditCardFormData(&credit_card_form, true, false);
FormsSeen(std::vector<FormData>(1, credit_card_form));
// Edit the data, and submit.
credit_card_form.fields[0].value = ASCIIToUTF16("Flo Master");
credit_card_form.fields[1].value = ASCIIToUTF16("4111111111111111");
credit_card_form.fields[2].value = ASCIIToUTF16("11");
credit_card_form.fields[3].value = ASCIIToUTF16(NextYear());
credit_card_form.fields[4].value = ASCIIToUTF16("123");
base::HistogramTester histogram_tester;
// Neither a local save nor an upload should happen in this case.
EXPECT_CALL(autofill_client_, ConfirmSaveCreditCardLocally(_, _)).Times(0);
FormSubmitted(credit_card_form);
EXPECT_FALSE(credit_card_save_manager_->CreditCardWasUploaded());
// Verify that the correct histogram entry (and only that) was logged.
ExpectUniqueCardUploadDecision(
histogram_tester,
AutofillMetrics::UPLOAD_NOT_OFFERED_NO_RECENTLY_USED_ADDRESS);
// Verify that the correct UKM was logged.
ExpectCardUploadDecisionUkm(
AutofillMetrics::UPLOAD_NOT_OFFERED_NO_RECENTLY_USED_ADDRESS);
// Verify the histogram entry for recent profile modification.
histogram_tester.ExpectUniqueSample(
"Autofill.HasModifiedProfile.CreditCardFormSubmission", false, 1);
}
TEST_F(CreditCardSaveManagerTest,
UploadCreditCard_CvcUnavailableAndNoProfileAvailable) {
personal_data_.ClearProfiles();
credit_card_save_manager_->SetCreditCardUploadEnabled(true);
// Don't fill or submit an address form.
// Set up our credit card form data.
FormData credit_card_form;
CreateTestCreditCardFormData(&credit_card_form, true, false);
FormsSeen(std::vector<FormData>(1, credit_card_form));
// Edit the data, and submit.
credit_card_form.fields[0].value = ASCIIToUTF16("Flo Master");
credit_card_form.fields[1].value = ASCIIToUTF16("4111111111111111");
credit_card_form.fields[2].value = ASCIIToUTF16("11");
credit_card_form.fields[3].value = ASCIIToUTF16(NextYear());
credit_card_form.fields[4].value = ASCIIToUTF16(""); // CVC MISSING
base::HistogramTester histogram_tester;
// With the offer-to-save decision deferred to Google Payments, Payments can
// still decide to allow saving despite the missing CVC, name, and address.
EXPECT_CALL(autofill_client_, ConfirmSaveCreditCardLocally(_, _)).Times(0);
FormSubmitted(credit_card_form);
EXPECT_TRUE(credit_card_save_manager_->CreditCardWasUploaded());
// Verify that the correct histogram entries were logged.
ExpectCardUploadDecision(histogram_tester, AutofillMetrics::UPLOAD_OFFERED);
ExpectCardUploadDecision(histogram_tester,
AutofillMetrics::CVC_VALUE_NOT_FOUND);
ExpectCardUploadDecision(
histogram_tester, AutofillMetrics::UPLOAD_NOT_OFFERED_NO_ADDRESS_PROFILE);
// Verify that the correct UKM was logged.
ExpectCardUploadDecisionUkm(
AutofillMetrics::UPLOAD_OFFERED | AutofillMetrics::CVC_VALUE_NOT_FOUND |
AutofillMetrics::UPLOAD_NOT_OFFERED_NO_ADDRESS_PROFILE);
}
TEST_F(CreditCardSaveManagerTest,
UploadCreditCard_CvcUnavailableAndNoProfileAvailable_DetectedValuesOff) {
DisableAutofillUpstreamSendDetectedValuesExperiment();
personal_data_.ClearProfiles();
credit_card_save_manager_->SetCreditCardUploadEnabled(true);
// Don't fill or submit an address form.
// Set up our credit card form data.
FormData credit_card_form;
CreateTestCreditCardFormData(&credit_card_form, true, false);
FormsSeen(std::vector<FormData>(1, credit_card_form));
// Edit the data, and submit.
credit_card_form.fields[0].value = ASCIIToUTF16("Flo Master");
credit_card_form.fields[1].value = ASCIIToUTF16("4111111111111111");
credit_card_form.fields[2].value = ASCIIToUTF16("11");
credit_card_form.fields[3].value = ASCIIToUTF16(NextYear());
credit_card_form.fields[4].value = ASCIIToUTF16(""); // CVC MISSING
base::HistogramTester histogram_tester;
// Neither a local save nor an upload should happen in this case.
EXPECT_CALL(autofill_client_, ConfirmSaveCreditCardLocally(_, _)).Times(0);
FormSubmitted(credit_card_form);
EXPECT_FALSE(credit_card_save_manager_->CreditCardWasUploaded());
// Verify that the correct histogram entries were logged.
ExpectCardUploadDecision(histogram_tester,
AutofillMetrics::CVC_VALUE_NOT_FOUND);
ExpectCardUploadDecision(
histogram_tester, AutofillMetrics::UPLOAD_NOT_OFFERED_NO_ADDRESS_PROFILE);
// Verify that the correct UKM was logged.
ExpectMetric(UkmCardUploadDecisionType::kUploadDecisionName,
UkmCardUploadDecisionType::kEntryName,
AutofillMetrics::CVC_VALUE_NOT_FOUND |
AutofillMetrics::UPLOAD_NOT_OFFERED_NO_ADDRESS_PROFILE,
1 /* expected_num_matching_entries */);
}
TEST_F(CreditCardSaveManagerTest, UploadCreditCard_NoNameAvailable) {
personal_data_.ClearProfiles();
credit_card_save_manager_->SetCreditCardUploadEnabled(true);
// Create, fill and submit an address form in order to establish a recent
// profile which can be selected for the upload request.
FormData address_form;
test::CreateTestAddressFormData(&address_form);
FormsSeen(std::vector<FormData>(1, address_form));
// But omit the name:
ManuallyFillAddressForm("", "", "77401", "US", &address_form);
FormSubmitted(address_form);
// Set up our credit card form data.
FormData credit_card_form;
CreateTestCreditCardFormData(&credit_card_form, true, false);
FormsSeen(std::vector<FormData>(1, credit_card_form));
// Edit the data, but don't include a name, and submit.
credit_card_form.fields[1].value = ASCIIToUTF16("4111111111111111");
credit_card_form.fields[2].value = ASCIIToUTF16("11");
credit_card_form.fields[3].value = ASCIIToUTF16(NextYear());
credit_card_form.fields[4].value = ASCIIToUTF16("123");
base::HistogramTester histogram_tester;
// With the offer-to-save decision deferred to Google Payments, Payments can
// still decide to allow saving despite the missing name.
EXPECT_CALL(autofill_client_, ConfirmSaveCreditCardLocally(_, _)).Times(0);
FormSubmitted(credit_card_form);
EXPECT_TRUE(credit_card_save_manager_->CreditCardWasUploaded());
// Verify that the correct histogram entries were logged.
ExpectCardUploadDecision(histogram_tester, AutofillMetrics::UPLOAD_OFFERED);
ExpectCardUploadDecision(histogram_tester,
AutofillMetrics::UPLOAD_NOT_OFFERED_NO_NAME);
// Verify that the correct UKM was logged.
ExpectCardUploadDecisionUkm(AutofillMetrics::UPLOAD_OFFERED |
AutofillMetrics::UPLOAD_NOT_OFFERED_NO_NAME);
}
TEST_F(CreditCardSaveManagerTest,
UploadCreditCard_NoNameAvailable_DetectedValuesOff) {
DisableAutofillUpstreamSendDetectedValuesExperiment();
personal_data_.ClearProfiles();
credit_card_save_manager_->SetCreditCardUploadEnabled(true);
// Create, fill and submit an address form in order to establish a recent
// profile which can be selected for the upload request.
FormData address_form;
test::CreateTestAddressFormData(&address_form);
FormsSeen(std::vector<FormData>(1, address_form));
// But omit the name:
ManuallyFillAddressForm("", "", "77401", "US", &address_form);
FormSubmitted(address_form);
// Set up our credit card form data.
FormData credit_card_form;
CreateTestCreditCardFormData(&credit_card_form, true, false);
FormsSeen(std::vector<FormData>(1, credit_card_form));
// Edit the data, but don't include a name, and submit.
credit_card_form.fields[1].value = ASCIIToUTF16("4111111111111111");
credit_card_form.fields[2].value = ASCIIToUTF16("11");
credit_card_form.fields[3].value = ASCIIToUTF16(NextYear());
credit_card_form.fields[4].value = ASCIIToUTF16("123");
base::HistogramTester histogram_tester;
// Neither a local save nor an upload should happen in this case.
EXPECT_CALL(autofill_client_, ConfirmSaveCreditCardLocally(_, _)).Times(0);
FormSubmitted(credit_card_form);
EXPECT_FALSE(credit_card_save_manager_->CreditCardWasUploaded());
// Verify that the correct histogram entry (and only that) was logged.
ExpectUniqueCardUploadDecision(histogram_tester,
AutofillMetrics::UPLOAD_NOT_OFFERED_NO_NAME);
// Verify that the correct UKM was logged.
ExpectCardUploadDecisionUkm(AutofillMetrics::UPLOAD_NOT_OFFERED_NO_NAME);
}
TEST_F(CreditCardSaveManagerTest,
UploadCreditCard_NoNameAvailableAndNoProfileAvailable) {
personal_data_.ClearProfiles();
credit_card_save_manager_->SetCreditCardUploadEnabled(true);
// Don't fill or submit an address form.
// Set up our credit card form data.
FormData credit_card_form;
CreateTestCreditCardFormData(&credit_card_form, true, false);
FormsSeen(std::vector<FormData>(1, credit_card_form));
// Edit the data, but don't include a name, and submit.
credit_card_form.fields[1].value = ASCIIToUTF16("4111111111111111");
credit_card_form.fields[2].value = ASCIIToUTF16("11");
credit_card_form.fields[3].value = ASCIIToUTF16(NextYear());
credit_card_form.fields[4].value = ASCIIToUTF16("123");
base::HistogramTester histogram_tester;
// With the offer-to-save decision deferred to Google Payments, Payments can
// still decide to allow saving despite the missing names/address.
EXPECT_CALL(autofill_client_, ConfirmSaveCreditCardLocally(_, _)).Times(0);
FormSubmitted(credit_card_form);
EXPECT_TRUE(credit_card_save_manager_->CreditCardWasUploaded());
// Verify that the correct histogram entries were logged.
ExpectCardUploadDecision(histogram_tester, AutofillMetrics::UPLOAD_OFFERED);
ExpectCardUploadDecision(
histogram_tester, AutofillMetrics::UPLOAD_NOT_OFFERED_NO_ADDRESS_PROFILE);
ExpectCardUploadDecision(histogram_tester,
AutofillMetrics::UPLOAD_NOT_OFFERED_NO_NAME);
// Verify that the correct UKM was logged.
ExpectCardUploadDecisionUkm(
AutofillMetrics::UPLOAD_OFFERED |
AutofillMetrics::UPLOAD_NOT_OFFERED_NO_ADDRESS_PROFILE |
AutofillMetrics::UPLOAD_NOT_OFFERED_NO_NAME);
}
TEST_F(
CreditCardSaveManagerTest,
UploadCreditCard_NoNameAvailableAndNoProfileAvailable_DetectedValuesOff) {
DisableAutofillUpstreamSendDetectedValuesExperiment();
personal_data_.ClearProfiles();
credit_card_save_manager_->SetCreditCardUploadEnabled(true);
// Don't fill or submit an address form.
// Set up our credit card form data.
FormData credit_card_form;
CreateTestCreditCardFormData(&credit_card_form, true, false);
FormsSeen(std::vector<FormData>(1, credit_card_form));
// Edit the data, but don't include a name, and submit.
credit_card_form.fields[1].value = ASCIIToUTF16("4111111111111111");
credit_card_form.fields[2].value = ASCIIToUTF16("11");
credit_card_form.fields[3].value = ASCIIToUTF16(NextYear());
credit_card_form.fields[4].value = ASCIIToUTF16("123");
base::HistogramTester histogram_tester;
// Neither a local save nor an upload should happen in this case.
EXPECT_CALL(autofill_client_, ConfirmSaveCreditCardLocally(_, _)).Times(0);
FormSubmitted(credit_card_form);
EXPECT_FALSE(credit_card_save_manager_->CreditCardWasUploaded());
// Verify that the correct histogram entries were logged.
ExpectCardUploadDecision(
histogram_tester, AutofillMetrics::UPLOAD_NOT_OFFERED_NO_ADDRESS_PROFILE);
ExpectCardUploadDecision(histogram_tester,
AutofillMetrics::UPLOAD_NOT_OFFERED_NO_NAME);
// Verify that the correct UKM was logged.
ExpectMetric(UkmCardUploadDecisionType::kUploadDecisionName,
UkmCardUploadDecisionType::kEntryName,
AutofillMetrics::UPLOAD_NOT_OFFERED_NO_ADDRESS_PROFILE |
AutofillMetrics::UPLOAD_NOT_OFFERED_NO_NAME,
1 /* expected_num_matching_entries */);
}
TEST_F(CreditCardSaveManagerTest, UploadCreditCard_ZipCodesConflict) {
personal_data_.ClearProfiles();
credit_card_save_manager_->SetCreditCardUploadEnabled(true);
// Create, fill and submit two address forms with different zip codes.
FormData address_form1, address_form2;
test::CreateTestAddressFormData(&address_form1);
test::CreateTestAddressFormData(&address_form2);
std::vector<FormData> address_forms;
address_forms.push_back(address_form1);
address_forms.push_back(address_form2);
FormsSeen(address_forms);
ExpectFillableFormParsedUkm(2 /* num_fillable_forms_parsed */);
ManuallyFillAddressForm("Flo", "Master", "77401-8294", "US", &address_form1);
FormSubmitted(address_form1);
ManuallyFillAddressForm("Flo", "Master", "77401-1234", "US", &address_form2);
FormSubmitted(address_form2);
// Set up our credit card form data.
FormData credit_card_form;
CreateTestCreditCardFormData(&credit_card_form, true, false);
FormsSeen(std::vector<FormData>(1, credit_card_form));
ExpectFillableFormParsedUkm(3 /* num_fillable_forms_parsed */);
// Edit the data and submit.
credit_card_form.fields[0].value = ASCIIToUTF16("Flo Master");
credit_card_form.fields[1].value = ASCIIToUTF16("4111111111111111");
credit_card_form.fields[2].value = ASCIIToUTF16("11");
credit_card_form.fields[3].value = ASCIIToUTF16(NextYear());
credit_card_form.fields[4].value = ASCIIToUTF16("123");
base::HistogramTester histogram_tester;
// With the offer-to-save decision deferred to Google Payments, Payments can
// still decide to allow saving despite the conflicting zip codes.
EXPECT_CALL(autofill_client_, ConfirmSaveCreditCardLocally(_, _)).Times(0);
FormSubmitted(credit_card_form);
EXPECT_TRUE(credit_card_save_manager_->CreditCardWasUploaded());
// Verify that the correct histogram entries were logged.
ExpectCardUploadDecision(histogram_tester, AutofillMetrics::UPLOAD_OFFERED);
ExpectCardUploadDecision(
histogram_tester, AutofillMetrics::UPLOAD_NOT_OFFERED_CONFLICTING_ZIPS);
// Verify that the correct UKM was logged.
ExpectCardUploadDecisionUkm(
AutofillMetrics::UPLOAD_OFFERED |
AutofillMetrics::UPLOAD_NOT_OFFERED_CONFLICTING_ZIPS);
}
TEST_F(CreditCardSaveManagerTest,
UploadCreditCard_ZipCodesConflict_DetectedValuesOff) {
DisableAutofillUpstreamSendDetectedValuesExperiment();
personal_data_.ClearProfiles();
credit_card_save_manager_->SetCreditCardUploadEnabled(true);
// Create, fill and submit two address forms with different zip codes.
FormData address_form1, address_form2;
test::CreateTestAddressFormData(&address_form1);
test::CreateTestAddressFormData(&address_form2);
std::vector<FormData> address_forms;
address_forms.push_back(address_form1);
address_forms.push_back(address_form2);
FormsSeen(address_forms);
ExpectFillableFormParsedUkm(2 /* num_fillable_forms_parsed */);
ManuallyFillAddressForm("Flo", "Master", "77401-8294", "US", &address_form1);
FormSubmitted(address_form1);
ManuallyFillAddressForm("Flo", "Master", "77401-1234", "US", &address_form2);
FormSubmitted(address_form2);
// Set up our credit card form data.
FormData credit_card_form;
CreateTestCreditCardFormData(&credit_card_form, true, false);
FormsSeen(std::vector<FormData>(1, credit_card_form));
ExpectFillableFormParsedUkm(3 /* num_fillable_forms_parsed */);
// Edit the data and submit.
credit_card_form.fields[0].value = ASCIIToUTF16("Flo Master");
credit_card_form.fields[1].value = ASCIIToUTF16("4111111111111111");
credit_card_form.fields[2].value = ASCIIToUTF16("11");
credit_card_form.fields[3].value = ASCIIToUTF16(NextYear());
credit_card_form.fields[4].value = ASCIIToUTF16("123");
base::HistogramTester histogram_tester;
// Neither a local save nor an upload should happen in this case.
EXPECT_CALL(autofill_client_, ConfirmSaveCreditCardLocally(_, _)).Times(0);
FormSubmitted(credit_card_form);
EXPECT_FALSE(credit_card_save_manager_->CreditCardWasUploaded());
// Verify that the correct histogram entry (and only that) was logged.
ExpectUniqueCardUploadDecision(
histogram_tester, AutofillMetrics::UPLOAD_NOT_OFFERED_CONFLICTING_ZIPS);
// Verify that the correct UKM was logged.
ExpectCardUploadDecisionUkm(
AutofillMetrics::UPLOAD_NOT_OFFERED_CONFLICTING_ZIPS);
}
TEST_F(CreditCardSaveManagerTest,
UploadCreditCard_ZipCodesDoNotDiscardWhitespace) {
personal_data_.ClearProfiles();
credit_card_save_manager_->SetCreditCardUploadEnabled(true);
// Create two separate profiles with different zip codes. Must directly add
// instead of submitting a form, because they're deduped on form submit.
AutofillProfile profile1;
profile1.set_guid("00000000-0000-0000-0000-000000000001");
profile1.SetInfo(NAME_FULL, ASCIIToUTF16("Flo Master"), "en-US");
profile1.SetInfo(ADDRESS_HOME_ZIP, ASCIIToUTF16("H3B2Y5"), "en-US");
profile1.SetInfo(ADDRESS_HOME_COUNTRY, ASCIIToUTF16("CA"), "en-US");
personal_data_.AddProfile(profile1);
AutofillProfile profile2;
profile2.set_guid("00000000-0000-0000-0000-000000000002");
profile2.SetInfo(NAME_FULL, ASCIIToUTF16("Flo Master"), "en-US");
profile2.SetInfo(ADDRESS_HOME_ZIP, ASCIIToUTF16("h3b 2y5"), "en-US");
profile2.SetInfo(ADDRESS_HOME_COUNTRY, ASCIIToUTF16("CA"), "en-US");
personal_data_.AddProfile(profile2);
// Set up our credit card form data.
FormData credit_card_form;
CreateTestCreditCardFormData(&credit_card_form, true, false);
FormsSeen({credit_card_form});
// Edit the data and submit.
credit_card_form.fields[0].value = ASCIIToUTF16("Flo Master");
credit_card_form.fields[1].value = ASCIIToUTF16("4111111111111111");
credit_card_form.fields[2].value = ASCIIToUTF16("11");
credit_card_form.fields[3].value = ASCIIToUTF16(NextYear());
credit_card_form.fields[4].value = ASCIIToUTF16("123");
base::HistogramTester histogram_tester;
// With the offer-to-save decision deferred to Google Payments, Payments can
// still decide to allow saving despite the conflicting zip codes.
EXPECT_CALL(autofill_client_, ConfirmSaveCreditCardLocally(_, _)).Times(0);
FormSubmitted(credit_card_form);
EXPECT_TRUE(credit_card_save_manager_->CreditCardWasUploaded());
// Verify that the correct histogram entries were logged.
ExpectCardUploadDecision(histogram_tester, AutofillMetrics::UPLOAD_OFFERED);
ExpectCardUploadDecision(
histogram_tester, AutofillMetrics::UPLOAD_NOT_OFFERED_CONFLICTING_ZIPS);
// Verify that the correct UKM was logged.
ExpectCardUploadDecisionUkm(
AutofillMetrics::UPLOAD_OFFERED |
AutofillMetrics::UPLOAD_NOT_OFFERED_CONFLICTING_ZIPS);
}
TEST_F(CreditCardSaveManagerTest,
UploadCreditCard_ZipCodesDoNotDiscardWhitespace_DetectedValuesOff) {
DisableAutofillUpstreamSendDetectedValuesExperiment();
personal_data_.ClearProfiles();
credit_card_save_manager_->SetCreditCardUploadEnabled(true);
// Create two separate profiles with different zip codes. Must directly add
// instead of submitting a form, because they're deduped on form submit.
AutofillProfile profile1;
profile1.set_guid("00000000-0000-0000-0000-000000000001");
profile1.SetInfo(NAME_FULL, ASCIIToUTF16("Flo Master"), "en-US");
profile1.SetInfo(ADDRESS_HOME_ZIP, ASCIIToUTF16("H3B2Y5"), "en-US");
profile1.SetInfo(ADDRESS_HOME_COUNTRY, ASCIIToUTF16("CA"), "en-US");
personal_data_.AddProfile(profile1);
AutofillProfile profile2;
profile2.set_guid("00000000-0000-0000-0000-000000000002");
profile2.SetInfo(NAME_FULL, ASCIIToUTF16("Flo Master"), "en-US");
profile2.SetInfo(ADDRESS_HOME_ZIP, ASCIIToUTF16("h3b 2y5"), "en-US");
profile2.SetInfo(ADDRESS_HOME_COUNTRY, ASCIIToUTF16("CA"), "en-US");
personal_data_.AddProfile(profile2);
// Set up our credit card form data.
FormData credit_card_form;
CreateTestCreditCardFormData(&credit_card_form, true, false);
FormsSeen({credit_card_form});
// Edit the data and submit.
credit_card_form.fields[0].value = ASCIIToUTF16("Flo Master");
credit_card_form.fields[1].value = ASCIIToUTF16("4111111111111111");
credit_card_form.fields[2].value = ASCIIToUTF16("11");
credit_card_form.fields[3].value = ASCIIToUTF16(NextYear());
credit_card_form.fields[4].value = ASCIIToUTF16("123");
base::HistogramTester histogram_tester;
// Neither a local save nor an upload should happen in this case.
EXPECT_CALL(autofill_client_, ConfirmSaveCreditCardLocally(_, _)).Times(0);
FormSubmitted(credit_card_form);
EXPECT_FALSE(credit_card_save_manager_->CreditCardWasUploaded());
EXPECT_TRUE(payments_client_->GetActiveExperimentsSetInRequest().empty());
// Verify that the correct histogram entry (and only that) was logged.
ExpectUniqueCardUploadDecision(
histogram_tester, AutofillMetrics::UPLOAD_NOT_OFFERED_CONFLICTING_ZIPS);
}
TEST_F(CreditCardSaveManagerTest, UploadCreditCard_ZipCodesHavePrefixMatch) {
personal_data_.ClearProfiles();
credit_card_save_manager_->SetCreditCardUploadEnabled(true);
// Create, fill and submit two address forms with different zip codes.
FormData address_form1, address_form2;
test::CreateTestAddressFormData(&address_form1);
test::CreateTestAddressFormData(&address_form2);
std::vector<FormData> address_forms;
address_forms.push_back(address_form1);
address_forms.push_back(address_form2);
FormsSeen(address_forms);
ManuallyFillAddressForm("Flo", "Master", "77401", "US", &address_form1);
FormSubmitted(address_form1);
ManuallyFillAddressForm("Flo", "Master", "77401-8294", "US", &address_form2);
FormSubmitted(address_form2);
// Set up our credit card form data.
FormData credit_card_form;
CreateTestCreditCardFormData(&credit_card_form, true, false);
FormsSeen(std::vector<FormData>(1, credit_card_form));
// Edit the data and submit.
credit_card_form.fields[0].value = ASCIIToUTF16("Flo Master");
credit_card_form.fields[1].value = ASCIIToUTF16("4111111111111111");
credit_card_form.fields[2].value = ASCIIToUTF16("11");
credit_card_form.fields[3].value = ASCIIToUTF16(NextYear());
credit_card_form.fields[4].value = ASCIIToUTF16("123");
base::HistogramTester histogram_tester;
// One zip is a prefix of the other, upload should happen.
EXPECT_CALL(autofill_client_, ConfirmSaveCreditCardLocally(_, _)).Times(0);
FormSubmitted(credit_card_form);
EXPECT_TRUE(credit_card_save_manager_->CreditCardWasUploaded());
// Verify that the correct histogram entry (and only that) was logged.
ExpectUniqueCardUploadDecision(histogram_tester,
AutofillMetrics::UPLOAD_OFFERED);
// Verify that the correct UKM was logged.
ExpectCardUploadDecisionUkm(AutofillMetrics::UPLOAD_OFFERED);
}
TEST_F(CreditCardSaveManagerTest, UploadCreditCard_NoZipCodeAvailable) {
personal_data_.ClearProfiles();
credit_card_save_manager_->SetCreditCardUploadEnabled(true);
// Create, fill and submit an address form in order to establish a recent
// profile which can be selected for the upload request.
FormData address_form;
test::CreateTestAddressFormData(&address_form);
FormsSeen(std::vector<FormData>(1, address_form));
// Autofill's validation requirements for Venezuala ("VE", see
// src/components/autofill/core/browser/country_data.cc) do not require zip
// codes. We use Venezuala here because to use the US (or one of many other
// countries which autofill requires a zip code for) would result in no
// address being imported at all, and then we never reach the check for
// missing zip code in the upload code.
ManuallyFillAddressForm("Flo", "Master", "" /* zip_code */, "Venezuela",
&address_form);
FormSubmitted(address_form);
// Set up our credit card form data.
FormData credit_card_form;
CreateTestCreditCardFormData(&credit_card_form, true, false);
FormsSeen(std::vector<FormData>(1, credit_card_form));
// Edit the data, and submit.
credit_card_form.fields[0].value = ASCIIToUTF16("Flo Master");
credit_card_form.fields[1].value = ASCIIToUTF16("4111111111111111");
credit_card_form.fields[2].value = ASCIIToUTF16("11");
credit_card_form.fields[3].value = ASCIIToUTF16(NextYear());
credit_card_form.fields[4].value = ASCIIToUTF16("123");
base::HistogramTester histogram_tester;
// With the offer-to-save decision deferred to Google Payments, Payments can
// still decide to allow saving despite the missing zip code.
EXPECT_CALL(autofill_client_, ConfirmSaveCreditCardLocally(_, _)).Times(0);
FormSubmitted(credit_card_form);
EXPECT_TRUE(credit_card_save_manager_->CreditCardWasUploaded());
// Verify that the correct histogram entries were logged.
ExpectCardUploadDecision(histogram_tester, AutofillMetrics::UPLOAD_OFFERED);
ExpectCardUploadDecision(histogram_tester,
AutofillMetrics::UPLOAD_NOT_OFFERED_NO_ZIP_CODE);
// Verify that the correct UKM was logged.
ExpectCardUploadDecisionUkm(AutofillMetrics::UPLOAD_OFFERED |
AutofillMetrics::UPLOAD_NOT_OFFERED_NO_ZIP_CODE);
}
TEST_F(CreditCardSaveManagerTest,
UploadCreditCard_NoZipCodeAvailable_DetectedValuesOff) {
DisableAutofillUpstreamSendDetectedValuesExperiment();
personal_data_.ClearProfiles();
credit_card_save_manager_->SetCreditCardUploadEnabled(true);
// Create, fill and submit an address form in order to establish a recent
// profile which can be selected for the upload request.
FormData address_form;
test::CreateTestAddressFormData(&address_form);
FormsSeen(std::vector<FormData>(1, address_form));
// Autofill's validation requirements for Venezuala ("VE", see
// src/components/autofill/core/browser/country_data.cc) do not require zip
// codes. We use Venezuala here because to use the US (or one of many other
// countries which autofill requires a zip code for) would result in no
// address being imported at all, and then we never reach the check for
// missing zip code in the upload code.
ManuallyFillAddressForm("Flo", "Master", "" /* zip_code */, "Venezuela",
&address_form);
FormSubmitted(address_form);
// Set up our credit card form data.
FormData credit_card_form;
CreateTestCreditCardFormData(&credit_card_form, true, false);
FormsSeen(std::vector<FormData>(1, credit_card_form));
// Edit the data, and submit.
credit_card_form.fields[0].value = ASCIIToUTF16("Flo Master");
credit_card_form.fields[1].value = ASCIIToUTF16("4111111111111111");
credit_card_form.fields[2].value = ASCIIToUTF16("11");
credit_card_form.fields[3].value = ASCIIToUTF16(NextYear());
credit_card_form.fields[4].value = ASCIIToUTF16("123");
base::HistogramTester histogram_tester;
// Neither a local save nor an upload should happen in this case.
EXPECT_CALL(autofill_client_, ConfirmSaveCreditCardLocally(_, _)).Times(0);
FormSubmitted(credit_card_form);
EXPECT_FALSE(credit_card_save_manager_->CreditCardWasUploaded());
// Verify that the correct histogram entry (and only that) was logged.
ExpectUniqueCardUploadDecision(
histogram_tester, AutofillMetrics::UPLOAD_NOT_OFFERED_NO_ZIP_CODE);
// Verify that the correct UKM was logged.
ExpectCardUploadDecisionUkm(AutofillMetrics::UPLOAD_NOT_OFFERED_NO_ZIP_CODE);
}
TEST_F(CreditCardSaveManagerTest, UploadCreditCard_CCFormHasMiddleInitial) {
personal_data_.ClearProfiles();
credit_card_save_manager_->SetCreditCardUploadEnabled(true);
// Create, fill and submit two address forms with different names.
FormData address_form1, address_form2;
test::CreateTestAddressFormData(&address_form1);
test::CreateTestAddressFormData(&address_form2);
FormsSeen({address_form1, address_form2});
// Names can be different case.
ManuallyFillAddressForm("flo", "master", "77401", "US", &address_form1);
FormSubmitted(address_form1);
// And they can have a middle initial even if the other names don't.
ManuallyFillAddressForm("Flo W", "Master", "77401", "US", &address_form2);
FormSubmitted(address_form2);
// Set up our credit card form data.
FormData credit_card_form;
CreateTestCreditCardFormData(&credit_card_form, true, false);
FormsSeen({credit_card_form});
// Edit the data, but use the name with a middle initial *and* period, and
// submit.
credit_card_form.fields[0].value = ASCIIToUTF16("Flo W. Master");
credit_card_form.fields[1].value = ASCIIToUTF16("4111111111111111");
credit_card_form.fields[2].value = ASCIIToUTF16("11");
credit_card_form.fields[3].value = ASCIIToUTF16(NextYear());
credit_card_form.fields[4].value = ASCIIToUTF16("123");
base::HistogramTester histogram_tester;
// Names match loosely, upload should happen.
EXPECT_CALL(autofill_client_, ConfirmSaveCreditCardLocally(_, _)).Times(0);
FormSubmitted(credit_card_form);
EXPECT_TRUE(credit_card_save_manager_->CreditCardWasUploaded());
// Verify that the correct histogram entry (and only that) was logged.
ExpectUniqueCardUploadDecision(histogram_tester,
AutofillMetrics::UPLOAD_OFFERED);
// Verify that the correct UKM was logged.
ExpectCardUploadDecisionUkm(AutofillMetrics::UPLOAD_OFFERED);
}
TEST_F(CreditCardSaveManagerTest, UploadCreditCard_NoMiddleInitialInCCForm) {
personal_data_.ClearProfiles();
credit_card_save_manager_->SetCreditCardUploadEnabled(true);
// Create, fill and submit two address forms with different names.
FormData address_form1, address_form2;
test::CreateTestAddressFormData(&address_form1);
test::CreateTestAddressFormData(&address_form2);
FormsSeen({address_form1, address_form2});
// Names can have different variations of middle initials.
ManuallyFillAddressForm("flo w.", "master", "77401", "US", &address_form1);
FormSubmitted(address_form1);
ManuallyFillAddressForm("Flo W", "Master", "77401", "US", &address_form2);
FormSubmitted(address_form2);
// Set up our credit card form data.
FormData credit_card_form;
CreateTestCreditCardFormData(&credit_card_form, true, false);
FormsSeen({credit_card_form});
// Edit the data, but do not use middle initial.
credit_card_form.fields[0].value = ASCIIToUTF16("Flo Master");
credit_card_form.fields[1].value = ASCIIToUTF16("4111111111111111");
credit_card_form.fields[2].value = ASCIIToUTF16("11");
credit_card_form.fields[3].value = ASCIIToUTF16(NextYear());
credit_card_form.fields[4].value = ASCIIToUTF16("123");
base::HistogramTester histogram_tester;
// Names match loosely, upload should happen.
EXPECT_CALL(autofill_client_, ConfirmSaveCreditCardLocally(_, _)).Times(0);
FormSubmitted(credit_card_form);
EXPECT_TRUE(credit_card_save_manager_->CreditCardWasUploaded());
// Verify that the correct histogram entry (and only that) was logged.
ExpectUniqueCardUploadDecision(histogram_tester,
AutofillMetrics::UPLOAD_OFFERED);
// Verify that the correct UKM was logged.
ExpectCardUploadDecisionUkm(AutofillMetrics::UPLOAD_OFFERED);
}
TEST_F(CreditCardSaveManagerTest,
UploadCreditCard_CCFormHasCardholderMiddleName) {
personal_data_.ClearProfiles();
credit_card_save_manager_->SetCreditCardUploadEnabled(true);
// Create, fill and submit address form without middle name.
FormData address_form;
test::CreateTestAddressFormData(&address_form);
FormsSeen({address_form});
ManuallyFillAddressForm("John", "Adams", "77401", "US", &address_form);
FormSubmitted(address_form);
// Set up our credit card form data.
FormData credit_card_form;
CreateTestCreditCardFormData(&credit_card_form, true, false);
FormsSeen({credit_card_form});
// Edit the name by adding a middle name.
credit_card_form.fields[0].value = ASCIIToUTF16("John Quincy Adams");
credit_card_form.fields[1].value = ASCIIToUTF16("4111111111111111");
credit_card_form.fields[2].value = ASCIIToUTF16("11");
credit_card_form.fields[3].value = ASCIIToUTF16(NextYear());
credit_card_form.fields[4].value = ASCIIToUTF16("123");
base::HistogramTester histogram_tester;
// With the offer-to-save decision deferred to Google Payments, Payments can
// still decide to allow saving despite the mismatching names.
EXPECT_CALL(autofill_client_, ConfirmSaveCreditCardLocally(_, _)).Times(0);
FormSubmitted(credit_card_form);
EXPECT_TRUE(credit_card_save_manager_->CreditCardWasUploaded());
// Verify that the correct histogram entries were logged.
ExpectCardUploadDecision(histogram_tester, AutofillMetrics::UPLOAD_OFFERED);
ExpectCardUploadDecision(
histogram_tester, AutofillMetrics::UPLOAD_NOT_OFFERED_CONFLICTING_NAMES);
// Verify that the correct UKM was logged.
ExpectCardUploadDecisionUkm(
AutofillMetrics::UPLOAD_OFFERED |
AutofillMetrics::UPLOAD_NOT_OFFERED_CONFLICTING_NAMES);
}
TEST_F(CreditCardSaveManagerTest,
UploadCreditCard_CCFormHasCardholderMiddleName_DetectedValuesOff) {
DisableAutofillUpstreamSendDetectedValuesExperiment();
personal_data_.ClearProfiles();
credit_card_save_manager_->SetCreditCardUploadEnabled(true);
// Create, fill and submit address form without middle name.
FormData address_form;
test::CreateTestAddressFormData(&address_form);
FormsSeen({address_form});
ManuallyFillAddressForm("John", "Adams", "77401", "US", &address_form);
FormSubmitted(address_form);
// Set up our credit card form data.
FormData credit_card_form;
CreateTestCreditCardFormData(&credit_card_form, true, false);
FormsSeen({credit_card_form});
// Edit the name by adding a middle name.
credit_card_form.fields[0].value = ASCIIToUTF16("John Quincy Adams");
credit_card_form.fields[1].value = ASCIIToUTF16("4111111111111111");
credit_card_form.fields[2].value = ASCIIToUTF16("11");
credit_card_form.fields[3].value = ASCIIToUTF16(NextYear());
credit_card_form.fields[4].value = ASCIIToUTF16("123");
base::HistogramTester histogram_tester;
// Names match loosely but middle name mismatches. Upload should not happen.
EXPECT_CALL(autofill_client_, ConfirmSaveCreditCardLocally(_, _)).Times(0);
FormSubmitted(credit_card_form);
EXPECT_FALSE(credit_card_save_manager_->CreditCardWasUploaded());
// Verify that the correct histogram entry (and only that) was logged.
ExpectUniqueCardUploadDecision(
histogram_tester, AutofillMetrics::UPLOAD_NOT_OFFERED_CONFLICTING_NAMES);
}
TEST_F(CreditCardSaveManagerTest, UploadCreditCard_CCFormHasAddressMiddleName) {
personal_data_.ClearProfiles();
credit_card_save_manager_->SetCreditCardUploadEnabled(true);
// Create, fill and submit address form with middle name.
FormData address_form;
test::CreateTestAddressFormData(&address_form);
FormsSeen({address_form});
ManuallyFillAddressForm("John Quincy", "Adams", "77401", "US", &address_form);
FormSubmitted(address_form);
// Set up our credit card form data.
FormData credit_card_form;
CreateTestCreditCardFormData(&credit_card_form, true, false);
FormsSeen({credit_card_form});
// Edit the name by removing middle name.
credit_card_form.fields[0].value = ASCIIToUTF16("John Adams");
credit_card_form.fields[1].value = ASCIIToUTF16("4111111111111111");
credit_card_form.fields[2].value = ASCIIToUTF16("11");
credit_card_form.fields[3].value = ASCIIToUTF16(NextYear());
credit_card_form.fields[4].value = ASCIIToUTF16("123");
base::HistogramTester histogram_tester;
// With the offer-to-save decision deferred to Google Payments, Payments can
// still decide to allow saving despite the mismatching names.
EXPECT_CALL(autofill_client_, ConfirmSaveCreditCardLocally(_, _)).Times(0);
FormSubmitted(credit_card_form);
EXPECT_TRUE(credit_card_save_manager_->CreditCardWasUploaded());
// Verify that the correct histogram entries were logged.
ExpectCardUploadDecision(histogram_tester, AutofillMetrics::UPLOAD_OFFERED);
ExpectCardUploadDecision(
histogram_tester, AutofillMetrics::UPLOAD_NOT_OFFERED_CONFLICTING_NAMES);
// Verify that the correct UKM was logged.
ExpectCardUploadDecisionUkm(
AutofillMetrics::UPLOAD_OFFERED |
AutofillMetrics::UPLOAD_NOT_OFFERED_CONFLICTING_NAMES);
}
TEST_F(CreditCardSaveManagerTest,
UploadCreditCard_CCFormHasAddressMiddleName_DetectedValuesOff) {
DisableAutofillUpstreamSendDetectedValuesExperiment();
personal_data_.ClearProfiles();
credit_card_save_manager_->SetCreditCardUploadEnabled(true);
// Create, fill and submit address form with middle name.
FormData address_form;
test::CreateTestAddressFormData(&address_form);
FormsSeen({address_form});
ManuallyFillAddressForm("John Quincy", "Adams", "77401", "US", &address_form);
FormSubmitted(address_form);
// Set up our credit card form data.
FormData credit_card_form;
CreateTestCreditCardFormData(&credit_card_form, true, false);
FormsSeen({credit_card_form});
// Edit the name by removing middle name.
credit_card_form.fields[0].value = ASCIIToUTF16("John Adams");
credit_card_form.fields[1].value = ASCIIToUTF16("4111111111111111");
credit_card_form.fields[2].value = ASCIIToUTF16("11");
credit_card_form.fields[3].value = ASCIIToUTF16(NextYear());
credit_card_form.fields[4].value = ASCIIToUTF16("123");
base::HistogramTester histogram_tester;
// Names match loosely but middle name mismatches. Upload should not happen.
EXPECT_CALL(autofill_client_, ConfirmSaveCreditCardLocally(_, _)).Times(0);
FormSubmitted(credit_card_form);
EXPECT_FALSE(credit_card_save_manager_->CreditCardWasUploaded());
// Verify that the correct histogram entry (and only that) was logged.
ExpectUniqueCardUploadDecision(
histogram_tester, AutofillMetrics::UPLOAD_NOT_OFFERED_CONFLICTING_NAMES);
// Verify that the correct UKM was logged.
ExpectCardUploadDecisionUkm(
AutofillMetrics::UPLOAD_NOT_OFFERED_CONFLICTING_NAMES);
}
TEST_F(CreditCardSaveManagerTest, UploadCreditCard_NamesHaveToMatch) {
personal_data_.ClearProfiles();
credit_card_save_manager_->SetCreditCardUploadEnabled(true);
// Create, fill and submit two address forms with different names.
FormData address_form1, address_form2;
test::CreateTestAddressFormData(&address_form1);
test::CreateTestAddressFormData(&address_form2);
std::vector<FormData> address_forms;
address_forms.push_back(address_form1);
address_forms.push_back(address_form2);
FormsSeen(address_forms);
ManuallyFillAddressForm("Flo", "Master", "77401", "US", &address_form1);
FormSubmitted(address_form1);
ManuallyFillAddressForm("Master", "Blaster", "77401", "US", &address_form2);
FormSubmitted(address_form2);
// Set up our credit card form data.
FormData credit_card_form;
CreateTestCreditCardFormData(&credit_card_form, true, false);
FormsSeen(std::vector<FormData>(1, credit_card_form));
// Edit the data, but use yet another name, and submit.
credit_card_form.fields[0].value = ASCIIToUTF16("Bob Master");
credit_card_form.fields[1].value = ASCIIToUTF16("4111111111111111");
credit_card_form.fields[2].value = ASCIIToUTF16("11");
credit_card_form.fields[3].value = ASCIIToUTF16(NextYear());
credit_card_form.fields[4].value = ASCIIToUTF16("123");
base::HistogramTester histogram_tester;
// With the offer-to-save decision deferred to Google Payments, Payments can
// still decide to allow saving despite the mismatching names.
EXPECT_CALL(autofill_client_, ConfirmSaveCreditCardLocally(_, _)).Times(0);
FormSubmitted(credit_card_form);
EXPECT_TRUE(credit_card_save_manager_->CreditCardWasUploaded());
// Verify that the correct histogram entries were logged.
ExpectCardUploadDecision(histogram_tester, AutofillMetrics::UPLOAD_OFFERED);
ExpectCardUploadDecision(
histogram_tester, AutofillMetrics::UPLOAD_NOT_OFFERED_CONFLICTING_NAMES);
// Verify that the correct UKM was logged.
ExpectCardUploadDecisionUkm(
AutofillMetrics::UPLOAD_OFFERED |
AutofillMetrics::UPLOAD_NOT_OFFERED_CONFLICTING_NAMES);
}
TEST_F(CreditCardSaveManagerTest,
UploadCreditCard_NamesHaveToMatch_DetectedValuesOff) {
DisableAutofillUpstreamSendDetectedValuesExperiment();
personal_data_.ClearProfiles();
credit_card_save_manager_->SetCreditCardUploadEnabled(true);
// Create, fill and submit two address forms with different names.
FormData address_form1, address_form2;
test::CreateTestAddressFormData(&address_form1);
test::CreateTestAddressFormData(&address_form2);
std::vector<FormData> address_forms;
address_forms.push_back(address_form1);
address_forms.push_back(address_form2);
FormsSeen(address_forms);
ManuallyFillAddressForm("Flo", "Master", "77401", "US", &address_form1);
FormSubmitted(address_form1);
ManuallyFillAddressForm("Master", "Blaster", "77401", "US", &address_form2);
FormSubmitted(address_form2);
// Set up our credit card form data.
FormData credit_card_form;
CreateTestCreditCardFormData(&credit_card_form, true, false);
FormsSeen(std::vector<FormData>(1, credit_card_form));
// Edit the data, but use yet another name, and submit.
credit_card_form.fields[0].value = ASCIIToUTF16("Bob Master");
credit_card_form.fields[1].value = ASCIIToUTF16("4111111111111111");
credit_card_form.fields[2].value = ASCIIToUTF16("11");
credit_card_form.fields[3].value = ASCIIToUTF16(NextYear());
credit_card_form.fields[4].value = ASCIIToUTF16("123");
base::HistogramTester histogram_tester;
// Names are required to match, upload should not happen.
EXPECT_CALL(autofill_client_, ConfirmSaveCreditCardLocally(_, _)).Times(0);
FormSubmitted(credit_card_form);
EXPECT_FALSE(credit_card_save_manager_->CreditCardWasUploaded());
// Verify that the correct histogram entry (and only that) was logged.
ExpectUniqueCardUploadDecision(
histogram_tester, AutofillMetrics::UPLOAD_NOT_OFFERED_CONFLICTING_NAMES);
// Verify that the correct UKM was logged.
ExpectCardUploadDecisionUkm(
AutofillMetrics::UPLOAD_NOT_OFFERED_CONFLICTING_NAMES);
}
TEST_F(CreditCardSaveManagerTest, UploadCreditCard_IgnoreOldProfiles) {
// Create the test clock and set the time to a specific value.
TestAutofillClock test_clock;
test_clock.SetNow(kArbitraryTime);
personal_data_.ClearProfiles();
credit_card_save_manager_->SetCreditCardUploadEnabled(true);
// Create, fill and submit two address forms with different names.
FormData address_form1, address_form2;
test::CreateTestAddressFormData(&address_form1);
test::CreateTestAddressFormData(&address_form2);
FormsSeen({address_form1, address_form2});
ManuallyFillAddressForm("Flo", "Master", "77401", "US", &address_form1);
FormSubmitted(address_form1);
// Advance the current time. Since |address_form1| will not be a recently
// used address profile, we will not include it in the candidate profiles.
test_clock.SetNow(kMuchLaterTime);
ManuallyFillAddressForm("Master", "Blaster", "77401", "US", &address_form2);
FormSubmitted(address_form2);
// Set up our credit card form data.
FormData credit_card_form;
CreateTestCreditCardFormData(&credit_card_form, true, false);
FormsSeen(std::vector<FormData>(1, credit_card_form));
// Edit the data, but use yet another name, and submit.
credit_card_form.fields[0].value = ASCIIToUTF16("Master Blaster");
credit_card_form.fields[1].value = ASCIIToUTF16("4111111111111111");
credit_card_form.fields[2].value = ASCIIToUTF16("11");
credit_card_form.fields[3].value = ASCIIToUTF16(NextYear());
credit_card_form.fields[4].value = ASCIIToUTF16("123");
base::HistogramTester histogram_tester;
// Name matches recently used profile, should offer upload.
EXPECT_CALL(autofill_client_, ConfirmSaveCreditCardLocally(_, _)).Times(0);
FormSubmitted(credit_card_form);
EXPECT_TRUE(credit_card_save_manager_->CreditCardWasUploaded());
// Verify that the correct histogram entry (and only that) was logged.
ExpectUniqueCardUploadDecision(histogram_tester,
AutofillMetrics::UPLOAD_OFFERED);
}
TEST_F(CreditCardSaveManagerTest, UploadCreditCard_LogPreviousUseDate) {
// Create the test clock and set the time to a specific value.
TestAutofillClock test_clock;
test_clock.SetNow(kArbitraryTime);
personal_data_.ClearProfiles();
credit_card_save_manager_->SetCreditCardUploadEnabled(true);
// Create, fill and submit an address form in order to establish a recent
// profile which can be selected for the upload request.
FormData address_form;
test::CreateTestAddressFormData(&address_form);
FormsSeen({address_form});
ManuallyFillAddressForm("Flo", "Master", "77401", "US", &address_form);
FormSubmitted(address_form);
const std::vector<AutofillProfile*>& profiles =
personal_data_.GetProfilesToSuggest();
ASSERT_EQ(1U, profiles.size());
// Advance the current time and simulate use of the address profile.
test_clock.SetNow(kMuchLaterTime);
profiles[0]->RecordAndLogUse();
// Set up our credit card form data.
FormData credit_card_form;
CreateTestCreditCardFormData(&credit_card_form, true, false);
FormsSeen({credit_card_form});
// Edit the credit card form and submit.
credit_card_form.fields[0].value = ASCIIToUTF16("Flo Master");
credit_card_form.fields[1].value = ASCIIToUTF16("4111111111111111");
credit_card_form.fields[2].value = ASCIIToUTF16("11");
credit_card_form.fields[3].value = ASCIIToUTF16(NextYear());
credit_card_form.fields[4].value = ASCIIToUTF16("123");
base::HistogramTester histogram_tester;
EXPECT_CALL(autofill_client_, ConfirmSaveCreditCardLocally(_, _)).Times(0);
FormSubmitted(credit_card_form);
EXPECT_TRUE(credit_card_save_manager_->CreditCardWasUploaded());
// Verify that UMA for "DaysSincePreviousUse" is logged.
histogram_tester.ExpectUniqueSample(
"Autofill.DaysSincePreviousUseAtSubmission.Profile",
(kMuchLaterTime - kArbitraryTime).InDays(),
/*expected_count=*/1);
}
TEST_F(CreditCardSaveManagerTest, UploadCreditCard_UploadDetailsFails) {
personal_data_.ClearProfiles();
credit_card_save_manager_->SetCreditCardUploadEnabled(true);
// Anything other than "en-US" will cause GetUploadDetails to return a failure
// response.
credit_card_save_manager_->SetAppLocale("pt-BR");
// Create, fill and submit an address form in order to establish a recent
// profile which can be selected for the upload request.
FormData address_form;
test::CreateTestAddressFormData(&address_form);
FormsSeen(std::vector<FormData>(1, address_form));
ManuallyFillAddressForm("Flo", "Master", "77401", "US", &address_form);
FormSubmitted(address_form);
// Set up our credit card form data.
FormData credit_card_form;
CreateTestCreditCardFormData(&credit_card_form, true, false);
FormsSeen(std::vector<FormData>(1, credit_card_form));
// Edit the data, and submit.
credit_card_form.fields[0].value = ASCIIToUTF16("Flo Master");
credit_card_form.fields[1].value = ASCIIToUTF16("4111111111111111");
credit_card_form.fields[2].value = ASCIIToUTF16("11");
credit_card_form.fields[3].value = ASCIIToUTF16(NextYear());
credit_card_form.fields[4].value = ASCIIToUTF16("123");
base::HistogramTester histogram_tester;
// The save prompt should be shown instead of doing an upload.
EXPECT_CALL(autofill_client_, ConfirmSaveCreditCardLocally(_, _));
FormSubmitted(credit_card_form);
EXPECT_FALSE(credit_card_save_manager_->CreditCardWasUploaded());
// Verify that the correct histogram entry (and only that) was logged.
ExpectUniqueCardUploadDecision(
histogram_tester,
AutofillMetrics::UPLOAD_NOT_OFFERED_GET_UPLOAD_DETAILS_FAILED);
// Verify that the correct UKM was logged.
ExpectCardUploadDecisionUkm(
AutofillMetrics::UPLOAD_NOT_OFFERED_GET_UPLOAD_DETAILS_FAILED);
}
TEST_F(CreditCardSaveManagerTest, DuplicateMaskedCreditCard_NoUpload) {
personal_data_.ClearProfiles();
credit_card_save_manager_->SetCreditCardUploadEnabled(true);
credit_card_save_manager_->SetAppLocale("en-US");
// Create, fill and submit an address form in order to establish a recent
// profile which can be selected for the upload request.
FormData address_form;
test::CreateTestAddressFormData(&address_form);
FormsSeen(std::vector<FormData>(1, address_form));
ManuallyFillAddressForm("Flo", "Master", "77401", "US", &address_form);
FormSubmitted(address_form);
// Add a masked credit card whose |TypeAndLastFourDigits| matches what we will
// enter below.
CreditCard credit_card(CreditCard::MASKED_SERVER_CARD, "a123");
test::SetCreditCardInfo(&credit_card, "Flo Master", "1111", "11",
NextYear().c_str(), "1");
credit_card.SetNetworkForMaskedCard(kVisaCard);
personal_data_.AddServerCreditCard(credit_card);
// Set up our credit card form data.
FormData credit_card_form;
CreateTestCreditCardFormData(&credit_card_form, true, false);
FormsSeen(std::vector<FormData>(1, credit_card_form));
// Edit the data, and submit.
credit_card_form.fields[0].value = ASCIIToUTF16("Flo Master");
credit_card_form.fields[1].value = ASCIIToUTF16("4111111111111111");
credit_card_form.fields[2].value = ASCIIToUTF16("11");
credit_card_form.fields[3].value = ASCIIToUTF16(NextYear());
credit_card_form.fields[4].value = ASCIIToUTF16("123");
// Local save prompt should not be shown as there is alredy masked
// card with same |TypeAndLastFourDigits|.
EXPECT_CALL(autofill_client_, ConfirmSaveCreditCardLocally(_, _)).Times(0);
FormSubmitted(credit_card_form);
EXPECT_FALSE(credit_card_save_manager_->CreditCardWasUploaded());
}
TEST_F(CreditCardSaveManagerTest, GetDetectedValues_NothingIfNothingFound) {
EnableAutofillUpstreamSendDetectedValuesExperiment();
personal_data_.ClearProfiles();
credit_card_save_manager_->SetCreditCardUploadEnabled(true);
// Set up our credit card form data.
FormData credit_card_form;
CreateTestCreditCardFormData(&credit_card_form, true, false);
FormsSeen(std::vector<FormData>(1, credit_card_form));
// Edit the data, and submit.
credit_card_form.fields[0].value = ASCIIToUTF16(""); // No name set
credit_card_form.fields[1].value = ASCIIToUTF16("4111111111111111");
credit_card_form.fields[2].value = ASCIIToUTF16("11");
credit_card_form.fields[3].value = ASCIIToUTF16(NextYear());
credit_card_form.fields[4].value = ASCIIToUTF16(""); // No CVC set
// Submit the form and check what detected_values for an upload save would be.
FormSubmitted(credit_card_form);
EXPECT_EQ(payments_client_->GetDetectedValuesSetInRequest(), 0);
}
TEST_F(CreditCardSaveManagerTest, GetDetectedValues_DetectCvc) {
EnableAutofillUpstreamSendDetectedValuesExperiment();
personal_data_.ClearProfiles();
credit_card_save_manager_->SetCreditCardUploadEnabled(true);
// Set up our credit card form data.
FormData credit_card_form;
CreateTestCreditCardFormData(&credit_card_form, true, false);
FormsSeen(std::vector<FormData>(1, credit_card_form));
// Edit the data, and submit.
credit_card_form.fields[0].value = ASCIIToUTF16(""); // No name set
credit_card_form.fields[1].value = ASCIIToUTF16("4111111111111111");
credit_card_form.fields[2].value = ASCIIToUTF16("11");
credit_card_form.fields[3].value = ASCIIToUTF16(NextYear());
credit_card_form.fields[4].value = ASCIIToUTF16("123");
// Submit the form and check what detected_values for an upload save would be.
FormSubmitted(credit_card_form);
EXPECT_EQ(payments_client_->GetDetectedValuesSetInRequest(),
CreditCardSaveManager::DetectedValue::CVC);
}
TEST_F(CreditCardSaveManagerTest, GetDetectedValues_DetectCardholderName) {
EnableAutofillUpstreamSendDetectedValuesExperiment();
personal_data_.ClearProfiles();
credit_card_save_manager_->SetCreditCardUploadEnabled(true);
// Set up our credit card form data.
FormData credit_card_form;
CreateTestCreditCardFormData(&credit_card_form, true, false);
FormsSeen(std::vector<FormData>(1, credit_card_form));
// Edit the data, and submit.
credit_card_form.fields[0].value = ASCIIToUTF16("John Smith");
credit_card_form.fields[1].value = ASCIIToUTF16("4111111111111111");
credit_card_form.fields[2].value = ASCIIToUTF16("11");
credit_card_form.fields[3].value = ASCIIToUTF16(NextYear());
credit_card_form.fields[4].value = ASCIIToUTF16(""); // No CVC set
// Submit the form and check what detected_values for an upload save would be.
FormSubmitted(credit_card_form);
EXPECT_EQ(payments_client_->GetDetectedValuesSetInRequest(),
CreditCardSaveManager::DetectedValue::CARDHOLDER_NAME);
}
TEST_F(CreditCardSaveManagerTest, GetDetectedValues_DetectAddressName) {
EnableAutofillUpstreamSendDetectedValuesExperiment();
personal_data_.ClearProfiles();
credit_card_save_manager_->SetCreditCardUploadEnabled(true);
// Set up a new address profile.
AutofillProfile profile;
profile.set_guid("00000000-0000-0000-0000-000000000200");
profile.SetInfo(NAME_FULL, ASCIIToUTF16("John Smith"), "en-US");
personal_data_.AddProfile(profile);
// Set up our credit card form data.
FormData credit_card_form;
CreateTestCreditCardFormData(&credit_card_form, true, false);
FormsSeen(std::vector<FormData>(1, credit_card_form));
// Edit the data, and submit.
credit_card_form.fields[0].value = ASCIIToUTF16(""); // No name set
credit_card_form.fields[1].value = ASCIIToUTF16("4111111111111111");
credit_card_form.fields[2].value = ASCIIToUTF16("11");
credit_card_form.fields[3].value = ASCIIToUTF16(NextYear());
credit_card_form.fields[4].value = ASCIIToUTF16(""); // No CVC set
// Submit the form and check what detected_values for an upload save would be.
FormSubmitted(credit_card_form);
EXPECT_EQ(payments_client_->GetDetectedValuesSetInRequest(),
CreditCardSaveManager::DetectedValue::ADDRESS_NAME);
}
TEST_F(CreditCardSaveManagerTest,
GetDetectedValues_DetectCardholderAndAddressNameIfMatching) {
EnableAutofillUpstreamSendDetectedValuesExperiment();
personal_data_.ClearProfiles();
credit_card_save_manager_->SetCreditCardUploadEnabled(true);
// Set up a new address profile.
AutofillProfile profile;
profile.set_guid("00000000-0000-0000-0000-000000000200");
profile.SetInfo(NAME_FULL, ASCIIToUTF16("John Smith"), "en-US");
personal_data_.AddProfile(profile);
// Set up our credit card form data.
FormData credit_card_form;
CreateTestCreditCardFormData(&credit_card_form, true, false);
FormsSeen(std::vector<FormData>(1, credit_card_form));
// Edit the data, and submit.
credit_card_form.fields[0].value = ASCIIToUTF16("John Smith");
credit_card_form.fields[1].value = ASCIIToUTF16("4111111111111111");
credit_card_form.fields[2].value = ASCIIToUTF16("11");
credit_card_form.fields[3].value = ASCIIToUTF16(NextYear());
credit_card_form.fields[4].value = ASCIIToUTF16(""); // No CVC set
// Submit the form and check what detected_values for an upload save would be.
FormSubmitted(credit_card_form);
EXPECT_EQ(payments_client_->GetDetectedValuesSetInRequest(),
CreditCardSaveManager::DetectedValue::CARDHOLDER_NAME |
CreditCardSaveManager::DetectedValue::ADDRESS_NAME);
}
TEST_F(CreditCardSaveManagerTest,
GetDetectedValues_DetectNoUniqueNameIfNamesConflict) {
EnableAutofillUpstreamSendDetectedValuesExperiment();
personal_data_.ClearProfiles();
credit_card_save_manager_->SetCreditCardUploadEnabled(true);
// Set up a new address profile.
AutofillProfile profile;
profile.set_guid("00000000-0000-0000-0000-000000000200");
profile.SetInfo(NAME_FULL, ASCIIToUTF16("John Smith"), "en-US");
personal_data_.AddProfile(profile);
// Set up our credit card form data.
FormData credit_card_form;
CreateTestCreditCardFormData(&credit_card_form, true, false);
FormsSeen(std::vector<FormData>(1, credit_card_form));
// Edit the data, and submit.
credit_card_form.fields[0].value = ASCIIToUTF16("Miles Prower"); // Conflict!
credit_card_form.fields[1].value = ASCIIToUTF16("4111111111111111");
credit_card_form.fields[2].value = ASCIIToUTF16("11");
credit_card_form.fields[3].value = ASCIIToUTF16(NextYear());
credit_card_form.fields[4].value = ASCIIToUTF16(""); // No CVC set
// Submit the form and check what detected_values for an upload save would be.
FormSubmitted(credit_card_form);
EXPECT_EQ(payments_client_->GetDetectedValuesSetInRequest(), 0);
}
TEST_F(CreditCardSaveManagerTest, GetDetectedValues_DetectPostalCode) {
EnableAutofillUpstreamSendDetectedValuesExperiment();
personal_data_.ClearProfiles();
credit_card_save_manager_->SetCreditCardUploadEnabled(true);
// Set up a new address profile.
AutofillProfile profile;
profile.set_guid("00000000-0000-0000-0000-000000000200");
profile.SetInfo(ADDRESS_HOME_ZIP, ASCIIToUTF16("94043"), "en-US");
personal_data_.AddProfile(profile);
// Set up our credit card form data.
FormData credit_card_form;
CreateTestCreditCardFormData(&credit_card_form, true, false);
FormsSeen(std::vector<FormData>(1, credit_card_form));
// Edit the data, and submit.
credit_card_form.fields[0].value = ASCIIToUTF16(""); // No name set
credit_card_form.fields[1].value = ASCIIToUTF16("4111111111111111");
credit_card_form.fields[2].value = ASCIIToUTF16("11");
credit_card_form.fields[3].value = ASCIIToUTF16(NextYear());
credit_card_form.fields[4].value = ASCIIToUTF16(""); // No CVC set
// Submit the form and check what detected_values for an upload save would be.
FormSubmitted(credit_card_form);
EXPECT_EQ(payments_client_->GetDetectedValuesSetInRequest(),
CreditCardSaveManager::DetectedValue::POSTAL_CODE);
}
TEST_F(CreditCardSaveManagerTest,
GetDetectedValues_DetectNoUniquePostalCodeIfZipsConflict) {
EnableAutofillUpstreamSendDetectedValuesExperiment();
personal_data_.ClearProfiles();
credit_card_save_manager_->SetCreditCardUploadEnabled(true);
// Set up two new address profiles with conflicting postal codes.
AutofillProfile profile1;
profile1.set_guid("00000000-0000-0000-0000-000000000200");
profile1.SetInfo(ADDRESS_HOME_ZIP, ASCIIToUTF16("94043"), "en-US");
personal_data_.AddProfile(profile1);
AutofillProfile profile2;
profile2.set_guid("00000000-0000-0000-0000-000000000201");
profile2.SetInfo(ADDRESS_HOME_ZIP, ASCIIToUTF16("95051"), "en-US");
personal_data_.AddProfile(profile2);
// Set up our credit card form data.
FormData credit_card_form;
CreateTestCreditCardFormData(&credit_card_form, true, false);
FormsSeen(std::vector<FormData>(1, credit_card_form));
// Edit the data, and submit.
credit_card_form.fields[0].value = ASCIIToUTF16(""); // No name set
credit_card_form.fields[1].value = ASCIIToUTF16("4111111111111111");
credit_card_form.fields[2].value = ASCIIToUTF16("11");
credit_card_form.fields[3].value = ASCIIToUTF16(NextYear());
credit_card_form.fields[4].value = ASCIIToUTF16(""); // No CVC set
// Submit the form and check what detected_values for an upload save would be.
FormSubmitted(credit_card_form);
EXPECT_EQ(payments_client_->GetDetectedValuesSetInRequest(), 0);
}
TEST_F(CreditCardSaveManagerTest, GetDetectedValues_DetectAddressLine) {
EnableAutofillUpstreamSendDetectedValuesExperiment();
personal_data_.ClearProfiles();
credit_card_save_manager_->SetCreditCardUploadEnabled(true);
// Set up a new address profile.
AutofillProfile profile;
profile.set_guid("00000000-0000-0000-0000-000000000200");
profile.SetInfo(ADDRESS_HOME_LINE1, ASCIIToUTF16("123 Testing St."), "en-US");
personal_data_.AddProfile(profile);
// Set up our credit card form data.
FormData credit_card_form;
CreateTestCreditCardFormData(&credit_card_form, true, false);
FormsSeen(std::vector<FormData>(1, credit_card_form));
// Edit the data, and submit.
credit_card_form.fields[0].value = ASCIIToUTF16(""); // No name set
credit_card_form.fields[1].value = ASCIIToUTF16("4111111111111111");
credit_card_form.fields[2].value = ASCIIToUTF16("11");
credit_card_form.fields[3].value = ASCIIToUTF16(NextYear());
credit_card_form.fields[4].value = ASCIIToUTF16(""); // No CVC set
// Submit the form and check what detected_values for an upload save would be.
FormSubmitted(credit_card_form);
EXPECT_EQ(payments_client_->GetDetectedValuesSetInRequest(),
CreditCardSaveManager::DetectedValue::ADDRESS_LINE);
}
TEST_F(CreditCardSaveManagerTest, GetDetectedValues_DetectLocality) {
EnableAutofillUpstreamSendDetectedValuesExperiment();
personal_data_.ClearProfiles();
credit_card_save_manager_->SetCreditCardUploadEnabled(true);
// Set up a new address profile.
AutofillProfile profile;
profile.set_guid("00000000-0000-0000-0000-000000000200");
profile.SetInfo(ADDRESS_HOME_CITY, ASCIIToUTF16("Mountain View"), "en-US");
personal_data_.AddProfile(profile);
// Set up our credit card form data.
FormData credit_card_form;
CreateTestCreditCardFormData(&credit_card_form, true, false);
FormsSeen(std::vector<FormData>(1, credit_card_form));
// Edit the data, and submit.
credit_card_form.fields[0].value = ASCIIToUTF16(""); // No name set
credit_card_form.fields[1].value = ASCIIToUTF16("4111111111111111");
credit_card_form.fields[2].value = ASCIIToUTF16("11");
credit_card_form.fields[3].value = ASCIIToUTF16(NextYear());
credit_card_form.fields[4].value = ASCIIToUTF16(""); // No CVC set
// Submit the form and check what detected_values for an upload save would be.
FormSubmitted(credit_card_form);
EXPECT_EQ(payments_client_->GetDetectedValuesSetInRequest(),
CreditCardSaveManager::DetectedValue::LOCALITY);
}
TEST_F(CreditCardSaveManagerTest, GetDetectedValues_DetectAdministrativeArea) {
EnableAutofillUpstreamSendDetectedValuesExperiment();
personal_data_.ClearProfiles();
credit_card_save_manager_->SetCreditCardUploadEnabled(true);
// Set up a new address profile.
AutofillProfile profile;
profile.set_guid("00000000-0000-0000-0000-000000000200");
profile.SetInfo(ADDRESS_HOME_STATE, ASCIIToUTF16("California"), "en-US");
personal_data_.AddProfile(profile);
// Set up our credit card form data.
FormData credit_card_form;
CreateTestCreditCardFormData(&credit_card_form, true, false);
FormsSeen(std::vector<FormData>(1, credit_card_form));
// Edit the data, and submit.
credit_card_form.fields[0].value = ASCIIToUTF16(""); // No name set
credit_card_form.fields[1].value = ASCIIToUTF16("4111111111111111");
credit_card_form.fields[2].value = ASCIIToUTF16("11");
credit_card_form.fields[3].value = ASCIIToUTF16(NextYear());
credit_card_form.fields[4].value = ASCIIToUTF16(""); // No CVC set
// Submit the form and check what detected_values for an upload save would be.
FormSubmitted(credit_card_form);
EXPECT_EQ(payments_client_->GetDetectedValuesSetInRequest(),
CreditCardSaveManager::DetectedValue::ADMINISTRATIVE_AREA);
}
TEST_F(CreditCardSaveManagerTest, GetDetectedValues_DetectCountryCode) {
EnableAutofillUpstreamSendDetectedValuesExperiment();
personal_data_.ClearProfiles();
credit_card_save_manager_->SetCreditCardUploadEnabled(true);
// Set up a new address profile.
AutofillProfile profile;
profile.set_guid("00000000-0000-0000-0000-000000000200");
profile.SetInfo(ADDRESS_HOME_COUNTRY, ASCIIToUTF16("US"), "en-US");
personal_data_.AddProfile(profile);
// Set up our credit card form data.
FormData credit_card_form;
CreateTestCreditCardFormData(&credit_card_form, true, false);
FormsSeen(std::vector<FormData>(1, credit_card_form));
// Edit the data, and submit.
credit_card_form.fields[0].value = ASCIIToUTF16(""); // No name set
credit_card_form.fields[1].value = ASCIIToUTF16("4111111111111111");
credit_card_form.fields[2].value = ASCIIToUTF16("11");
credit_card_form.fields[3].value = ASCIIToUTF16(NextYear());
credit_card_form.fields[4].value = ASCIIToUTF16(""); // No CVC set
// Submit the form and check what detected_values for an upload save would be.
FormSubmitted(credit_card_form);
EXPECT_EQ(payments_client_->GetDetectedValuesSetInRequest(),
CreditCardSaveManager::DetectedValue::COUNTRY_CODE);
}
TEST_F(CreditCardSaveManagerTest,
GetDetectedValues_DetectHasGooglePaymentAccount) {
EnableAutofillUpstreamSendDetectedValuesExperiment();
personal_data_.ClearProfiles();
credit_card_save_manager_->SetCreditCardUploadEnabled(true);
// Set the billing_customer_number Priority Preference to designate existence
// of a Payments account.
autofill_client_.GetPrefs()->SetDouble(prefs::kAutofillBillingCustomerNumber,
12345);
// Set up our credit card form data.
FormData credit_card_form;
CreateTestCreditCardFormData(&credit_card_form, true, false);
FormsSeen(std::vector<FormData>(1, credit_card_form));
// Edit the data, and submit.
credit_card_form.fields[0].value = ASCIIToUTF16(""); // No name set
credit_card_form.fields[1].value = ASCIIToUTF16("4111111111111111");
credit_card_form.fields[2].value = ASCIIToUTF16("11");
credit_card_form.fields[3].value = ASCIIToUTF16(NextYear());
credit_card_form.fields[4].value = ASCIIToUTF16(""); // No CVC set
// Submit the form and check what detected_values for an upload save would be.
FormSubmitted(credit_card_form);
EXPECT_EQ(payments_client_->GetDetectedValuesSetInRequest(),
CreditCardSaveManager::DetectedValue::HAS_GOOGLE_PAYMENTS_ACCOUNT);
}
TEST_F(CreditCardSaveManagerTest, GetDetectedValues_DetectEverythingAtOnce) {
EnableAutofillUpstreamSendDetectedValuesExperiment();
personal_data_.ClearProfiles();
credit_card_save_manager_->SetCreditCardUploadEnabled(true);
// Set up a new address profile.
AutofillProfile profile;
profile.set_guid("00000000-0000-0000-0000-000000000200");
profile.SetInfo(NAME_FULL, ASCIIToUTF16("John Smith"), "en-US");
profile.SetInfo(ADDRESS_HOME_LINE1, ASCIIToUTF16("123 Testing St."), "en-US");
profile.SetInfo(ADDRESS_HOME_CITY, ASCIIToUTF16("Mountain View"), "en-US");
profile.SetInfo(ADDRESS_HOME_STATE, ASCIIToUTF16("California"), "en-US");
profile.SetInfo(ADDRESS_HOME_ZIP, ASCIIToUTF16("94043"), "en-US");
profile.SetInfo(ADDRESS_HOME_COUNTRY, ASCIIToUTF16("US"), "en-US");
personal_data_.AddProfile(profile);
// Set up our credit card form data.
FormData credit_card_form;
CreateTestCreditCardFormData(&credit_card_form, true, false);
FormsSeen(std::vector<FormData>(1, credit_card_form));
// Edit the data, and submit.
credit_card_form.fields[0].value = ASCIIToUTF16("John Smith");
credit_card_form.fields[1].value = ASCIIToUTF16("4111111111111111");
credit_card_form.fields[2].value = ASCIIToUTF16("11");
credit_card_form.fields[3].value = ASCIIToUTF16(NextYear());
credit_card_form.fields[4].value = ASCIIToUTF16("123");
// Submit the form and check what detected_values for an upload save would be.
FormSubmitted(credit_card_form);
EXPECT_EQ(payments_client_->GetDetectedValuesSetInRequest(),
CreditCardSaveManager::DetectedValue::CVC |
CreditCardSaveManager::DetectedValue::CARDHOLDER_NAME |
CreditCardSaveManager::DetectedValue::ADDRESS_NAME |
CreditCardSaveManager::DetectedValue::ADDRESS_LINE |
CreditCardSaveManager::DetectedValue::LOCALITY |
CreditCardSaveManager::DetectedValue::ADMINISTRATIVE_AREA |
CreditCardSaveManager::DetectedValue::POSTAL_CODE |
CreditCardSaveManager::DetectedValue::COUNTRY_CODE);
}
TEST_F(CreditCardSaveManagerTest,
GetDetectedValues_DetectSubsetOfPossibleFields) {
EnableAutofillUpstreamSendDetectedValuesExperiment();
personal_data_.ClearProfiles();
credit_card_save_manager_->SetCreditCardUploadEnabled(true);
// Set up a new address profile, taking out address line and state.
AutofillProfile profile;
profile.set_guid("00000000-0000-0000-0000-000000000200");
profile.SetInfo(NAME_FULL, ASCIIToUTF16("John Smith"), "en-US");
profile.SetInfo(ADDRESS_HOME_CITY, ASCIIToUTF16("Mountain View"), "en-US");
profile.SetInfo(ADDRESS_HOME_ZIP, ASCIIToUTF16("94043"), "en-US");
profile.SetInfo(ADDRESS_HOME_COUNTRY, ASCIIToUTF16("US"), "en-US");
personal_data_.AddProfile(profile);
// Set up our credit card form data.
FormData credit_card_form;
CreateTestCreditCardFormData(&credit_card_form, true, false);
FormsSeen(std::vector<FormData>(1, credit_card_form));
// Edit the data, and submit.
credit_card_form.fields[0].value = ASCIIToUTF16("Miles Prower"); // Conflict!
credit_card_form.fields[1].value = ASCIIToUTF16("4111111111111111");
credit_card_form.fields[2].value = ASCIIToUTF16("11");
credit_card_form.fields[3].value = ASCIIToUTF16(NextYear());
credit_card_form.fields[4].value = ASCIIToUTF16("123");
// Submit the form and check what detected_values for an upload save would be.
FormSubmitted(credit_card_form);
EXPECT_EQ(payments_client_->GetDetectedValuesSetInRequest(),
CreditCardSaveManager::DetectedValue::CVC |
CreditCardSaveManager::DetectedValue::LOCALITY |
CreditCardSaveManager::DetectedValue::POSTAL_CODE |
CreditCardSaveManager::DetectedValue::COUNTRY_CODE);
}
// This test checks that ADDRESS_LINE, LOCALITY, ADMINISTRATIVE_AREA, and
// COUNTRY_CODE don't care about possible conflicts or consistency and are
// populated if even one address profile contains it.
TEST_F(CreditCardSaveManagerTest,
GetDetectedValues_DetectAddressComponentsAcrossProfiles) {
EnableAutofillUpstreamSendDetectedValuesExperiment();
personal_data_.ClearProfiles();
credit_card_save_manager_->SetCreditCardUploadEnabled(true);
// Set up four new address profiles, each with a different address component.
AutofillProfile profile1;
profile1.set_guid("00000000-0000-0000-0000-000000000200");
profile1.SetInfo(ADDRESS_HOME_LINE1, ASCIIToUTF16("123 Testing St."),
"en-US");
personal_data_.AddProfile(profile1);
AutofillProfile profile2;
profile2.set_guid("00000000-0000-0000-0000-000000000201");
profile2.SetInfo(ADDRESS_HOME_CITY, ASCIIToUTF16("Mountain View"), "en-US");
personal_data_.AddProfile(profile2);
AutofillProfile profile3;
profile3.set_guid("00000000-0000-0000-0000-000000000202");
profile3.SetInfo(ADDRESS_HOME_STATE, ASCIIToUTF16("California"), "en-US");
personal_data_.AddProfile(profile3);
AutofillProfile profile4;
profile4.set_guid("00000000-0000-0000-0000-000000000203");
profile4.SetInfo(ADDRESS_HOME_COUNTRY, ASCIIToUTF16("US"), "en-US");
personal_data_.AddProfile(profile4);
// Set up our credit card form data.
FormData credit_card_form;
CreateTestCreditCardFormData(&credit_card_form, true, false);
FormsSeen(std::vector<FormData>(1, credit_card_form));
// Edit the data, and submit.
credit_card_form.fields[0].value = ASCIIToUTF16(""); // No name set
credit_card_form.fields[1].value = ASCIIToUTF16("4111111111111111");
credit_card_form.fields[2].value = ASCIIToUTF16("11");
credit_card_form.fields[3].value = ASCIIToUTF16(NextYear());
credit_card_form.fields[4].value = ASCIIToUTF16(""); // No CVC set
// Submit the form and check what detected_values for an upload save would be.
FormSubmitted(credit_card_form);
EXPECT_EQ(payments_client_->GetDetectedValuesSetInRequest(),
CreditCardSaveManager::DetectedValue::ADDRESS_LINE |
CreditCardSaveManager::DetectedValue::LOCALITY |
CreditCardSaveManager::DetectedValue::ADMINISTRATIVE_AREA |
CreditCardSaveManager::DetectedValue::COUNTRY_CODE);
}
TEST_F(CreditCardSaveManagerTest,
UploadCreditCard_AddSendDetectedValuesFlagStateToRequestIfExperimentOn) {
EnableAutofillUpstreamSendDetectedValuesExperiment();
personal_data_.ClearProfiles();
credit_card_save_manager_->SetCreditCardUploadEnabled(true);
// Set up our credit card form data.
FormData credit_card_form;
CreateTestCreditCardFormData(&credit_card_form, true, false);
FormsSeen(std::vector<FormData>(1, credit_card_form));
// Edit the data, and submit.
credit_card_form.fields[0].value = ASCIIToUTF16("Flo Master");
credit_card_form.fields[1].value = ASCIIToUTF16("4111111111111111");
credit_card_form.fields[2].value = ASCIIToUTF16("11");
credit_card_form.fields[3].value = ASCIIToUTF16(NextYear());
credit_card_form.fields[4].value = ASCIIToUTF16("123");
// Confirm upload happened and the send detected values flag was sent in the
// request.
EXPECT_CALL(autofill_client_, ConfirmSaveCreditCardLocally(_, _)).Times(0);
FormSubmitted(credit_card_form);
EXPECT_TRUE(credit_card_save_manager_->CreditCardWasUploaded());
EXPECT_THAT(payments_client_->GetActiveExperimentsSetInRequest(),
UnorderedElementsAre(kAutofillUpstreamSendDetectedValues.name));
}
TEST_F(CreditCardSaveManagerTest,
UploadCreditCard_LogAdditionalErrorsWithUploadDetailsFailureIfExpOn) {
EnableAutofillUpstreamSendDetectedValuesExperiment();
personal_data_.ClearProfiles();
credit_card_save_manager_->SetCreditCardUploadEnabled(true);
// Anything other than "en-US" will cause GetUploadDetails to return a failure
// response.
credit_card_save_manager_->SetAppLocale("pt-BR");
// Set up a new address profile without a name or postal code.
AutofillProfile profile;
profile.set_guid("00000000-0000-0000-0000-000000000200");
profile.SetInfo(ADDRESS_HOME_LINE1, ASCIIToUTF16("123 Testing St."), "en-US");
profile.SetInfo(ADDRESS_HOME_CITY, ASCIIToUTF16("Mountain View"), "en-US");
profile.SetInfo(ADDRESS_HOME_STATE, ASCIIToUTF16("California"), "en-US");
profile.SetInfo(ADDRESS_HOME_COUNTRY, ASCIIToUTF16("US"), "en-US");
personal_data_.AddProfile(profile);
// Set up our credit card form data.
FormData credit_card_form;
CreateTestCreditCardFormData(&credit_card_form, true, false);
FormsSeen(std::vector<FormData>(1, credit_card_form));
// Edit the data, and submit.
credit_card_form.fields[0].value = ASCIIToUTF16(""); // No name!
credit_card_form.fields[1].value = ASCIIToUTF16("4111111111111111");
credit_card_form.fields[2].value = ASCIIToUTF16("11");
credit_card_form.fields[3].value = ASCIIToUTF16(NextYear());
credit_card_form.fields[4].value = ASCIIToUTF16(""); // No CVC!
base::HistogramTester histogram_tester;
FormSubmitted(credit_card_form);
// Verify that the correct histogram entries were logged.
ExpectCardUploadDecision(
histogram_tester,
AutofillMetrics::UPLOAD_NOT_OFFERED_GET_UPLOAD_DETAILS_FAILED);
ExpectCardUploadDecision(histogram_tester,
AutofillMetrics::UPLOAD_NOT_OFFERED_NO_NAME);
ExpectCardUploadDecision(histogram_tester,
AutofillMetrics::UPLOAD_NOT_OFFERED_NO_ZIP_CODE);
ExpectCardUploadDecision(histogram_tester,
AutofillMetrics::CVC_VALUE_NOT_FOUND);
// Verify that the correct UKM was logged.
ExpectMetric(UkmCardUploadDecisionType::kUploadDecisionName,
UkmCardUploadDecisionType::kEntryName,
AutofillMetrics::UPLOAD_NOT_OFFERED_GET_UPLOAD_DETAILS_FAILED |
AutofillMetrics::UPLOAD_NOT_OFFERED_NO_NAME |
AutofillMetrics::UPLOAD_NOT_OFFERED_NO_ZIP_CODE |
AutofillMetrics::CVC_VALUE_NOT_FOUND,
1 /* expected_num_matching_entries */);
}
TEST_F(
CreditCardSaveManagerTest,
UploadCreditCard_ShouldOfferLocalSaveIfEverythingDetectedAndPaymentsDeclinesIfExpOn) {
EnableAutofillUpstreamSendDetectedValuesExperiment();
personal_data_.ClearProfiles();
credit_card_save_manager_->SetCreditCardUploadEnabled(true);
// Anything other than "en-US" will cause GetUploadDetails to return a failure
// response.
credit_card_save_manager_->SetAppLocale("pt-BR");
// Set up a new address profile.
AutofillProfile profile;
profile.set_guid("00000000-0000-0000-0000-000000000200");
profile.SetInfo(NAME_FULL, ASCIIToUTF16("John Smith"), "en-US");
profile.SetInfo(ADDRESS_HOME_LINE1, ASCIIToUTF16("123 Testing St."), "en-US");
profile.SetInfo(ADDRESS_HOME_CITY, ASCIIToUTF16("Mountain View"), "en-US");
profile.SetInfo(ADDRESS_HOME_STATE, ASCIIToUTF16("California"), "en-US");
profile.SetInfo(ADDRESS_HOME_ZIP, ASCIIToUTF16("94043"), "en-US");
profile.SetInfo(ADDRESS_HOME_COUNTRY, ASCIIToUTF16("US"), "en-US");
personal_data_.AddProfile(profile);
// Set up our credit card form data.
FormData credit_card_form;
CreateTestCreditCardFormData(&credit_card_form, true, false);
FormsSeen(std::vector<FormData>(1, credit_card_form));
// Edit the data, and submit.
credit_card_form.fields[0].value = ASCIIToUTF16("John Smith");
credit_card_form.fields[1].value = ASCIIToUTF16("4111111111111111");
credit_card_form.fields[2].value = ASCIIToUTF16("11");
credit_card_form.fields[3].value = ASCIIToUTF16(NextYear());
credit_card_form.fields[4].value = ASCIIToUTF16("123");
base::HistogramTester histogram_tester;
// Because Payments rejects the offer to upload save but CVC + name + address
// were all found, the local save prompt should be shown instead of the upload
// prompt.
EXPECT_CALL(autofill_client_, ConfirmSaveCreditCardLocally(_, _));
FormSubmitted(credit_card_form);
EXPECT_FALSE(credit_card_save_manager_->CreditCardWasUploaded());
}
TEST_F(
CreditCardSaveManagerTest,
UploadCreditCard_ShouldNotOfferLocalSaveIfSomethingNotDetectedAndPaymentsDeclinesIfExpOn) {
EnableAutofillUpstreamSendDetectedValuesExperiment();
personal_data_.ClearProfiles();
credit_card_save_manager_->SetCreditCardUploadEnabled(true);
// Anything other than "en-US" will cause GetUploadDetails to return a failure
// response.
credit_card_save_manager_->SetAppLocale("pt-BR");
// Set up a new address profile without a name or postal code.
AutofillProfile profile;
profile.set_guid("00000000-0000-0000-0000-000000000200");
profile.SetInfo(ADDRESS_HOME_LINE1, ASCIIToUTF16("123 Testing St."), "en-US");
profile.SetInfo(ADDRESS_HOME_CITY, ASCIIToUTF16("Mountain View"), "en-US");
profile.SetInfo(ADDRESS_HOME_STATE, ASCIIToUTF16("California"), "en-US");
profile.SetInfo(ADDRESS_HOME_COUNTRY, ASCIIToUTF16("US"), "en-US");
personal_data_.AddProfile(profile);
// Set up our credit card form data.
FormData credit_card_form;
CreateTestCreditCardFormData(&credit_card_form, true, false);
FormsSeen(std::vector<FormData>(1, credit_card_form));
// Edit the data, and submit.
credit_card_form.fields[0].value = ASCIIToUTF16(""); // No name!
credit_card_form.fields[1].value = ASCIIToUTF16("4111111111111111");
credit_card_form.fields[2].value = ASCIIToUTF16("11");
credit_card_form.fields[3].value = ASCIIToUTF16(NextYear());
credit_card_form.fields[4].value = ASCIIToUTF16(""); // No CVC!
base::HistogramTester histogram_tester;
// Because Payments rejects the offer to upload save but not all of CVC + name
// + address were detected, the local save prompt should not be shown either.
EXPECT_CALL(autofill_client_, ConfirmSaveCreditCardLocally(_, _)).Times(0);
FormSubmitted(credit_card_form);
EXPECT_FALSE(credit_card_save_manager_->CreditCardWasUploaded());
}
TEST_F(CreditCardSaveManagerTest,
UploadCreditCard_PaymentsDecidesOfferToSaveIfNoCvcAndExpOn) {
EnableAutofillUpstreamSendDetectedValuesExperiment();
personal_data_.ClearProfiles();
credit_card_save_manager_->SetCreditCardUploadEnabled(true);
// Create, fill and submit an address form in order to establish a recent
// profile which can be selected for the upload request.
FormData address_form;
test::CreateTestAddressFormData(&address_form);
FormsSeen(std::vector<FormData>(1, address_form));
ManuallyFillAddressForm("Flo", "Master", "77401", "US", &address_form);
FormSubmitted(address_form);
// Set up our credit card form data.
FormData credit_card_form;
CreateTestCreditCardFormData(&credit_card_form, true, false);
FormsSeen(std::vector<FormData>(1, credit_card_form));
// Edit the data, and submit.
credit_card_form.fields[0].value = ASCIIToUTF16("Flo Master");
credit_card_form.fields[1].value = ASCIIToUTF16("4111111111111111");
credit_card_form.fields[2].value = ASCIIToUTF16("11");
credit_card_form.fields[3].value = ASCIIToUTF16(NextYear());
credit_card_form.fields[4].value = ASCIIToUTF16(""); // No CVC!
base::HistogramTester histogram_tester;
// Because the send detected values experiment is on, Payments should be asked
// whether upload save can be offered. (Unit tests assume they reply yes and
// save is successful.)
EXPECT_CALL(autofill_client_, ConfirmSaveCreditCardLocally(_, _)).Times(0);
FormSubmitted(credit_card_form);
EXPECT_TRUE(credit_card_save_manager_->CreditCardWasUploaded());
// Verify that the correct histogram entries were logged.
ExpectCardUploadDecision(histogram_tester, AutofillMetrics::UPLOAD_OFFERED);
ExpectCardUploadDecision(histogram_tester,
AutofillMetrics::CVC_VALUE_NOT_FOUND);
// Verify that the correct UKM was logged.
ExpectMetric(
UkmCardUploadDecisionType::kUploadDecisionName,
UkmCardUploadDecisionType::kEntryName,
AutofillMetrics::UPLOAD_OFFERED | AutofillMetrics::CVC_VALUE_NOT_FOUND,
1 /* expected_num_matching_entries */);
}
TEST_F(CreditCardSaveManagerTest,
UploadCreditCard_PaymentsDecidesOfferToSaveIfNoNameAndExpOn) {
EnableAutofillUpstreamSendDetectedValuesExperiment();
personal_data_.ClearProfiles();
credit_card_save_manager_->SetCreditCardUploadEnabled(true);
// Create, fill and submit an address form in order to establish a recent
// profile which can be selected for the upload request.
FormData address_form;
test::CreateTestAddressFormData(&address_form);
FormsSeen(std::vector<FormData>(1, address_form));
// But omit the name:
ManuallyFillAddressForm("", "", "77401", "US", &address_form);
FormSubmitted(address_form);
// Set up our credit card form data.
FormData credit_card_form;
CreateTestCreditCardFormData(&credit_card_form, true, false);
FormsSeen(std::vector<FormData>(1, credit_card_form));
// Edit the data, and submit.
credit_card_form.fields[0].value = ASCIIToUTF16(""); // No name!
credit_card_form.fields[1].value = ASCIIToUTF16("4111111111111111");
credit_card_form.fields[2].value = ASCIIToUTF16("11");
credit_card_form.fields[3].value = ASCIIToUTF16(NextYear());
credit_card_form.fields[4].value = ASCIIToUTF16("123");
base::HistogramTester histogram_tester;
// Because the send detected values experiment is on, Payments should be asked
// whether upload save can be offered. (Unit tests assume they reply yes and
// save is successful.)
EXPECT_CALL(autofill_client_, ConfirmSaveCreditCardLocally(_, _)).Times(0);
FormSubmitted(credit_card_form);
EXPECT_TRUE(credit_card_save_manager_->CreditCardWasUploaded());
// Verify that the correct histogram entries were logged.
ExpectCardUploadDecision(histogram_tester, AutofillMetrics::UPLOAD_OFFERED);
ExpectCardUploadDecision(histogram_tester,
AutofillMetrics::UPLOAD_NOT_OFFERED_NO_NAME);
// Verify that the correct UKM was logged.
ExpectMetric(UkmCardUploadDecisionType::kUploadDecisionName,
UkmCardUploadDecisionType::kEntryName,
AutofillMetrics::UPLOAD_OFFERED |
AutofillMetrics::UPLOAD_NOT_OFFERED_NO_NAME,
1 /* expected_num_matching_entries */);
}
TEST_F(CreditCardSaveManagerTest,
UploadCreditCard_PaymentsDecidesOfferToSaveIfConflictingNamesAndExpOn) {
EnableAutofillUpstreamSendDetectedValuesExperiment();
personal_data_.ClearProfiles();
credit_card_save_manager_->SetCreditCardUploadEnabled(true);
// Create, fill and submit an address form in order to establish a recent
// profile which can be selected for the upload request.
FormData address_form;
test::CreateTestAddressFormData(&address_form);
FormsSeen(std::vector<FormData>(1, address_form));
ManuallyFillAddressForm("Flo", "Master", "77401", "US", &address_form);
FormSubmitted(address_form);
// Set up our credit card form data.
FormData credit_card_form;
CreateTestCreditCardFormData(&credit_card_form, true, false);
FormsSeen(std::vector<FormData>(1, credit_card_form));
// Edit the data, and submit.
credit_card_form.fields[0].value = ASCIIToUTF16("Miles Prower"); // Conflict!
credit_card_form.fields[1].value = ASCIIToUTF16("4111111111111111");
credit_card_form.fields[2].value = ASCIIToUTF16("11");
credit_card_form.fields[3].value = ASCIIToUTF16(NextYear());
credit_card_form.fields[4].value = ASCIIToUTF16("123");
base::HistogramTester histogram_tester;
// Because the send detected values experiment is on, Payments should be asked
// whether upload save can be offered. (Unit tests assume they reply yes and
// save is successful.)
EXPECT_CALL(autofill_client_, ConfirmSaveCreditCardLocally(_, _)).Times(0);
FormSubmitted(credit_card_form);
EXPECT_TRUE(credit_card_save_manager_->CreditCardWasUploaded());
// Verify that the correct histogram entries were logged.
ExpectCardUploadDecision(histogram_tester, AutofillMetrics::UPLOAD_OFFERED);
ExpectCardUploadDecision(
histogram_tester, AutofillMetrics::UPLOAD_NOT_OFFERED_CONFLICTING_NAMES);
// Verify that the correct UKM was logged.
ExpectMetric(UkmCardUploadDecisionType::kUploadDecisionName,
UkmCardUploadDecisionType::kEntryName,
AutofillMetrics::UPLOAD_OFFERED |
AutofillMetrics::UPLOAD_NOT_OFFERED_CONFLICTING_NAMES,
1 /* expected_num_matching_entries */);
}
TEST_F(CreditCardSaveManagerTest,
UploadCreditCard_PaymentsDecidesOfferToSaveIfNoZipAndExpOn) {
EnableAutofillUpstreamSendDetectedValuesExperiment();
personal_data_.ClearProfiles();
credit_card_save_manager_->SetCreditCardUploadEnabled(true);
// Set up a new address profile without a postal code.
AutofillProfile profile;
profile.set_guid("00000000-0000-0000-0000-000000000200");
profile.SetInfo(NAME_FULL, ASCIIToUTF16("Flo Master"), "en-US");
profile.SetInfo(ADDRESS_HOME_LINE1, ASCIIToUTF16("123 Testing St."), "en-US");
profile.SetInfo(ADDRESS_HOME_CITY, ASCIIToUTF16("Mountain View"), "en-US");
profile.SetInfo(ADDRESS_HOME_STATE, ASCIIToUTF16("California"), "en-US");
profile.SetInfo(ADDRESS_HOME_COUNTRY, ASCIIToUTF16("US"), "en-US");
personal_data_.AddProfile(profile);
// Set up our credit card form data.
FormData credit_card_form;
CreateTestCreditCardFormData(&credit_card_form, true, false);
FormsSeen(std::vector<FormData>(1, credit_card_form));
// Edit the data, and submit.
credit_card_form.fields[0].value = ASCIIToUTF16("Flo Master");
credit_card_form.fields[1].value = ASCIIToUTF16("4111111111111111");
credit_card_form.fields[2].value = ASCIIToUTF16("11");
credit_card_form.fields[3].value = ASCIIToUTF16(NextYear());
credit_card_form.fields[4].value = ASCIIToUTF16("123");
base::HistogramTester histogram_tester;
// Because the send detected values experiment is on, Payments should be asked
// whether upload save can be offered. (Unit tests assume they reply yes and
// save is successful.)
EXPECT_CALL(autofill_client_, ConfirmSaveCreditCardLocally(_, _)).Times(0);
FormSubmitted(credit_card_form);
EXPECT_TRUE(credit_card_save_manager_->CreditCardWasUploaded());
// Verify that the correct histogram entries were logged.
ExpectCardUploadDecision(histogram_tester, AutofillMetrics::UPLOAD_OFFERED);
ExpectCardUploadDecision(histogram_tester,
AutofillMetrics::UPLOAD_NOT_OFFERED_NO_ZIP_CODE);
// Verify that the correct UKM was logged.
ExpectMetric(UkmCardUploadDecisionType::kUploadDecisionName,
UkmCardUploadDecisionType::kEntryName,
AutofillMetrics::UPLOAD_OFFERED |
AutofillMetrics::UPLOAD_NOT_OFFERED_NO_ZIP_CODE,
1 /* expected_num_matching_entries */);
}
TEST_F(CreditCardSaveManagerTest,
UploadCreditCard_PaymentsDecidesOfferToSaveIfConflictingZipsAndExpOn) {
EnableAutofillUpstreamSendDetectedValuesExperiment();
personal_data_.ClearProfiles();
credit_card_save_manager_->SetCreditCardUploadEnabled(true);
// Set up two new address profiles with conflicting postal codes.
AutofillProfile profile1;
profile1.set_guid("00000000-0000-0000-0000-000000000200");
profile1.SetInfo(NAME_FULL, ASCIIToUTF16("Flo Master"), "en-US");
profile1.SetInfo(ADDRESS_HOME_LINE1, ASCIIToUTF16("123 Testing St."),
"en-US");
profile1.SetInfo(ADDRESS_HOME_CITY, ASCIIToUTF16("Mountain View"), "en-US");
profile1.SetInfo(ADDRESS_HOME_STATE, ASCIIToUTF16("California"), "en-US");
profile1.SetInfo(ADDRESS_HOME_ZIP, ASCIIToUTF16("94043"), "en-US");
profile1.SetInfo(ADDRESS_HOME_COUNTRY, ASCIIToUTF16("US"), "en-US");
personal_data_.AddProfile(profile1);
AutofillProfile profile2;
profile2.set_guid("00000000-0000-0000-0000-000000000201");
profile2.SetInfo(NAME_FULL, ASCIIToUTF16("Flo Master"), "en-US");
profile2.SetInfo(ADDRESS_HOME_LINE1, ASCIIToUTF16("234 Other Place"),
"en-US");
profile2.SetInfo(ADDRESS_HOME_CITY, ASCIIToUTF16("Fake City"), "en-US");
profile2.SetInfo(ADDRESS_HOME_STATE, ASCIIToUTF16("Stateland"), "en-US");
profile2.SetInfo(ADDRESS_HOME_ZIP, ASCIIToUTF16("12345"), "en-US");
profile2.SetInfo(ADDRESS_HOME_COUNTRY, ASCIIToUTF16("US"), "en-US");
personal_data_.AddProfile(profile2);
// Set up our credit card form data.
FormData credit_card_form;
CreateTestCreditCardFormData(&credit_card_form, true, false);
FormsSeen(std::vector<FormData>(1, credit_card_form));
// Edit the data, and submit.
credit_card_form.fields[0].value = ASCIIToUTF16("Flo Master");
credit_card_form.fields[1].value = ASCIIToUTF16("4111111111111111");
credit_card_form.fields[2].value = ASCIIToUTF16("11");
credit_card_form.fields[3].value = ASCIIToUTF16(NextYear());
credit_card_form.fields[4].value = ASCIIToUTF16("123");
base::HistogramTester histogram_tester;
// Because the send detected values experiment is on, Payments should be asked
// whether upload save can be offered. (Unit tests assume they reply yes and
// save is successful.)
EXPECT_CALL(autofill_client_, ConfirmSaveCreditCardLocally(_, _)).Times(0);
FormSubmitted(credit_card_form);
EXPECT_TRUE(credit_card_save_manager_->CreditCardWasUploaded());
// Verify that the correct histogram entries were logged.
ExpectCardUploadDecision(histogram_tester, AutofillMetrics::UPLOAD_OFFERED);
ExpectCardUploadDecision(
histogram_tester, AutofillMetrics::UPLOAD_NOT_OFFERED_CONFLICTING_ZIPS);
// Verify that the correct UKM was logged.
ExpectMetric(UkmCardUploadDecisionType::kUploadDecisionName,
UkmCardUploadDecisionType::kEntryName,
AutofillMetrics::UPLOAD_OFFERED |
AutofillMetrics::UPLOAD_NOT_OFFERED_CONFLICTING_ZIPS,
1 /* expected_num_matching_entries */);
}
TEST_F(CreditCardSaveManagerTest,
UploadCreditCard_PaymentsDecidesOfferToSaveIfNothingFoundAndExpOn) {
EnableAutofillUpstreamSendDetectedValuesExperiment();
personal_data_.ClearProfiles();
credit_card_save_manager_->SetCreditCardUploadEnabled(true);
// Set up a new address profile without a name or postal code.
AutofillProfile profile;
profile.set_guid("00000000-0000-0000-0000-000000000200");
profile.SetInfo(ADDRESS_HOME_LINE1, ASCIIToUTF16("123 Testing St."), "en-US");
profile.SetInfo(ADDRESS_HOME_CITY, ASCIIToUTF16("Mountain View"), "en-US");
profile.SetInfo(ADDRESS_HOME_STATE, ASCIIToUTF16("California"), "en-US");
profile.SetInfo(ADDRESS_HOME_COUNTRY, ASCIIToUTF16("US"), "en-US");
personal_data_.AddProfile(profile);
// Set up our credit card form data.
FormData credit_card_form;
CreateTestCreditCardFormData(&credit_card_form, true, false);
FormsSeen(std::vector<FormData>(1, credit_card_form));
// Edit the data, and submit.
credit_card_form.fields[0].value = ASCIIToUTF16(""); // No name!
credit_card_form.fields[1].value = ASCIIToUTF16("4111111111111111");
credit_card_form.fields[2].value = ASCIIToUTF16("11");
credit_card_form.fields[3].value = ASCIIToUTF16(NextYear());
credit_card_form.fields[4].value = ASCIIToUTF16(""); // No CVC!
base::HistogramTester histogram_tester;
// Because the send detected values experiment is on, Payments should be asked
// whether upload save can be offered. (Unit tests assume they reply yes and
// save is successful.)
EXPECT_CALL(autofill_client_, ConfirmSaveCreditCardLocally(_, _)).Times(0);
FormSubmitted(credit_card_form);
EXPECT_TRUE(credit_card_save_manager_->CreditCardWasUploaded());
// Verify that the correct histogram entries were logged.
ExpectCardUploadDecision(histogram_tester, AutofillMetrics::UPLOAD_OFFERED);
ExpectCardUploadDecision(histogram_tester,
AutofillMetrics::CVC_VALUE_NOT_FOUND);
ExpectCardUploadDecision(histogram_tester,
AutofillMetrics::UPLOAD_NOT_OFFERED_NO_NAME);
ExpectCardUploadDecision(histogram_tester,
AutofillMetrics::UPLOAD_NOT_OFFERED_NO_ZIP_CODE);
// Verify that the correct UKM was logged.
ExpectMetric(UkmCardUploadDecisionType::kUploadDecisionName,
UkmCardUploadDecisionType::kEntryName,
AutofillMetrics::UPLOAD_OFFERED |
AutofillMetrics::CVC_VALUE_NOT_FOUND |
AutofillMetrics::UPLOAD_NOT_OFFERED_NO_NAME |
AutofillMetrics::UPLOAD_NOT_OFFERED_NO_ZIP_CODE,
1 /* expected_num_matching_entries */);
}
TEST_F(
CreditCardSaveManagerTest,
UploadCreditCard_AddUpdatePromptExplanationFlagStateToRequestIfExperimentOn) {
EnableAutofillUpstreamUpdatePromptExplanationExperiment();
personal_data_.ClearProfiles();
credit_card_save_manager_->SetCreditCardUploadEnabled(true);
// Create, fill and submit an address form in order to establish a recent
// profile which can be selected for the upload request.
FormData address_form;
test::CreateTestAddressFormData(&address_form);
FormsSeen(std::vector<FormData>(1, address_form));
ManuallyFillAddressForm("Flo", "Master", "77401", "US", &address_form);
FormSubmitted(address_form);
// Set up our credit card form data.
FormData credit_card_form;
CreateTestCreditCardFormData(&credit_card_form, true, false);
FormsSeen(std::vector<FormData>(1, credit_card_form));
// Edit the data, and submit.
credit_card_form.fields[0].value = ASCIIToUTF16("Flo Master");
credit_card_form.fields[1].value = ASCIIToUTF16("4444333322221111");
credit_card_form.fields[2].value = ASCIIToUTF16("11");
credit_card_form.fields[3].value = ASCIIToUTF16(NextYear());
credit_card_form.fields[4].value = ASCIIToUTF16("123");
// Confirm that upload happened and that the enabled UpdatePromptExplanation
// experiment flag state was sent in the request.
EXPECT_CALL(autofill_client_, ConfirmSaveCreditCardLocally(_, _)).Times(0);
FormSubmitted(credit_card_form);
EXPECT_TRUE(credit_card_save_manager_->CreditCardWasUploaded());
EXPECT_THAT(
payments_client_->GetActiveExperimentsSetInRequest(),
UnorderedElementsAre(kAutofillUpstreamSendDetectedValues.name,
kAutofillUpstreamUpdatePromptExplanation.name));
}
TEST_F(CreditCardSaveManagerTest,
UploadCreditCard_DoNotAddAnyFlagStatesToRequestIfExperimentsOff) {
DisableAutofillUpstreamSendDetectedValuesExperiment();
personal_data_.ClearProfiles();
credit_card_save_manager_->SetCreditCardUploadEnabled(true);
// Create, fill and submit an address form in order to establish a recent
// profile which can be selected for the upload request.
FormData address_form;
test::CreateTestAddressFormData(&address_form);
FormsSeen(std::vector<FormData>(1, address_form));
ManuallyFillAddressForm("Flo", "Master", "77401", "US", &address_form);
FormSubmitted(address_form);
// Set up our credit card form data.
FormData credit_card_form;
CreateTestCreditCardFormData(&credit_card_form, true, false);
FormsSeen(std::vector<FormData>(1, credit_card_form));
// Edit the data, and submit.
credit_card_form.fields[0].value = ASCIIToUTF16("Flo Master");
credit_card_form.fields[1].value = ASCIIToUTF16("4111111111111111");
credit_card_form.fields[2].value = ASCIIToUTF16("11");
credit_card_form.fields[3].value = ASCIIToUTF16(NextYear());
credit_card_form.fields[4].value = ASCIIToUTF16("123");
// Confirm upload happened and that no experiment flag state was sent in the
// request.
EXPECT_CALL(autofill_client_, ConfirmSaveCreditCardLocally(_, _)).Times(0);
FormSubmitted(credit_card_form);
EXPECT_TRUE(credit_card_save_manager_->CreditCardWasUploaded());
EXPECT_TRUE(payments_client_->GetActiveExperimentsSetInRequest().empty());
}
TEST_F(CreditCardSaveManagerTest, UploadCreditCard_AddPanFirstSixToRequest) {
EnableAutofillUpstreamSendPanFirstSixExperiment();
personal_data_.ClearProfiles();
credit_card_save_manager_->SetCreditCardUploadEnabled(true);
// Create, fill and submit an address form in order to establish a recent
// profile which can be selected for the upload request.
FormData address_form;
test::CreateTestAddressFormData(&address_form);
FormsSeen(std::vector<FormData>(1, address_form));
ManuallyFillAddressForm("Flo", "Master", "77401", "US", &address_form);
FormSubmitted(address_form);
// Set up our credit card form data.
FormData credit_card_form;
CreateTestCreditCardFormData(&credit_card_form, true, false);
FormsSeen(std::vector<FormData>(1, credit_card_form));
// Edit the data, and submit.
credit_card_form.fields[0].value = ASCIIToUTF16("Flo Master");
credit_card_form.fields[1].value = ASCIIToUTF16("4444333322221111");
credit_card_form.fields[2].value = ASCIIToUTF16("11");
credit_card_form.fields[3].value = ASCIIToUTF16(NextYear());
credit_card_form.fields[4].value = ASCIIToUTF16("123");
// Confirm that the first six digits of the credit card number were included
// in the request.
EXPECT_CALL(autofill_client_, ConfirmSaveCreditCardLocally(_, _)).Times(0);
FormSubmitted(credit_card_form);
EXPECT_TRUE(credit_card_save_manager_->CreditCardWasUploaded());
EXPECT_EQ(payments_client_->GetPanFirstSixSetInRequest(), "444433");
// Confirm that the "send pan first six" experiment flag was sent in the
// request.
EXPECT_THAT(payments_client_->GetActiveExperimentsSetInRequest(),
UnorderedElementsAre(kAutofillUpstreamSendDetectedValues.name,
kAutofillUpstreamSendPanFirstSix.name));
}
TEST_F(CreditCardSaveManagerTest, UploadCreditCard_UploadOfLocalCard) {
personal_data_.ClearCreditCards();
personal_data_.ClearProfiles();
credit_card_save_manager_->SetCreditCardUploadEnabled(true);
// Add a local credit card whose |TypeAndLastFourDigits| matches what we will
// enter below.
CreditCard local_card;
test::SetCreditCardInfo(&local_card, "Flo Master", "4111111111111111", "11",
NextYear().c_str(), "1");
local_card.set_record_type(CreditCard::LOCAL_CARD);
personal_data_.AddCreditCard(local_card);
// Create, fill and submit an address form in order to establish a recent
// profile which can be selected for the upload request.
FormData address_form;
test::CreateTestAddressFormData(&address_form);
FormsSeen(std::vector<FormData>(1, address_form));
ExpectUniqueFillableFormParsedUkm();
ManuallyFillAddressForm("Flo", "Master", "77401", "US", &address_form);
FormSubmitted(address_form);
// Set up our credit card form data.
FormData credit_card_form;
CreateTestCreditCardFormData(&credit_card_form, true, false);
FormsSeen(std::vector<FormData>(1, credit_card_form));
ExpectFillableFormParsedUkm(2 /* num_fillable_forms_parsed */);
// Edit the data, and submit.
credit_card_form.fields[0].value = ASCIIToUTF16("Flo Master");
credit_card_form.fields[1].value = ASCIIToUTF16("4111111111111111");
credit_card_form.fields[2].value = ASCIIToUTF16("11");
credit_card_form.fields[3].value = ASCIIToUTF16(NextYear());
credit_card_form.fields[4].value = ASCIIToUTF16("123");
base::HistogramTester histogram_tester;
EXPECT_CALL(autofill_client_, ConfirmSaveCreditCardLocally(_, _)).Times(0);
FormSubmitted(credit_card_form);
EXPECT_TRUE(credit_card_save_manager_->CreditCardWasUploaded());
// Verify that metrics noted it was an existing local card for which credit
// card upload was offered and accepted.
histogram_tester.ExpectUniqueSample(
"Autofill.UploadOfferedCardOrigin",
AutofillMetrics::OFFERING_UPLOAD_OF_LOCAL_CARD, 1);
histogram_tester.ExpectUniqueSample(
"Autofill.UploadAcceptedCardOrigin",
AutofillMetrics::USER_ACCEPTED_UPLOAD_OF_LOCAL_CARD, 1);
}
TEST_F(CreditCardSaveManagerTest, UploadCreditCard_UploadOfNewCard) {
// No cards already on the device.
personal_data_.ClearCreditCards();
personal_data_.ClearProfiles();
credit_card_save_manager_->SetCreditCardUploadEnabled(true);
// Create, fill and submit an address form in order to establish a recent
// profile which can be selected for the upload request.
FormData address_form;
test::CreateTestAddressFormData(&address_form);
FormsSeen(std::vector<FormData>(1, address_form));
ExpectUniqueFillableFormParsedUkm();
ManuallyFillAddressForm("Flo", "Master", "77401", "US", &address_form);
FormSubmitted(address_form);
// Set up our credit card form data.
FormData credit_card_form;
CreateTestCreditCardFormData(&credit_card_form, true, false);
FormsSeen(std::vector<FormData>(1, credit_card_form));
ExpectFillableFormParsedUkm(2 /* num_fillable_forms_parsed */);
// Edit the data, and submit.
credit_card_form.fields[0].value = ASCIIToUTF16("Flo Master");
credit_card_form.fields[1].value = ASCIIToUTF16("4111111111111111");
credit_card_form.fields[2].value = ASCIIToUTF16("11");
credit_card_form.fields[3].value = ASCIIToUTF16(NextYear());
credit_card_form.fields[4].value = ASCIIToUTF16("123");
base::HistogramTester histogram_tester;
EXPECT_CALL(autofill_client_, ConfirmSaveCreditCardLocally(_, _)).Times(0);
FormSubmitted(credit_card_form);
EXPECT_TRUE(credit_card_save_manager_->CreditCardWasUploaded());
// Verify that metrics noted it was a brand new card for which credit card
// upload was offered and accepted.
histogram_tester.ExpectUniqueSample(
"Autofill.UploadOfferedCardOrigin",
AutofillMetrics::OFFERING_UPLOAD_OF_NEW_CARD, 1);
histogram_tester.ExpectUniqueSample(
"Autofill.UploadAcceptedCardOrigin",
AutofillMetrics::USER_ACCEPTED_UPLOAD_OF_NEW_CARD, 1);
}
} // namespace autofill
| 44.123896 | 95 | 0.764899 | [
"vector"
] |
e90829400b3708383734cc873ab5cea7b7a70c8b | 9,948 | cpp | C++ | src/oddlib/audio/AliveAudio.cpp | mouzedrift/alive | 7c297a39c60e930933c0a93ea373226907f8b1c7 | [
"MIT"
] | 131 | 2015-03-21T14:10:21.000Z | 2021-01-19T03:54:04.000Z | src/oddlib/audio/AliveAudio.cpp | mouzedrift/alive | 7c297a39c60e930933c0a93ea373226907f8b1c7 | [
"MIT"
] | 51 | 2015-04-06T17:24:45.000Z | 2018-02-03T14:36:37.000Z | src/oddlib/audio/AliveAudio.cpp | mouzedrift/alive | 7c297a39c60e930933c0a93ea373226907f8b1c7 | [
"MIT"
] | 17 | 2015-10-07T10:20:47.000Z | 2021-08-02T04:14:11.000Z | #include "oddlib/audio/AliveAudio.h"
#include "imgui/imgui.h"
void AliveAudio::CleanVoices()
{
std::vector<AliveAudioVoice *> deadVoices;
std::unique_lock<std::recursive_mutex> voiceLock(mVoiceMutex);
for (auto& voice : m_Voices)
{
if (voice->b_Dead)
{
deadVoices.push_back(voice);
}
}
for (auto& obj : deadVoices)
{
delete obj;
m_Voices.erase(std::remove(m_Voices.begin(), m_Voices.end(), obj), m_Voices.end());
}
}
void AliveAudio::AliveRenderAudio(f32 * AudioStream, int StreamLength)
{
// Reset buffers
for (int i = 0; i < StreamLength; ++i)
{
m_DryChannelBuffer[i] = 0;
m_ReverbChannelBuffer[i] = 0;
}
{
std::unique_lock<std::recursive_mutex> voiceLock(mVoiceMutex);
const size_t voiceCount = m_Voices.size();
AliveAudioVoice ** rawPointer = m_Voices.data(); // Real nice speed boost here.
for (int i = 0; i < StreamLength; i += 2)
{
for (size_t v = 0; v < voiceCount; v++)
{
AliveAudioVoice * voice = rawPointer[v]; // Raw pointer skips all that vector bottleneck crap
voice->f_TrackDelay--;
if (voice->m_UsesNoteOffDelay)
{
voice->f_NoteOffDelay--;
}
if (voice->m_UsesNoteOffDelay && voice->f_NoteOffDelay <= 0 && voice->b_NoteOn == true)
{
voice->b_NoteOn = false;
//printf("off");
}
if (voice->b_Dead || voice->f_TrackDelay > 0)
{
continue;
}
f32 centerPan = voice->m_Tone->f_Pan;
f32 leftPan = 1.0f;
f32 rightPan = 1.0f;
if (centerPan > 0)
{
leftPan = 1.0f - std::abs(centerPan);
}
if (centerPan < 0)
{
rightPan = 1.0f - std::abs(centerPan);
}
// TODO FIX ME
f32 s = voice->GetSample(Interpolation, false);
f32 leftSample = (s * leftPan);
f32 rightSample = (s * rightPan);
if (voice->m_Tone->Reverbate || ForceReverb)
{
m_ReverbChannelBuffer[i] += leftSample;
m_ReverbChannelBuffer[i + 1] += rightSample;
}
else
{
m_DryChannelBuffer[i] += leftSample;
m_DryChannelBuffer[i + 1] += rightSample;
}
}
mCurrentSampleIndex++;
}
}
m_Reverb.setEffectMix(ReverbMix);
// TODO: Find a better way of feeding the data in
for (int i = 0; i < StreamLength; i += 2)
{
const f32 left = static_cast<f32>(m_Reverb.tick(m_ReverbChannelBuffer[i], m_ReverbChannelBuffer[i + 1], 0));
const f32 right = static_cast<f32>(m_Reverb.lastOut(1));
m_ReverbChannelBuffer[i] = left;
m_ReverbChannelBuffer[i + 1] = right;
}
for (int i = 0; i < StreamLength; i += 2)
{
const f32 left = m_DryChannelBuffer[i] + m_ReverbChannelBuffer[i];
const f32 right = m_DryChannelBuffer[i + 1] + m_ReverbChannelBuffer[i + 1];
SDL_MixAudioFormat((u8 *)(AudioStream + i), (const u8*)&left, AUDIO_F32, sizeof(f32), SDL_MIX_MAXVOLUME);
SDL_MixAudioFormat((u8 *)(AudioStream + i + 1), (const u8*)&right, AUDIO_F32, sizeof(f32), SDL_MIX_MAXVOLUME);
}
CleanVoices();
}
void AliveAudio::Play(f32* stream, u32 len)
{
if (m_DryChannelBuffer.size() != len)
{
// Maybe it's ok to have some crackles when the buffer size changes.
// (This allocates memory, which you should never do in audio thread.)
m_DryChannelBuffer.resize(len);
m_ReverbChannelBuffer.resize(len);
}
AliveRenderAudio(stream, len);
}
void AliveAudio::VabBrowserUi()
{
if (m_Soundbank)
{
ImGui::Begin("VAB content");
int i = 0;
for (std::unique_ptr<AliveAudioProgram>& prog : m_Soundbank->m_Programs)
{
if (!prog->m_Tones.empty())
{
ImGui::TextUnformatted(("Program number: " + std::to_string(i)).c_str());
int j = 0;
for (std::unique_ptr<AliveAudioTone>& tone : prog->m_Tones)
{
if (ImGui::Button((" Tone number: " +
std::to_string(i) + "_"
+ std::to_string(j++)
+ " min key: " + std::to_string(tone->Min)
+ " max key: " + std::to_string(tone->Max)
).c_str()))
{
ClearAllTrackVoices(true);
NoteOn(i, tone->Min, 127, 0.0, 0.0);
}
}
}
i++;
}
ImGui::End();
}
}
/*
void AliveAudio::PlayOneShot(int program, int note, f32 volume, f32 pitch)
{
std::lock_guard<std::recursive_mutex> lock(voiceListMutex);
for (auto& tone : m_CurrentSoundbank->m_Programs[program]->m_Tones)
{
if (note >= tone->Min && note <= tone->Max)
{
AliveAudioVoice * voice = new AliveAudioVoice();
voice->i_Note = note;
voice->f_Velocity = volume;
voice->m_Tone = tone.get();
voice->f_Pitch = pitch;
voice->m_DebugDisableResampling = DebugDisableVoiceResampling;
m_Voices.push_back(voice);
}
}
}
*/
/*
void AliveAudio::PlayOneShot(std::string soundID)
{
jsonxx::Array soundList = m_Config.get<jsonxx::Array>("sounds");
for (size_t i = 0; i < soundList.size(); i++)
{
jsonxx::Object sndObj = soundList.get<jsonxx::Object>(static_cast<unsigned int>(i));
if (sndObj.get<jsonxx::String>("id") == soundID)
{
f32 randA = 0;
f32 randB = 0;
if (sndObj.has<jsonxx::Array>("pitchrand"))
{
randA = (f32)sndObj.get<jsonxx::Array>("pitchrand").get<jsonxx::Number>(0);
randB = (f32)sndObj.get<jsonxx::Array>("pitchrand").get<jsonxx::Number>(1);
}
PlayOneShot((int)sndObj.get<jsonxx::Number>("prog"), (int)sndObj.get<jsonxx::Number>("note"), 1.0f, RandFloat(randA, randB));
}
}
}
*/
void AliveAudio::NoteOn(int program, int note, char velocity, f64 trackDelay, f64 pitch, bool ignoreLoops)
{
for (auto& tone : m_Soundbank->m_Programs[program]->m_Tones)
{
if (note >= tone->Min && note <= tone->Max)
{
AliveAudioVoice * voice = new AliveAudioVoice();
voice->i_Note = note;
voice->m_Tone = tone.get();
voice->f_Pitch = pitch;
voice->i_Program = program;
voice->f_Velocity = velocity / 127.0f;
voice->f_TrackDelay = trackDelay;
voice->m_DebugDisableResampling = DebugDisableVoiceResampling;
voice->mbIgnoreLoops = ignoreLoops;
std::unique_lock<std::recursive_mutex> voiceLock(mVoiceMutex);
m_Voices.push_back(voice);
}
}
}
void AliveAudio::NoteOff(int program, int note)
{
std::unique_lock<std::recursive_mutex> voiceLock(mVoiceMutex);
for (auto& voice : m_Voices)
{
if (voice->i_Note == note && voice->i_Program == program)
{
voice->b_NoteOn = false;
}
}
}
void AliveAudio::NoteOffDelay(int program, int note, f32 trackDelay)
{
std::unique_lock<std::recursive_mutex> voiceLock(mVoiceMutex);
for (auto& voice : m_Voices)
{
if (voice->i_Note == note && voice->i_Program == program && voice->f_TrackDelay < trackDelay && voice->f_NoteOffDelay <= 0)
{
voice->m_UsesNoteOffDelay = true;
voice->f_NoteOffDelay = trackDelay;
}
}
}
void AliveAudio::ClearAllVoices(bool forceKill)
{
std::vector<AliveAudioVoice *> deadVoices;
std::unique_lock<std::recursive_mutex> voiceLock(mVoiceMutex);
for (auto& voice : m_Voices)
{
if (forceKill)
{
deadVoices.push_back(voice);
}
else
{
voice->b_NoteOn = false; // Send a note off to all of the notes though.
if (voice->f_SampleOffset == 0) // Let the voices that are CURRENTLY playing play.
{
deadVoices.push_back(voice);
}
}
}
for (auto& obj : deadVoices)
{
delete obj;
m_Voices.erase(std::remove(m_Voices.begin(), m_Voices.end(), obj), m_Voices.end());
}
}
void AliveAudio::ClearAllTrackVoices(bool forceKill)
{
std::vector<AliveAudioVoice *> deadVoices;
std::unique_lock<std::recursive_mutex> voiceLock(mVoiceMutex);
for (auto& voice : m_Voices)
{
if (forceKill)
{
// Kill the voices no matter what. Cuts of any sounds = Ugly sound
deadVoices.push_back(voice);
}
else
{
voice->b_NoteOn = false; // Send a note off to all of the notes though.
if (voice->f_SampleOffset == 0) // Let the voices that are CURRENTLY playing play.
{
// TODO: This will make us delete them all after this loop as with force kill
// probably we shouldn't be adding to the "delete" list here?
deadVoices.push_back(voice);
}
}
}
for (auto& obj : deadVoices)
{
delete obj;
m_Voices.erase(std::remove(m_Voices.begin(), m_Voices.end(), obj), m_Voices.end());
}
}
void AliveAudio::SetSoundbank(std::unique_ptr<AliveAudioSoundbank> soundbank)
{
ClearAllVoices(true);
m_Soundbank = std::move(soundbank);
}
| 30.237082 | 137 | 0.536992 | [
"object",
"vector"
] |
e9093d87f96d2bd5d2ca95c722de9bd375bdf502 | 4,869 | cc | C++ | Geometry/MuonNumbering/src/DD4hep_RPCNumberingScheme.cc | gputtley/cmssw | c1ef8454804e4ebea8b65f59c4a952a6c94fde3b | [
"Apache-2.0"
] | 2 | 2020-01-27T15:21:37.000Z | 2020-05-11T11:13:18.000Z | Geometry/MuonNumbering/src/DD4hep_RPCNumberingScheme.cc | gputtley/cmssw | c1ef8454804e4ebea8b65f59c4a952a6c94fde3b | [
"Apache-2.0"
] | 26 | 2018-10-30T12:47:58.000Z | 2022-03-29T08:39:00.000Z | Geometry/MuonNumbering/src/DD4hep_RPCNumberingScheme.cc | p2l1pfp/cmssw | 9bda22bf33ecf18dd19a3af2b3a8cbdb1de556a9 | [
"Apache-2.0"
] | 3 | 2019-03-09T13:06:43.000Z | 2020-07-03T00:47:30.000Z |
#include "Geometry/MuonNumbering/interface/DD4hep_RPCNumberingScheme.h"
#include "Geometry/MuonNumbering/interface/DD4hep_MuonNumbering.h"
#include "DataFormats/MuonDetId/interface/RPCDetId.h"
#include "Geometry/MuonNumbering/interface/MuonBaseNumber.h"
#include <FWCore/Utilities/interface/Exception.h>
#include <cassert>
using namespace cms;
RPCNumberingScheme::RPCNumberingScheme(const MuonConstants& muonConstants) { initMe(muonConstants); }
void RPCNumberingScheme::initMe(const MuonConstants& muonConstants) {
int levelPart = get("level", muonConstants);
assert(levelPart != 0);
theRegionLevel = get("mr_region", muonConstants) / levelPart;
theBWheelLevel = get("mr_bwheel", muonConstants) / levelPart;
theBStationLevel = get("mr_bstation", muonConstants) / levelPart;
theBPlaneLevel = get("mr_bplane", muonConstants) / levelPart;
theBChamberLevel = get("mr_bchamber", muonConstants) / levelPart;
theEPlaneLevel = get("mr_eplane", muonConstants) / levelPart;
theESectorLevel = get("mr_esector", muonConstants) / levelPart;
theERollLevel = get("mr_eroll", muonConstants) / levelPart;
}
void RPCNumberingScheme::baseNumberToUnitNumber(const MuonBaseNumber& num) {
const int barrel = num.getSuperNo(theRegionLevel);
bool barrel_muon = (barrel == 1);
int maxLevel;
if (barrel_muon) {
maxLevel = theBChamberLevel;
} else {
maxLevel = theERollLevel;
}
if (num.getLevels() != maxLevel) {
throw cms::Exception("DD4hep_RPCNumberingScheme", "num.getLevels() != maxLevel");
}
int plane_id = 0;
int sector_id = 0;
int copy_id = 0;
int roll_id = 0;
int eta_id = 0;
int rr12_id = 0;
bool forward = false;
int sector_copy = 0;
for (int level = 1; level <= maxLevel; level++) {
if (level == theRegionLevel) {
if (barrel_muon) {
roll_id = 0;
} else {
copy_id = 1;
}
}
if (barrel_muon) {
if (level == theBWheelLevel) {
const int copyno = num.getBaseNo(level);
eta_id = 4 + copyno;
} else if (level == theBStationLevel) {
const int copyno = num.getBaseNo(level);
sector_id = copyno + 1;
if (sector_id == 13) {
sector_id = 4;
sector_copy = 1;
} else if (sector_id == 14) {
sector_id = 10;
sector_copy = 1;
}
sector_id *= 3;
} else if (level == theBPlaneLevel) {
const int plane_tag = num.getSuperNo(level);
if (plane_tag == 1) {
plane_id = 1;
} else if (plane_tag == 2) {
plane_id = 5;
} else if (plane_tag == 3) {
plane_id = 2;
} else if (plane_tag == 4) {
plane_id = 6;
} else if (plane_tag == 5) {
plane_id = 3;
} else {
plane_id = 4;
}
} else if (level == theBChamberLevel) {
const int copyno = num.getBaseNo(level);
if ((plane_id == 4) && (sector_id == 4 * 3)) {
copy_id = sector_copy * 2 + copyno + 1;
} else if ((plane_id == 4) && (sector_id == 10 * 3)) {
copy_id = sector_copy + 1;
} else {
copy_id = copyno + 1;
}
const int rollno = num.getSuperNo(level);
roll_id = rollno;
}
} else {
if (level == theRegionLevel) {
const int copyno = num.getBaseNo(level);
forward = (copyno == 0);
} else if (level == theEPlaneLevel) {
const int plane_tag = num.getSuperNo(level);
const int rr12_tag = num.getBaseNo(level);
plane_id = plane_tag;
rr12_id = rr12_tag;
} else if (level == theESectorLevel) {
const int copyno = num.getBaseNo(level);
sector_id = copyno + 1;
if (rr12_id == 1) {
sector_id = sector_id * 2 - 1;
} else if (rr12_id == 2) {
sector_id = sector_id * 2;
}
} else if (level == theERollLevel) {
const int copyno = num.getBaseNo(level);
const int eta_tag = num.getSuperNo(level);
if ((eta_tag == 1) || (eta_tag == 4) || (eta_tag == 7) || (eta_tag == 8)) {
eta_id = 1;
} else if ((eta_tag == 2) || (eta_tag == 5)) {
eta_id = 2;
} else if ((eta_tag == 3) || (eta_tag == 6)) {
eta_id = 3;
}
if (forward)
eta_id = 12 - eta_id;
if ((eta_tag == 4) || (eta_tag == 7) || (eta_tag == 8)) {
sector_id *= 2;
}
roll_id = copyno + 1;
}
}
}
int trIndex = (eta_id * 10000 + plane_id * 1000 + sector_id * 10 + copy_id) * 10 + roll_id;
RPCDetId id;
id.buildfromTrIndex(trIndex);
setDetId(id.rawId());
}
const int RPCNumberingScheme::get(const char* key, const MuonConstants& muonConstants) const {
int result(0);
auto const& it = (muonConstants.find(key));
if (it != end(muonConstants))
result = it->second;
return result;
}
| 32.677852 | 101 | 0.586568 | [
"geometry"
] |
e90a27b1f27a99db5b1baefc23d872c12b7d3acb | 16,073 | cpp | C++ | fboss/agent/hw/bcm/BcmWarmBootCache.cpp | NunoEdgarGFlowHub/fboss | b665a1dac4917dd8984573ef5a471e4825d506f9 | [
"BSD-3-Clause"
] | 1 | 2015-03-12T11:40:43.000Z | 2015-03-12T11:40:43.000Z | fboss/agent/hw/bcm/BcmWarmBootCache.cpp | NunoEdgarGFlowHub/fboss | b665a1dac4917dd8984573ef5a471e4825d506f9 | [
"BSD-3-Clause"
] | null | null | null | fboss/agent/hw/bcm/BcmWarmBootCache.cpp | NunoEdgarGFlowHub/fboss | b665a1dac4917dd8984573ef5a471e4825d506f9 | [
"BSD-3-Clause"
] | null | null | null | /*
* Copyright (c) 2004-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
#include "BcmWarmBootCache.h"
#include <limits>
#include <string>
#include <utility>
#include "fboss/agent/hw/bcm/BcmEgress.h"
#include "fboss/agent/hw/bcm/BcmSwitch.h"
#include "fboss/agent/hw/bcm/BcmError.h"
#include "fboss/agent/hw/bcm/Utils.h"
#include "fboss/agent/state/Interface.h"
#include "fboss/agent/state/Port.h"
#include "fboss/agent/state/ArpTable.h"
#include "fboss/agent/state/NdpTable.h"
#include "fboss/agent/state/InterfaceMap.h"
#include "fboss/agent/state/Vlan.h"
#include "fboss/agent/state/VlanMap.h"
using std::make_pair;
using std::make_tuple;
using std::make_shared;
using std::numeric_limits;
using std::string;
using std::vector;
using std::shared_ptr;
using boost::container::flat_map;
using folly::ByteRange;
using folly::IPAddress;
using folly::MacAddress;
using boost::container::flat_map;
using boost::container::flat_set;
using namespace facebook::fboss;
namespace {
struct AddrTables {
AddrTables() : arpTable(make_shared<ArpTable>()),
ndpTable(make_shared<NdpTable>()) {}
shared_ptr<facebook::fboss::ArpTable> arpTable;
shared_ptr<facebook::fboss::NdpTable> ndpTable;
};
}
namespace facebook { namespace fboss {
BcmWarmBootCache::BcmWarmBootCache(const BcmSwitch* hw)
: hw_(hw),
dropEgressId_(BcmEgressBase::INVALID),
toCPUEgressId_(BcmEgressBase::INVALID) {
}
shared_ptr<InterfaceMap> BcmWarmBootCache::reconstructInterfaceMap() const {
auto intfMap = make_shared<InterfaceMap>();
for (const auto& vlanMacAndIntf: vlanAndMac2Intf_) {
const auto& bcmIntf = vlanMacAndIntf.second;
// Note : missing addresses and inteface name. This should be
// fixed with t4155406
intfMap->addInterface(make_shared<Interface>(InterfaceID(bcmIntf.l3a_vid),
RouterID(bcmIntf.l3a_vrf), VlanID(bcmIntf.l3a_vid), "",
vlanMacAndIntf.first.second));
}
return intfMap;
}
shared_ptr<VlanMap> BcmWarmBootCache::reconstructVlanMap() const {
auto vlans = make_shared<VlanMap>();
flat_map<VlanID, VlanFields> vlan2VlanFields;
// Get vlan and port mapping
for (auto vlanAndInfo: vlan2VlanInfo_) {
// Note : missing vlan name. This should be
// fixed with t4155406
auto vlan = make_shared<Vlan>(vlanAndInfo.first, "");
flat_set<int> untagged;
int idx;
OPENNSL_PBMP_ITER(vlanAndInfo.second.untagged, idx) {
vlan->addPort(PortID(idx), false);
untagged.insert(idx);
}
OPENNSL_PBMP_ITER(vlanAndInfo.second.allPorts, idx) {
if (untagged.find(idx) != untagged.end()) {
continue;
}
vlan->addPort(PortID(idx), true);
}
vlans->addVlan(vlan);
}
flat_map<VlanID, AddrTables> vlan2AddrTables;
// Populate ARP and NDP tables of VLANs using egress
// entries
for (auto vrfIpAndEgress : vrfIp2Egress_) {
const auto& bcmEgress = vrfIpAndEgress.second.second;
if (bcmEgress.vlan == 0) {
// Ignore to CPU egress entries which get mapped to vlan 0
continue;
}
const auto& ip = vrfIpAndEgress.first.second;
auto titr = vlan2AddrTables.find(VlanID(bcmEgress.vlan));
if (titr == vlan2AddrTables.end()) {
titr = vlan2AddrTables.insert(make_pair(VlanID(bcmEgress.vlan),
AddrTables())).first;
}
if (ip.isV4()) {
titr->second.arpTable->addEntry(ip.asV4(), macFromBcm(bcmEgress.mac_addr),
PortID(bcmEgress.port), InterfaceID(bcmEgress.vlan));
} else {
titr->second.ndpTable->addEntry(ip.asV6(), macFromBcm(bcmEgress.mac_addr),
PortID(bcmEgress.port), InterfaceID(bcmEgress.vlan));
}
}
for (auto vlanAndAddrTable: vlan2AddrTables) {
auto vlan = vlans->getVlanIf(vlanAndAddrTable.first);
if(!vlan) {
LOG(FATAL) << "Vlan: " << vlanAndAddrTable.first << " not found";
}
vlan->setArpTable(vlanAndAddrTable.second.arpTable);
vlan->setNdpTable(vlanAndAddrTable.second.ndpTable);
}
return vlans;
}
void BcmWarmBootCache::populate() {
opennsl_vlan_data_t* vlanList = nullptr;
int vlanCount = 0;
SCOPE_EXIT {
opennsl_vlan_list_destroy(hw_->getUnit(), vlanList, vlanCount);
};
auto rv = opennsl_vlan_list(hw_->getUnit(), &vlanList, &vlanCount);
bcmCheckError(rv, "Unable to get vlan information");
for (auto i = 0; i < vlanCount; ++i) {
opennsl_vlan_data_t& vlanData = vlanList[i];
int portCount;
OPENNSL_PBMP_COUNT(vlanData.port_bitmap, portCount);
VLOG (1) << "Got vlan : " << vlanData.vlan_tag
<<" with : " << portCount << " ports";
// TODO: Investigate why port_bitmap contains
// the untagged ports rather than ut_port_bitmap
vlan2VlanInfo_.insert(make_pair
(BcmSwitch::getVlanId(vlanData.vlan_tag),
VlanInfo(VlanID(vlanData.vlan_tag), vlanData.port_bitmap,
vlanData.port_bitmap)));
opennsl_l3_intf_t l3Intf;
opennsl_l3_intf_t_init(&l3Intf);
// Implicit here is the assumption that we have a interface
// per vlan (since we are looking up the inteface by vlan).
// If this changes we will have to store extra information
// somewhere (e.g. interface id or vlan, mac pairs for interfaces
// created) and then use that for lookup during warm boot.
l3Intf.l3a_vid = vlanData.vlan_tag;
bool intfFound = false;
rv = opennsl_l3_intf_find_vlan(hw_->getUnit(), &l3Intf);
if (rv != OPENNSL_E_NOT_FOUND) {
bcmCheckError(rv, "failed to find interface for ",
vlanData.vlan_tag);
intfFound = true;
vlanAndMac2Intf_[make_pair(BcmSwitch::getVlanId(l3Intf.l3a_vid),
macFromBcm(l3Intf.l3a_mac_addr))] = l3Intf;
VLOG(1) << "Found l3 interface for vlan : " << vlanData.vlan_tag;
}
if (intfFound) {
opennsl_l2_station_t l2Station;
opennsl_l2_station_t_init(&l2Station);
rv = opennsl_l2_station_get(hw_->getUnit(), l3Intf.l3a_vid, &l2Station);
if (!OPENNSL_FAILURE(rv)) {
VLOG (1) << " Found l2 station with id : " << l3Intf.l3a_vid;
vlan2Station_[VlanID(vlanData.vlan_tag)] = l2Station;
} else {
// FIXME Why are we unable to find l2 stations on a warm boot ?.
VLOG(1) << "Could not get l2 station for vlan : " << vlanData.vlan_tag;
}
}
}
opennsl_l3_info_t l3Info;
opennsl_l3_info_t_init(&l3Info);
opennsl_l3_info(hw_->getUnit(), &l3Info);
// Traverse V4 hosts
opennsl_l3_host_traverse(hw_->getUnit(), 0, 0, l3Info.l3info_max_host,
hostTraversalCallback, this);
// Traverse V6 hosts
opennsl_l3_host_traverse(hw_->getUnit(), OPENNSL_L3_IP6, 0,
// Diag shell uses this for getting # of v6 host entries
l3Info.l3info_max_host / 2,
hostTraversalCallback, this);
// Get egress entries
opennsl_l3_egress_traverse(hw_->getUnit(), egressTraversalCallback, this);
// Traverse V4 routes
opennsl_l3_route_traverse(hw_->getUnit(), 0, 0, l3Info.l3info_max_route,
routeTraversalCallback, this);
// Traverse V6 routes
opennsl_l3_route_traverse(hw_->getUnit(), OPENNSL_L3_IP6, 0,
// Diag shell uses this for getting # of v6 route entries
l3Info.l3info_max_route / 2,
routeTraversalCallback, this);
// Traverse ecmp egress entries
opennsl_l3_egress_ecmp_traverse(hw_->getUnit(), ecmpEgressTraversalCallback,
this);
// Clear internal egress id table which just gets used while populating
// warm boot cache
egressId2VrfIp_.clear();
}
bool BcmWarmBootCache::fillVlanPortInfo(Vlan* vlan) {
auto vlanItr = vlan2VlanInfo_.find(vlan->getID());
if (vlanItr != vlan2VlanInfo_.end()) {
Vlan::MemberPorts memberPorts;
opennsl_port_t idx;
OPENNSL_PBMP_ITER(vlanItr->second.untagged, idx) {
memberPorts.insert(make_pair(PortID(idx), false));
}
OPENNSL_PBMP_ITER(vlanItr->second.allPorts, idx) {
if (memberPorts.find(PortID(idx)) == memberPorts.end()) {
memberPorts.insert(make_pair(PortID(idx), true));
}
}
vlan->setPorts(memberPorts);
return true;
}
return false;
}
int BcmWarmBootCache::hostTraversalCallback(int unit, int index,
opennsl_l3_host_t* host, void* userData) {
BcmWarmBootCache* cache = static_cast<BcmWarmBootCache*>(userData);
auto ip = host->l3a_flags & OPENNSL_L3_IP6 ?
IPAddress::fromBinary(ByteRange(host->l3a_ip6_addr,
sizeof(host->l3a_ip6_addr))) :
IPAddress::fromLongHBO(host->l3a_ip_addr);
cache->vrfIp2Host_[make_pair(host->l3a_vrf, ip)] = *host;
VLOG(1) << "Adding egress id: " << host->l3a_intf << " to " << ip
<<" mapping";
cache->egressId2VrfIp_[host->l3a_intf] = make_pair(host->l3a_vrf, ip);
return 0;
}
int BcmWarmBootCache::egressTraversalCallback(int unit, EgressId egressId,
opennsl_l3_egress_t *egress, void *userData) {
BcmWarmBootCache* cache = static_cast<BcmWarmBootCache*>(userData);
auto itr = cache->egressId2VrfIp_.find(egressId);
if (itr != cache->egressId2VrfIp_.end()) {
VLOG(1) << "Adding bcm egress entry for : " << itr->second.second
<< " in VRF : " << itr->second.first;
cache->vrfIp2Egress_[itr->second] = make_pair(egressId, *egress);
} else {
// found egress ID that is not used by any host entry, we shall
// only have two of them. One is for drop and the other one is for TO CPU.
if ((egress->flags & OPENNSL_L3_DST_DISCARD)) {
if (cache->dropEgressId_ != BcmEgressBase::INVALID) {
LOG(FATAL) << "duplicated drop egress found in HW. " << egressId
<< " and " << cache->dropEgressId_;
}
VLOG(1) << "Found drop egress id " << egressId;
cache->dropEgressId_ = egressId;
} else if ((egress->flags & (OPENNSL_L3_L2TOCPU|OPENNSL_L3_COPY_TO_CPU))) {
if (cache->toCPUEgressId_ != BcmEgressBase::INVALID) {
LOG(FATAL) << "duplicated generic TO_CPU egress found in HW. "
<< egressId << " and " << cache->toCPUEgressId_;
}
VLOG(1) << "Found generic TO CPU egress id " << egressId;
cache->toCPUEgressId_ = egressId;
} else {
LOG (FATAL) << " vrf and ip not found for egress : " << egressId;
}
}
return 0;
}
int BcmWarmBootCache::routeTraversalCallback(int unit, int index,
opennsl_l3_route_t* route, void* userData) {
BcmWarmBootCache* cache = static_cast<BcmWarmBootCache*>(userData);
auto ip = route->l3a_flags & OPENNSL_L3_IP6 ?
IPAddress::fromBinary(ByteRange(route->l3a_ip6_net,
sizeof(route->l3a_ip6_net))) :
IPAddress::fromLongHBO(route->l3a_subnet);
auto mask = route->l3a_flags & OPENNSL_L3_IP6 ?
IPAddress::fromBinary(ByteRange(route->l3a_ip6_mask,
sizeof(route->l3a_ip6_mask))) :
IPAddress::fromLongHBO(route->l3a_ip_mask);
VLOG (1) << "In vrf : " << route->l3a_vrf << " adding route for : "
<< ip << " mask: " << mask;
cache->vrfPrefix2Route_[make_tuple(route->l3a_vrf, ip, mask)] = *route;
return 0;
}
int BcmWarmBootCache::ecmpEgressTraversalCallback(int unit,
opennsl_l3_egress_ecmp_t *ecmp, int intfCount, opennsl_if_t *intfArray,
void *userData) {
if (intfCount == 0) {
// ecmp egress table on BCM has holes, ignore these entries
return 0;
}
BcmWarmBootCache* cache = static_cast<BcmWarmBootCache*>(userData);
EgressIds egressIds = cache->toEgressIds(intfArray, intfCount);;
CHECK(cache->egressIds2Ecmp_.find(egressIds) ==
cache->egressIds2Ecmp_.end());
cache->egressIds2Ecmp_[egressIds] = *ecmp;
VLOG(1) << "Added ecmp egress id : " << ecmp->ecmp_intf <<
" pointing to : " << toEgressIdsStr(egressIds) << " egress ids";
return 0;
}
std::string BcmWarmBootCache::toEgressIdsStr(const EgressIds& egressIds) {
string egressStr;
int i = 0;
for (auto egressId : egressIds) {
egressStr += folly::to<string>(egressId);
egressStr += ++i < egressIds.size() ? ", " : "";
}
return egressStr;
}
void BcmWarmBootCache::clear() {
// Get rid of all unclaimed entries. The order is important here
// since we want to delete entries only after there are no more
// references to them.
VLOG(1) << "Warm boot : removing unreferenced entries";
// Nothing references routes, but routes reference ecmp egress
// and egress entries which are deleted later
for (auto vrfPfxAndRoute : vrfPrefix2Route_) {
VLOG(1) << "Deleting unreferenced route in vrf:" <<
std::get<0>(vrfPfxAndRoute.first) << " for prefix : " <<
std::get<1>(vrfPfxAndRoute.first) << "/" <<
std::get<2>(vrfPfxAndRoute.first);
auto rv = opennsl_l3_route_delete(hw_->getUnit(), &(vrfPfxAndRoute.second));
bcmLogFatal(rv, hw_, "failed to delete unreferenced route in vrf:",
std::get<0>(vrfPfxAndRoute.first) , " for prefix : " ,
std::get<1>(vrfPfxAndRoute.first) , "/" ,
std::get<2>(vrfPfxAndRoute.first));
}
vrfPrefix2Route_.clear();
// Only routes refer ecmp egress objects. Ecmp egress objects in turn
// refer to egress objects which we delete later
for (auto idsAndEcmp : egressIds2Ecmp_) {
auto& ecmp = idsAndEcmp.second;
VLOG(1) << "Deleting ecmp egress object " << ecmp.ecmp_intf
<< " pointing to : " << toEgressIdsStr(idsAndEcmp.first);
auto rv = opennsl_l3_egress_ecmp_destroy(hw_->getUnit(), &ecmp);
bcmLogFatal(rv, hw_, "failed to destroy ecmp egress object :",
ecmp.ecmp_intf, " referring to ",
toEgressIdsStr(idsAndEcmp.first));
}
egressIds2Ecmp_.clear();
// Delete bcm host entries. Nobody references bcm hosts, but
// hosts reference egress objects
for (auto vrfIpAndHost : vrfIp2Host_) {
VLOG(1)<< "Deleting host entry in vrf: " <<
vrfIpAndHost.first.first << " for : " << vrfIpAndHost.first.second;
auto rv = opennsl_l3_host_delete(hw_->getUnit(), &vrfIpAndHost.second);
bcmLogFatal(rv, hw_, "failed to delete host entry in vrf: ",
vrfIpAndHost.first.first, " for : ", vrfIpAndHost.first.second);
}
vrfIp2Host_.clear();
// Delete bcm egress entries. These are referenced by routes, ecmp egress
// and host objects all of which we deleted above. Egress objects in turn
// my point to a interface which we delete later
for (auto vrfIpAndEgress : vrfIp2Egress_) {
VLOG(1) << "Deleting egress object " << vrfIpAndEgress.second.first;
auto rv = opennsl_l3_egress_destroy(hw_->getUnit(),
vrfIpAndEgress.second.first);
bcmLogFatal(rv, hw_, "failed to destroy egress object ",
vrfIpAndEgress.second.first);
}
vrfIp2Egress_.clear();
// Delete interfaces
for (auto vlanMacAndIntf : vlanAndMac2Intf_) {
VLOG(1) <<"Deletingl3 interface for vlan: " << vlanMacAndIntf.first.first
<<" and mac : " << vlanMacAndIntf.first.second;
auto rv = opennsl_l3_intf_delete(hw_->getUnit(), &vlanMacAndIntf.second);
bcmLogFatal(rv, hw_, "failed to delete l3 interface for vlan: ",
vlanMacAndIntf.first.first, " and mac : ", vlanMacAndIntf.first.second);
}
vlanAndMac2Intf_.clear();
// Delete stations
for (auto vlanAndStation : vlan2Station_) {
VLOG(1) << "Deleting station for vlan : " << vlanAndStation.first;
auto rv = opennsl_l2_station_delete(hw_->getUnit(), vlanAndStation.first);
bcmLogFatal(rv, hw_, "failed to delete station for vlan : ",
vlanAndStation.first);
}
vlan2Station_.clear();
opennsl_vlan_t defaultVlan;
auto rv = opennsl_vlan_default_get(hw_->getUnit(), &defaultVlan);
bcmLogFatal(rv, hw_, "failed to get default VLAN");
// Finally delete the vlans
for (auto vlanItr = vlan2VlanInfo_.begin();
vlanItr != vlan2VlanInfo_.end();) {
if (defaultVlan == vlanItr->first) {
++vlanItr;
continue; // Can't delete the default vlan
}
VLOG(1) << "Deleting vlan : " << vlanItr->first;
auto rv = opennsl_vlan_destroy(hw_->getUnit(), vlanItr->first);
bcmLogFatal(rv, hw_, "failed to destroy vlan: ", vlanItr->first);
vlanItr = vlan2VlanInfo_.erase(vlanItr);
}
}
}}
| 39.58867 | 80 | 0.685435 | [
"object",
"vector"
] |
e90e55423762b158eda9bce9431ff3e3d801181e | 750 | cpp | C++ | src/MainThreadTaskRunner.cpp | paolo-projects/TouchCPLib | ee37fcf0cdbce67dc3392ab5a65c6a2c4ab09303 | [
"BSD-2-Clause"
] | 2 | 2021-07-19T02:23:20.000Z | 2021-11-19T16:58:38.000Z | src/MainThreadTaskRunner.cpp | paolo-projects/TouchCPLib | ee37fcf0cdbce67dc3392ab5a65c6a2c4ab09303 | [
"BSD-2-Clause"
] | null | null | null | src/MainThreadTaskRunner.cpp | paolo-projects/TouchCPLib | ee37fcf0cdbce67dc3392ab5a65c6a2c4ab09303 | [
"BSD-2-Clause"
] | null | null | null | #include "TouchCP/MainThreadTaskRunner.h"
MainThreadTaskRunner::MainThreadTaskRunner()
{
}
MainThreadTaskRunner::~MainThreadTaskRunner()
{
// Delete the pending tasks
// The worker thread has to be dead at this point
// to avoid referencing to a deleted object
while (taskDeque.size() > 0)
{
Task *task = taskDeque.back();
delete task;
taskDeque.pop_back();
}
}
void MainThreadTaskRunner::addTask(Task *task)
{
std::lock_guard<std::mutex> lock(taskDequeMutex);
taskDeque.push_front(task);
}
void MainThreadTaskRunner::runTasks()
{
std::lock_guard<std::mutex> lock(taskDequeMutex);
// Run the pending tasks
while (taskDeque.size() > 0)
{
Task *task = taskDeque.back();
(*task)();
delete task;
taskDeque.pop_back();
}
}
| 19.230769 | 50 | 0.713333 | [
"object"
] |
e91047c09b9c76e1158d5c1e10e04ab9cd15066b | 36,103 | cpp | C++ | src/main/native/glue/com_jme3_bullet_MultiBody.cpp | WinsonDeng/Libbulletjme | 711ce236f375c70e38db448ee9653e5dc998cdd9 | [
"BSD-3-Clause"
] | null | null | null | src/main/native/glue/com_jme3_bullet_MultiBody.cpp | WinsonDeng/Libbulletjme | 711ce236f375c70e38db448ee9653e5dc998cdd9 | [
"BSD-3-Clause"
] | null | null | null | src/main/native/glue/com_jme3_bullet_MultiBody.cpp | WinsonDeng/Libbulletjme | 711ce236f375c70e38db448ee9653e5dc998cdd9 | [
"BSD-3-Clause"
] | null | null | null | /*
* Copyright (c) 2020 jMonkeyEngine
* 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 'jMonkeyEngine' 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.
*/
#include "com_jme3_bullet_MultiBody.h"
#include "btMultiBody.h"
#include "jmeBulletUtil.h"
#include "jmeUserInfo.h"
/*
* Author: Stephen Gold
*/
/*
* Class: com_jme3_bullet_MultiBody
* Method: addBaseForce
* Signature: (JLcom/jme3/math/Vector3f;)V
*/
JNIEXPORT void JNICALL Java_com_jme3_bullet_MultiBody_addBaseForce
(JNIEnv *pEnv, jclass, jlong multiBodyId, jobject forceVector) {
btMultiBody * const
pMultiBody = reinterpret_cast<btMultiBody *> (multiBodyId);
NULL_CHK(pEnv, pMultiBody, "The multibody does not exist.",);
NULL_CHK(pEnv, forceVector, "The force vector does not exist.",)
btVector3 force;
jmeBulletUtil::convert(pEnv, forceVector, &force);
pMultiBody->addBaseForce(force);
}
/*
* Class: com_jme3_bullet_MultiBody
* Method: addBaseTorque
* Signature: (JLcom/jme3/math/Vector3f;)V
*/
JNIEXPORT void JNICALL Java_com_jme3_bullet_MultiBody_addBaseTorque
(JNIEnv *pEnv, jclass, jlong multiBodyId, jobject torqueVector) {
btMultiBody * const
pMultiBody = reinterpret_cast<btMultiBody *> (multiBodyId);
NULL_CHK(pEnv, pMultiBody, "The multibody does not exist.",);
NULL_CHK(pEnv, torqueVector, "The torque vector does not exist.",)
btVector3 torque;
jmeBulletUtil::convert(pEnv, torqueVector, &torque);
pMultiBody->addBaseTorque(torque);
}
/*
* Class: com_jme3_bullet_MultiBody
* Method: clearConstraintForces
* Signature: (J)V
*/
JNIEXPORT void JNICALL Java_com_jme3_bullet_MultiBody_clearConstraintForces
(JNIEnv *pEnv, jclass, jlong multiBodyId) {
btMultiBody * const
pMultiBody = reinterpret_cast<btMultiBody *> (multiBodyId);
NULL_CHK(pEnv, pMultiBody, "The multibody does not exist.",)
pMultiBody->clearConstraintForces();
}
/*
* Class: com_jme3_bullet_MultiBody
* Method: clearForcesAndTorques
* Signature: (J)V
*/
JNIEXPORT void JNICALL Java_com_jme3_bullet_MultiBody_clearForcesAndTorques
(JNIEnv *pEnv, jclass, jlong multiBodyId) {
btMultiBody * const
pMultiBody = reinterpret_cast<btMultiBody *> (multiBodyId);
NULL_CHK(pEnv, pMultiBody, "The multibody does not exist.",)
pMultiBody->clearForcesAndTorques();
}
/*
* Class: com_jme3_bullet_MultiBody
* Method: clearVelocities
* Signature: (J)V
*/
JNIEXPORT void JNICALL Java_com_jme3_bullet_MultiBody_clearVelocities
(JNIEnv *pEnv, jclass, jlong multiBodyId) {
btMultiBody * const
pMultiBody = reinterpret_cast<btMultiBody *> (multiBodyId);
NULL_CHK(pEnv, pMultiBody, "The multibody does not exist.",)
pMultiBody->clearVelocities();
}
/*
* Class: com_jme3_bullet_MultiBody
* Method: create
* Signature: (IFLcom/jme3/math/Vector3f;ZZ)J
*/
JNIEXPORT jlong JNICALL Java_com_jme3_bullet_MultiBody_create
(JNIEnv *pEnv, jobject object, jint numLinks, jfloat baseMass,
jobject inertiaVector, jboolean fixedBase, jboolean canSleep) {
jmeClasses::initJavaClasses(pEnv);
NULL_CHK(pEnv, inertiaVector, "The intertia vector does not exist.", 0)
btVector3 inertia;
jmeBulletUtil::convert(pEnv, inertiaVector, &inertia);
btMultiBody * const
pMultiBody = new btMultiBody(numLinks, baseMass, inertia, fixedBase,
canSleep); //dance004
jmeUserPointer const pUser = new jmeUserInfo(); //dance005
pUser->m_javaRef = pEnv->NewWeakGlobalRef(object);
pUser->m_group = 0x1;
pUser->m_groups = 0x1;
pUser->m_jmeSpace = NULL;
pMultiBody->setUserPointer(pUser);
return reinterpret_cast<jlong> (pMultiBody);
}
/*
* Class: com_jme3_bullet_MultiBody
* Method: finalizeMultiDof
* Signature: (J)V
*/
JNIEXPORT void JNICALL Java_com_jme3_bullet_MultiBody_finalizeMultiDof
(JNIEnv *pEnv, jclass, jlong multiBodyId) {
btMultiBody * const
pMultiBody = reinterpret_cast<btMultiBody *> (multiBodyId);
NULL_CHK(pEnv, pMultiBody, "The multibody does not exist.",)
pMultiBody->finalizeMultiDof();
}
/*
* Class: com_jme3_bullet_MultiBody
* Method: finalizeNative
* Signature: (J)V
*/
JNIEXPORT void JNICALL Java_com_jme3_bullet_MultiBody_finalizeNative
(JNIEnv *, jclass, jlong multiBodyId) {
const btMultiBody * const
pMultiBody = reinterpret_cast<btMultiBody *> (multiBodyId);
if (pMultiBody) {
jmeUserPointer const
pUser = (jmeUserPointer) pMultiBody->getUserPointer();
if (pUser) {
delete pUser; //dance005
}
delete pMultiBody; //dance004
}
}
/*
* Class: com_jme3_bullet_MultiBody
* Method: getAngularDamping
* Signature: (J)F
*/
JNIEXPORT jfloat JNICALL Java_com_jme3_bullet_MultiBody_getAngularDamping
(JNIEnv *pEnv, jclass, jlong multiBodyId) {
const btMultiBody * const
pMultiBody = reinterpret_cast<btMultiBody *> (multiBodyId);
NULL_CHK(pEnv, pMultiBody, "The multibody does not exist.", 0);
btScalar angularDamping = pMultiBody->getAngularDamping();
return (jfloat) angularDamping;
}
/*
* Class: com_jme3_bullet_MultiBody
* Method: getAngularMomentum
* Signature: (JLcom/jme3/math/Vector3f;)V
*/
JNIEXPORT void JNICALL Java_com_jme3_bullet_MultiBody_getAngularMomentum
(JNIEnv *pEnv, jclass, jlong multiBodyId, jobject storeVector) {
const btMultiBody * const
pMultiBody = reinterpret_cast<btMultiBody *> (multiBodyId);
NULL_CHK(pEnv, pMultiBody, "The multibody does not exist.",);
NULL_CHK(pEnv, storeVector, "The store vector does not exist.",);
const btVector3& angularMomentum = pMultiBody->getAngularMomentum();
jmeBulletUtil::convert(pEnv, &angularMomentum, storeVector);
}
/*
* Class: com_jme3_bullet_MultiBody
* Method: getBaseCollider
* Signature: (J)J
*/
JNIEXPORT jlong JNICALL Java_com_jme3_bullet_MultiBody_getBaseCollider
(JNIEnv *pEnv, jclass, jlong multiBodyId) {
const btMultiBody * const
pMultiBody = reinterpret_cast<btMultiBody *> (multiBodyId);
NULL_CHK(pEnv, pMultiBody, "The multibody does not exist.", 0);
const btMultiBodyLinkCollider * pCollider = pMultiBody->getBaseCollider();
return reinterpret_cast<jlong> (pCollider);
}
/*
* Class: com_jme3_bullet_MultiBody
* Method: getBaseForce
* Signature: (JLcom/jme3/math/Vector3f;)V
*/
JNIEXPORT void JNICALL Java_com_jme3_bullet_MultiBody_getBaseForce
(JNIEnv *pEnv, jclass, jlong multiBodyId, jobject storeVector) {
const btMultiBody * const
pMultiBody = reinterpret_cast<btMultiBody *> (multiBodyId);
NULL_CHK(pEnv, pMultiBody, "The multibody does not exist.",);
NULL_CHK(pEnv, storeVector, "The store vector does not exist.",);
const btVector3& baseForce = pMultiBody->getBaseForce();
jmeBulletUtil::convert(pEnv, &baseForce, storeVector);
}
/*
* Class: com_jme3_bullet_MultiBody
* Method: getBaseInertia
* Signature: (JLcom/jme3/math/Vector3f;)V
*/
JNIEXPORT void JNICALL Java_com_jme3_bullet_MultiBody_getBaseInertia
(JNIEnv *pEnv, jclass, jlong multiBodyId, jobject storeVector) {
const btMultiBody * const
pMultiBody = reinterpret_cast<btMultiBody *> (multiBodyId);
NULL_CHK(pEnv, pMultiBody, "The multibody does not exist.",);
NULL_CHK(pEnv, storeVector, "The store vector does not exist.",);
const btVector3& baseInertia = pMultiBody->getBaseInertia();
jmeBulletUtil::convert(pEnv, &baseInertia, storeVector);
}
/*
* Class: com_jme3_bullet_MultiBody
* Method: getBaseMass
* Signature: (J)F
*/
JNIEXPORT jfloat JNICALL Java_com_jme3_bullet_MultiBody_getBaseMass
(JNIEnv *pEnv, jclass, jlong multiBodyId) {
const btMultiBody * const
pMultiBody = reinterpret_cast<btMultiBody *> (multiBodyId);
NULL_CHK(pEnv, pMultiBody, "The multibody does not exist.", 0);
const btScalar baseMass = pMultiBody->getBaseMass();
return (jfloat) baseMass;
}
/*
* Class: com_jme3_bullet_MultiBody
* Method: getBaseOmega
* Signature: (JLcom/jme3/math/Vector3f;)V
*/
JNIEXPORT void JNICALL Java_com_jme3_bullet_MultiBody_getBaseOmega
(JNIEnv *pEnv, jclass, jlong multiBodyId, jobject storeVector) {
const btMultiBody * const
pMultiBody = reinterpret_cast<btMultiBody *> (multiBodyId);
NULL_CHK(pEnv, pMultiBody, "The multibody does not exist.",);
NULL_CHK(pEnv, storeVector, "The store vector does not exist.",);
const btVector3& baseOmega = pMultiBody->getBaseOmega();
jmeBulletUtil::convert(pEnv, &baseOmega, storeVector);
}
/*
* Class: com_jme3_bullet_MultiBody
* Method: getBasePos
* Signature: (JLcom/jme3/math/Vector3f;)V
*/
JNIEXPORT void JNICALL Java_com_jme3_bullet_MultiBody_getBasePos
(JNIEnv *pEnv, jclass, jlong multiBodyId, jobject storeVector) {
const btMultiBody * const
pMultiBody = reinterpret_cast<btMultiBody *> (multiBodyId);
NULL_CHK(pEnv, pMultiBody, "The multibody does not exist.",);
NULL_CHK(pEnv, storeVector, "The store vector does not exist.",);
const btVector3& basePos = pMultiBody->getBasePos();
jmeBulletUtil::convert(pEnv, &basePos, storeVector);
}
/*
* Class: com_jme3_bullet_MultiBody
* Method: getBaseTorque
* Signature: (JLcom/jme3/math/Vector3f;)V
*/
JNIEXPORT void JNICALL Java_com_jme3_bullet_MultiBody_getBaseTorque
(JNIEnv *pEnv, jclass, jlong multiBodyId, jobject storeVector) {
const btMultiBody * const
pMultiBody = reinterpret_cast<btMultiBody *> (multiBodyId);
NULL_CHK(pEnv, pMultiBody, "The multibody does not exist.",);
NULL_CHK(pEnv, storeVector, "The store vector does not exist.",);
const btVector3& baseTorque = pMultiBody->getBaseTorque();
jmeBulletUtil::convert(pEnv, &baseTorque, storeVector);
}
/*
* Class: com_jme3_bullet_MultiBody
* Method: getBaseVel
* Signature: (JLcom/jme3/math/Vector3f;)V
*/
JNIEXPORT void JNICALL Java_com_jme3_bullet_MultiBody_getBaseVel
(JNIEnv *pEnv, jclass, jlong multiBodyId, jobject storeVector) {
const btMultiBody * const
pMultiBody = reinterpret_cast<btMultiBody *> (multiBodyId);
NULL_CHK(pEnv, pMultiBody, "The multibody does not exist.",);
NULL_CHK(pEnv, storeVector, "The store vector does not exist.",);
const btVector3& baseVel = pMultiBody->getBaseVel();
jmeBulletUtil::convert(pEnv, &baseVel, storeVector);
}
/*
* Class: com_jme3_bullet_MultiBody
* Method: getBaseWorldTransform
* Signature: (JLcom/jme3/math/Transform;)V
*/
JNIEXPORT void JNICALL Java_com_jme3_bullet_MultiBody_getBaseWorldTransform
(JNIEnv *pEnv, jclass, jlong multiBodyId, jobject storeTransform) {
const btMultiBody * const
pMultiBody = reinterpret_cast<btMultiBody *> (multiBodyId);
NULL_CHK(pEnv, pMultiBody, "The multibody does not exist.",);
NULL_CHK(pEnv, storeTransform, "The storeTransform does not exist.",);
const btTransform& baseWorldTransform = pMultiBody->getBaseWorldTransform();
jmeBulletUtil::convert(pEnv, &baseWorldTransform, storeTransform);
}
/*
* Class: com_jme3_bullet_MultiBody
* Method: getCanSleep
* Signature: (J)Z
*/
JNIEXPORT jboolean JNICALL Java_com_jme3_bullet_MultiBody_getCanSleep
(JNIEnv *pEnv, jclass, jlong multiBodyId) {
const btMultiBody * const
pMultiBody = reinterpret_cast<btMultiBody *> (multiBodyId);
NULL_CHK(pEnv, pMultiBody, "The multibody does not exist.", JNI_FALSE);
bool canSleep = pMultiBody->getCanSleep();
return (jboolean) canSleep;
}
/*
* Class: com_jme3_bullet_MultiBody
* Method: getCanWakeup
* Signature: (J)Z
*/
JNIEXPORT jboolean JNICALL Java_com_jme3_bullet_MultiBody_getCanWakeup
(JNIEnv *pEnv, jclass, jlong multiBodyId) {
const btMultiBody * const
pMultiBody = reinterpret_cast<btMultiBody *> (multiBodyId);
NULL_CHK(pEnv, pMultiBody, "The multibody does not exist.", JNI_FALSE);
bool canWakeup = pMultiBody->getCanWakeup();
return (jboolean) canWakeup;
}
/*
* Class: com_jme3_bullet_MultiBody
* Method: getCollideWithGroups
* Signature: (J)I
*/
JNIEXPORT jint JNICALL Java_com_jme3_bullet_MultiBody_getCollideWithGroups
(JNIEnv *pEnv, jclass, jlong multiBodyId) {
const btMultiBody * const
pMultiBody = reinterpret_cast<btMultiBody *> (multiBodyId);
NULL_CHK(pEnv, pMultiBody, "The multibody does not exist.", 0);
jmeUserPointer const pUser = (jmeUserPointer) pMultiBody->getUserPointer();
jint groups = pUser->m_groups;
return groups;
}
/*
* Class: com_jme3_bullet_MultiBody
* Method: getCollisionGroup
* Signature: (J)I
*/
JNIEXPORT jint JNICALL Java_com_jme3_bullet_MultiBody_getCollisionGroup
(JNIEnv *pEnv, jclass, jlong multiBodyId) {
const btMultiBody * const
pMultiBody = reinterpret_cast<btMultiBody *> (multiBodyId);
NULL_CHK(pEnv, pMultiBody, "The multibody does not exist.", 0);
jmeUserPointer const pUser = (jmeUserPointer) pMultiBody->getUserPointer();
jint group = pUser->m_group;
return group;
}
/*
* Class: com_jme3_bullet_MultiBody
* Method: getKineticEnergy
* Signature: (J)F
*/
JNIEXPORT jfloat JNICALL Java_com_jme3_bullet_MultiBody_getKineticEnergy
(JNIEnv *pEnv, jclass, jlong multiBodyId) {
const btMultiBody * const
pMultiBody = reinterpret_cast<btMultiBody *> (multiBodyId);
NULL_CHK(pEnv, pMultiBody, "The multibody does not exist.", 0);
btScalar kineticEnergy = pMultiBody->getKineticEnergy();
return (jfloat) kineticEnergy;
}
/*
* Class: com_jme3_bullet_MultiBody
* Method: getLinearDamping
* Signature: (J)F
*/
JNIEXPORT jfloat JNICALL Java_com_jme3_bullet_MultiBody_getLinearDamping
(JNIEnv *pEnv, jclass, jlong multiBodyId) {
const btMultiBody * const
pMultiBody = reinterpret_cast<btMultiBody *> (multiBodyId);
NULL_CHK(pEnv, pMultiBody, "The multibody does not exist.", 0);
btScalar linearDamping = pMultiBody->getLinearDamping();
return (jfloat) linearDamping;
}
/*
* Class: com_jme3_bullet_MultiBody
* Method: getMaxAppliedImpulse
* Signature: (J)F
*/
JNIEXPORT jfloat JNICALL Java_com_jme3_bullet_MultiBody_getMaxAppliedImpulse
(JNIEnv *pEnv, jclass, jlong multiBodyId) {
const btMultiBody * const
pMultiBody = reinterpret_cast<btMultiBody *> (multiBodyId);
NULL_CHK(pEnv, pMultiBody, "The multibody does not exist.", 0);
btScalar maxAppliedImpulse = pMultiBody->getMaxAppliedImpulse();
return (jfloat) maxAppliedImpulse;
}
/*
* Class: com_jme3_bullet_MultiBody
* Method: getMaxCoordinateVelocity
* Signature: (J)F
*/
JNIEXPORT jfloat JNICALL Java_com_jme3_bullet_MultiBody_getMaxCoordinateVelocity
(JNIEnv *pEnv, jclass, jlong multiBodyId) {
const btMultiBody * const
pMultiBody = reinterpret_cast<btMultiBody *> (multiBodyId);
NULL_CHK(pEnv, pMultiBody, "The multibody does not exist.", 0);
btScalar maxCoordinateVelocity = pMultiBody->getMaxCoordinateVelocity();
return (jfloat) maxCoordinateVelocity;
}
/*
* Class: com_jme3_bullet_MultiBody
* Method: getNumDofs
* Signature: (J)I
*/
JNIEXPORT jint JNICALL Java_com_jme3_bullet_MultiBody_getNumDofs
(JNIEnv *pEnv, jclass, jlong multiBodyId) {
const btMultiBody * const
pMultiBody = reinterpret_cast<btMultiBody *> (multiBodyId);
NULL_CHK(pEnv, pMultiBody, "The multibody does not exist.", 0);
int numDofs = pMultiBody->getNumDofs();
return (jint) numDofs;
}
/*
* Class: com_jme3_bullet_MultiBody
* Method: getNumLinks
* Signature: (J)I
*/
JNIEXPORT jint JNICALL Java_com_jme3_bullet_MultiBody_getNumLinks
(JNIEnv *pEnv, jclass, jlong multiBodyId) {
const btMultiBody * const
pMultiBody = reinterpret_cast<btMultiBody *> (multiBodyId);
NULL_CHK(pEnv, pMultiBody, "The multibody does not exist.", 0);
int numLinks = pMultiBody->getNumLinks();
return (jint) numLinks;
}
/*
* Class: com_jme3_bullet_MultiBody
* Method: getNumPosVars
* Signature: (J)I
*/
JNIEXPORT jint JNICALL Java_com_jme3_bullet_MultiBody_getNumPosVars
(JNIEnv *pEnv, jclass, jlong multiBodyId) {
const btMultiBody * const
pMultiBody = reinterpret_cast<btMultiBody *> (multiBodyId);
NULL_CHK(pEnv, pMultiBody, "The multibody does not exist.", 0);
int numPosVars = pMultiBody->getNumPosVars();
return (jint) numPosVars;
}
/*
* Class: com_jme3_bullet_MultiBody
* Method: getSpace
* Signature: (J)J
*/
JNIEXPORT jlong JNICALL Java_com_jme3_bullet_MultiBody_getSpace
(JNIEnv *pEnv, jclass, jlong multiBodyId) {
const btMultiBody * const
pMultiBody = reinterpret_cast<btMultiBody *> (multiBodyId);
NULL_CHK(pEnv, pMultiBody, "The multibody does not exist.", 0);
jmeUserPointer const pUser = (jmeUserPointer) pMultiBody->getUserPointer();
jmeCollisionSpace *pSpace = pUser->m_jmeSpace;
return reinterpret_cast<jlong> (pSpace);
}
/*
* Class: com_jme3_bullet_MultiBody
* Method: getUseGyroTerm
* Signature: (J)Z
*/
JNIEXPORT jboolean JNICALL Java_com_jme3_bullet_MultiBody_getUseGyroTerm
(JNIEnv *pEnv, jclass, jlong multiBodyId) {
const btMultiBody * const
pMultiBody = reinterpret_cast<btMultiBody *> (multiBodyId);
NULL_CHK(pEnv, pMultiBody, "The multibody does not exist.", JNI_FALSE);
bool useGyroTerm = pMultiBody->getUseGyroTerm();
return (jboolean) useGyroTerm;
}
/*
* Class: com_jme3_bullet_MultiBody
* Method: getWorldToBaseRot
* Signature: (JLcom/jme3/math/Quaternion;)V
*/
JNIEXPORT void JNICALL Java_com_jme3_bullet_MultiBody_getWorldToBaseRot
(JNIEnv *pEnv, jclass, jlong multiBodyId, jobject storeQuaternion) {
const btMultiBody * const
pMultiBody = reinterpret_cast<btMultiBody *> (multiBodyId);
NULL_CHK(pEnv, pMultiBody, "The multibody does not exist.",);
NULL_CHK(pEnv, storeQuaternion, "The storeQuaternion does not exist.",);
btQuaternion worldToBaseRot = pMultiBody->getWorldToBaseRot();
jmeBulletUtil::convert(pEnv, &worldToBaseRot, storeQuaternion);
}
/*
* Class: com_jme3_bullet_MultiBody
* Method: hasFixedBase
* Signature: (J)Z
*/
JNIEXPORT jboolean JNICALL Java_com_jme3_bullet_MultiBody_hasFixedBase
(JNIEnv *pEnv, jclass, jlong multiBodyId) {
const btMultiBody * const
pMultiBody = reinterpret_cast<btMultiBody *> (multiBodyId);
NULL_CHK(pEnv, pMultiBody, "The multibody does not exist.", JNI_FALSE);
bool hasFixedBase = pMultiBody->hasFixedBase();
return (jboolean) hasFixedBase;
}
/*
* Class: com_jme3_bullet_MultiBody
* Method: isUsingGlobalVelocities
* Signature: (J)Z
*/
JNIEXPORT jboolean JNICALL Java_com_jme3_bullet_MultiBody_isUsingGlobalVelocities
(JNIEnv *pEnv, jclass, jlong multiBodyId) {
const btMultiBody * const
pMultiBody = reinterpret_cast<btMultiBody *> (multiBodyId);
NULL_CHK(pEnv, pMultiBody, "The multibody does not exist.", JNI_FALSE);
bool isUsingGlobalVelocities = pMultiBody->isUsingGlobalVelocities();
return (jboolean) isUsingGlobalVelocities;
}
/*
* Class: com_jme3_bullet_MultiBody
* Method: isUsingRK4Integration
* Signature: (J)Z
*/
JNIEXPORT jboolean JNICALL Java_com_jme3_bullet_MultiBody_isUsingRK4Integration
(JNIEnv *pEnv, jclass, jlong multiBodyId) {
const btMultiBody * const
pMultiBody = reinterpret_cast<btMultiBody *> (multiBodyId);
NULL_CHK(pEnv, pMultiBody, "The multibody does not exist.", JNI_FALSE);
bool isUsingRK4Integration = pMultiBody->isUsingRK4Integration();
return (jboolean) isUsingRK4Integration;
}
/*
* Class: com_jme3_bullet_MultiBody
* Method: setBaseCollider
* Signature: (JJ)V
*/
JNIEXPORT void JNICALL Java_com_jme3_bullet_MultiBody_setBaseCollider
(JNIEnv *pEnv, jclass, jlong multiBodyId, jlong colliderId) {
btMultiBody * const
pMultiBody = reinterpret_cast<btMultiBody *> (multiBodyId);
NULL_CHK(pEnv, pMultiBody, "The multibody does not exist.",);
btMultiBodyLinkCollider * const
pCollider = reinterpret_cast<btMultiBodyLinkCollider *> (colliderId);
NULL_CHK(pEnv, pCollider, "The collider does not exist.",);
pMultiBody->setBaseCollider(pCollider);
}
/*
* Class: com_jme3_bullet_MultiBody
* Method: setBaseOmega
* Signature: (JLcom/jme3/math/Vector3f;)V
*/
JNIEXPORT void JNICALL Java_com_jme3_bullet_MultiBody_setBaseOmega
(JNIEnv *pEnv, jclass, jlong multiBodyId, jobject angularVelocityVector) {
btMultiBody * const
pMultiBody = reinterpret_cast<btMultiBody *> (multiBodyId);
NULL_CHK(pEnv, pMultiBody, "The multibody does not exist.",)
NULL_CHK(pEnv, angularVelocityVector,
"The angular velocity vector does not exist.",);
btVector3 omega;
jmeBulletUtil::convert(pEnv, angularVelocityVector, &omega);
pMultiBody->setBaseOmega(omega);
}
/*
* Class: com_jme3_bullet_MultiBody
* Method: setBasePos
* Signature: (JLcom/jme3/math/Vector3f;)V
*/
JNIEXPORT void JNICALL Java_com_jme3_bullet_MultiBody_setBasePos
(JNIEnv *pEnv, jclass, jlong multiBodyId, jobject positionVector) {
btMultiBody * const
pMultiBody = reinterpret_cast<btMultiBody *> (multiBodyId);
NULL_CHK(pEnv, pMultiBody, "The multibody does not exist.",)
NULL_CHK(pEnv, positionVector, "The position vector does not exist.",);
btVector3 pos;
jmeBulletUtil::convert(pEnv, positionVector, &pos);
pMultiBody->setBasePos(pos);
}
/*
* Class: com_jme3_bullet_MultiBody
* Method: setBaseVel
* Signature: (JLcom/jme3/math/Vector3f;)V
*/
JNIEXPORT void JNICALL Java_com_jme3_bullet_MultiBody_setBaseVel
(JNIEnv *pEnv, jclass, jlong multiBodyId, jobject velocityVector) {
btMultiBody * const
pMultiBody = reinterpret_cast<btMultiBody *> (multiBodyId);
NULL_CHK(pEnv, pMultiBody, "The multibody does not exist.",)
NULL_CHK(pEnv, velocityVector, "The velocity vector does not exist.",);
btVector3 vel;
jmeBulletUtil::convert(pEnv, velocityVector, &vel);
pMultiBody->setBaseVel(vel);
}
/*
* Class: com_jme3_bullet_MultiBody
* Method: setBaseWorldTransform
* Signature: (JLcom/jme3/math/Transform;)V
*/
JNIEXPORT void JNICALL Java_com_jme3_bullet_MultiBody_setBaseWorldTransform
(JNIEnv *pEnv, jclass, jlong multiBodyId, jobject transform) {
btMultiBody * const
pMultiBody = reinterpret_cast<btMultiBody *> (multiBodyId);
NULL_CHK(pEnv, pMultiBody, "The multibody does not exist.",)
NULL_CHK(pEnv, transform, "The transform does not exist.",);
btTransform tr;
btVector3 scale;
jmeBulletUtil::convert(pEnv, transform, &tr, &scale);
pMultiBody->setBaseWorldTransform(tr);
}
/*
* Class: com_jme3_bullet_MultiBody
* Method: setCollideWithGroups
* Signature: (JI)V
*/
JNIEXPORT void JNICALL Java_com_jme3_bullet_MultiBody_setCollideWithGroups
(JNIEnv *pEnv, jclass, jlong multiBodyId, jint groups) {
btMultiBody * const
pMultiBody = reinterpret_cast<btMultiBody *> (multiBodyId);
NULL_CHK(pEnv, pMultiBody, "The multibody does not exist.",);
jmeUserPointer const pUser = (jmeUserPointer) pMultiBody->getUserPointer();
pUser->m_groups = groups;
}
/*
* Class: com_jme3_bullet_MultiBody
* Method: setCollisionGroup
* Signature: (JI)V
*/
JNIEXPORT void JNICALL Java_com_jme3_bullet_MultiBody_setCollisionGroup
(JNIEnv *pEnv, jclass, jlong multiBodyId, jint group) {
btMultiBody * const
pMultiBody = reinterpret_cast<btMultiBody *> (multiBodyId);
NULL_CHK(pEnv, pMultiBody, "The multibody does not exist.",);
jmeUserPointer const pUser = (jmeUserPointer) pMultiBody->getUserPointer();
pUser->m_group = group;
}
/*
* Class: com_jme3_bullet_MultiBody
* Method: setupFixed
* Signature: (JIFLcom/jme3/math/Vector3f;ILcom/jme3/math/Quaternion;Lcom/jme3/math/Vector3f;Lcom/jme3/math/Vector3f;)V
*/
JNIEXPORT void JNICALL Java_com_jme3_bullet_MultiBody_setupFixed
(JNIEnv *pEnv, jclass, jlong multiBodyId, jint linkIndex, jfloat mass,
jobject inertiaVector, jint parentLinkIndex,
jobject parent2LinkQuaternion, jobject parent2PivotVector,
jobject pivot2LinkVector) {
btMultiBody * const
pMultiBody = reinterpret_cast<btMultiBody *> (multiBodyId);
NULL_CHK(pEnv, pMultiBody, "The multibody does not exist.",);
const int i = (int) linkIndex;
btAssert(i >= 0);
btScalar m = (btScalar) mass;
btAssert(mass > 0);
NULL_CHK(pEnv, inertiaVector, "The inertia vector does not exist.",);
btVector3 inertia;
jmeBulletUtil::convert(pEnv, inertiaVector, &inertia);
int parent = (int) parentLinkIndex;
btAssert(i >= -1);
NULL_CHK(pEnv, parent2LinkQuaternion,
"The parent2Link quaternion does not exist.",);
btQuaternion rotParentToThis;
jmeBulletUtil::convert(pEnv, parent2LinkQuaternion, &rotParentToThis);
NULL_CHK(pEnv, parent2PivotVector, "The parent2pivot vector does not exist.",);
btVector3 parentComToThisPivotOffset;
jmeBulletUtil::convert(pEnv, parent2PivotVector, &parentComToThisPivotOffset);
NULL_CHK(pEnv, pivot2LinkVector, "The pivot2link vector does not exist.",);
btVector3 thisPivotToThisComOffset;
jmeBulletUtil::convert(pEnv, pivot2LinkVector, &thisPivotToThisComOffset);
pMultiBody->setupFixed(i, m, inertia, parent, rotParentToThis,
parentComToThisPivotOffset, thisPivotToThisComOffset);
}
/*
* Class: com_jme3_bullet_MultiBody
* Method: setupPlanar
* Signature: (JIFLcom/jme3/math/Vector3f;ILcom/jme3/math/Quaternion;Lcom/jme3/math/Vector3f;Lcom/jme3/math/Vector3f;Z)V
*/
JNIEXPORT void JNICALL Java_com_jme3_bullet_MultiBody_setupPlanar
(JNIEnv *pEnv, jclass, jlong multiBodyId, jint linkIndex, jfloat mass,
jobject inertiaVector, jint parentLinkIndex,
jobject parent2LinkQuaternion, jobject axisVector,
jobject parent2LinkVector, jboolean disableParentCollision) {
btMultiBody * const
pMultiBody = reinterpret_cast<btMultiBody *> (multiBodyId);
NULL_CHK(pEnv, pMultiBody, "The multibody does not exist.",);
const int i = (int) linkIndex;
btAssert(i >= 0);
btScalar m = (btScalar) mass;
btAssert(mass > 0);
NULL_CHK(pEnv, inertiaVector, "The inertia vector does not exist.",);
btVector3 inertia;
jmeBulletUtil::convert(pEnv, inertiaVector, &inertia);
int parent = (int) parentLinkIndex;
btAssert(i >= -1);
NULL_CHK(pEnv, parent2LinkQuaternion,
"The parent2Link quaternion does not exist.",);
btQuaternion rotParentToThis;
jmeBulletUtil::convert(pEnv, parent2LinkQuaternion, &rotParentToThis);
NULL_CHK(pEnv, axisVector, "The axis vector does not exist.",);
btVector3 rotationAxis;
jmeBulletUtil::convert(pEnv, axisVector, &rotationAxis);
NULL_CHK(pEnv, parent2LinkVector, "The parent2link vector does not exist.",);
btVector3 parentComToThisComOffset;
jmeBulletUtil::convert(pEnv, parent2LinkVector, &parentComToThisComOffset);
pMultiBody->setupPlanar(i, m, inertia, parent, rotParentToThis,
rotationAxis, parentComToThisComOffset,
(bool)disableParentCollision);
}
/*
* Class: com_jme3_bullet_MultiBody
* Method: setupPrismatic
* Signature: (JIFLcom/jme3/math/Vector3f;ILcom/jme3/math/Quaternion;Lcom/jme3/math/Vector3f;Lcom/jme3/math/Vector3f;Lcom/jme3/math/Vector3f;Z)V
*/
JNIEXPORT void JNICALL Java_com_jme3_bullet_MultiBody_setupPrismatic
(JNIEnv *pEnv, jclass, jlong multiBodyId, jint linkIndex, jfloat mass,
jobject inertiaVector, jint parentLinkIndex,
jobject parent2LinkQuaternion, jobject axisVector,
jobject parent2PivotVector, jobject pivot2LinkVector,
jboolean disableParentCollision) {
btMultiBody * const
pMultiBody = reinterpret_cast<btMultiBody *> (multiBodyId);
NULL_CHK(pEnv, pMultiBody, "The multibody does not exist.",);
const int i = (int) linkIndex;
btAssert(i >= 0);
btScalar m = (btScalar) mass;
btAssert(mass > 0);
NULL_CHK(pEnv, inertiaVector, "The inertia vector does not exist.",);
btVector3 inertia;
jmeBulletUtil::convert(pEnv, inertiaVector, &inertia);
int parent = (int) parentLinkIndex;
btAssert(i >= -1);
NULL_CHK(pEnv, parent2LinkQuaternion,
"The parent2Link quaternion does not exist.",);
btQuaternion rotParentToThis;
jmeBulletUtil::convert(pEnv, parent2LinkQuaternion, &rotParentToThis);
NULL_CHK(pEnv, axisVector, "The axis vector does not exist.",);
btVector3 jointAxis;
jmeBulletUtil::convert(pEnv, axisVector, &jointAxis);
NULL_CHK(pEnv, parent2PivotVector, "The parent2pivot vector does not exist.",);
btVector3 parentComToThisPivotOffset;
jmeBulletUtil::convert(pEnv, parent2PivotVector, &parentComToThisPivotOffset);
NULL_CHK(pEnv, pivot2LinkVector, "The pivot2link vector does not exist.",);
btVector3 thisPivotToThisComOffset;
jmeBulletUtil::convert(pEnv, pivot2LinkVector, &thisPivotToThisComOffset);
pMultiBody->setupPrismatic(i, m, inertia, parent, rotParentToThis,
jointAxis, parentComToThisPivotOffset, thisPivotToThisComOffset,
(bool)disableParentCollision);
}
/*
* Class: com_jme3_bullet_MultiBody
* Method: setupRevolute
* Signature: (JIFLcom/jme3/math/Vector3f;ILcom/jme3/math/Quaternion;Lcom/jme3/math/Vector3f;Lcom/jme3/math/Vector3f;Lcom/jme3/math/Vector3f;Z)V
*/
JNIEXPORT void JNICALL Java_com_jme3_bullet_MultiBody_setupRevolute
(JNIEnv *pEnv, jclass, jlong multiBodyId, jint linkIndex, jfloat mass,
jobject inertiaVector, jint parentLinkIndex,
jobject parent2LinkQuaternion, jobject axisVector,
jobject parent2PivotVector, jobject pivot2LinkVector,
jboolean disableParentCollision) {
btMultiBody * const
pMultiBody = reinterpret_cast<btMultiBody *> (multiBodyId);
NULL_CHK(pEnv, pMultiBody, "The multibody does not exist.",);
const int i = (int) linkIndex;
btAssert(i >= 0);
btScalar m = (btScalar) mass;
btAssert(mass > 0);
NULL_CHK(pEnv, inertiaVector, "The inertia vector does not exist.",);
btVector3 inertia;
jmeBulletUtil::convert(pEnv, inertiaVector, &inertia);
int parent = (int) parentLinkIndex;
btAssert(i >= -1);
NULL_CHK(pEnv, parent2LinkQuaternion,
"The parent2Link quaternion does not exist.",);
btQuaternion rotParentToThis;
jmeBulletUtil::convert(pEnv, parent2LinkQuaternion, &rotParentToThis);
NULL_CHK(pEnv, axisVector, "The axis vector does not exist.",);
btVector3 jointAxis;
jmeBulletUtil::convert(pEnv, axisVector, &jointAxis);
NULL_CHK(pEnv, parent2PivotVector, "The parent2pivot vector does not exist.",);
btVector3 parentComToThisPivotOffset;
jmeBulletUtil::convert(pEnv, parent2PivotVector, &parentComToThisPivotOffset);
NULL_CHK(pEnv, pivot2LinkVector, "The pivot2link vector does not exist.",);
btVector3 thisPivotToThisComOffset;
jmeBulletUtil::convert(pEnv, pivot2LinkVector, &thisPivotToThisComOffset);
pMultiBody->setupRevolute(i, m, inertia, parent, rotParentToThis,
jointAxis, parentComToThisPivotOffset, thisPivotToThisComOffset,
(bool)disableParentCollision);
}
/*
* Class: com_jme3_bullet_MultiBody
* Method: setupSpherical
* Signature: (JIFLcom/jme3/math/Vector3f;ILcom/jme3/math/Quaternion;Lcom/jme3/math/Vector3f;Lcom/jme3/math/Vector3f;Z)V
*/
JNIEXPORT void JNICALL Java_com_jme3_bullet_MultiBody_setupSpherical
(JNIEnv *pEnv, jclass, jlong multiBodyId, jint linkIndex, jfloat mass,
jobject inertiaVector, jint parentLinkIndex,
jobject parent2LinkQuaternion, jobject parent2PivotVector,
jobject pivot2LinkVector, jboolean disableParentCollision) {
btMultiBody * const
pMultiBody = reinterpret_cast<btMultiBody *> (multiBodyId);
NULL_CHK(pEnv, pMultiBody, "The multibody does not exist.",);
const int i = (int) linkIndex;
btAssert(i >= 0);
btScalar m = (btScalar) mass;
btAssert(mass > 0);
NULL_CHK(pEnv, inertiaVector, "The inertia vector does not exist.",);
btVector3 inertia;
jmeBulletUtil::convert(pEnv, inertiaVector, &inertia);
int parent = (int) parentLinkIndex;
btAssert(i >= -1);
NULL_CHK(pEnv, parent2LinkQuaternion,
"The parent2Link quaternion does not exist.",);
btQuaternion rotParentToThis;
jmeBulletUtil::convert(pEnv, parent2LinkQuaternion, &rotParentToThis);
NULL_CHK(pEnv, parent2PivotVector, "The parent2pivot vector does not exist.",);
btVector3 parentComToThisPivotOffset;
jmeBulletUtil::convert(pEnv, parent2PivotVector, &parentComToThisPivotOffset);
NULL_CHK(pEnv, pivot2LinkVector, "The pivot2link vector does not exist.",);
btVector3 thisPivotToThisComOffset;
jmeBulletUtil::convert(pEnv, pivot2LinkVector, &thisPivotToThisComOffset);
pMultiBody->setupSpherical(i, m, inertia, parent, rotParentToThis,
parentComToThisPivotOffset, thisPivotToThisComOffset,
(bool)disableParentCollision);
}
/*
* Class: com_jme3_bullet_MultiBody
* Method: setWorldToBaseRot
* Signature: (JLcom/jme3/math/Quaternion;)V
*/
JNIEXPORT void JNICALL Java_com_jme3_bullet_MultiBody_setWorldToBaseRot
(JNIEnv *pEnv, jclass, jlong multiBodyId, jobject quaternion) {
btMultiBody * const
pMultiBody = reinterpret_cast<btMultiBody *> (multiBodyId);
NULL_CHK(pEnv, pMultiBody, "The multibody does not exist.",);
NULL_CHK(pEnv, quaternion, "The quaternion does not exist.",);
btQuaternion rot;
jmeBulletUtil::convert(pEnv, quaternion, &rot);
pMultiBody->setWorldToBaseRot(rot);
}
/*
* Class: com_jme3_bullet_MultiBody
* Method: useGlobalVelocities
* Signature: (JZ)V
*/
JNIEXPORT void JNICALL Java_com_jme3_bullet_MultiBody_useGlobalVelocities
(JNIEnv *pEnv, jclass, jlong multiBodyId, jboolean use) {
btMultiBody * const
pMultiBody = reinterpret_cast<btMultiBody *> (multiBodyId);
NULL_CHK(pEnv, pMultiBody, "The multibody does not exist.",);
pMultiBody->useGlobalVelocities(use);
}
/*
* Class: com_jme3_bullet_MultiBody
* Method: useRK4Integration
* Signature: (JZ)V
*/
JNIEXPORT void JNICALL Java_com_jme3_bullet_MultiBody_useRK4Integration
(JNIEnv *pEnv, jclass, jlong multiBodyId, jboolean use) {
btMultiBody * const
pMultiBody = reinterpret_cast<btMultiBody *> (multiBodyId);
NULL_CHK(pEnv, pMultiBody, "The multibody does not exist.",);
pMultiBody->useRK4Integration(use);
}
| 35.604536 | 144 | 0.728721 | [
"object",
"vector",
"transform"
] |
e911749b3ff8a1f93c3c49768ddcff8974491196 | 24,135 | hpp | C++ | deps/boost/boost/date_time/format_date_parser.hpp | laborautonomo/poedit | 4ccc4e40334cc8b147d77077d1e5522a55862b3d | [
"MIT"
] | 1 | 2015-11-05T17:34:34.000Z | 2015-11-05T17:34:34.000Z | deps/boost/boost/date_time/format_date_parser.hpp | laborautonomo/poedit | 4ccc4e40334cc8b147d77077d1e5522a55862b3d | [
"MIT"
] | null | null | null | deps/boost/boost/date_time/format_date_parser.hpp | laborautonomo/poedit | 4ccc4e40334cc8b147d77077d1e5522a55862b3d | [
"MIT"
] | null | null | null |
#ifndef DATE_TIME_FORMAT_DATE_PARSER_HPP__
#define DATE_TIME_FORMAT_DATE_PARSER_HPP__
/* Copyright (c) 2004-2005 CrystalClear Software, Inc.
* Use, modification and distribution is subject to the
* Boost Software License, Version 1.0. (See accompanying
* file LICENSE_1_0.txt or http://www.boost.org/LICENSE_1_0.txt)
* Author: Jeff Garland, Bart Garst
* $Date: 2013-09-21 13:17:00 -0700 (Sat, 21 Sep 2013) $
*/
#include "boost/lexical_cast.hpp"
#include "boost/date_time/string_parse_tree.hpp"
#include "boost/date_time/strings_from_facet.hpp"
#include "boost/date_time/special_values_parser.hpp"
#include <string>
#include <vector>
#include <sstream>
#include <iterator>
#ifndef BOOST_NO_STDC_NAMESPACE
# include <cctype>
#else
# include <ctype.h>
#endif
#ifdef BOOST_NO_STDC_NAMESPACE
namespace std {
using ::isspace;
using ::isdigit;
}
#endif
namespace boost { namespace date_time {
//! Helper function for parsing fixed length strings into integers
/*! Will consume 'length' number of characters from stream. Consumed
* character are transfered to parse_match_result struct.
* Returns '-1' if no number can be parsed or incorrect number of
* digits in stream. */
template<typename int_type, typename charT>
inline
int_type
fixed_string_to_int(std::istreambuf_iterator<charT>& itr,
std::istreambuf_iterator<charT>& stream_end,
parse_match_result<charT>& mr,
unsigned int length,
const charT& fill_char)
{
//typedef std::basic_string<charT> string_type;
unsigned int j = 0;
//string_type s;
while (j < length && itr != stream_end &&
(std::isdigit(*itr) || *itr == fill_char)) {
if(*itr == fill_char) {
/* Since a fill_char can be anything, we convert it to a zero.
* lexical_cast will behave predictably when zero is used as fill. */
mr.cache += ('0');
}
else {
mr.cache += (*itr);
}
itr++;
j++;
}
int_type i = -1;
// mr.cache will hold leading zeros. size() tells us when input is too short.
if(mr.cache.size() < length) {
return i;
}
try {
i = boost::lexical_cast<int_type>(mr.cache);
}catch(bad_lexical_cast&){
// we want to return -1 if the cast fails so nothing to do here
}
return i;
}
//! Helper function for parsing fixed length strings into integers
/*! Will consume 'length' number of characters from stream. Consumed
* character are transfered to parse_match_result struct.
* Returns '-1' if no number can be parsed or incorrect number of
* digits in stream. */
template<typename int_type, typename charT>
inline
int_type
fixed_string_to_int(std::istreambuf_iterator<charT>& itr,
std::istreambuf_iterator<charT>& stream_end,
parse_match_result<charT>& mr,
unsigned int length)
{
return fixed_string_to_int<int_type, charT>(itr, stream_end, mr, length, '0');
}
//! Helper function for parsing varied length strings into integers
/*! Will consume 'max_length' characters from stream only if those
* characters are digits. Returns '-1' if no number can be parsed.
* Will not parse a number preceeded by a '+' or '-'. */
template<typename int_type, typename charT>
inline
int_type
var_string_to_int(std::istreambuf_iterator<charT>& itr,
const std::istreambuf_iterator<charT>& stream_end,
unsigned int max_length)
{
typedef std::basic_string<charT> string_type;
unsigned int j = 0;
string_type s;
while (itr != stream_end && (j < max_length) && std::isdigit(*itr)) {
s += (*itr);
++itr;
++j;
}
int_type i = -1;
if(!s.empty()) {
i = boost::lexical_cast<int_type>(s);
}
return i;
}
//! Class with generic date parsing using a format string
/*! The following is the set of recognized format specifiers
- %a - Short weekday name
- %A - Long weekday name
- %b - Abbreviated month name
- %B - Full month name
- %d - Day of the month as decimal 01 to 31
- %j - Day of year as decimal from 001 to 366
- %m - Month name as a decimal 01 to 12
- %U - Week number 00 to 53 with first Sunday as the first day of week 1?
- %w - Weekday as decimal number 0 to 6 where Sunday == 0
- %W - Week number 00 to 53 where Monday is first day of week 1
- %x - facet default date representation
- %y - Year without the century - eg: 04 for 2004
- %Y - Year with century
The weekday specifiers (%a and %A) do not add to the date construction,
but they provide a way to skip over the weekday names for formats that
provide them.
todo -- Another interesting feature that this approach could provide is
an option to fill in any missing fields with the current values
from the clock. So if you have %m-%d the parser would detect
the missing year value and fill it in using the clock.
todo -- What to do with the %x. %x in the classic facet is just bad...
*/
template<class date_type, typename charT>
class format_date_parser
{
public:
typedef std::basic_string<charT> string_type;
typedef std::basic_istringstream<charT> stringstream_type;
typedef std::istreambuf_iterator<charT> stream_itr_type;
typedef typename string_type::const_iterator const_itr;
typedef typename date_type::year_type year_type;
typedef typename date_type::month_type month_type;
typedef typename date_type::day_type day_type;
typedef typename date_type::duration_type duration_type;
typedef typename date_type::day_of_week_type day_of_week_type;
typedef typename date_type::day_of_year_type day_of_year_type;
typedef string_parse_tree<charT> parse_tree_type;
typedef typename parse_tree_type::parse_match_result_type match_results;
typedef std::vector<std::basic_string<charT> > input_collection_type;
// TODO sv_parser uses its default constructor - write the others
format_date_parser(const string_type& format_str,
const input_collection_type& month_short_names,
const input_collection_type& month_long_names,
const input_collection_type& weekday_short_names,
const input_collection_type& weekday_long_names) :
m_format(format_str),
m_month_short_names(month_short_names, 1),
m_month_long_names(month_long_names, 1),
m_weekday_short_names(weekday_short_names),
m_weekday_long_names(weekday_long_names)
{}
format_date_parser(const string_type& format_str,
const std::locale& locale) :
m_format(format_str),
m_month_short_names(gather_month_strings<charT>(locale), 1),
m_month_long_names(gather_month_strings<charT>(locale, false), 1),
m_weekday_short_names(gather_weekday_strings<charT>(locale)),
m_weekday_long_names(gather_weekday_strings<charT>(locale, false))
{}
format_date_parser(const format_date_parser<date_type,charT>& fdp)
{
this->m_format = fdp.m_format;
this->m_month_short_names = fdp.m_month_short_names;
this->m_month_long_names = fdp.m_month_long_names;
this->m_weekday_short_names = fdp.m_weekday_short_names;
this->m_weekday_long_names = fdp.m_weekday_long_names;
}
string_type format() const
{
return m_format;
}
void format(string_type format_str)
{
m_format = format_str;
}
void short_month_names(const input_collection_type& month_names)
{
m_month_short_names = parse_tree_type(month_names, 1);
}
void long_month_names(const input_collection_type& month_names)
{
m_month_long_names = parse_tree_type(month_names, 1);
}
void short_weekday_names(const input_collection_type& weekday_names)
{
m_weekday_short_names = parse_tree_type(weekday_names);
}
void long_weekday_names(const input_collection_type& weekday_names)
{
m_weekday_long_names = parse_tree_type(weekday_names);
}
date_type
parse_date(const string_type& value,
const string_type& format_str,
const special_values_parser<date_type,charT>& sv_parser) const
{
stringstream_type ss(value);
stream_itr_type sitr(ss);
stream_itr_type stream_end;
return parse_date(sitr, stream_end, format_str, sv_parser);
}
date_type
parse_date(std::istreambuf_iterator<charT>& sitr,
std::istreambuf_iterator<charT>& stream_end,
const special_values_parser<date_type,charT>& sv_parser) const
{
return parse_date(sitr, stream_end, m_format, sv_parser);
}
/*! Of all the objects that the format_date_parser can parse, only a
* date can be a special value. Therefore, only parse_date checks
* for special_values. */
date_type
parse_date(std::istreambuf_iterator<charT>& sitr,
std::istreambuf_iterator<charT>& stream_end,
string_type format_str,
const special_values_parser<date_type,charT>& sv_parser) const
{
bool use_current_char = false;
// skip leading whitespace
while(std::isspace(*sitr) && sitr != stream_end) { ++sitr; }
short year(0), month(0), day(0), day_of_year(0);// wkday(0);
/* Initialized the following to their minimum values. These intermediate
* objects are used so we get specific exceptions when part of the input
* is unparsable.
* Ex: "205-Jan-15" will throw a bad_year, "2005-Jsn-15"- bad_month, etc.*/
year_type t_year(1400);
month_type t_month(1);
day_type t_day(1);
day_of_week_type wkday(0);
const_itr itr(format_str.begin());
while (itr != format_str.end() && (sitr != stream_end)) {
if (*itr == '%') {
itr++;
if (*itr != '%') {
switch(*itr) {
case 'a':
{
//this value is just throw away. It could be used for
//error checking potentially, but it isn't helpful in
//actually constructing the date - we just need to get it
//out of the stream
match_results mr = m_weekday_short_names.match(sitr, stream_end);
if(mr.current_match == match_results::PARSE_ERROR) {
// check special_values
if(sv_parser.match(sitr, stream_end, mr)) {
return date_type(static_cast<special_values>(mr.current_match));
}
}
wkday = mr.current_match;
if (mr.has_remaining()) {
use_current_char = true;
}
break;
}
case 'A':
{
//this value is just throw away. It could be used for
//error checking potentially, but it isn't helpful in
//actually constructing the date - we just need to get it
//out of the stream
match_results mr = m_weekday_long_names.match(sitr, stream_end);
if(mr.current_match == match_results::PARSE_ERROR) {
// check special_values
if(sv_parser.match(sitr, stream_end, mr)) {
return date_type(static_cast<special_values>(mr.current_match));
}
}
wkday = mr.current_match;
if (mr.has_remaining()) {
use_current_char = true;
}
break;
}
case 'b':
{
match_results mr = m_month_short_names.match(sitr, stream_end);
if(mr.current_match == match_results::PARSE_ERROR) {
// check special_values
if(sv_parser.match(sitr, stream_end, mr)) {
return date_type(static_cast<special_values>(mr.current_match));
}
}
t_month = month_type(mr.current_match);
if (mr.has_remaining()) {
use_current_char = true;
}
break;
}
case 'B':
{
match_results mr = m_month_long_names.match(sitr, stream_end);
if(mr.current_match == match_results::PARSE_ERROR) {
// check special_values
if(sv_parser.match(sitr, stream_end, mr)) {
return date_type(static_cast<special_values>(mr.current_match));
}
}
t_month = month_type(mr.current_match);
if (mr.has_remaining()) {
use_current_char = true;
}
break;
}
case 'd':
{
match_results mr;
day = fixed_string_to_int<short, charT>(sitr, stream_end, mr, 2);
if(day == -1) {
if(sv_parser.match(sitr, stream_end, mr)) {
return date_type(static_cast<special_values>(mr.current_match));
}
}
t_day = day_type(day);
break;
}
case 'e':
{
match_results mr;
day = fixed_string_to_int<short, charT>(sitr, stream_end, mr, 2, ' ');
if(day == -1) {
if(sv_parser.match(sitr, stream_end, mr)) {
return date_type(static_cast<special_values>(mr.current_match));
}
}
t_day = day_type(day);
break;
}
case 'j':
{
match_results mr;
day_of_year = fixed_string_to_int<short, charT>(sitr, stream_end, mr, 3);
if(day_of_year == -1) {
if(sv_parser.match(sitr, stream_end, mr)) {
return date_type(static_cast<special_values>(mr.current_match));
}
}
// these next two lines are so we get an exception with bad input
day_of_year_type t_day_of_year(1);
t_day_of_year = day_of_year_type(day_of_year);
break;
}
case 'm':
{
match_results mr;
month = fixed_string_to_int<short, charT>(sitr, stream_end, mr, 2);
if(month == -1) {
if(sv_parser.match(sitr, stream_end, mr)) {
return date_type(static_cast<special_values>(mr.current_match));
}
}
t_month = month_type(month);
break;
}
case 'Y':
{
match_results mr;
year = fixed_string_to_int<short, charT>(sitr, stream_end, mr, 4);
if(year == -1) {
if(sv_parser.match(sitr, stream_end, mr)) {
return date_type(static_cast<special_values>(mr.current_match));
}
}
t_year = year_type(year);
break;
}
case 'y':
{
match_results mr;
year = fixed_string_to_int<short, charT>(sitr, stream_end, mr, 2);
if(year == -1) {
if(sv_parser.match(sitr, stream_end, mr)) {
return date_type(static_cast<special_values>(mr.current_match));
}
}
year += 2000; //make 2 digit years in this century
t_year = year_type(year);
break;
}
default:
{} //ignore those we don't understand
}//switch
}
else { // itr == '%', second consecutive
sitr++;
}
itr++; //advance past format specifier
}
else { //skip past chars in format and in buffer
itr++;
if (use_current_char) {
use_current_char = false;
}
else {
sitr++;
}
}
}
if (day_of_year > 0) {
date_type d(static_cast<unsigned short>(year-1),12,31); //end of prior year
return d + duration_type(day_of_year);
}
return date_type(t_year, t_month, t_day); // exceptions were thrown earlier
// if input was no good
}
//! Throws bad_month if unable to parse
month_type
parse_month(std::istreambuf_iterator<charT>& sitr,
std::istreambuf_iterator<charT>& stream_end,
string_type format_str) const
{
match_results mr;
return parse_month(sitr, stream_end, format_str, mr);
}
//! Throws bad_month if unable to parse
month_type
parse_month(std::istreambuf_iterator<charT>& sitr,
std::istreambuf_iterator<charT>& stream_end,
string_type format_str,
match_results& mr) const
{
bool use_current_char = false;
// skip leading whitespace
while(std::isspace(*sitr) && sitr != stream_end) { ++sitr; }
short month(0);
const_itr itr(format_str.begin());
while (itr != format_str.end() && (sitr != stream_end)) {
if (*itr == '%') {
itr++;
if (*itr != '%') {
switch(*itr) {
case 'b':
{
mr = m_month_short_names.match(sitr, stream_end);
month = mr.current_match;
if (mr.has_remaining()) {
use_current_char = true;
}
break;
}
case 'B':
{
mr = m_month_long_names.match(sitr, stream_end);
month = mr.current_match;
if (mr.has_remaining()) {
use_current_char = true;
}
break;
}
case 'm':
{
month = var_string_to_int<short, charT>(sitr, stream_end, 2);
// var_string_to_int returns -1 if parse failed. That will
// cause a bad_month exception to be thrown so we do nothing here
break;
}
default:
{} //ignore those we don't understand
}//switch
}
else { // itr == '%', second consecutive
sitr++;
}
itr++; //advance past format specifier
}
else { //skip past chars in format and in buffer
itr++;
if (use_current_char) {
use_current_char = false;
}
else {
sitr++;
}
}
}
return month_type(month); // throws bad_month exception when values are zero
}
//! Expects 1 or 2 digits 1-31. Throws bad_day_of_month if unable to parse
day_type
parse_var_day_of_month(std::istreambuf_iterator<charT>& sitr,
std::istreambuf_iterator<charT>& stream_end) const
{
// skip leading whitespace
while(std::isspace(*sitr) && sitr != stream_end) { ++sitr; }
return day_type(var_string_to_int<short, charT>(sitr, stream_end, 2));
}
//! Expects 2 digits 01-31. Throws bad_day_of_month if unable to parse
day_type
parse_day_of_month(std::istreambuf_iterator<charT>& sitr,
std::istreambuf_iterator<charT>& stream_end) const
{
// skip leading whitespace
while(std::isspace(*sitr) && sitr != stream_end) { ++sitr; }
//return day_type(var_string_to_int<short, charT>(sitr, stream_end, 2));
match_results mr;
return day_type(fixed_string_to_int<short, charT>(sitr, stream_end, mr, 2));
}
day_of_week_type
parse_weekday(std::istreambuf_iterator<charT>& sitr,
std::istreambuf_iterator<charT>& stream_end,
string_type format_str) const
{
match_results mr;
return parse_weekday(sitr, stream_end, format_str, mr);
}
day_of_week_type
parse_weekday(std::istreambuf_iterator<charT>& sitr,
std::istreambuf_iterator<charT>& stream_end,
string_type format_str,
match_results& mr) const
{
bool use_current_char = false;
// skip leading whitespace
while(std::isspace(*sitr) && sitr != stream_end) { ++sitr; }
short wkday(0);
const_itr itr(format_str.begin());
while (itr != format_str.end() && (sitr != stream_end)) {
if (*itr == '%') {
itr++;
if (*itr != '%') {
switch(*itr) {
case 'a':
{
//this value is just throw away. It could be used for
//error checking potentially, but it isn't helpful in
//actually constructing the date - we just need to get it
//out of the stream
mr = m_weekday_short_names.match(sitr, stream_end);
wkday = mr.current_match;
if (mr.has_remaining()) {
use_current_char = true;
}
break;
}
case 'A':
{
//this value is just throw away. It could be used for
//error checking potentially, but it isn't helpful in
//actually constructing the date - we just need to get it
//out of the stream
mr = m_weekday_long_names.match(sitr, stream_end);
wkday = mr.current_match;
if (mr.has_remaining()) {
use_current_char = true;
}
break;
}
case 'w':
{
// weekday as number 0-6, Sunday == 0
wkday = var_string_to_int<short, charT>(sitr, stream_end, 2);
break;
}
default:
{} //ignore those we don't understand
}//switch
}
else { // itr == '%', second consecutive
sitr++;
}
itr++; //advance past format specifier
}
else { //skip past chars in format and in buffer
itr++;
if (use_current_char) {
use_current_char = false;
}
else {
sitr++;
}
}
}
return day_of_week_type(wkday); // throws bad_day_of_month exception
// when values are zero
}
//! throws bad_year if unable to parse
year_type
parse_year(std::istreambuf_iterator<charT>& sitr,
std::istreambuf_iterator<charT>& stream_end,
string_type format_str) const
{
match_results mr;
return parse_year(sitr, stream_end, format_str, mr);
}
//! throws bad_year if unable to parse
year_type
parse_year(std::istreambuf_iterator<charT>& sitr,
std::istreambuf_iterator<charT>& stream_end,
string_type format_str,
match_results& mr) const
{
bool use_current_char = false;
// skip leading whitespace
while(std::isspace(*sitr) && sitr != stream_end) { ++sitr; }
unsigned short year(0);
const_itr itr(format_str.begin());
while (itr != format_str.end() && (sitr != stream_end)) {
if (*itr == '%') {
itr++;
if (*itr != '%') {
//match_results mr;
switch(*itr) {
case 'Y':
{
// year from 4 digit string
year = fixed_string_to_int<short, charT>(sitr, stream_end, mr, 4);
break;
}
case 'y':
{
// year from 2 digit string (no century)
year = fixed_string_to_int<short, charT>(sitr, stream_end, mr, 2);
year += 2000; //make 2 digit years in this century
break;
}
default:
{} //ignore those we don't understand
}//switch
}
else { // itr == '%', second consecutive
sitr++;
}
itr++; //advance past format specifier
}
else { //skip past chars in format and in buffer
itr++;
if (use_current_char) {
use_current_char = false;
}
else {
sitr++;
}
}
}
return year_type(year); // throws bad_year exception when values are zero
}
private:
string_type m_format;
parse_tree_type m_month_short_names;
parse_tree_type m_month_long_names;
parse_tree_type m_weekday_short_names;
parse_tree_type m_weekday_long_names;
};
} } //namespace
#endif
| 33.152473 | 87 | 0.581935 | [
"vector"
] |
e913cf2632f7f7cbf6011f992add35694e659244 | 4,993 | cc | C++ | gazebo/math/Vector2i.cc | harderthan/gazebo | f00a0e4239ddb08b299dc21ab1ef106ecedb0fac | [
"ECL-2.0",
"Apache-2.0"
] | 1 | 2015-04-06T16:17:36.000Z | 2015-04-06T16:17:36.000Z | gazebo/math/Vector2i.cc | harderthan/gazebo | f00a0e4239ddb08b299dc21ab1ef106ecedb0fac | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | gazebo/math/Vector2i.cc | harderthan/gazebo | f00a0e4239ddb08b299dc21ab1ef106ecedb0fac | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | /*
* Copyright (C) 2012-2015 Open Source Robotics Foundation
*
* 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.
*
*/
/* Desc: Vector 2
* Author: Nate Koenig
* Date: 21 July 2007
*/
#include <math.h>
#include "gazebo/math/Vector2i.hh"
using namespace gazebo;
using namespace math;
//////////////////////////////////////////////////
Vector2i::Vector2i()
: x(0), y(0)
{
}
//////////////////////////////////////////////////
Vector2i::Vector2i(const int &_x, const int &_y)
: x(_x), y(_y)
{
}
//////////////////////////////////////////////////
Vector2i::Vector2i(const Vector2i &_pt)
: x(_pt.x), y(_pt.y)
{
}
//////////////////////////////////////////////////
Vector2i::Vector2i(const ignition::math::Vector2i &_pt)
: x(_pt.X()), y(_pt.Y())
{
}
//////////////////////////////////////////////////
Vector2i::~Vector2i()
{
}
//////////////////////////////////////////////////
int Vector2i::Distance(const Vector2i &_pt) const
{
return sqrt((this->x-_pt.x)*(this->x-_pt.x) +
(this->y-_pt.y)*(this->y-_pt.y));
}
//////////////////////////////////////////////////
void Vector2i::Normalize()
{
int d = sqrt(this->x * this->x + this->y * this->y);
this->x /= d;
this->y /= d;
}
//////////////////////////////////////////////////
void Vector2i::Set(int _x, int _y)
{
this->x = _x;
this->y = _y;
}
//////////////////////////////////////////////////
Vector2i &Vector2i::operator =(const Vector2i &_pt)
{
this->x = _pt.x;
this->y = _pt.y;
return *this;
}
//////////////////////////////////////////////////
Vector2i &Vector2i::operator=(const ignition::math::Vector2i &_pt)
{
this->x = _pt.X();
this->y = _pt.Y();
return *this;
}
//////////////////////////////////////////////////
const Vector2i &Vector2i::operator =(int _value)
{
this->x = _value;
this->y = _value;
return *this;
}
//////////////////////////////////////////////////
Vector2i Vector2i::operator+(const Vector2i &_pt) const
{
return Vector2i(this->x + _pt.x, this->y + _pt.y);
}
//////////////////////////////////////////////////
const Vector2i &Vector2i::operator+=(const Vector2i &_pt)
{
this->x += _pt.x;
this->y += _pt.y;
return *this;
}
//////////////////////////////////////////////////
Vector2i Vector2i::operator-(const Vector2i &_pt) const
{
return Vector2i(this->x - _pt.x, this->y - _pt.y);
}
//////////////////////////////////////////////////
const Vector2i &Vector2i::operator-=(const Vector2i &_pt)
{
this->x -= _pt.x;
this->y -= _pt.y;
return *this;
}
//////////////////////////////////////////////////
const Vector2i Vector2i::operator/(const Vector2i &_pt) const
{
return Vector2i(this->x / _pt.x, this->y / _pt.y);
}
//////////////////////////////////////////////////
const Vector2i &Vector2i::operator/=(const Vector2i &_pt)
{
this->x /= _pt.x;
this->y /= _pt.y;
return *this;
}
//////////////////////////////////////////////////
const Vector2i Vector2i::operator/(int _v) const
{
return Vector2i(this->x / _v, this->y / _v);
}
//////////////////////////////////////////////////
const Vector2i &Vector2i::operator/=(int _v)
{
this->x /= _v;
this->y /= _v;
return *this;
}
//////////////////////////////////////////////////
const Vector2i Vector2i::operator*(const Vector2i &_pt) const
{
return Vector2i(this->x * _pt.x, this->y * _pt.y);
}
//////////////////////////////////////////////////
const Vector2i &Vector2i::operator*=(const Vector2i &_pt)
{
this->x *= _pt.x;
this->y *= _pt.y;
return *this;
}
//////////////////////////////////////////////////
const Vector2i Vector2i::operator*(int _v) const
{
return Vector2i(this->x * _v, this->y * _v);
}
//////////////////////////////////////////////////
const Vector2i &Vector2i::operator*=(int _v)
{
this->x *= _v;
this->y *= _v;
return *this;
}
//////////////////////////////////////////////////
bool Vector2i::operator ==(const Vector2i &_pt) const
{
return this->x == _pt.x && this->y == _pt.y;
}
//////////////////////////////////////////////////
bool Vector2i::IsFinite() const
{
// integer types are always finite
return true;
}
//////////////////////////////////////////////////
int Vector2i::operator[](unsigned int index) const
{
switch (index)
{
case 0:
return this->x;
case 1:
return this->y;
default:
return 0;
}
}
//////////////////////////////////////////////////
ignition::math::Vector2i Vector2i::Ign() const
{
return ignition::math::Vector2i(this->x, this->y);
}
| 21.803493 | 75 | 0.463449 | [
"vector"
] |
e916a064238e71904bcabd364d517b4efb73c584 | 3,855 | cxx | C++ | Modules/IO/IOGDAL/src/otbGDALDriverManagerWrapper.cxx | liuxuvip/OTB | 73ed482d62c2924aea158aac14d725dc9447083b | [
"Apache-2.0"
] | 317 | 2015-01-19T08:40:58.000Z | 2022-03-17T11:55:48.000Z | Modules/IO/IOGDAL/src/otbGDALDriverManagerWrapper.cxx | guandd/OTB | 707ce4c6bb4c7186e3b102b2b00493a5050872cb | [
"Apache-2.0"
] | 18 | 2015-07-29T14:13:45.000Z | 2021-03-29T12:36:24.000Z | Modules/IO/IOGDAL/src/otbGDALDriverManagerWrapper.cxx | guandd/OTB | 707ce4c6bb4c7186e3b102b2b00493a5050872cb | [
"Apache-2.0"
] | 132 | 2015-02-21T23:57:25.000Z | 2022-03-25T16:03:16.000Z | /*
* Copyright (C) 2005-2020 Centre National d'Etudes Spatiales (CNES)
*
* This file is part of Orfeo Toolbox
*
* https://www.orfeo-toolbox.org/
*
* 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 "otbGDALDriverManagerWrapper.h"
#include <vector>
#include "otb_boost_string_header.h"
#include "otbSystem.h"
namespace otb
{
// GDALDriverManagerWrapper method implementation
GDALDriverManagerWrapper::GDALDriverManagerWrapper()
{
GDALAllRegister();
GDALDriver* driver = nullptr;
// Ignore incompatible Jpeg2000 drivers (Jasper)
driver = GetGDALDriverManager()->GetDriverByName("JPEG2000");
if (driver)
GetGDALDriverManager()->DeregisterDriver(driver);
// #ifndef CHECK_HDF4OPEN_SYMBOL
// // Get rid of the HDF4 driver when it is buggy
// driver = GetGDALDriverManager()->GetDriverByName( "hdf4" );
// if (driver)
// GetGDALDriverManager()->DeregisterDriver( driver );
// #endif
}
GDALDriverManagerWrapper::~GDALDriverManagerWrapper()
{
// calling GDALDestroyDriverManager() (or GDALDestroy) from the destructor of a
// static C++ object is unsafe.
// GDALDestroyDriverManager();
}
// Open the file for reading and returns a smart dataset pointer
GDALDatasetWrapper::Pointer GDALDriverManagerWrapper::Open(std::string filename) const
{
GDALDatasetWrapper::Pointer datasetWrapper;
// test if a driver can identify the dataset
GDALDriverH identifyDriverH = GDALIdentifyDriver(filename.c_str(), nullptr);
if (identifyDriverH == nullptr)
{
// don't try to open it and exit
return datasetWrapper;
}
GDALDriver* identifyDriver = static_cast<GDALDriver*>(identifyDriverH);
// check if Jasper will be used
if (strcmp(identifyDriver->GetDescription(), "JPEG2000") == 0)
{
itkGenericExceptionMacro(<< "Error : tried to open the file " << filename << " with GDAL driver Jasper "
"(which fails on OTB). Try setting the environment variable GDAL_SKIP"
" in order to avoid this driver.");
}
GDALDatasetH dataset = GDALOpen(filename.c_str(), GA_ReadOnly);
if (dataset != nullptr)
{
datasetWrapper = GDALDatasetWrapper::New();
datasetWrapper->m_Dataset = static_cast<GDALDataset*>(dataset);
}
return datasetWrapper;
}
// Open the new file for writing and returns a smart dataset pointer
GDALDatasetWrapper::Pointer GDALDriverManagerWrapper::Create(std::string& driverShortName, std::string filename, int nXSize, int nYSize, int nBands,
GDALDataType eType, char** papszOptions) const
{
GDALDatasetWrapper::Pointer datasetWrapper;
GDALDriver* driver = GetDriverByName(driverShortName);
if (driver != nullptr)
{
GDALDataset* dataset = driver->Create(filename.c_str(), nXSize, nYSize, nBands, eType, papszOptions);
if (dataset != nullptr)
{
datasetWrapper = GDALDatasetWrapper::New();
datasetWrapper->m_Dataset = dataset;
}
}
return datasetWrapper;
}
GDALDriver* GDALDriverManagerWrapper::GetDriverByName(std::string driverShortName) const
{
return GetGDALDriverManager()->GetDriverByName(driverShortName.c_str());
}
} // end namespace otb
| 33.232759 | 151 | 0.686641 | [
"object",
"vector"
] |
e917a3b372955b77ea90c3fb3dfad4b813c0888f | 2,538 | cpp | C++ | src/ovs/user_reader/src/Skiplist.cpp | Bilal-Tayh/q-MAX | b0999f6458eb6ba7ae89b330d7a88640b9af943c | [
"MIT"
] | 2 | 2021-03-05T02:05:44.000Z | 2021-05-26T16:13:57.000Z | src/ovs/user_reader/src/Skiplist.cpp | Bilal-Tayh/q-MAX | b0999f6458eb6ba7ae89b330d7a88640b9af943c | [
"MIT"
] | null | null | null | src/ovs/user_reader/src/Skiplist.cpp | Bilal-Tayh/q-MAX | b0999f6458eb6ba7ae89b330d7a88640b9af943c | [
"MIT"
] | 2 | 2019-12-03T12:59:40.000Z | 2021-03-05T01:49:58.000Z | #include "Skiplist.hpp"
#include <stdexcept>
#include <utility>
Skiplist::Node *Skiplist::create_node_from_int(int level, int item) {
auto *p = new Skiplist::Node(level);
p->item = item;
return p;
}
int Skiplist::random_level() {
int level = 1;
while (rand() % 2 && level < MAX_L) {
level++;
}
return level;
}
bool Skiplist::add(int item) {
bool added = false;
if (_size >= max_size) {
auto min_item = getMinimalItem();
if (item <= min_item) {
return false;
} else {
bool added = _insert(item);
if (added) {
_remove(min_item);
}
return added;
}
} else {
return _insert(item);
}
}
bool Skiplist::_insert(int item) {
Node *update[MAX_L];
Node *p = head;
Node *q = nullptr;
for (int i = level - 1; i >= 0; --i) {
q = p->next[i];
while ((q != nullptr) && (q->item < item)) {
p = q;
q = p->next[i];
}
update[i] = p;
}
if ((q != nullptr) && (q->item == item)) {
return false;
}
int rand_level = random_level();
if (rand_level > level) {
for (int i = level; i < rand_level; ++i) {
update[i] = head;
}
level = rand_level;
}
q = create_node_from_int(rand_level, item);
if (!q) {
return false;
}
for (int i = rand_level - 1; i >= 0; --i) {
q->next[i] = update[i]->next[i];
update[i]->next[i] = q;
}
++_size;
return true;
}
bool Skiplist::_remove(int item) {
Node *update[MAX_L];
Node *p = head;
Node *q = nullptr;
for (int i = level - 1; i >= 0; --i) {
q = p->next[i];
while ((q != nullptr) && (q->item < item)) {
p = q;
q = p->next[i];
}
update[i] = p;
}
if ((q == nullptr) || (q->item != item)) {
return false;
}
for (int i = level - 1; i >= 0; --i) {
if (update[i]->next[i] == q) {
update[i]->next[i] = q->next[i];
if (head->next[i] == nullptr) {
level--;
}
}
}
delete (q);
--_size;
return true;
}
inline unsigned long Skiplist::size() const {
return _size;
}
inline int Skiplist::getMinimalItem() const {
if (_size != 0) {
return head->next[0]->item;
} else {
throw std::runtime_error("can not get minimal item when Skiplist is empty.");
}
}
vector<int> Skiplist::getItems() const {
vector<int> res;
Node *q = head->next[0];
while (q != nullptr) {
res.push_back(q->item);
q = q->next[0];
}
return res;
}
void Skiplist::merge(const vector<int> &rhs) {
throw std::runtime_error("merge is not implemented for Skiplist.");
}
| 19.227273 | 81 | 0.537431 | [
"vector"
] |
e9199155ad1083e7c45b25f1c07735abc847d306 | 8,597 | cpp | C++ | scenes/inf443/03b_hierarchy/src/main.cpp | baptiste-fague/INF443 | 3a9a939afef0f596f013b7b0feef42f045a62491 | [
"MIT"
] | null | null | null | scenes/inf443/03b_hierarchy/src/main.cpp | baptiste-fague/INF443 | 3a9a939afef0f596f013b7b0feef42f045a62491 | [
"MIT"
] | null | null | null | scenes/inf443/03b_hierarchy/src/main.cpp | baptiste-fague/INF443 | 3a9a939afef0f596f013b7b0feef42f045a62491 | [
"MIT"
] | null | null | null | #include "vcl/vcl.hpp"
#include <iostream>
using namespace vcl;
struct scene_environment
{
camera_around_center camera;
mat4 projection;
vec3 light;
};
scene_environment scene;
struct gui_parameters {
bool display_frame = false;
bool display_surface = true;
bool display_wireframe = false;
};
struct user_interaction_parameters {
vec2 mouse_prev;
timer_fps fps_record;
mesh_drawable global_frame;
gui_parameters gui;
bool cursor_on_gui;
};
user_interaction_parameters user;
void mouse_move_callback(GLFWwindow* window, double xpos, double ypos);
void window_size_callback(GLFWwindow* window, int width, int height);
void initialize_data();
void display_interface();
void display_frame();
timer_interval timer;
hierarchy_mesh_drawable hierarchy;
int main(int, char* argv[])
{
std::cout << "Run " << argv[0] << std::endl;
int const width = 1280, height = 1024;
GLFWwindow* window = create_window(width, height);
window_size_callback(window, width, height);
std::cout << opengl_info_display() << std::endl;;
imgui_init(window);
glfwSetCursorPosCallback(window, mouse_move_callback);
glfwSetWindowSizeCallback(window, window_size_callback);
std::cout<<"Initialize data ..."<<std::endl;
initialize_data();
std::cout<<"Start animation loop ..."<<std::endl;
user.fps_record.start();
glEnable(GL_DEPTH_TEST);
while (!glfwWindowShouldClose(window))
{
scene.light = scene.camera.position();
user.fps_record.update();
glClearColor(1.0f, 1.0f, 1.0f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT);
glClear(GL_DEPTH_BUFFER_BIT);
imgui_create_frame();
if(user.fps_record.event) {
std::string const title = "VCL Display - "+str(user.fps_record.fps)+" fps";
glfwSetWindowTitle(window, title.c_str());
}
ImGui::Begin("GUI",NULL,ImGuiWindowFlags_AlwaysAutoResize);
user.cursor_on_gui = ImGui::IsAnyWindowFocused();
if(user.gui.display_frame) draw(user.global_frame, scene);
display_interface();
display_frame();
ImGui::End();
imgui_render_frame(window);
glfwSwapBuffers(window);
glfwPollEvents();
}
imgui_cleanup();
glfwDestroyWindow(window);
glfwTerminate();
return 0;
}
void initialize_data()
{
// Basic setups of shaders and camera
GLuint const shader_mesh = opengl_create_shader_program(opengl_shader_preset("mesh_vertex"), opengl_shader_preset("mesh_fragment"));
mesh_drawable::default_shader = shader_mesh;
mesh_drawable::default_texture = opengl_texture_to_gpu(image_raw{1,1,image_color_type::rgba,{255,255,255,255}});
user.global_frame = mesh_drawable(mesh_primitive_frame());
user.gui.display_frame = false;
scene.camera.distance_to_center = 2.5f;
scene.camera.look_at({-0.5f,2.5f,1}, {0,0,0}, {0,0,1});
// Definition of the elements of the hierarchy
// ------------------------------------------- //
float const radius_body = 0.25f;
float const radius_arm = 0.05f;
float const length_arm = 0.2f;
// The geometry of the body is a sphere
mesh_drawable body = mesh_drawable(mesh_primitive_ellipsoid({ 0.2,0.4,0.2 }, { 0,0,0 }, 40, 20));
//Geometry of head
mesh_drawable head = mesh_drawable(mesh_primitive_sphere(0.15, {0,0,0}, 20, 20));
// Geometry of the eyes: black spheres
mesh_drawable eye = mesh_drawable(mesh_primitive_sphere(0.03f, {0,0,0}, 20, 20));
eye.shading.color = {0,0,0};
//Geometry of the beak : orange cone
mesh_drawable beak = mesh_drawable(mesh_primitive_cone(0.07f, 0.13f, { 0,0,0 }, { 0,0,1 }, true, 20, 10));
beak.shading.color = { 1,0,0 };
// Shoulder part and arm are displayed as cylinder
mesh_drawable shoulder_left = mesh_drawable(mesh_primitive_quadrangle({ 0,0,0 }, { -0.3f,0,0 }, { -0.3f,0.3f,0 }, { 0,0.3f,0 }));
mesh_drawable arm_left = mesh_drawable(mesh_primitive_triangle({ 0,0,0 }, { -0.55f,0,0 }, { 0,0.3f,0 }));
mesh_drawable shoulder_right = mesh_drawable(mesh_primitive_quadrangle({ 0,0,0 }, { 0.3f,0,0 }, { 0.3f,0.3f,0 }, { 0,0.3f,0 }));
mesh_drawable arm_right = mesh_drawable(mesh_primitive_triangle({ 0,0,0 }, { 0.55f,0,0 }, { 0,0.3f,0 }));
// An elbow displayed as a sphere
mesh_drawable elbow = mesh_drawable(mesh_primitive_sphere(0.055f));
// Build the hierarchy:
// ------------------------------------------- //
// Syntax to add element
// hierarchy.add(visual_element, element_name, parent_name, (opt)[translation, rotation])
// The root of the hierarchy is the body
hierarchy.add(body, "body");
//Head position with respect to body
hierarchy.add(head, "head", "body", { 0,0.42f,0.13f });
// Eyes positions are set with respect to some ratio of the head
hierarchy.add(eye, "eye_left", "head" , 0.15 * vec3( 1/3.0f, 1/2.0f, 1/1.5f));
hierarchy.add(eye, "eye_right", "head", 0.15 * vec3(-1/3.0f, 1/2.0f, 1/1.5f));
//Beak position with repect to the head
hierarchy.add(beak, "beak", "head", {0,0.13f,-0.03f});
hierarchy["beak"].transform.rotate = rotation({ 1,0,0 }, 4.5f);
// Set the left part of the body arm: shoulder-elbow-arm
hierarchy.add(shoulder_left, "shoulder_left", "body", {-0.2f+0.05f,0,0}); // extremity of the spherical body
//hierarchy.add(elbow, "elbow_left", "shoulder_left", {-length_arm,0,0}); // place the elbow the extremity of the "shoulder cylinder"
hierarchy.add(arm_left, "arm_bottom_left", "shoulder_left", { -0.3f,0,0 }); // the arm start at the center of the elbow
// Set the right part of the body arm: similar to the left part with a symmetry in x direction
hierarchy.add(shoulder_right, "shoulder_right", "body", {0.2f-0.05f,0,0});
//hierarchy.add(elbow, "elbow_right", "shoulder_right", {length_arm,0,0});
hierarchy.add(arm_right, "arm_bottom_right", "shoulder_right", { 0.3f,0,0 });
}
void display_frame()
{
// Update the current time
timer.update();
float const t = timer.t;
/** ************************************************************* **/
/** Compute the (animated) transformations applied to the elements **/
/** ************************************************************* **/
// The body oscillate along the z direction
hierarchy["body"].transform.translate = {0,0,0.2f * (1 + std::sin(2 * 3.14f * t)) };
// Rotation of the shoulder-left around the y axis
hierarchy["shoulder_left"].transform.rotate = rotation({0,1,0}, std::sin(2*3.14f*(t-0.4f)) );
// Rotation of the arm-left around the y axis (delayed with respect to the shoulder)
hierarchy["arm_bottom_left"].transform.rotate = rotation({0,1,0}, std::sin(2*3.14f*(t-0.6f)) );
// Rotation of the shoulder-right around the y axis
hierarchy["shoulder_right"].transform.rotate = rotation({0,-1,0}, std::sin(2*3.14f*(t-0.4f)) );
// Rotation of the arm-right around the y axis (delayed with respect to the shoulder)
hierarchy["arm_bottom_right"].transform.rotate = rotation({0,-1,0}, std::sin(2*3.14f*(t-0.6f)) );
// update the global coordinates
hierarchy.update_local_to_global_coordinates();
// display the hierarchy
if(user.gui.display_surface)
draw(hierarchy, scene);
if(user.gui.display_wireframe)
draw_wireframe(hierarchy, scene);
}
void display_interface()
{
ImGui::SliderFloat("Time", &timer.t, timer.t_min, timer.t_max);
ImGui::SliderFloat("Time scale", &timer.scale, 0.0f, 2.0f);
ImGui::Checkbox("Frame", &user.gui.display_frame);
ImGui::Checkbox("Surface", &user.gui.display_surface);
ImGui::Checkbox("Wireframe", &user.gui.display_wireframe);
}
void window_size_callback(GLFWwindow* , int width, int height)
{
glViewport(0, 0, width, height);
float const aspect = width / static_cast<float>(height);
float const fov = 50.0f * pi /180.0f;
float const z_min = 0.1f;
float const z_max = 100.0f;
scene.projection = projection_perspective(fov, aspect, z_min, z_max);
}
void mouse_move_callback(GLFWwindow* window, double xpos, double ypos)
{
vec2 const p1 = glfw_get_mouse_cursor(window, xpos, ypos);
vec2 const& p0 = user.mouse_prev;
glfw_state state = glfw_current_state(window);
auto& camera = scene.camera;
if(!user.cursor_on_gui){
if(state.mouse_click_left && !state.key_ctrl)
scene.camera.manipulator_rotate_trackball(p0, p1);
if(state.mouse_click_left && state.key_ctrl)
camera.manipulator_translate_in_plane(p1-p0);
if(state.mouse_click_right)
camera.manipulator_scale_distance_to_center( (p1-p0).y );
}
user.mouse_prev = p1;
}
void opengl_uniform(GLuint shader, scene_environment const& current_scene)
{
opengl_uniform(shader, "projection", current_scene.projection);
opengl_uniform(shader, "view", current_scene.camera.matrix_view());
opengl_uniform(shader, "light", current_scene.light, false);
}
| 32.938697 | 146 | 0.693149 | [
"geometry",
"transform"
] |
e91bc92c3c2326fa2aabe240b99f5f9dc61213fd | 13,242 | hpp | C++ | include/sdsl/wt_rlmn.hpp | qPCR4vir/sdsl-lite | 3ae7ac30c3837553cf20243cc3df8ee658b9f00f | [
"BSD-3-Clause"
] | null | null | null | include/sdsl/wt_rlmn.hpp | qPCR4vir/sdsl-lite | 3ae7ac30c3837553cf20243cc3df8ee658b9f00f | [
"BSD-3-Clause"
] | null | null | null | include/sdsl/wt_rlmn.hpp | qPCR4vir/sdsl-lite | 3ae7ac30c3837553cf20243cc3df8ee658b9f00f | [
"BSD-3-Clause"
] | null | null | null | // Copyright (c) 2016, the SDSL Project Authors. All rights reserved.
// Please see the AUTHORS file for details. Use of this source code is governed
// by a BSD license that can be found in the LICENSE file.
/*! \file wt_rlmn.hpp
\brief wt_rlmn.hpp contains a class for a compressed wavelet tree.
Compression is achieved by exploiting runs in the input sequence.
\author Simon Gog
*/
#ifndef INCLUDED_SDSL_WT_RLMN
#define INCLUDED_SDSL_WT_RLMN
#include "sdsl_concepts.hpp"
#include "int_vector.hpp"
#include "sd_vector.hpp" // for standard initialisation of template parameters
#include "util.hpp"
#include "wt_huff.hpp"
#include <algorithm> // for std::swap
#include <stdexcept>
#include <vector>
#include <utility> // for pair
#include <queue>
#include <iostream>
//! Namespace for the succinct data structure library.
namespace sdsl {
template <class t_alphabet_cat>
struct wt_rlmn_trait {
enum { width = 0 };
typedef int_vector<> C_type;
typedef int_vector<> C_bf_rank_type;
static std::map<uint64_t, uint64_t> temp_C() { return std::map<uint64_t, uint64_t>(); }
static C_type init_C(std::map<uint64_t, uint64_t>& C, uint64_t size)
{
uint64_t max_symbol = (--C.end())->first;
return C_type(max_symbol + 1, 0, bits::hi(size) + 1);
}
static C_bf_rank_type init_C_bf_rank(const C_type& C, uint64_t size)
{
return C_bf_rank_type(C.size(), 0, bits::hi(size) + 1);
}
};
template <>
struct wt_rlmn_trait<byte_alphabet_tag> {
enum { width = 8 };
typedef int_vector<64> C_type;
typedef int_vector<64> C_bf_rank_type;
static int_vector<64> temp_C() { return int_vector<64>(256, 0); }
static C_type init_C(C_type& C, uint64_t) { return C; }
static C_bf_rank_type init_C_bf_rank(const C_type&, uint64_t) { return int_vector<64>(256, 0); }
};
//! A Wavelet Tree class for byte sequences.
/*!
* \par Space complexity
* \f$ nH_0 + 2|\Sigma|\log n + 2n + o(n) \f$ bits, where \f$n\f$
* is the size of the vector the wavelet tree was build for.
*
* @ingroup wt
*
* \tparam t_bitvector Type of the bitvector which is used to represent bf and
* bl which mark the head of each run in the original
* sequence.
* \tparam t_rank Type of the rank support for bitvectors bf and bl.
* \tparam t_select Type of the select support for bitvectors bf and lb.
* \tparam t_wt Type of the wavelet tree for the string consisting of
* the heads of the runs of the original sequence.
* \par Reference:
* Veli Mäkinen, Gonzalo Navarro:
* Succinct Suffix Arrays Based on Run-Length Encoding.
* CPM 2005: 45-56
*/
template <class t_bitvector = sd_vector<>,
class t_rank = typename t_bitvector::rank_1_type,
class t_select = typename t_bitvector::select_1_type,
class t_wt = wt_huff<>>
class wt_rlmn {
public:
typedef t_wt wt_type;
typedef int_vector<>::size_type size_type;
typedef typename t_wt::value_type value_type;
typedef typename t_bitvector::difference_type difference_type;
typedef random_access_const_iterator<wt_rlmn> const_iterator;
typedef const_iterator iterator;
typedef t_bitvector bit_vector_type;
typedef t_rank rank_support_type;
typedef t_select select_support_type;
typedef wt_tag index_category;
typedef typename t_wt::alphabet_category alphabet_category;
enum { lex_ordered = false }; // TODO: is should be possible
enum { width = wt_rlmn_trait<alphabet_category>::width };
typedef typename wt_rlmn_trait<alphabet_category>::C_type C_type;
typedef typename wt_rlmn_trait<alphabet_category>::C_bf_rank_type C_bf_rank_type;
// to support all lex_ordered
// operations if t_wt::lex_ordered is
// true
private:
size_type m_size = 0; // size of the original input sequence
bit_vector_type m_bl; // bit vector for starts of runs in
// the BWT (or last column), i.e. _b_ _l_ast
bit_vector_type m_bf; // bit vector for starts of runs in
// the first column of the sorted suffixes, i.e _b_ _f_irst
wt_type m_wt; // wavelet tree for all levels
// two equal chars
rank_support_type m_bl_rank; // rank support for bit vector bl
rank_support_type m_bf_rank; // rank support for bit vector bf
select_support_type m_bl_select; // select support for bit vector bl
select_support_type m_bf_select; // select support for bit vector bf
C_type m_C; //
C_bf_rank_type m_C_bf_rank; // stores the number of 1s in m_bf for
// the prefixes m_bf[0..m_C[0]],m_bf[0..m_C[1]],....,m_bf[0..m_C[255]];
// named C_s in the original paper
public:
const size_type& sigma = m_wt.sigma;
// Default constructor
wt_rlmn() = default;
//! Construct the wavelet tree from a sequence defined by two interators
/*!
* \param begin Iterator to the start of the input.
* \param end Iterator one past the end of the input.
* \param tmp_dir Temporary directory for intermediate results.
*/
template <typename t_it>
wt_rlmn(t_it begin, t_it end, std::string tmp_dir = ram_file_name(""))
: m_size(std::distance(begin, end))
{
std::string temp_file =
tmp_dir + +"_wt_rlmn_" + util::to_string(util::pid()) + "_" + util::to_string(util::id());
{
if (0 == m_size) return;
int_vector_buffer<width> condensed_wt(temp_file, std::ios::out);
// scope for bl and bf
bit_vector bl = bit_vector(m_size, 0);
auto C = wt_rlmn_trait<alphabet_category>::temp_C();
value_type last_c = (value_type)0;
size_type j = 0;
for (auto it = begin; it != end; ++it, ++j) {
value_type c = *it;
if (last_c != c or it == begin) {
bl[j] = 1;
condensed_wt.push_back(c);
}
++C[c];
last_c = c;
}
condensed_wt.close();
m_C = wt_rlmn_trait<alphabet_category>::init_C(C, m_size);
for (size_type i = 0, prefix_sum = 0; i < m_C.size(); ++i) {
m_C[i] = prefix_sum;
prefix_sum += C[i];
}
C_type lf_map = m_C;
bit_vector bf = bit_vector(m_size + 1, 0);
bf[m_size] = 1; // initialize last element
j = 0;
for (auto it = begin; it != end; ++it, ++j) {
value_type c = *it;
if (bl[j]) {
bf[lf_map[c]] = 1;
}
++lf_map[c];
}
{
int_vector_buffer<width> temp_bwt_buf(temp_file);
m_wt = wt_type(temp_bwt_buf.begin(), temp_bwt_buf.end(), tmp_dir);
}
sdsl::remove(temp_file);
m_bl = bit_vector_type(std::move(bl));
m_bf = bit_vector_type(std::move(bf));
}
util::init_support(m_bl_rank, &m_bl);
util::init_support(m_bf_rank, &m_bf);
util::init_support(m_bf_select, &m_bf);
util::init_support(m_bl_select, &m_bl);
m_C_bf_rank = wt_rlmn_trait<alphabet_category>::init_C_bf_rank(m_C, m_size);
for (size_type i = 0; i < m_C.size(); ++i) {
m_C_bf_rank[i] = m_bf_rank(m_C[i]);
}
}
//! Copy constructor
wt_rlmn(const wt_rlmn& wt)
: m_size(wt.m_size)
, m_bl(wt.m_bl)
, m_bf(wt.m_bf)
, m_wt(wt.m_wt)
, m_bl_rank(wt.m_bl_rank)
, m_bf_rank(wt.m_bf_rank)
, m_bl_select(wt.m_bl_select)
, m_bf_select(wt.m_bf_select)
, m_C(wt.m_C)
, m_C_bf_rank(wt.m_C_bf_rank)
{
m_bl_rank.set_vector(&m_bl);
m_bf_rank.set_vector(&m_bf);
m_bl_select.set_vector(&m_bl);
m_bf_select.set_vector(&m_bf);
}
//! Move constructor
wt_rlmn(wt_rlmn&& wt)
: m_size(wt.m_size)
, m_bl(std::move(wt.m_bl))
, m_bf(std::move(wt.m_bf))
, m_wt(std::move(wt.m_wt))
, m_bl_rank(std::move(wt.m_bl_rank))
, m_bf_rank(std::move(wt.m_bf_rank))
, m_bl_select(std::move(wt.m_bl_select))
, m_bf_select(std::move(wt.m_bf_select))
, m_C(std::move(wt.m_C))
, m_C_bf_rank(std::move(wt.m_C_bf_rank))
{
m_bl_rank.set_vector(&m_bl);
m_bf_rank.set_vector(&m_bf);
m_bl_select.set_vector(&m_bl);
m_bf_select.set_vector(&m_bf);
}
//! Assignment operator
wt_rlmn& operator=(const wt_rlmn& wt)
{
if (this != &wt) {
wt_rlmn tmp(wt);
*this = std::move(tmp);
}
return *this;
}
//! Assignment move operator
wt_rlmn& operator=(wt_rlmn&& wt)
{
if (this != &wt) {
m_size = std::move(wt.m_size);
m_bl = std::move(wt.m_bl);
m_bf = std::move(wt.m_bf);
m_wt = std::move(wt.m_wt);
m_bl_rank = std::move(wt.m_bl_rank);
m_bl_rank.set_vector(&m_bl);
m_bf_rank = std::move(wt.m_bf_rank);
m_bf_rank.set_vector(&m_bf);
m_bl_select = std::move(wt.m_bl_select);
m_bl_select.set_vector(&m_bl);
m_bf_select = std::move(wt.m_bf_select);
m_bf_select.set_vector(&m_bf);
m_C = std::move(wt.m_C);
m_C_bf_rank = std::move(wt.m_C_bf_rank);
}
return *this;
}
//! Returns the size of the original vector.
size_type size() const { return m_size; }
//! Returns whether the wavelet tree contains no data.
bool empty() const { return 0 == m_size; }
//! Recovers the i-th symbol of the original vector.
/*! \param i Index in the original vector. \f$i \in [0..size()-1]\f$.
* \return The i-th symbol of the original vector.
* \par Time complexity
* \f$ \Order{H_0} \f$ on average, where \f$ H_0 \f$ is the
* zero order entropy of the sequence
*/
value_type operator[](size_type i) const
{
assert(i < size());
return m_wt[m_bl_rank(i + 1) - 1];
};
//! Calculates how many symbols c are in the prefix [0..i-1].
/*!
* \param i Exclusive right bound of the range (\f$i\in[0..size()]\f$).
* \param c Symbol c.
* \return Number of occurrences of symbol c in the prefix [0..i-1].
* \par Time complexity
* \f$ \Order{H_0} \f$ on average, where \f$ H_0 \f$ is the
* zero order entropy of the sequence
*/
size_type rank(size_type i, value_type c) const
{
assert(i <= size());
if (i == 0) return 0;
size_type wt_ex_pos = m_bl_rank(i);
size_type c_runs = m_wt.rank(wt_ex_pos, c);
if (c_runs == 0) return 0;
if (m_wt[wt_ex_pos - 1] == c) {
size_type c_run_begin = m_bl_select(wt_ex_pos);
return m_bf_select(m_C_bf_rank[c] + c_runs) - m_C[c] + i - c_run_begin;
} else {
return m_bf_select(m_C_bf_rank[c] + c_runs + 1) - m_C[c];
}
};
//! Calculates how many times symbol wt[i] occurs in the prefix [0..i-1].
/*!
* \param i The index of the symbol.
* \return Pair (rank(wt[i],i),wt[i])
* \par Time complexity
* \f$ \Order{H_0} \f$
*/
std::pair<size_type, value_type> inverse_select(size_type i) const
{
assert(i < size());
if (i == 0) {
return std::make_pair(0, m_wt[0]);
}
size_type wt_ex_pos = m_bl_rank(i + 1);
auto rc = m_wt.inverse_select(wt_ex_pos - 1);
size_type c_runs = rc.first + 1;
value_type c = rc.second;
if (c_runs == 0) return std::make_pair(0, c);
if (m_wt[wt_ex_pos - 1] == c) {
size_type c_run_begin = m_bl_select(wt_ex_pos);
return std::make_pair(m_bf_select(m_C_bf_rank[c] + c_runs) - m_C[c] + i - c_run_begin,
c);
} else {
return std::make_pair(m_bf_select(m_C_bf_rank[c] + c_runs + 1) - m_C[c], c);
}
}
//! Calculates the ith occurrence of the symbol c in the supported vector.
/*!
* \param i The ith occurrence. \f$i\in [1..rank(size(),c)]\f$.
* \param c The symbol c.
* \par Time complexity
* \f$ \Order{H_0} \f$ on average, where \f$ H_0 \f$ is the zero order
* entropy of the sequence
*/
size_type select(size_type i, value_type c) const
{
assert(i > 0);
assert(i <= rank(size(), c));
size_type c_runs = m_bf_rank(m_C[c] + i) - m_C_bf_rank[c];
size_type offset = m_C[c] + i - 1 - m_bf_select(c_runs + m_C_bf_rank[c]);
return m_bl_select(m_wt.select(c_runs, c) + 1) + offset;
};
//! Returns a const_iterator to the first element.
const_iterator begin() const { return const_iterator(this, 0); }
//! Returns a const_iterator to the element after the last element.
const_iterator end() const { return const_iterator(this, size()); }
//! Serializes the data structure into the given ostream
size_type
serialize(std::ostream& out, structure_tree_node* v = nullptr, std::string name = "") const
{
structure_tree_node* child = structure_tree::add_child(v, name, util::class_name(*this));
size_type written_bytes = 0;
written_bytes += write_member(m_size, out, child, "size");
written_bytes += m_bl.serialize(out, child, "bl");
written_bytes += m_bf.serialize(out, child, "bf");
written_bytes += m_wt.serialize(out, child, "wt");
written_bytes += m_bl_rank.serialize(out, child, "bl_rank");
written_bytes += m_bf_rank.serialize(out, child, "bf_rank");
written_bytes += m_bl_select.serialize(out, child, "bl_select");
written_bytes += m_bf_select.serialize(out, child, "bf_select");
written_bytes += m_C.serialize(out, child, "C");
written_bytes += m_C_bf_rank.serialize(out, child, "C_bf_rank");
structure_tree::add_size(child, written_bytes);
return written_bytes;
}
//! Loads the data structure from the given istream.
void load(std::istream& in)
{
read_member(m_size, in);
m_bl.load(in);
m_bf.load(in);
m_wt.load(in);
m_bl_rank.load(in, &m_bl);
m_bf_rank.load(in, &m_bf);
m_bl_select.load(in, &m_bl);
m_bf_select.load(in, &m_bf);
m_C.load(in);
m_C_bf_rank.load(in);
}
};
} // end namespace sdsl
#endif
| 33.271357 | 97 | 0.659568 | [
"vector"
] |
e91cabb222375f02a62f9b5d46b33ee2596899e7 | 2,400 | cpp | C++ | 2020/23day/cpp/task2.cpp | zagura/aoc-2017 | bfd38fb6fbe4211017a306d218b32ecff741e006 | [
"MIT"
] | 2 | 2018-12-09T16:00:09.000Z | 2018-12-09T17:56:15.000Z | 2020/23day/cpp/task2.cpp | zagura/aoc-2017 | bfd38fb6fbe4211017a306d218b32ecff741e006 | [
"MIT"
] | null | null | null | 2020/23day/cpp/task2.cpp | zagura/aoc-2017 | bfd38fb6fbe4211017a306d218b32ecff741e006 | [
"MIT"
] | null | null | null | /*
* =====================================================================================
*
* Filename: task1.cpp
*
* Description: Advent of Code 2020 - Day 23
*
* Version: 0.2.0
* Created: 02.01.2021
*
* Author: Michał Zagórski (zagura), <zagura6@gmail.com>
*
* =====================================================================================
*/
#include <iostream>
#include <string>
#include <fstream>
#include <sstream>
#include <algorithm>
#include <array>
#include <map>
#include <list>
#include <vector>
#include <cinttypes>
constexpr int million = 1000 * 1000;
constexpr size_t kCupsSize = million;
constexpr int kRoundCount = 10 * million;
constexpr size_t kPickupSize = 3;
using std::string;
using std::vector;
using std::array;
using std::map;
using std::stringstream;
using Cups = std::vector<int>;
void next_move(Cups& cups, int& current) {
std::array<int, kPickupSize> pick_up;
pick_up[0] = cups[current];
for (size_t i = 1; i < kPickupSize; i++) {
pick_up[i] = cups[pick_up[i-1]];
}
// Skip pick_up part
int destination = current - 1;
current = cups[current] = cups[pick_up.back()];
if (destination == 0) {
destination = kCupsSize;
}
while (std::find(pick_up.begin(), pick_up.end(), destination) != pick_up.end()) {
destination--;
if (destination < 1) {
destination = kCupsSize;
}
}
cups[pick_up.back()] = cups[destination];
cups[destination] = pick_up.front();
}
int main(int argc, char* argv[]) {
std::ifstream input { "input.in" };
if (argc == 2) {
input = std::ifstream { argv[1] };
}
if (!input.good()) {
::fprintf(stderr, "Cannot open input file\n");
return 2;
}
string line;
getline(input, line);
Cups cups {};
cups.resize(kCupsSize + 1);
int last = kCupsSize;
int start = line.front() - '0';
for (char c: line) {
int val = c - '0';
cups[last] = val;
last = val;
}
for (size_t s = line.size() + 1; s <= kCupsSize; ++s) {
cups[last] = s;
last = s;
}
for (size_t round = 0; round < kRoundCount; round++) {
next_move(cups, start);
}
uint64_t a = cups[1];
uint64_t b = cups[a];
printf("\n");
printf("Part 2 result: %" PRIu64 "\n", a * b);
return 0;
}
| 23.529412 | 88 | 0.524583 | [
"vector"
] |
e91dc58dbdfbbcac273bdd592f70622023b59863 | 1,694 | cpp | C++ | library/game/game_map.cpp | chegoryu/auralux | 236c681260f51b0ff4ad5592324b012bf3204162 | [
"MIT"
] | 1 | 2021-06-15T15:51:23.000Z | 2021-06-15T15:51:23.000Z | library/game/game_map.cpp | chegoryu/auralux | 236c681260f51b0ff4ad5592324b012bf3204162 | [
"MIT"
] | 1 | 2021-06-18T07:26:38.000Z | 2021-06-18T10:48:55.000Z | library/game/game_map.cpp | chegoryu/auralux | 236c681260f51b0ff4ad5592324b012bf3204162 | [
"MIT"
] | 2 | 2021-06-17T14:50:24.000Z | 2021-06-18T07:09:24.000Z | //
// Created by Egor Chunaev on 14.06.2021.
//
#include "game_map.h"
#include <cmath>
#include <stdexcept>
#include <string>
TGameMap LoadPlanarGraph(int maxDistBetweenPlanets, std::function<int()> readInt) {
TGameMap gameMap;
int planetCount = readInt();
int playerCount = readInt();
for (int i = 0; i < playerCount; ++i) {
gameMap.StartPlanets_.push_back(readInt());
}
gameMap.Points_ = std::vector<TGameMap::TPoint>();
gameMap.Points_->resize(planetCount);
for (int i = 0; i < planetCount; ++i) {
gameMap.Points_->at(i).x = readInt();
gameMap.Points_->at(i).y = readInt();
}
gameMap.Dists_.resize(planetCount, std::vector<int>(planetCount, 0));
for (int i = 0; i < planetCount; ++i) {
for (int j = i + 1; j < planetCount; ++j) {
long long int dx = gameMap.Points_->at(i).x - gameMap.Points_->at(j).x;
long long int dy = gameMap.Points_->at(i).y - gameMap.Points_->at(j).y;
long long int sqDist = dx * dx + dy * dy;
int dist = std::round(sqrtl(sqDist));
if (dist <= 0 || dist > maxDistBetweenPlanets) {
throw std::runtime_error(
"distance between "
+ std::to_string(i + 1)
+ " and "
+ std::to_string(j + 1)
+ " is " + std::to_string(dist)
+ " but allowed distance range is "
+ "[" + std::to_string(1) + "; " + std::to_string(maxDistBetweenPlanets) + "]"
);
}
gameMap.Dists_[i][j] = gameMap.Dists_[j][i] = dist;
}
}
return gameMap;
}
| 31.37037 | 98 | 0.524793 | [
"vector"
] |
11e69bfeeb04463daf8b80fd839499411f85a44d | 15,753 | cpp | C++ | C++/Example/mainwindow.cpp | sunoval2016/RoboDK-API | 47a4905f8021b5b75fea0300136ea1ea8bb3e33d | [
"Apache-2.0"
] | null | null | null | C++/Example/mainwindow.cpp | sunoval2016/RoboDK-API | 47a4905f8021b5b75fea0300136ea1ea8bb3e33d | [
"Apache-2.0"
] | null | null | null | C++/Example/mainwindow.cpp | sunoval2016/RoboDK-API | 47a4905f8021b5b75fea0300136ea1ea8bb3e33d | [
"Apache-2.0"
] | null | null | null | #include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QFileDialog>
#include <QWindow>
#ifdef WIN32
// this is used to integrate RoboDK window as a child window
#include <windows.h>
#pragma comment(lib,"user32.lib")
#endif
//#include <thread>
#define M_PI 3.14159265358979323846
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
robodk_window = NULL;
ui->setupUi(this);
ui->widgetRoboDK->hide();
adjustSize();
// Start RoboDK API here (RoboDK will start if it is not running)
ROBOT = NULL;
RDK = new RoboDK();
if (!RDK->Connected()){
qDebug() << "Failed to start RoboDK API!!";
}
}
MainWindow::~MainWindow() {
robodk_window_clear();
RDK->CloseRoboDK();
delete ui;
delete RDK;
}
bool MainWindow::Check_RoboDK(){
if (RDK == NULL){
statusBar()->showMessage("RoboDK API is not connected");
return false;
}
if (!RDK->Connected()){
statusBar()->showMessage("RoboDK is not running");
return false;
}
return true;
}
bool MainWindow::Check_Robot(){
if (!Check_RoboDK()){ return false; }
if (ROBOT == NULL){
statusBar()->showMessage("Select a robot first");
return false;
}
if (!ROBOT->Valid()){
statusBar()->showMessage("Robot item is not valid");
return false;
}
return true;
}
void MainWindow::Select_Robot(){
if (ROBOT != NULL){
delete ROBOT;
ROBOT = NULL;
}
ROBOT = new Item(RDK->ItemUserPick("Select a robot", RoboDK::ITEM_TYPE_ROBOT));
//ROBOT = new Item(RDK->getItem("UR10", RoboDK::ITEM_TYPE_ROBOT));
if (Check_Robot()){
statusBar()->showMessage("Robot selected: " + ROBOT->Name());
}
}
void MainWindow::on_btnLoadFile_clicked() {
if (!Check_RoboDK()){ return; }
QStringList files = QFileDialog::getOpenFileNames(this, tr("Open one or more files with RoboDK"));
foreach (QString file, files){
qDebug() << "Loading: " << file;
RDK->AddFile(file);
}
if (!Check_Robot()){
Select_Robot();
}
}
void MainWindow::on_btnSelectRobot_clicked(){
Select_Robot();
}
void MainWindow::on_btnGetPosition_clicked(){
if (!Check_Robot()){ return; }
QString separator = " , ";
int decimals = 1;
// Get robot joints
tJoints joints(ROBOT->Joints());
QString joints_str = joints.ToString(separator, decimals);
ui->txtJoints->setText(joints_str);
// Get robot pose
Mat robot_pose(ROBOT->Pose());
QString pose_str = robot_pose.ToString(separator, decimals);
ui->txtXYZWPR->setText(pose_str);
}
void MainWindow::on_btnMoveJoints_clicked(){
if (!Check_Robot()){ return; }
tJoints joints;
joints.FromString(ui->txtJoints->text());
bool blocking = true;
ROBOT->MoveJ(joints, blocking);
}
void MainWindow::on_btnMovePose_clicked(){
if (!Check_Robot()){ return; }
Mat pose;
pose.FromString(ui->txtXYZWPR->text());
bool blocking = true;
ROBOT->MoveJ(pose, blocking);
}
void MainWindow::on_btnProgRun_clicked(){
if (!Check_Robot()){ return; }
QString program_name = ui->txtProgName->text();
RDK->RunProgram(program_name);
}
// Example to run a second instance of the RoboDK api in parallel:
// make sure to include #include <thread>
//std::thread *t1 = new std::thread(blocking_task);
/*
void blocking_task(){
RoboDK rdk; // important! It will not block the main thread (blocking or non blocking won'T make a difference)
// show the blocking popup:
rdk.Popup_ISO9283_CubeProgram();
}
*/
// then, start the thread and let it finish once the user finishes with the popup
void MainWindow::on_btnTestButton_clicked(){
if (!Check_Robot()){ return; }
//int runmode = RDK->RunMode(); // retrieve the run mode
//RoboDK *RDK = new RoboDK();
//Item *ROBOT = new Item(RDK->getItem("Motoman SV3"));
// Draw a hexagon inside a circle of radius 100.0 mm
int n_sides = 6;
float size = 100.0;
// retrieve the reference frame and the tool frame (TCP)
Mat pose_frame = ROBOT->PoseFrame();
Mat pose_tool = ROBOT->PoseTool();
Mat pose_ref = ROBOT->Pose();
// Program start
ROBOT->MoveJ(pose_ref);
ROBOT->setPoseFrame(pose_frame); // set the reference frame
ROBOT->setPoseTool(pose_tool); // set the tool frame: important for Online Programming
ROBOT->setSpeed(100); // Set Speed to 100 mm/s
ROBOT->setRounding(5); // set the rounding instruction (C_DIS & APO_DIS / CNT / ZoneData / Blend Radius / ...)
ROBOT->RunInstruction("CallOnStart"); // run a program
for (int i = 0; i <= n_sides; i++) {
// calculate angle in degrees:
double angle = ((double) i / n_sides) * 360.0;
// create a pose relative to the pose_ref
Mat pose_i(pose_ref);
pose_i.rotate(angle,0,0,1.0);
pose_i.translate(size, 0, 0);
pose_i.rotate(-angle,0,0,1.0);
// add a comment (when generating code)
ROBOT->RunInstruction("Moving to point " + QString::number(i), RoboDK::INSTRUCTION_COMMENT);
// example to retrieve the pose as Euler angles (X,Y,Z,W,P,R)
double xyzwpr[6];
pose_i.ToXYZRPW(xyzwpr);
ROBOT->MoveL(pose_i); // move the robot
}
ROBOT->RunInstruction("CallOnFinish");
ROBOT->MoveL(pose_ref); // move back to the reference point
return;
// Example to iterate through all the existing targets in the station (blocking):
QList<Item> targets = RDK->getItemList(RoboDK::ITEM_TYPE_TARGET);
foreach (Item target, targets){
if (target.Type() == RoboDK::ITEM_TYPE_TARGET){
ui->statusBar->showMessage("Moving to: " + target.Name());
qApp->processEvents();
ROBOT->MoveJ(target);
}
}
return;
QList<Item> list = RDK->getItemList();
Mat pose_robot_base_abs = ROBOT->PoseAbs();
Mat pose_robot = ROBOT->Pose();
Mat pose_tcp = ROBOT->PoseTool();
qDebug() << "Absolute Position of the robot:";
qDebug() << pose_robot_base_abs;
qDebug() << "Current robot position (active tool with respect to the active reference):";
qDebug() << pose_robot;
qDebug() << "Position of the active TCP:";
qDebug() << pose_tcp;
QList<Item> tool_list = ROBOT->Childs();
if (tool_list.length() <= 0){
statusBar()->showMessage("No tools available for the robot " + ROBOT->Name());
return;
}
Item tool = tool_list.at(0);
qDebug() << "Using tool: " << tool.Name();
Mat pose_robot_flange_abs = tool.PoseAbs();
pose_tcp = tool.PoseTool();
Mat pose_tcp_abs = pose_robot_flange_abs * pose_tcp;
Item object = RDK->getItem("", RoboDK::ITEM_TYPE_FRAME);
Mat pose_object_abs = object.PoseAbs();
qDebug() << pose_tcp;
Mat tcp_wrt_obj = pose_object_abs.inverted() * pose_tcp_abs;
qDebug() << "Pose of the TCP with respect to the selected reference frame";
qDebug() << tcp_wrt_obj;
tXYZWPR xyzwpr;
tcp_wrt_obj.ToXYZRPW(xyzwpr);
this->statusBar()->showMessage(QString("Tool with respect to %1").arg(object.Name()) + QString(": [X,Y,Z,W,P,R]=[%1, %2, %3, %4, %5, %6] mm/deg").arg(xyzwpr[0],0,'f',3).arg(xyzwpr[1],0,'f',3).arg(xyzwpr[2],0,'f',3).arg(xyzwpr[3],0,'f',3).arg(xyzwpr[4],0,'f',3).arg(xyzwpr[5],0,'f',3) );
// Example to define a reference frame given 3 points:
tMatrix2D* framePts = Matrix2D_Create();
Matrix2D_Set_Size(framePts, 3, 3);
double *p1 = Matrix2D_Get_col(framePts, 0);
double *p2 = Matrix2D_Get_col(framePts, 1);
double *p3 = Matrix2D_Get_col(framePts, 2);
// Define point 1:
p1[0] = 100;
p1[1] = 200;
p1[2] = 300;
// Define point 2:
p2[0] = 500;
p2[1] = 200;
p2[2] = 300;
// Define point 3:
p3[0] = 100;
p3[1] = 500;
p3[2] = 300;
Mat diagLocalFrame = RDK->CalibrateReference(framePts, RoboDK::CALIBRATE_FRAME_3P_P1_ON_X);
Item localPlaneFrame = RDK->AddFrame("Plane Coord");
localPlaneFrame.setPose(diagLocalFrame);
Matrix2D_Delete(&framePts);
return;
// Inverse kinematics test:
//Mat tool_pose = transl(10,20,30);
//Mat ref_pose = transl(100, 100,500);
qDebug() << "Testing pose:";
qDebug() << "Using robot: " << ROBOT;
Mat pose_test(0.733722985, 0.0145948902, -0.679291904, -814.060547, 0.000000000, -0.999769211, -0.0214804877, -8.96536446, -0.679448724, 0.0157607272, -0.733553648, 340.561951);
ROBOT->setAccuracyActive(1);
pose_test.MakeHomogeneous();
qDebug() << pose_test;
// Calculate a single solution (closest to the current robot position):
tJoints joints = ROBOT->SolveIK(pose_test); //, &tool_pose, &ref_pose);
qDebug() << "Solution : " << joints;
// Iterate through all possible solutions
// Calculate all nominal solutions:
ROBOT->setAccuracyActive(0);
auto all_solutions = ROBOT->SolveIK_All(pose_test); //, &tool_pose, &ref_pose);
// Use accurate kinematics and calculate inverse kinematics using the closest point
ROBOT->setAccuracyActive(1);
for (int i=0; i<all_solutions.length(); i++){
tJoints joints_nominal_i = all_solutions.at(i);
qDebug() << "Nominal solution " << i << ": " << joints_nominal_i;
tJoints joints_accurate_i = ROBOT->SolveIK(pose_test, joints_nominal_i); //, &tool_pose, &ref_pose);
qDebug() << "Accurate solution " << i << ": " << joints_accurate_i;
}
/*qDebug() << joints.ToString();
tJoints joints = ROBOT->SolveIK(pose_problems);
qDebug() << joints.ToString();
*/
return;
/*
// Example to create the ISO cube program
tXYZ xyz;
xyz[0] = 100;
xyz[1] = 200;
xyz[2] = 300;
RDK->Popup_ISO9283_CubeProgram(ROBOT, xyz, 100, false);
return;
*/
}
void MainWindow::on_btnTXn_clicked(){ IncrementalMove(0, -1); }
void MainWindow::on_btnTYn_clicked(){ IncrementalMove(1, -1); }
void MainWindow::on_btnTZn_clicked(){ IncrementalMove(2, -1); }
void MainWindow::on_btnRXn_clicked(){ IncrementalMove(3, -1); }
void MainWindow::on_btnRYn_clicked(){ IncrementalMove(4, -1); }
void MainWindow::on_btnRZn_clicked(){ IncrementalMove(5, -1); }
void MainWindow::on_btnTXp_clicked(){ IncrementalMove(0, +1); }
void MainWindow::on_btnTYp_clicked(){ IncrementalMove(1, +1); }
void MainWindow::on_btnTZp_clicked(){ IncrementalMove(2, +1); }
void MainWindow::on_btnRXp_clicked(){ IncrementalMove(3, +1); }
void MainWindow::on_btnRYp_clicked(){ IncrementalMove(4, +1); }
void MainWindow::on_btnRZp_clicked(){ IncrementalMove(5, +1); }
void MainWindow::IncrementalMove(int id, double sense){
if (!Check_Robot()) { return; }
// check the index
if (id < 0 || id >= 6){
qDebug()<< "Invalid id provided to for an incremental move";
return;
}
// calculate the relative movement
double step = sense * ui->spnStep->value();
// apply to XYZWPR
tXYZWPR xyzwpr;
for (int i=0; i<6; i++){
xyzwpr[i] = 0;
}
xyzwpr[id] = step;
Mat pose_increment;
pose_increment.FromXYZRPW(xyzwpr);
Mat pose_robot = ROBOT->Pose();
Mat pose_robot_new;
// apply relative to the TCP:
pose_robot_new = pose_robot * pose_increment;
ROBOT->MoveJ(pose_robot_new);
}
void MainWindow::on_radSimulation_clicked()
{
if (!Check_Robot()) { return; }
// Important: stop any previous program generation (if we selected offline programming mode)
ROBOT->Finish();
// Set simulation mode
RDK->setRunMode(RoboDK::RUNMODE_SIMULATE);
}
void MainWindow::on_radOfflineProgramming_clicked()
{
if (!Check_Robot()) { return; }
// Important: stop any previous program generation (if we selected offline programming mode)
ROBOT->Finish();
// Set simulation mode
RDK->setRunMode(RoboDK::RUNMODE_MAKE_ROBOTPROG);
// specify a program name, a folder to save the program and a post processor if desired
RDK->ProgramStart("NewProgram");
}
void MainWindow::on_radRunOnRobot_clicked()
{
if (!Check_Robot()) { return; }
// Important: stop any previous program generation (if we selected offline programming mode)
ROBOT->Finish();
// Connect to real robot
if (ROBOT->Connect())
{
// Set simulation mode
RDK->setRunMode(RoboDK::RUNMODE_RUN_ROBOT);
}
else
{
ui->statusBar->showMessage("Can't connect to the robot. Check connection and parameters.");
}
}
void MainWindow::on_btnMakeProgram_clicked()
{
if (!Check_Robot()) { return; }
// Trigger program generation
ROBOT->Finish();
}
void MainWindow::robodk_window_clear(){
if (robodk_window != NULL){
robodk_window->setParent(NULL);
robodk_window->setFlags(Qt::Window);
//robodk_window->deleteLater();
robodk_window = NULL;
ui->widgetRoboDK->layout()->deleteLater();
}
// Make sure RoboDK widget is hidden
ui->widgetRoboDK->hide();
// Adjust the main window size
adjustSize();
}
void MainWindow::on_radShowRoboDK_clicked()
{
if (!Check_RoboDK()){ return; }
// Hide embedded window
robodk_window_clear();
RDK->setWindowState(RoboDK::WINDOWSTATE_NORMAL);
RDK->setWindowState(RoboDK::WINDOWSTATE_SHOW);
}
void MainWindow::on_radHideRoboDK_clicked()
{
if (!Check_RoboDK()){ return; }
// Hide embedded window
robodk_window_clear();
RDK->setWindowState(RoboDK::WINDOWSTATE_HIDDEN);
}
#ifdef _MSC_VER
HWND FindTopWindow(DWORD pid)
{
std::pair<HWND, DWORD> params = { 0, pid };
// Enumerate the windows using a lambda to process each window
BOOL bResult = EnumWindows([](HWND hwnd, LPARAM lParam) -> BOOL
{
auto pParams = (std::pair<HWND, DWORD>*)(lParam);
DWORD processId;
if (GetWindowThreadProcessId(hwnd, &processId) && processId == pParams->second)
{
// Stop enumerating
SetLastError(-1);
pParams->first = hwnd;
return FALSE;
}
// Continue enumerating
return TRUE;
}, (LPARAM)¶ms);
if (!bResult && GetLastError() == -1 && params.first)
{
return params.first;
}
return 0;
}
#endif
void MainWindow::on_radIntegrateRoboDK_clicked()
{
if (!Check_RoboDK()){ return; }
qint64 procWID = RDK->ProcessID();
if (procWID == 0) {
ui->statusBar->showMessage("Invalid handle. Close RoboDK and open RoboDK with this application");
return;
}
#ifdef _MSC_VER
if (procWID != 0){
qDebug() << "Using parent process=" << procWID;
//SetParent((HWND) procWID, (HWND)widget_container->window()->winId());
// Retrieve the top level window
HWND wid_rdk = FindTopWindow(procWID);
qDebug() << "HWND RoboDK window: " << wid_rdk;
//SetParent((HWND) wid_rdk, (HWND)widget_container->winId());//->window()->winId());
if (wid_rdk == NULL){
ui->statusBar->showMessage("RoboDK top level window was not found...");
return;
}
//HWND wid_rdk = (HWND) RDK->WindowID();
// set parent widget
robodk_window = QWindow::fromWinId((WId)wid_rdk);
QWidget *new_widget = createWindowContainer(robodk_window);
QVBoxLayout *vl = new QVBoxLayout();
ui->widgetRoboDK->setLayout(vl);
vl->addWidget(new_widget);
new_widget->show();
this->adjustSize();
RDK->setWindowState(RoboDK::WINDOWSTATE_SHOW);
RDK->setWindowState(RoboDK::WINDOWSTATE_FULLSCREEN_CINEMA);
// Show the RoboDK widget (embedded screen)
ui->widgetRoboDK->show();
}
#endif
}
| 27.492147 | 290 | 0.633911 | [
"object"
] |
11e94fc0da2dda6b0915395bf8ab96c95b1876ee | 21,731 | cpp | C++ | lib/parser/expr-parsers.cpp | arjunsuresh1987/f18 | 35fd0cda58776389d2ed68eaefbc1e1d59423ec8 | [
"Apache-2.0"
] | null | null | null | lib/parser/expr-parsers.cpp | arjunsuresh1987/f18 | 35fd0cda58776389d2ed68eaefbc1e1d59423ec8 | [
"Apache-2.0"
] | null | null | null | lib/parser/expr-parsers.cpp | arjunsuresh1987/f18 | 35fd0cda58776389d2ed68eaefbc1e1d59423ec8 | [
"Apache-2.0"
] | null | null | null | //===-- lib/parser/expr-parsers.cpp ---------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
// Per-type parsers for expressions.
#include "expr-parsers.h"
#include "basic-parsers.h"
#include "debug-parser.h"
#include "misc-parsers.h"
#include "stmt-parser.h"
#include "token-parsers.h"
#include "type-parser-implementation.h"
#include "flang/parser/characters.h"
#include "flang/parser/parse-tree.h"
namespace Fortran::parser {
// R764 boz-literal-constant -> binary-constant | octal-constant | hex-constant
// R765 binary-constant -> B ' digit [digit]... ' | B " digit [digit]... "
// R766 octal-constant -> O ' digit [digit]... ' | O " digit [digit]... "
// R767 hex-constant ->
// Z ' hex-digit [hex-digit]... ' | Z " hex-digit [hex-digit]... "
// extension: X accepted for Z
// extension: BOZX suffix accepted
TYPE_PARSER(construct<BOZLiteralConstant>(BOZLiteral{}))
// R769 array-constructor -> (/ ac-spec /) | lbracket ac-spec rbracket
TYPE_CONTEXT_PARSER("array constructor"_en_US,
construct<ArrayConstructor>(
"(/" >> Parser<AcSpec>{} / "/)" || bracketed(Parser<AcSpec>{})))
// R770 ac-spec -> type-spec :: | [type-spec ::] ac-value-list
TYPE_PARSER(construct<AcSpec>(maybe(typeSpec / "::"),
nonemptyList("expected array constructor values"_err_en_US,
Parser<AcValue>{})) ||
construct<AcSpec>(typeSpec / "::"))
// R773 ac-value -> expr | ac-implied-do
TYPE_PARSER(
// PGI/Intel extension: accept triplets in array constructors
extension<LanguageFeature::TripletInArrayConstructor>(
construct<AcValue>(construct<AcValue::Triplet>(scalarIntExpr,
":" >> scalarIntExpr, maybe(":" >> scalarIntExpr)))) ||
construct<AcValue>(indirect(expr)) ||
construct<AcValue>(indirect(Parser<AcImpliedDo>{})))
// R774 ac-implied-do -> ( ac-value-list , ac-implied-do-control )
TYPE_PARSER(parenthesized(
construct<AcImpliedDo>(nonemptyList(Parser<AcValue>{} / lookAhead(","_tok)),
"," >> Parser<AcImpliedDoControl>{})))
// R775 ac-implied-do-control ->
// [integer-type-spec ::] ac-do-variable = scalar-int-expr ,
// scalar-int-expr [, scalar-int-expr]
// R776 ac-do-variable -> do-variable
TYPE_PARSER(construct<AcImpliedDoControl>(
maybe(integerTypeSpec / "::"), loopBounds(scalarIntExpr)))
// R1001 primary ->
// literal-constant | designator | array-constructor |
// structure-constructor | function-reference | type-param-inquiry |
// type-param-name | ( expr )
// N.B. type-param-inquiry is parsed as a structure component
constexpr auto primary{instrumented("primary"_en_US,
first(construct<Expr>(indirect(Parser<CharLiteralConstantSubstring>{})),
construct<Expr>(literalConstant),
construct<Expr>(construct<Expr::Parentheses>(parenthesized(expr))),
construct<Expr>(indirect(functionReference) / !"("_tok),
construct<Expr>(designator / !"("_tok),
construct<Expr>(Parser<StructureConstructor>{}),
construct<Expr>(Parser<ArrayConstructor>{}),
// PGI/XLF extension: COMPLEX constructor (x,y)
extension<LanguageFeature::ComplexConstructor>(
construct<Expr>(parenthesized(
construct<Expr::ComplexConstructor>(expr, "," >> expr)))),
extension<LanguageFeature::PercentLOC>(construct<Expr>("%LOC" >>
parenthesized(construct<Expr::PercentLoc>(indirect(variable)))))))};
// R1002 level-1-expr -> [defined-unary-op] primary
// TODO: Reasonable extension: permit multiple defined-unary-ops
constexpr auto level1Expr{sourced(
first(primary, // must come before define op to resolve .TRUE._8 ambiguity
construct<Expr>(construct<Expr::DefinedUnary>(definedOpName, primary)),
extension<LanguageFeature::SignedPrimary>(
construct<Expr>(construct<Expr::UnaryPlus>("+" >> primary))),
extension<LanguageFeature::SignedPrimary>(
construct<Expr>(construct<Expr::Negate>("-" >> primary)))))};
// R1004 mult-operand -> level-1-expr [power-op mult-operand]
// R1007 power-op -> **
// Exponentiation (**) is Fortran's only right-associative binary operation.
struct MultOperand {
using resultType = Expr;
constexpr MultOperand() {}
static inline std::optional<Expr> Parse(ParseState &);
};
static constexpr auto multOperand{sourced(MultOperand{})};
inline std::optional<Expr> MultOperand::Parse(ParseState &state) {
std::optional<Expr> result{level1Expr.Parse(state)};
if (result) {
static constexpr auto op{attempt("**"_tok)};
if (op.Parse(state)) {
std::function<Expr(Expr &&)> power{[&result](Expr &&right) {
return Expr{Expr::Power(std::move(result).value(), std::move(right))};
}};
return applyLambda(power, multOperand).Parse(state); // right-recursive
}
}
return result;
}
// R1005 add-operand -> [add-operand mult-op] mult-operand
// R1008 mult-op -> * | /
// The left recursion in the grammar is implemented iteratively.
constexpr struct AddOperand {
using resultType = Expr;
constexpr AddOperand() {}
static inline std::optional<Expr> Parse(ParseState &state) {
std::optional<Expr> result{multOperand.Parse(state)};
if (result) {
auto source{result->source};
std::function<Expr(Expr &&)> multiply{[&result](Expr &&right) {
return Expr{
Expr::Multiply(std::move(result).value(), std::move(right))};
}};
std::function<Expr(Expr &&)> divide{[&result](Expr &&right) {
return Expr{Expr::Divide(std::move(result).value(), std::move(right))};
}};
auto more{attempt(sourced("*" >> applyLambda(multiply, multOperand) ||
"/" >> applyLambda(divide, multOperand)))};
while (std::optional<Expr> next{more.Parse(state)}) {
result = std::move(next);
result->source.ExtendToCover(source);
}
}
return result;
}
} addOperand;
// R1006 level-2-expr -> [[level-2-expr] add-op] add-operand
// R1009 add-op -> + | -
// These are left-recursive productions, implemented iteratively.
// Note that standard Fortran admits a unary + or - to appear only here,
// by means of a missing first operand; e.g., 2*-3 is valid in C but not
// standard Fortran. We accept unary + and - to appear before any primary
// as an extension.
constexpr struct Level2Expr {
using resultType = Expr;
constexpr Level2Expr() {}
static inline std::optional<Expr> Parse(ParseState &state) {
static constexpr auto unary{
sourced(
construct<Expr>(construct<Expr::UnaryPlus>("+" >> addOperand)) ||
construct<Expr>(construct<Expr::Negate>("-" >> addOperand))) ||
addOperand};
std::optional<Expr> result{unary.Parse(state)};
if (result) {
auto source{result->source};
std::function<Expr(Expr &&)> add{[&result](Expr &&right) {
return Expr{Expr::Add(std::move(result).value(), std::move(right))};
}};
std::function<Expr(Expr &&)> subtract{[&result](Expr &&right) {
return Expr{
Expr::Subtract(std::move(result).value(), std::move(right))};
}};
auto more{attempt(sourced("+" >> applyLambda(add, addOperand) ||
"-" >> applyLambda(subtract, addOperand)))};
while (std::optional<Expr> next{more.Parse(state)}) {
result = std::move(next);
result->source.ExtendToCover(source);
}
}
return result;
}
} level2Expr;
// R1010 level-3-expr -> [level-3-expr concat-op] level-2-expr
// R1011 concat-op -> //
// Concatenation (//) is left-associative for parsing performance, although
// one would never notice if it were right-associated.
constexpr struct Level3Expr {
using resultType = Expr;
constexpr Level3Expr() {}
static inline std::optional<Expr> Parse(ParseState &state) {
std::optional<Expr> result{level2Expr.Parse(state)};
if (result) {
auto source{result->source};
std::function<Expr(Expr &&)> concat{[&result](Expr &&right) {
return Expr{Expr::Concat(std::move(result).value(), std::move(right))};
}};
auto more{attempt(sourced("//" >> applyLambda(concat, level2Expr)))};
while (std::optional<Expr> next{more.Parse(state)}) {
result = std::move(next);
result->source.ExtendToCover(source);
}
}
return result;
}
} level3Expr;
// R1012 level-4-expr -> [level-3-expr rel-op] level-3-expr
// R1013 rel-op ->
// .EQ. | .NE. | .LT. | .LE. | .GT. | .GE. |
// == | /= | < | <= | > | >= @ | <>
// N.B. relations are not recursive (i.e., LOGICAL is not ordered)
constexpr struct Level4Expr {
using resultType = Expr;
constexpr Level4Expr() {}
static inline std::optional<Expr> Parse(ParseState &state) {
std::optional<Expr> result{level3Expr.Parse(state)};
if (result) {
auto source{result->source};
std::function<Expr(Expr &&)> lt{[&result](Expr &&right) {
return Expr{Expr::LT(std::move(result).value(), std::move(right))};
}};
std::function<Expr(Expr &&)> le{[&result](Expr &&right) {
return Expr{Expr::LE(std::move(result).value(), std::move(right))};
}};
std::function<Expr(Expr &&)> eq{[&result](Expr &&right) {
return Expr{Expr::EQ(std::move(result).value(), std::move(right))};
}};
std::function<Expr(Expr &&)> ne{[&result](Expr &&right) {
return Expr{Expr::NE(std::move(result).value(), std::move(right))};
}};
std::function<Expr(Expr &&)> ge{[&result](Expr &&right) {
return Expr{Expr::GE(std::move(result).value(), std::move(right))};
}};
std::function<Expr(Expr &&)> gt{[&result](Expr &&right) {
return Expr{Expr::GT(std::move(result).value(), std::move(right))};
}};
auto more{attempt(
sourced((".LT."_tok || "<"_tok) >> applyLambda(lt, level3Expr) ||
(".LE."_tok || "<="_tok) >> applyLambda(le, level3Expr) ||
(".EQ."_tok || "=="_tok) >> applyLambda(eq, level3Expr) ||
(".NE."_tok || "/="_tok ||
extension<LanguageFeature::AlternativeNE>(
"<>"_tok /* PGI/Cray extension; Cray also has .LG. */)) >>
applyLambda(ne, level3Expr) ||
(".GE."_tok || ">="_tok) >> applyLambda(ge, level3Expr) ||
(".GT."_tok || ">"_tok) >> applyLambda(gt, level3Expr)))};
if (std::optional<Expr> next{more.Parse(state)}) {
next->source.ExtendToCover(source);
return next;
}
}
return result;
}
} level4Expr;
// R1014 and-operand -> [not-op] level-4-expr
// R1018 not-op -> .NOT.
// N.B. Fortran's .NOT. binds less tightly than its comparison operators do.
// PGI/Intel extension: accept multiple .NOT. operators
constexpr struct AndOperand {
using resultType = Expr;
constexpr AndOperand() {}
static inline std::optional<Expr> Parse(ParseState &);
} andOperand;
// Match a logical operator or, optionally, its abbreviation.
inline constexpr auto logicalOp(const char *op, const char *abbrev) {
return TokenStringMatch{op} ||
extension<LanguageFeature::LogicalAbbreviations>(
TokenStringMatch{abbrev});
}
inline std::optional<Expr> AndOperand::Parse(ParseState &state) {
static constexpr auto notOp{attempt(logicalOp(".NOT.", ".N.") >> andOperand)};
if (std::optional<Expr> negation{notOp.Parse(state)}) {
return Expr{Expr::NOT{std::move(*negation)}};
} else {
return level4Expr.Parse(state);
}
}
// R1015 or-operand -> [or-operand and-op] and-operand
// R1019 and-op -> .AND.
// .AND. is left-associative
constexpr struct OrOperand {
using resultType = Expr;
constexpr OrOperand() {}
static inline std::optional<Expr> Parse(ParseState &state) {
static constexpr auto operand{sourced(andOperand)};
std::optional<Expr> result{operand.Parse(state)};
if (result) {
auto source{result->source};
std::function<Expr(Expr &&)> logicalAnd{[&result](Expr &&right) {
return Expr{Expr::AND(std::move(result).value(), std::move(right))};
}};
auto more{attempt(sourced(
logicalOp(".AND.", ".A.") >> applyLambda(logicalAnd, andOperand)))};
while (std::optional<Expr> next{more.Parse(state)}) {
result = std::move(next);
result->source.ExtendToCover(source);
}
}
return result;
}
} orOperand;
// R1016 equiv-operand -> [equiv-operand or-op] or-operand
// R1020 or-op -> .OR.
// .OR. is left-associative
constexpr struct EquivOperand {
using resultType = Expr;
constexpr EquivOperand() {}
static inline std::optional<Expr> Parse(ParseState &state) {
std::optional<Expr> result{orOperand.Parse(state)};
if (result) {
auto source{result->source};
std::function<Expr(Expr &&)> logicalOr{[&result](Expr &&right) {
return Expr{Expr::OR(std::move(result).value(), std::move(right))};
}};
auto more{attempt(sourced(
logicalOp(".OR.", ".O.") >> applyLambda(logicalOr, orOperand)))};
while (std::optional<Expr> next{more.Parse(state)}) {
result = std::move(next);
result->source.ExtendToCover(source);
}
}
return result;
}
} equivOperand;
// R1017 level-5-expr -> [level-5-expr equiv-op] equiv-operand
// R1021 equiv-op -> .EQV. | .NEQV.
// Logical equivalence is left-associative.
// Extension: .XOR. as synonym for .NEQV.
constexpr struct Level5Expr {
using resultType = Expr;
constexpr Level5Expr() {}
static inline std::optional<Expr> Parse(ParseState &state) {
std::optional<Expr> result{equivOperand.Parse(state)};
if (result) {
auto source{result->source};
std::function<Expr(Expr &&)> eqv{[&result](Expr &&right) {
return Expr{Expr::EQV(std::move(result).value(), std::move(right))};
}};
std::function<Expr(Expr &&)> neqv{[&result](Expr &&right) {
return Expr{Expr::NEQV(std::move(result).value(), std::move(right))};
}};
auto more{attempt(sourced(".EQV." >> applyLambda(eqv, equivOperand) ||
(".NEQV."_tok ||
extension<LanguageFeature::XOROperator>(
logicalOp(".XOR.", ".X."))) >>
applyLambda(neqv, equivOperand)))};
while (std::optional<Expr> next{more.Parse(state)}) {
result = std::move(next);
result->source.ExtendToCover(source);
}
}
return result;
}
} level5Expr;
// R1022 expr -> [expr defined-binary-op] level-5-expr
// Defined binary operators associate leftwards.
template<> std::optional<Expr> Parser<Expr>::Parse(ParseState &state) {
std::optional<Expr> result{level5Expr.Parse(state)};
if (result) {
auto source{result->source};
std::function<Expr(DefinedOpName &&, Expr &&)> defBinOp{
[&result](DefinedOpName &&op, Expr &&right) {
return Expr{Expr::DefinedBinary(
std::move(op), std::move(result).value(), std::move(right))};
}};
auto more{
attempt(sourced(applyLambda(defBinOp, definedOpName, level5Expr)))};
while (std::optional<Expr> next{more.Parse(state)}) {
result = std::move(next);
result->source.ExtendToCover(source);
}
}
return result;
}
// R1003 defined-unary-op -> . letter [letter]... .
// R1023 defined-binary-op -> . letter [letter]... .
// R1414 local-defined-operator -> defined-unary-op | defined-binary-op
// R1415 use-defined-operator -> defined-unary-op | defined-binary-op
// C1003 A defined operator must be distinct from logical literal constants
// and intrinsic operator names; this is handled by attempting their parses
// first, and by name resolution on their definitions, for best errors.
// N.B. The name of the operator is captured with the dots around it.
constexpr auto definedOpNameChar{
letter || extension<LanguageFeature::PunctuationInNames>("$@"_ch)};
TYPE_PARSER(
space >> construct<DefinedOpName>(sourced("."_ch >>
some(definedOpNameChar) >> construct<Name>() / "."_ch)))
// R1028 specification-expr -> scalar-int-expr
TYPE_PARSER(construct<SpecificationExpr>(scalarIntExpr))
// R1032 assignment-stmt -> variable = expr
TYPE_CONTEXT_PARSER("assignment statement"_en_US,
construct<AssignmentStmt>(variable / "=", expr))
// R1033 pointer-assignment-stmt ->
// data-pointer-object [( bounds-spec-list )] => data-target |
// data-pointer-object ( bounds-remapping-list ) => data-target |
// proc-pointer-object => proc-target
// R1034 data-pointer-object ->
// variable-name | scalar-variable % data-pointer-component-name
// C1022 a scalar-variable shall be a data-ref
// C1024 a data-pointer-object shall not be a coindexed object
// R1038 proc-pointer-object -> proc-pointer-name | proc-component-ref
//
// A distinction can't be made at the time of the initial parse between
// data-pointer-object and proc-pointer-object, or between data-target
// and proc-target.
TYPE_CONTEXT_PARSER("pointer assignment statement"_en_US,
construct<PointerAssignmentStmt>(dataRef,
parenthesized(nonemptyList(Parser<BoundsRemapping>{})), "=>" >> expr) ||
construct<PointerAssignmentStmt>(dataRef,
defaulted(parenthesized(nonemptyList(Parser<BoundsSpec>{}))),
"=>" >> expr))
// R1035 bounds-spec -> lower-bound-expr :
TYPE_PARSER(construct<BoundsSpec>(boundExpr / ":"))
// R1036 bounds-remapping -> lower-bound-expr : upper-bound-expr
TYPE_PARSER(construct<BoundsRemapping>(boundExpr / ":", boundExpr))
// R1039 proc-component-ref -> scalar-variable % procedure-component-name
// C1027 the scalar-variable must be a data-ref without coindices.
TYPE_PARSER(construct<ProcComponentRef>(structureComponent))
// R1041 where-stmt -> WHERE ( mask-expr ) where-assignment-stmt
// R1045 where-assignment-stmt -> assignment-stmt
// R1046 mask-expr -> logical-expr
TYPE_CONTEXT_PARSER("WHERE statement"_en_US,
construct<WhereStmt>("WHERE" >> parenthesized(logicalExpr), assignmentStmt))
// R1042 where-construct ->
// where-construct-stmt [where-body-construct]...
// [masked-elsewhere-stmt [where-body-construct]...]...
// [elsewhere-stmt [where-body-construct]...] end-where-stmt
TYPE_CONTEXT_PARSER("WHERE construct"_en_US,
construct<WhereConstruct>(statement(Parser<WhereConstructStmt>{}),
many(whereBodyConstruct),
many(construct<WhereConstruct::MaskedElsewhere>(
statement(Parser<MaskedElsewhereStmt>{}),
many(whereBodyConstruct))),
maybe(construct<WhereConstruct::Elsewhere>(
statement(Parser<ElsewhereStmt>{}), many(whereBodyConstruct))),
statement(Parser<EndWhereStmt>{})))
// R1043 where-construct-stmt -> [where-construct-name :] WHERE ( mask-expr )
TYPE_CONTEXT_PARSER("WHERE construct statement"_en_US,
construct<WhereConstructStmt>(
maybe(name / ":"), "WHERE" >> parenthesized(logicalExpr)))
// R1044 where-body-construct ->
// where-assignment-stmt | where-stmt | where-construct
TYPE_PARSER(construct<WhereBodyConstruct>(statement(assignmentStmt)) ||
construct<WhereBodyConstruct>(statement(whereStmt)) ||
construct<WhereBodyConstruct>(indirect(whereConstruct)))
// R1047 masked-elsewhere-stmt ->
// ELSEWHERE ( mask-expr ) [where-construct-name]
TYPE_CONTEXT_PARSER("masked ELSEWHERE statement"_en_US,
construct<MaskedElsewhereStmt>(
"ELSE WHERE" >> parenthesized(logicalExpr), maybe(name)))
// R1048 elsewhere-stmt -> ELSEWHERE [where-construct-name]
TYPE_CONTEXT_PARSER("ELSEWHERE statement"_en_US,
construct<ElsewhereStmt>("ELSE WHERE" >> maybe(name)))
// R1049 end-where-stmt -> ENDWHERE [where-construct-name]
TYPE_CONTEXT_PARSER("END WHERE statement"_en_US,
construct<EndWhereStmt>(
recovery("END WHERE" >> maybe(name), endStmtErrorRecovery)))
// R1050 forall-construct ->
// forall-construct-stmt [forall-body-construct]... end-forall-stmt
TYPE_CONTEXT_PARSER("FORALL construct"_en_US,
construct<ForallConstruct>(statement(Parser<ForallConstructStmt>{}),
many(Parser<ForallBodyConstruct>{}),
statement(Parser<EndForallStmt>{})))
// R1051 forall-construct-stmt ->
// [forall-construct-name :] FORALL concurrent-header
TYPE_CONTEXT_PARSER("FORALL construct statement"_en_US,
construct<ForallConstructStmt>(
maybe(name / ":"), "FORALL" >> indirect(concurrentHeader)))
// R1052 forall-body-construct ->
// forall-assignment-stmt | where-stmt | where-construct |
// forall-construct | forall-stmt
TYPE_PARSER(construct<ForallBodyConstruct>(statement(forallAssignmentStmt)) ||
construct<ForallBodyConstruct>(statement(whereStmt)) ||
construct<ForallBodyConstruct>(whereConstruct) ||
construct<ForallBodyConstruct>(indirect(forallConstruct)) ||
construct<ForallBodyConstruct>(statement(forallStmt)))
// R1053 forall-assignment-stmt -> assignment-stmt | pointer-assignment-stmt
TYPE_PARSER(construct<ForallAssignmentStmt>(assignmentStmt) ||
construct<ForallAssignmentStmt>(pointerAssignmentStmt))
// R1054 end-forall-stmt -> END FORALL [forall-construct-name]
TYPE_CONTEXT_PARSER("END FORALL statement"_en_US,
construct<EndForallStmt>(
recovery("END FORALL" >> maybe(name), endStmtErrorRecovery)))
// R1055 forall-stmt -> FORALL concurrent-header forall-assignment-stmt
TYPE_CONTEXT_PARSER("FORALL statement"_en_US,
construct<ForallStmt>("FORALL" >> indirect(concurrentHeader),
unlabeledStatement(forallAssignmentStmt)))
}
| 42.032882 | 80 | 0.654641 | [
"object"
] |
11e98e7d8516723d1b176c0ae14461f90035cb20 | 1,154 | cpp | C++ | GeeksForGeeks/C Plus Plus/Kth_smallest_element_in_BST.cpp | ankit-sr/Competitive-Programming | 3397b313b80a32a47cfe224426a6e9c7cf05dec2 | [
"MIT"
] | 4 | 2021-06-19T14:15:34.000Z | 2021-06-21T13:53:53.000Z | GeeksForGeeks/C Plus Plus/Kth_smallest_element_in_BST.cpp | ankit-sr/Competitive-Programming | 3397b313b80a32a47cfe224426a6e9c7cf05dec2 | [
"MIT"
] | 2 | 2021-07-02T12:41:06.000Z | 2021-07-12T09:37:50.000Z | GeeksForGeeks/C Plus Plus/Kth_smallest_element_in_BST.cpp | ankit-sr/Competitive-Programming | 3397b313b80a32a47cfe224426a6e9c7cf05dec2 | [
"MIT"
] | 3 | 2021-06-19T15:19:20.000Z | 2021-07-02T17:24:51.000Z | /*
Problem Statement:
-----------------
Given a BST and an integer K. Find the Kth Smallest element in the BST.
Example 1:
---------
Input:
2
/ \
1 3
K = 2
Output: 2
Example 2:
----------
Input:
2
/ \
1 3
K = 5
Output: -1
Your Task: You don't need to read input or print anything. Your task is to complete the function KthSmallestElement() which takes the root of the BST
and integer K as inputs and return the Kth smallest element in the BST, if no such element exists return -1.
Expected Time Complexity: O(N).
Expected Auxiliary Space: O(1).
*/
// Link --> https://practice.geeksforgeeks.org/problems/find-k-th-smallest-element-in-bst/1
// Code:
class Solution
{
public:
vector <int> in;
void inorder(Node *root)
{
if(root == NULL)
return;
inorder(root->left);
in.push_back(root->data);
inorder(root->right);
}
int KthSmallestElement(Node *root , int k)
{
in.clear();
inorder(root);
if(in.size() >= k)
return in[k-1];
else
return -1;
}
};
| 19.233333 | 150 | 0.556326 | [
"vector"
] |
11ea9412b42326bae4a928763ae67a6ea4064251 | 3,921 | cpp | C++ | test/src/utils/HeapAllocatorTest.cpp | trgswe/fs2open.github.com | a159eba0cebca911ad14a118412fddfe5be8e9f8 | [
"Unlicense"
] | 307 | 2015-04-10T13:27:32.000Z | 2022-03-21T03:30:38.000Z | test/src/utils/HeapAllocatorTest.cpp | trgswe/fs2open.github.com | a159eba0cebca911ad14a118412fddfe5be8e9f8 | [
"Unlicense"
] | 2,231 | 2015-04-27T10:47:35.000Z | 2022-03-31T19:22:37.000Z | test/src/utils/HeapAllocatorTest.cpp | trgswe/fs2open.github.com | a159eba0cebca911ad14a118412fddfe5be8e9f8 | [
"Unlicense"
] | 282 | 2015-01-05T12:16:57.000Z | 2022-03-28T04:45:11.000Z |
#include <gtest/gtest.h>
#include <random>
#include "utils/HeapAllocator.h"
using namespace util;
namespace {
void dummyResizer(size_t) {}
}
TEST(HeapAllocatorTests, simpleAllocate) {
HeapAllocator allocator(dummyResizer);
ASSERT_EQ((size_t)0, allocator.numAllocations());
auto offset = allocator.allocate(200);
ASSERT_EQ((size_t)1, allocator.numAllocations());
allocator.free(offset);
ASSERT_EQ((size_t)0, allocator.numAllocations());
}
TEST(HeapAllocatorTests, manySmallAllocations) {
HeapAllocator allocator(dummyResizer);
std::random_device rd; //Will be used to obtain a seed for the random number engine
std::mt19937 gen(rd()); //Standard mersenne_twister_engine seeded with rd()
std::uniform_int_distribution<size_t> sizeDist(1, 50000);
SCP_vector<size_t> offsets;
// Allocate enough small ranges to require a resize at some point
for (auto i = 0; i < 1500; ++i) {
auto size = sizeDist(gen);
// Use multiples of 52 since that is what the model code uses as the vertex stride
size_t x = allocator.allocate(52 * size);
// Make sure that all offsets are aligned properly
ASSERT_EQ((size_t)0, x % 52);
offsets.push_back(x);
}
ASSERT_EQ(offsets.size(), allocator.numAllocations());
// Free some ranges in a non-contiguous manner to test range freeing and merging
while (offsets.size() > 512) {
std::uniform_int_distribution<size_t> dis(0, offsets.size() - 1);
auto el = std::next(offsets.begin(), dis(gen));
allocator.free(*el);
offsets.erase(el);
ASSERT_EQ(offsets.size(), allocator.numAllocations());
}
ASSERT_EQ(offsets.size(), allocator.numAllocations());
// Allocate some more ranges to test range reuse
for (auto i = 0; i < 1500; ++i) {
auto size = sizeDist(gen);
// Use multiples of 52 since that is what the model code uses as the vertex stride
size_t x = allocator.allocate(52 * size);
// Make sure that all offsets are aligned properly
ASSERT_EQ((size_t)0, x % 52);
offsets.push_back(x);
}
ASSERT_EQ(offsets.size(), allocator.numAllocations());
// And now empty the entire allocator
while (!offsets.empty()) {
std::uniform_int_distribution<size_t> dis(0, offsets.size() - 1);
auto el = std::next(offsets.begin(), dis(gen));
allocator.free(*el);
offsets.erase(el);
ASSERT_EQ(offsets.size(), allocator.numAllocations());
}
ASSERT_EQ(offsets.size(), allocator.numAllocations());
ASSERT_EQ((size_t)0, offsets.size());
}
TEST(HeapAllocatorTests, largeAllocations) {
HeapAllocator allocator(dummyResizer);
SCP_vector<size_t> offsets;
// Allocate enough small ranges to require a resize at some point
for (auto i = 0; i < 100; ++i) {
offsets.push_back(allocator.allocate(10 * 1024 * 1024));
}
ASSERT_EQ(offsets.size(), allocator.numAllocations());
std::random_device rd; //Will be used to obtain a seed for the random number engine
std::mt19937 gen(rd()); //Standard mersenne_twister_engine seeded with rd()
// Free some ranges in a non-contiguous manner to test range freeing and merging
while (offsets.size() > 50) {
std::uniform_int_distribution<size_t> dis(0, offsets.size() - 1);
auto el = std::next(offsets.begin(), dis(gen));
allocator.free(*el);
offsets.erase(el);
ASSERT_EQ(offsets.size(), allocator.numAllocations());
}
ASSERT_EQ(offsets.size(), allocator.numAllocations());
// Allocate some more ranges to test range reuse
for (auto i = 0; i < 100; ++i) {
offsets.push_back(allocator.allocate(10 * 1024 * 1024));
}
ASSERT_EQ(offsets.size(), allocator.numAllocations());
// And now empty the entire allocator
while (!offsets.empty()) {
std::uniform_int_distribution<size_t> dis(0, offsets.size() - 1);
auto el = std::next(offsets.begin(), dis(gen));
allocator.free(*el);
offsets.erase(el);
ASSERT_EQ(offsets.size(), allocator.numAllocations());
}
ASSERT_EQ(offsets.size(), allocator.numAllocations());
ASSERT_EQ((size_t)0, offsets.size());
}
| 27.612676 | 85 | 0.712573 | [
"model"
] |
11ed4c3601308b944b52bc56cf7808fdada82644 | 17,921 | cpp | C++ | torch/csrc/jit/passes/batch_mm.cpp | shivamsp133/pytorch | 457a3fb6d1441721cb72dca90b8f20b32d553856 | [
"Intel"
] | 206 | 2020-11-28T22:56:38.000Z | 2022-03-27T02:33:04.000Z | torch/csrc/jit/passes/batch_mm.cpp | shivamsp133/pytorch | 457a3fb6d1441721cb72dca90b8f20b32d553856 | [
"Intel"
] | 19 | 2020-12-09T23:13:14.000Z | 2022-01-24T23:24:08.000Z | torch/csrc/jit/passes/batch_mm.cpp | shivamsp133/pytorch | 457a3fb6d1441721cb72dca90b8f20b32d553856 | [
"Intel"
] | 28 | 2020-11-29T15:25:12.000Z | 2022-01-20T02:16:27.000Z | #include <torch/csrc/jit/passes/batch_mm.h>
#include <ATen/core/functional.h>
#include <ATen/core/interned_strings.h>
#include <c10/util/Exception.h>
#include <torch/csrc/jit/ir/alias_analysis.h>
#include <torch/csrc/jit/ir/constants.h>
#include <torch/csrc/jit/passes/dead_code_elimination.h>
#include <torch/csrc/jit/passes/peephole.h>
#include <torch/csrc/jit/runtime/custom_operator.h>
#include <ATen/ATen.h>
#include <algorithm>
#include <unordered_map>
namespace torch {
namespace jit {
namespace {
c10::AliasAnalysisKind aliasAnalysisIsSpecialCase() {
return AliasAnalysisKind::INTERNAL_SPECIAL_CASE;
}
} // namespace
// This pass looks for trees in the graph, where leaves are mm ops, and the
// inner vertices are add nodes. Once we have such a tree they can be reduced to
// two concats and a single mm (basically into a single multiply of a wide
// matrix, with a tall matrix). Such patterns show up mostly in backward of
// RNNs, since the derivative of many uses of matrix multiplies with same
// weights forms exactly such a tree (note that it's usually also highly
// imbalanced i.e. has O(n) depth).
//
// This (or any tree of adds of MMs):
//
// +------+ +------+ +------+ +------+ +------+
// | | | | | | | | | |
// | L1 | | R1 | + | L2 | | R2 | = | O |
// | | | | | | | | | |
// +------+ +------+ +------+ +------+ +------+
//
// can be basically transformed into a single MM which looks like this
// (we concat all lhs operands, concat rhs operands, do mm):
//
// +------+
// | |
// | R1 |
// | |
// +------+
// | |
// | R2 |
// | |
// +------+
// +------+------+ +------+
// | | | | |
// | L1 | L2 | | O |
// | | | | |
// +------+------+ +------+
// Note [Further optimizations]
// It would be straightforward to extend the TreeToken class to also detect if
// all MMs had the same lhs/rhs. In such case it's more efficient to expand the
// lhs and use bmm + sum instead of repeating it in memory via concat.
// Note [Overlapping trees]
// Additionally it wouldn't be too hard to add support for partially overlapping
// trees. Right now the it's forbidden in the algorithm (only a single tree will
// be allowed), so theoretically we might miss some optimization options,
// especially that the rejected tree could be much larger. I didn't implement
// that because it's not necessary for the simple RNN cases I saw, so I decided
// to keep stuff simple. If we ever get around implementing this, the right
// solution is probably to fuse MMs for the common part, and assume it's an
// input leaf for the outer two parts (I don't think it's beneficial to
// recompute, unless the subtree is super small, but let's not get into such
// details).
// The algorithm we're using is simple. We're iterating through the graph in the
// topological order and labeling nodes with TreeTokens. Then, we look for roots
// of the trees we formed and fuse them.
// Tunable parameter. Set to something larger if it turns out to be better.
static constexpr size_t min_fusion_size = 4;
bool have_same_shape(at::TensorList inputs) {
auto expected_sizes = inputs[0].sizes();
return (std::all_of(
inputs.begin(), inputs.end(), [expected_sizes](const at::Tensor& t) {
return t.sizes() == expected_sizes;
}));
}
bool should_be_transposed(at::TensorList inputs) {
return (std::all_of(inputs.begin(), inputs.end(), [](const at::Tensor& t) {
return t.stride(0) == 1 && t.stride(1) == t.size(0);
}));
}
std::vector<at::Tensor> transpose_inputs(at::TensorList inputs) {
return fmap(inputs, [](const at::Tensor& i) { return i.t(); });
}
bool shape_is_fast_for_reduce(const at::Tensor& lhs, const at::Tensor& rhs) {
size_t l = lhs.size(0);
size_t m = lhs.size(1);
size_t r = rhs.size(1);
// Numbers obtained by some simple benchmarks of fp32 gemms on a TITAN V
return m < 512 || ((l < 256 && r < 256) || (l > 256 && r > 256));
}
RegisterOperators mm_tree_reduction_reg({Operator(
"prim::MMTreeReduce(...) -> Tensor",
[](Stack* stack) {
auto num_inputs = pop(stack).toInt();
std::vector<at::Tensor> inputs;
inputs.reserve(num_inputs);
for (auto it = stack->end() - num_inputs; it != stack->end(); ++it) {
inputs.push_back(std::move(*it).toTensor());
}
drop(stack, num_inputs);
AT_ASSERT(inputs.size() > 0);
AT_ASSERT(inputs.size() % 2 == 0);
size_t side_num_elems = inputs.size() / 2;
auto lhs_inputs = at::TensorList(inputs).slice(0, side_num_elems);
auto rhs_inputs = at::TensorList(inputs).slice(side_num_elems);
// TODO: checking this is not free, so we should stop if this keeps
// failing
if (have_same_shape(lhs_inputs) && have_same_shape(rhs_inputs) &&
shape_is_fast_for_reduce(lhs_inputs[0], rhs_inputs[0])) {
// sometimes lhs_inputs or rhs_inputs are not contiguous, and that
// causes at::cat to go through slow path view them as contiguous if
// possible by transposing
bool lhs_input_transposed = should_be_transposed(lhs_inputs);
bool rhs_input_transposed = should_be_transposed(rhs_inputs);
at::Tensor lhs, rhs;
if (lhs_input_transposed) {
std::vector<at::Tensor> lhs_contig_inputs =
transpose_inputs(lhs_inputs);
lhs = at::cat(lhs_contig_inputs, /*dim*/ 0);
lhs = lhs.t();
} else {
lhs = at::cat(lhs_inputs, /*dim=*/1);
}
if (rhs_input_transposed) {
std::vector<at::Tensor> rhs_contig_inputs =
transpose_inputs(rhs_inputs);
rhs = at::cat(rhs_contig_inputs, /*dim*/ 1);
rhs = rhs.t();
} else {
rhs = at::cat(rhs_inputs, /*dim=*/0);
}
push(stack, at::mm(lhs, rhs));
} else {
auto acc = at::mm(inputs[0], inputs[side_num_elems]);
for (size_t i = 1; i < side_num_elems; ++i) {
acc.add_(at::mm(inputs[i], inputs[side_num_elems + i]));
}
push(stack, std::move(acc));
}
},
aliasAnalysisIsSpecialCase())});
// TreeTokens will be used to label nodes of the graph, if the nodes will fit
// our mm/add tree pattern. Basically we do dynamic programming on DAGs, where
// when we reach node N with inputs A and B, then A and B have already been
// processed, and we can try to unify their TreeTokens (if they have them)
// and build a larger tree.
struct TreeToken {
uint64_t tree_size = 0; // NOTE: measured in number of leaves i.e. mm ops
Node* node = nullptr;
bool is_root = false;
static TreeToken mm(Node* mm) {
TreeToken token;
token.tree_size = 1;
token.node = mm;
token.is_root = true;
return token;
}
// NB: the returned token might be invalid, so make sure to check its boolean
// value!
static TreeToken transpose(Node* t, TreeToken& inp_token) {
TreeToken token;
if (!inp_token.node->matches(
"aten::mm(Tensor self, Tensor mat2) -> Tensor")) {
return token;
}
token.tree_size = 1;
token.node = t;
token.is_root = true;
inp_token.is_root = false;
return token;
}
// NB: the returned token might be invalid, so make sure to check its boolean
// value!
static TreeToken add(Node* add, TreeToken& l, TreeToken& r) {
TreeToken token;
// See Note [Overlapping trees]
if (&l == &r || !l.is_root || !r.is_root)
return token;
token.tree_size = l.tree_size + r.tree_size;
token.node = add;
token.is_root = true;
l.is_root = r.is_root =
false; // Reserve the subtrees, so they can't be used again.
return token;
}
explicit operator bool() {
return is_root;
}
std::vector<Node*> removeTransposesAndGatherMatmuls() {
std::vector<Node*> matmuls;
std::vector<Node*> queue{node};
Graph* graph = node->owningGraph();
while (!queue.empty()) {
auto n = queue.back();
queue.pop_back();
if (n->matches("aten::mm(Tensor self, Tensor mat2) -> Tensor")) {
matmuls.push_back(n);
} else if (n->matches("aten::t(Tensor self) -> Tensor")) {
Node* input_node = n->input()->node();
AT_ASSERT(input_node->matches(
"aten::mm(Tensor self, Tensor mat2) -> Tensor"));
// (AB)^T == B^TA^T
WithInsertPoint insert_guard{input_node};
Value* A = input_node->inputs()[0];
Value* B = input_node->inputs()[1];
Value* AT = graph->insert(aten::t, {A});
Value* BT = graph->insert(aten::t, {B});
Value* BTAT = graph->insert(aten::mm, {BT, AT});
n->output()->replaceAllUsesWith(BTAT);
matmuls.push_back(BTAT->node());
} else if (
n->matches(
"aten::add(Tensor self, Tensor other, *, Scalar alpha) -> Tensor")) {
queue.push_back(n->inputs()[0]->node());
queue.push_back(n->inputs()[1]->node());
} else {
AT_ASSERTM(false, "Unsupported node found in a BatchMM tree!");
}
}
return matmuls;
}
};
enum class Side { LHS, RHS };
void BatchMMTreeReduce(Block* block) {
auto graph = block->owningGraph();
// Look for trees in the block
std::unordered_map<Node*, TreeToken> tokens;
for (auto node : block->nodes()) {
if (node->matches("aten::mm(Tensor self, Tensor mat2) -> Tensor")) {
tokens[node] = TreeToken::mm(node);
} else if (node->matches("aten::t(Tensor self) -> Tensor")) {
auto input_it = tokens.find(node->input()->node());
if (input_it != tokens.end()) {
tokens[node] = TreeToken::transpose(node, input_it->second);
}
} else if (
node->matches(
"aten::add(Tensor self, Tensor other, *, Scalar alpha) -> Tensor")) {
Node* lhs = node->inputs()[0]->node();
Node* rhs = node->inputs()[1]->node();
auto lhs_it = tokens.find(lhs);
auto rhs_it = tokens.find(rhs);
// See Note [Overlapping trees] (regarding the uses().size() == 1 check)
// We could treat a subtree with multiple uses as if it was overlapping.
// XXX: uses().size() == 1 is also something that guarantees that this
// transform is valid, because we know for sure that the none of these
// operands depend on the result of the other. If we were to remove this,
// we need to compute a transitive closure and actually check the
// dependencies.
if (lhs_it != tokens.end() && rhs_it != tokens.end() &&
lhs->output()->uses().size() == 1 &&
rhs->output()->uses().size() == 1) {
if (auto token = TreeToken::add(node, lhs_it->second, rhs_it->second)) {
tokens[node] = token;
}
}
} else {
for (auto block : node->blocks()) {
BatchMMTreeReduce(block);
}
}
}
// Merge trees we've found
for (auto& item : tokens) {
auto& root = item.second;
if (!root || root.tree_size < min_fusion_size)
continue;
auto matmuls = root.removeTransposesAndGatherMatmuls();
WithInsertPoint insert_guard{root.node};
Node* tree_reduce =
graph->insertNode(graph->create(Symbol::prim("MMTreeReduce")));
for (Node* matmul : matmuls) {
tree_reduce->addInput(matmul->inputs().at(0));
}
for (Node* matmul : matmuls) {
tree_reduce->addInput(matmul->inputs().at(1));
}
root.node->output()->replaceAllUsesWith(tree_reduce->output());
// NB: don't bother with cleaning up after yourself. We'll use DCE for that.
}
}
bool shape_is_fast_for_side(const at::Tensor& other_side_input) {
// Cutoff chosed by benchmarking on a TITAN V
return other_side_input.numel() <= 1024 * 2048;
}
RegisterOperators mm_batch_side_reg({Operator(
prim::MMBatchSide,
[](const Node* node) -> Operation {
size_t num_other_side_inputs = node->inputs().size() - 1;
Side single_side = static_cast<Side>(node->i(Symbol::attr("side")));
return [num_other_side_inputs, single_side](Stack* stack) {
at::Tensor side_input;
std::vector<at::Tensor> other_side_inputs;
other_side_inputs.reserve(num_other_side_inputs);
for (auto it = stack->end() - num_other_side_inputs; it != stack->end();
++it) {
other_side_inputs.push_back(std::move(*it).toTensor());
}
drop(stack, num_other_side_inputs);
pop(stack, side_input);
auto any_other_input = other_side_inputs[0];
if (have_same_shape(other_side_inputs) &&
shape_is_fast_for_side(other_side_inputs[0])) {
auto other_side_input =
at::cat(other_side_inputs, single_side == Side::LHS ? 1 : 0);
auto mm_out = single_side == Side::LHS
? side_input.mm(other_side_input)
: other_side_input.mm(side_input);
auto outputs = at::chunk(
mm_out,
num_other_side_inputs,
/*dim=*/single_side == Side::LHS ? 1 : 0);
stack->insert(
stack->end(),
std::make_move_iterator(outputs.begin()),
std::make_move_iterator(outputs.end()));
} else {
if (single_side == Side::LHS) {
for (at::Tensor& other : other_side_inputs) {
stack->emplace_back(side_input.mm(other));
}
} else {
for (at::Tensor& other : other_side_inputs) {
stack->emplace_back(other.mm(side_input));
}
}
}
};
},
aliasAnalysisIsSpecialCase())});
std::pair<std::vector<Node*>, std::vector<Node*>> gatherIndependentMMUses(
Value* value,
AliasDb& alias_db) {
const auto postprocess = [&](std::vector<Node*> mms) {
if (mms.size() == 0) {
return mms;
}
std::sort(mms.begin(), mms.end(), [](Node* n, Node* m) {
return n->isBefore(m);
});
// Filter out dependent MMs. This algorithm might do very badly if e.g. you
// have a lot of independent MMs, that depend on the first one, but I doubt
// this will be a common scenario.
for (size_t i = 0; i < mms.size(); ++i) {
if (mms[i] == nullptr)
continue;
for (size_t j = i + 1; j < mms.size(); ++j) {
if (mms[j] == nullptr)
continue;
if (!alias_db.couldMoveBeforeTopologically(mms[j], mms[i])) {
mms[j] = nullptr;
}
}
}
return c10::filter(mms, [](Node* n) { return n != nullptr; });
};
Block* block = value->node()->owningBlock();
std::vector<Node*> lhses; // Will contain nodes where value is used as an lhs
std::vector<Node*> rhses; // Like above, but rhs
for (Use u : value->uses()) {
if (u.user->owningBlock() == block &&
u.user->matches("aten::mm(Tensor self, Tensor mat2) -> Tensor")) {
if (u.offset == 0 && u.user->inputs()[1] != value) {
lhses.push_back(u.user);
} else if (u.offset == 1 && u.user->inputs()[0] != value) {
rhses.push_back(u.user);
}
}
}
return std::make_pair(postprocess(lhses), postprocess(rhses));
}
void BatchMMSide(Block* block, AliasDb& alias_db) {
// NB: 8 is the current loop unrolling factor
static constexpr size_t how_many_is_many = 8;
const auto batch_side = [&](std::vector<Node*>& mms, Side side) {
AT_ASSERT(!mms.empty());
for (int64_t i = static_cast<int64_t>(mms.size()) - 2; i >= 0; --i) {
bool move_ok = alias_db.moveBeforeTopologicallyValid(mms[i], mms[i + 1]);
AT_ASSERT(move_ok);
}
WithInsertPoint insert_guard{mms[0]};
Graph* graph = mms[0]->owningGraph();
Node* batch_mm = graph->create(
prim::MMBatchSide,
/*inputs=*/{},
/*num_outputs=*/mms.size());
graph->insertNode(batch_mm);
batch_mm->i_(Symbol::attr("side"), static_cast<int>(side));
Value* const_side = mms[0]->inputs().at(side == Side::LHS ? 0 : 1);
batch_mm->addInput(const_side);
for (size_t i = 0; i < mms.size(); ++i) {
batch_mm->addInput(mms[i]->inputs().at(side == Side::LHS ? 1 : 0));
mms[i]->output()->replaceAllUsesWith(batch_mm->outputs().at(i));
}
};
std::unordered_set<Value*> considered_values;
for (Node* node : block->nodes()) {
if (node->matches("aten::mm(Tensor self, Tensor mat2) -> Tensor")) {
for (Value* input : node->inputs()) {
if (/*bool not_inserted = */ !considered_values.emplace(input).second) {
continue;
}
auto uses_with_many = gatherIndependentMMUses(input, alias_db);
if (uses_with_many.first.size() >= how_many_is_many) {
batch_side(uses_with_many.first, Side::LHS);
}
if (uses_with_many.second.size() >= how_many_is_many) {
batch_side(uses_with_many.second, Side::RHS);
}
}
} else {
for (Block* subblock : node->blocks()) {
BatchMMSide(subblock, alias_db);
}
}
}
}
bool hasMutableOperators(Block* block) {
for (auto n : block->nodes()) {
if (n->kind().is_aten() && n->schema().is_mutable())
return true;
for (auto b : n->blocks()) {
if (hasMutableOperators(b))
return true;
}
}
return false;
}
void BatchMM(std::shared_ptr<Graph>& graph) {
if (hasMutableOperators(graph->block())) {
// TODO(suo): make BatchMM mutability-safe
return;
}
AliasDb alias_db(graph);
BatchMMTreeReduce(graph->block());
BatchMMSide(graph->block(), alias_db);
EliminateDeadCode(graph);
// It's possible that transpose rearrangements have created sequences of
// consecutive transposes that didn't exist before.
// tensor type properties are not guaranteed to be correct
PeepholeOptimize(graph, /*disable_shape_peepholes*/ true);
}
} // namespace jit
} // namespace torch
| 36.950515 | 83 | 0.601529 | [
"vector",
"transform"
] |
11ee848b5ba3f5815d24be5de8433df34f51c526 | 58,025 | cpp | C++ | lib/VM/JSProxy.cpp | Huxpro/hermes | 2a689c6850d597d2fcac2b5d6f2b08ac498255d0 | [
"MIT"
] | null | null | null | lib/VM/JSProxy.cpp | Huxpro/hermes | 2a689c6850d597d2fcac2b5d6f2b08ac498255d0 | [
"MIT"
] | 1 | 2021-04-19T09:50:36.000Z | 2021-04-19T09:50:36.000Z | lib/VM/JSProxy.cpp | Huxpro/hermes | 2a689c6850d597d2fcac2b5d6f2b08ac498255d0 | [
"MIT"
] | null | null | null | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#include "hermes/VM/JSProxy.h"
#include "hermes/VM/ArrayLike.h"
#include "hermes/VM/Callable.h"
#include "hermes/VM/JSArray.h"
#include "hermes/VM/JSCallableProxy.h"
#include "hermes/VM/OrderedHashMap.h"
#include "hermes/VM/PropertyAccessor.h"
#include "llvh/ADT/SmallSet.h"
namespace hermes {
namespace vm {
namespace detail {
ProxySlots &slots(JSObject *self) {
if (auto *proxy = dyn_vmcast<JSProxy>(self)) {
return proxy->slots_;
} else {
auto *cproxy = dyn_vmcast<JSCallableProxy>(self);
assert(
cproxy && "JSProxy methods must be passed JSProxy or JSCallableProxy");
return cproxy->slots_;
}
}
CallResult<Handle<Callable>>
findTrap(Handle<JSObject> selfHandle, Runtime *runtime, Predefined::Str name) {
// 2. Let handler be O.[[ProxyHandler]].
// 3. If handler is null, throw a TypeError exception.
JSObject *handlerPtr = detail::slots(*selfHandle).handler.get(runtime);
if (!handlerPtr) {
return runtime->raiseTypeError("Proxy handler is null");
}
GCScope gcScope(runtime);
// 4. Assert: Type(handler) is Object.
// 5. Let target be O.[[ProxyTarget]].
// 6. Let trap be ? GetMethod(handler, « name »).
Handle<JSObject> handler = runtime->makeHandle(handlerPtr);
CallResult<PseudoHandle<>> trapVal =
JSObject::getNamed_RJS(handler, runtime, Predefined::getSymbolID(name));
if (trapVal == ExecutionStatus::EXCEPTION) {
return ExecutionStatus::EXCEPTION;
}
if ((*trapVal)->isUndefined() || (*trapVal)->isNull()) {
return Runtime::makeNullHandle<Callable>();
}
if (!vmisa<Callable>(trapVal->get())) {
return runtime->raiseTypeErrorForValue(
runtime->makeHandle(std::move(*trapVal)),
" is not a Proxy trap function");
}
return runtime->makeHandleInParentScope<Callable>(std::move(trapVal->get()));
}
} // namespace detail
//===----------------------------------------------------------------------===//
// class JSProxy
const ObjectVTable JSProxy::vt{
VTable(CellKind::ProxyKind, cellSize<JSProxy>()),
JSProxy::_getOwnIndexedRangeImpl,
JSProxy::_haveOwnIndexedImpl,
JSProxy::_getOwnIndexedPropertyFlagsImpl,
JSProxy::_getOwnIndexedImpl,
JSProxy::_setOwnIndexedImpl,
JSProxy::_deleteOwnIndexedImpl,
JSProxy::_checkAllOwnIndexedImpl,
};
void ProxyBuildMeta(const GCCell *cell, Metadata::Builder &mb) {
mb.addJSObjectOverlapSlots(JSObject::numOverlapSlots<JSProxy>());
ObjectBuildMeta(cell, mb);
const auto *self = static_cast<const JSProxy *>(cell);
mb.addField("@target", &self->slots_.target);
mb.addField("@handler", &self->slots_.handler);
}
#ifdef HERMESVM_SERIALIZE
JSProxy::JSProxy(Deserializer &d) : JSObject(d, &vt.base) {
d.readRelocation(&slots_.target, RelocationKind::GCPointer);
d.readRelocation(&slots_.handler, RelocationKind::GCPointer);
}
void ProxySerialize(Serializer &s, const GCCell *cell) {
JSObject::serializeObjectImpl(s, cell, JSObject::numOverlapSlots<JSProxy>());
auto *self = vmcast<const JSProxy>(cell);
s.writeRelocation(self->slots_.target.get(s.getRuntime()));
s.writeRelocation(self->slots_.handler.get(s.getRuntime()));
s.endObject(cell);
}
void ProxyDeserialize(Deserializer &d, CellKind kind) {
assert(kind == CellKind::ProxyKind && "Expected Proxy");
auto *cell = d.getRuntime()->makeAFixed<JSProxy>(d);
d.endObject(cell);
}
#endif
PseudoHandle<JSProxy> JSProxy::create(Runtime *runtime) {
JSProxy *proxy = runtime->makeAFixed<JSProxy>(
runtime,
Handle<JSObject>::vmcast(&runtime->objectPrototype),
runtime->getHiddenClassForPrototype(
runtime->objectPrototypeRawPtr,
JSObject::numOverlapSlots<JSProxy>() + ANONYMOUS_PROPERTY_SLOTS));
proxy->flags_.proxyObject = true;
return JSObjectInit::initToPseudoHandle(runtime, proxy);
}
void JSProxy::setTargetAndHandler(
Handle<JSObject> selfHandle,
Runtime *runtime,
Handle<JSObject> target,
Handle<JSObject> handler) {
auto &slots = detail::slots(*selfHandle);
slots.target.set(runtime, target.get(), &runtime->getHeap());
slots.handler.set(runtime, handler.get(), &runtime->getHeap());
}
namespace {
void completePropertyDescriptor(DefinePropertyFlags &desc) {
if ((desc.setValue || desc.setWritable) ||
(!desc.setGetter && !desc.setSetter)) {
if (!desc.setWritable) {
desc.writable = false;
}
}
if (!desc.setEnumerable) {
desc.enumerable = false;
}
if (!desc.setConfigurable) {
desc.configurable = false;
}
}
// ES9 9.1.6.2 IsCompatiblePropertyDescriptor
// prereq: step 2 is already done externally.
// The abstract definition returns a boolean; this returns EXCEPTION
// (and sets an exception) or RETURNED instead of false or true, so
// the exception messages can be more specific.
ExecutionStatus isCompatiblePropertyDescriptor(
Runtime *runtime,
const DefinePropertyFlags &desc,
Handle<> descValueOrAccessor,
const ComputedPropertyDescriptor ¤t,
Handle<> currentValueOrAccessor) {
// 4. If current.[[Configurable]] is false, then
if (!current.flags.configurable) {
// a. If Desc.[[Configurable]] is present and its value is true, return
// false.
if (desc.setConfigurable && desc.configurable) {
return runtime->raiseTypeError(
"trap result is configurable but target property is non-configurable");
}
// b. If Desc.[[Enumerable]] is present and the [[Enumerable]]
// fields of current and Desc are the Boolean negation of each
// other, return false.
if (desc.setEnumerable && desc.enumerable != current.flags.enumerable) {
return runtime->raiseTypeError(
TwineChar16("trap result is ") + (desc.enumerable ? "" : "not ") +
"enumerable but target property is " +
(current.flags.enumerable ? "" : "not ") + "enumerable");
}
}
// 5. If IsGenericDescriptor(Desc) is true, no further validation is required.
bool descIsAccessor = desc.setSetter || desc.setGetter;
bool descIsData = desc.setValue || desc.setWritable;
assert(
(!descIsData || !descIsAccessor) &&
"descriptor cannot be both Data and Accessor");
if (!descIsData && !descIsAccessor) {
return ExecutionStatus::RETURNED;
}
// 6. Else if IsDataDescriptor(current) and IsDataDescriptor(Desc)
// have different results, then
bool currentIsAccessor = current.flags.accessor;
bool currentIsData = !currentIsAccessor;
if (currentIsData != descIsData) {
// a. If current.[[Configurable]] is false, return false.
if (!current.flags.configurable) {
return runtime->raiseTypeError(
TwineChar16("trap result is ") +
(currentIsData ? "data " : "accessor ") + "but target property is " +
(descIsData ? "data " : "accessor ") + "and non-configurable");
}
}
// 7. Else if IsDataDescriptor(current) and IsDataDescriptor(Desc) are both
// true, then
// a. If current.[[Configurable]] is false and current.[[Writable]] is
// false, then
if (currentIsData && descIsData && !current.flags.configurable &&
!current.flags.writable) {
// i. If Desc.[[Writable]] is present and Desc.[[Writable]] is true,
// return false.
if (desc.setWritable && desc.writable) {
return runtime->raiseTypeError(
"trap result is writable but "
"target property is non-configurable and non-writable");
}
// ii. If Desc.[[Value]] is present and SameValue(Desc.[[Value]],
// current.[[Value]]) is false, return false.
if (desc.setValue &&
!isSameValue(
descValueOrAccessor.getHermesValue(),
currentValueOrAccessor.getHermesValue())) {
return runtime->raiseTypeError(
"trap result has different value than target property but "
"target property is non-configurable and non-writable");
}
// iii. Return true.
return ExecutionStatus::RETURNED;
}
// 8. Else IsAccessorDescriptor(current) and IsAccessorDescriptor(Desc) are
// both true,
// a. If current.[[Configurable]] is false, then
if (currentIsAccessor && descIsAccessor && !current.flags.configurable) {
PropertyAccessor *descAccessor =
vmcast<PropertyAccessor>(descValueOrAccessor.get());
PropertyAccessor *currentAccessor =
vmcast<PropertyAccessor>(currentValueOrAccessor.get());
// i. If Desc.[[Set]] is present and SameValue(Desc.[[Set]],
// current.[[Set]]) is false, return false.
if (descAccessor->setter &&
descAccessor->setter != currentAccessor->setter) {
return runtime->raiseTypeError(
"trap result has different setter than target property but "
"target property is non-configurable");
}
// ii. If Desc.[[Get]] is present and SameValue(Desc.[[Get]],
// current.[[Get]]) is false, return false.
if (descAccessor->getter &&
descAccessor->getter != currentAccessor->getter) {
return runtime->raiseTypeError(
"trap result has different getter than target property but "
"target property is non-configurable");
}
// iii. Return true.
}
return ExecutionStatus::RETURNED;
}
} // namespace
CallResult<PseudoHandle<JSObject>> JSProxy::getPrototypeOf(
Handle<JSObject> selfHandle,
Runtime *runtime) {
// Proxies are complex, and various parts of the logic (finding
// traps, undefined traps handling, calling traps, etc) are all
// potentially recursive. Therefore, every entry point creates a
// scope and a ScopedNativeDepthTracker, as it's possible to use up
// arbitrary native stack depth with nested proxies.
GCScope gcScope(runtime);
ScopedNativeDepthTracker depthTracker(runtime);
if (LLVM_UNLIKELY(depthTracker.overflowed())) {
return runtime->raiseStackOverflow(Runtime::StackOverflowKind::NativeStack);
}
Handle<JSObject> target =
runtime->makeHandle(detail::slots(*selfHandle).target);
CallResult<Handle<Callable>> trapRes =
detail::findTrap(selfHandle, runtime, Predefined::getPrototypeOf);
if (LLVM_UNLIKELY(trapRes == ExecutionStatus::EXCEPTION)) {
return ExecutionStatus::EXCEPTION;
}
// 6. If trap is undefined, then
if (!*trapRes) {
// a. Return ? target.[[GetPrototypeOf]](P).
return JSObject::getPrototypeOf(target, runtime);
}
// 7. Let handlerProto be ? Call(trap, handler, « target »).
CallResult<PseudoHandle<>> handlerProtoRes = Callable::executeCall1(
*trapRes,
runtime,
runtime->makeHandle(detail::slots(*selfHandle).handler),
target.getHermesValue());
if (handlerProtoRes == ExecutionStatus::EXCEPTION) {
return ExecutionStatus::EXCEPTION;
}
// 8. If Type(handlerProto) is neither Object nor Null, throw a TypeError
// exception.
if (!(*handlerProtoRes)->isObject() && !(*handlerProtoRes)->isNull()) {
return runtime->raiseTypeError(
"getPrototypeOf trap result is neither Object nor Null");
}
Handle<JSObject> handlerProto =
runtime->makeHandle(dyn_vmcast<JSObject>(handlerProtoRes->get()));
// 9. Let extensibleTarget be ? IsExtensible(target).
CallResult<bool> extensibleRes = JSObject::isExtensible(target, runtime);
if (extensibleRes == ExecutionStatus::EXCEPTION) {
return ExecutionStatus::EXCEPTION;
}
// 10. If extensibleTarget is true, return handlerProto.
if (*extensibleRes) {
return createPseudoHandle(*handlerProto);
}
// 11. Let targetProto be ? target.[[GetPrototypeOf]]().
CallResult<PseudoHandle<JSObject>> targetProtoRes =
JSObject::getPrototypeOf(target, runtime);
if (targetProtoRes == ExecutionStatus::EXCEPTION) {
return ExecutionStatus::EXCEPTION;
}
// 12. If SameValue(handlerProto, targetProto) is false, throw a TypeError
// exception.
if (handlerProto.get() != targetProtoRes->get()) {
return runtime->raiseTypeError(
"getPrototypeOf trap result is not the same as non-extensible target getPrototypeOf");
}
// 13. Return handlerProto.
return std::move(*targetProtoRes);
}
CallResult<bool> JSProxy::setPrototypeOf(
Handle<JSObject> selfHandle,
Runtime *runtime,
Handle<JSObject> parent) {
GCScope gcScope{runtime};
ScopedNativeDepthTracker depthTracker(runtime);
if (LLVM_UNLIKELY(depthTracker.overflowed())) {
return runtime->raiseStackOverflow(Runtime::StackOverflowKind::NativeStack);
}
Handle<JSObject> target =
runtime->makeHandle(detail::slots(*selfHandle).target);
CallResult<Handle<Callable>> trapRes =
detail::findTrap(selfHandle, runtime, Predefined::setPrototypeOf);
if (trapRes == ExecutionStatus::EXCEPTION) {
return ExecutionStatus::EXCEPTION;
}
// 7. If trap is undefined, then
if (!*trapRes) {
// a. Return ? target.[[SetPrototypeOf]](V).
return JSObject::setParent(*target, runtime, *parent);
}
// 8. Let booleanTrapResult be ToBoolean(? Call(trap, handler, « target, V
// »)).
CallResult<PseudoHandle<>> booleanTrapRes = Callable::executeCall2(
*trapRes,
runtime,
runtime->makeHandle(detail::slots(*selfHandle).handler),
target.getHermesValue(),
*parent ? parent.getHermesValue() : HermesValue::encodeNullValue());
if (booleanTrapRes == ExecutionStatus::EXCEPTION) {
return ExecutionStatus::EXCEPTION;
}
// 9. If booleanTrapResult is false, return false.
if (!toBoolean(booleanTrapRes->get())) {
return false;
}
// 10. Let extensibleTarget be ? IsExtensible(target).
CallResult<bool> extensibleRes = JSObject::isExtensible(target, runtime);
if (extensibleRes == ExecutionStatus::EXCEPTION) {
return ExecutionStatus::EXCEPTION;
}
// 11. If extensibleTarget is true, return true.
if (*extensibleRes) {
return true;
}
// 12. Let targetProto be ? target.[[GetPrototypeOf]]().
CallResult<PseudoHandle<JSObject>> targetProtoRes =
JSObject::getPrototypeOf(target, runtime);
if (targetProtoRes == ExecutionStatus::EXCEPTION) {
return ExecutionStatus::EXCEPTION;
}
// 13. If SameValue(V, targetProto) is false, throw a TypeError exception.
if (parent.get() != targetProtoRes->get()) {
return runtime->raiseTypeError(
"setPrototypeOf trap changed prototype on non-extensible target");
}
// 14. Return true.
return true;
}
CallResult<bool> JSProxy::isExtensible(
Handle<JSObject> selfHandle,
Runtime *runtime) {
GCScope gcScope{runtime};
ScopedNativeDepthTracker depthTracker(runtime);
if (LLVM_UNLIKELY(depthTracker.overflowed())) {
return runtime->raiseStackOverflow(Runtime::StackOverflowKind::NativeStack);
}
Handle<JSObject> target =
runtime->makeHandle(detail::slots(*selfHandle).target);
CallResult<Handle<Callable>> trapRes =
detail::findTrap(selfHandle, runtime, Predefined::isExtensible);
if (trapRes == ExecutionStatus::EXCEPTION) {
return ExecutionStatus::EXCEPTION;
}
// 6. If trap is undefined, then
if (!*trapRes) {
// a. Return ? target.[[IsExtensible]]().
return JSObject::isExtensible(target, runtime);
}
// 7. Let booleanTrapResult be ToBoolean(? Call(trap, handler, « target »)).
CallResult<PseudoHandle<>> res = Callable::executeCall1(
*trapRes,
runtime,
runtime->makeHandle(detail::slots(*selfHandle).handler),
target.getHermesValue());
if (res == ExecutionStatus::EXCEPTION) {
return ExecutionStatus::EXCEPTION;
}
// 8. Let targetResult be ? target.[[IsExtensible]]().
CallResult<bool> targetRes = JSObject::isExtensible(target, runtime);
if (targetRes == ExecutionStatus::EXCEPTION) {
return ExecutionStatus::EXCEPTION;
}
// 9. If SameValue(booleanTrapResult, targetResult) is false, throw
// a TypeError exception.
bool booleanTrapResult = toBoolean(res->get());
if (booleanTrapResult != *targetRes) {
return runtime->raiseTypeError(
"isExtensible trap returned different value than target");
}
// 10. Return booleanTrapResult.
return booleanTrapResult;
}
CallResult<bool> JSProxy::preventExtensions(
Handle<JSObject> selfHandle,
Runtime *runtime,
PropOpFlags opFlags) {
GCScope gcScope{runtime};
ScopedNativeDepthTracker depthTracker(runtime);
if (LLVM_UNLIKELY(depthTracker.overflowed())) {
return runtime->raiseStackOverflow(Runtime::StackOverflowKind::NativeStack);
}
Handle<JSObject> target =
runtime->makeHandle(detail::slots(*selfHandle).target);
CallResult<Handle<Callable>> trapRes =
detail::findTrap(selfHandle, runtime, Predefined::preventExtensions);
if (trapRes == ExecutionStatus::EXCEPTION) {
return ExecutionStatus::EXCEPTION;
}
// 6. If trap is undefined, then
if (!*trapRes) {
// a. Return ? target.[[PreventExtensions]]().
// We pass in opFlags here. If getThrowOnError, then this will cause
// the underlying exception to bubble up. If !getThrowOnError, then
// we don't get a chance to raise a particular exception anyway. So in
// either case, just return the CallResult.
return JSObject::preventExtensions(target, runtime, opFlags);
}
// 7. Let booleanTrapResult be ToBoolean(? Call(trap, handler, « target »)).
CallResult<PseudoHandle<>> res = Callable::executeCall1(
*trapRes,
runtime,
runtime->makeHandle(detail::slots(*selfHandle).handler),
target.getHermesValue());
if (res == ExecutionStatus::EXCEPTION) {
return ExecutionStatus::EXCEPTION;
}
bool booleanTrapResult = toBoolean(res->get());
if (booleanTrapResult) {
// a. Let targetIsExtensible be ? target.[[IsExtensible]]().
CallResult<bool> targetRes = JSObject::isExtensible(target, runtime);
if (targetRes == ExecutionStatus::EXCEPTION) {
return ExecutionStatus::EXCEPTION;
}
// b. If targetIsExtensible is true, throw a TypeError exception.
if (*targetRes) {
return runtime->raiseTypeError(
"preventExtensions trap returned true for extensible target");
}
}
// 10. Return booleanTrapResult.
if (!booleanTrapResult && opFlags.getThrowOnError()) {
return runtime->raiseTypeError("preventExtensions trap returned false");
}
return booleanTrapResult;
}
CallResult<bool> JSProxy::getOwnProperty(
Handle<JSObject> selfHandle,
Runtime *runtime,
Handle<> nameValHandle,
ComputedPropertyDescriptor &desc,
MutableHandle<> *valueOrAccessor) {
GCScope gcScope{runtime};
ScopedNativeDepthTracker depthTracker(runtime);
if (LLVM_UNLIKELY(depthTracker.overflowed())) {
return runtime->raiseStackOverflow(Runtime::StackOverflowKind::NativeStack);
}
Handle<JSObject> target =
runtime->makeHandle(detail::slots(*selfHandle).target);
CallResult<Handle<Callable>> trapRes = detail::findTrap(
selfHandle, runtime, Predefined::getOwnPropertyDescriptor);
if (trapRes == ExecutionStatus::EXCEPTION) {
return ExecutionStatus::EXCEPTION;
}
MutableHandle<SymbolID> tmpPropNameStorage{runtime};
// 7. If trap is undefined, then
if (!*trapRes) {
// a. Return ? target.[[GetOwnProperty]](P).
return valueOrAccessor
? JSObject::getOwnComputedDescriptor(
target,
runtime,
nameValHandle,
tmpPropNameStorage,
desc,
*valueOrAccessor)
: JSObject::getOwnComputedDescriptor(
target, runtime, nameValHandle, tmpPropNameStorage, desc);
}
// 8. Let trapResultObj be ? Call(trap, handler, « target, P »).
// 9. If Type(trapResultObj) is neither Object nor Undefined, throw a
// TypeError exception.
CallResult<PseudoHandle<>> trapResultRes = Callable::executeCall2(
*trapRes,
runtime,
runtime->makeHandle(detail::slots(*selfHandle).handler),
target.getHermesValue(),
nameValHandle.getHermesValue());
if (trapResultRes == ExecutionStatus::EXCEPTION) {
return ExecutionStatus::EXCEPTION;
}
Handle<> trapResultObj = runtime->makeHandle(std::move(*trapResultRes));
// 10. Let targetDesc be ? target.[[GetOwnProperty]](P).
ComputedPropertyDescriptor targetDesc;
MutableHandle<> targetValueOrAccessor{runtime};
CallResult<bool> targetDescRes = JSObject::getOwnComputedDescriptor(
target,
runtime,
nameValHandle,
tmpPropNameStorage,
targetDesc,
targetValueOrAccessor);
if (targetDescRes == ExecutionStatus::EXCEPTION) {
return ExecutionStatus::EXCEPTION;
}
// 11. If trapResultObj is undefined, then
if (trapResultObj->isUndefined()) {
// a. If targetDesc is undefined, return undefined.
if (!*targetDescRes) {
return false;
}
// b. If targetDesc.[[Configurable]] is false, throw a TypeError
// exception.
if (!targetDesc.flags.configurable) {
return runtime->raiseTypeError(
"getOwnPropertyDescriptor trap result is not configurable");
}
// c. Let extensibleTarget be ? IsExtensible(target).
CallResult<bool> extensibleRes = JSObject::isExtensible(target, runtime);
if (extensibleRes == ExecutionStatus::EXCEPTION) {
return ExecutionStatus::EXCEPTION;
}
// d. Assert: Type(extensibleTarget) is Boolean.
// e. If extensibleTarget is false, throw a TypeError exception.
if (!*extensibleRes) {
return runtime->raiseTypeErrorForValue(
runtime->makeHandle(detail::slots(*selfHandle).target),
" is not extensible (getOwnPropertyDescriptor target)");
}
// f. Return undefined.
return false;
} else if (!trapResultObj->isObject()) {
// 9. If Type(trapResultObj) is neither Object nor Undefined, throw a
// TypeError exception.
return runtime->raiseTypeErrorForValue(
trapResultObj,
" is not undefined or Object (Proxy getOwnPropertyDescriptor)");
}
// 12. Let extensibleTarget be ? IsExtensible(target).
CallResult<bool> extensibleRes = JSObject::isExtensible(target, runtime);
if (extensibleRes == ExecutionStatus::EXCEPTION) {
return ExecutionStatus::EXCEPTION;
}
// 13. Let resultDesc be ? ToPropertyDescriptor(trapResultObj).
// 14. Call CompletePropertyDescriptor(resultDesc).
DefinePropertyFlags resultDesc;
MutableHandle<> resultValueOrAccessor{runtime};
Handle<JSObject> trapResult = runtime->makeHandle<JSObject>(*trapResultObj);
if (LLVM_UNLIKELY(
toPropertyDescriptor(
trapResult, runtime, resultDesc, resultValueOrAccessor) ==
ExecutionStatus::EXCEPTION)) {
return ExecutionStatus::EXCEPTION;
}
completePropertyDescriptor(resultDesc);
// 15. Let valid be IsCompatiblePropertyDescriptor(extensibleTarget,
// resultDesc, targetDesc).
// 16. If valid is false, throw a TypeError exception.
// ES9 9.1.6.3 ValidateAndApplyPropertyDescriptor step 2 [O is undefined]
if (!*targetDescRes) {
// a. If extensible is false, return false.
if (!*extensibleRes) {
return runtime->raiseTypeErrorForValue(
"getOwnPropertyDescriptor target is not extensible and has no property ",
nameValHandle,
"");
}
// e. return true
// this concludes steps 15 and 16.
} else {
if (LLVM_UNLIKELY(
isCompatiblePropertyDescriptor(
runtime,
resultDesc,
resultValueOrAccessor,
targetDesc,
targetValueOrAccessor) == ExecutionStatus::EXCEPTION)) {
return ExecutionStatus::EXCEPTION;
}
}
// 17. If resultDesc.[[Configurable]] is false, then
// a. If targetDesc is undefined or targetDesc.[[Configurable]] is true,
// then
// i. Throw a TypeError exception.
if (!resultDesc.configurable &&
(!*targetDescRes || targetDesc.flags.configurable)) {
return runtime->raiseTypeErrorForValue(
"getOwnPropertyDescriptor trap result is not configurable but "
"target property ",
nameValHandle,
" is configurable or non-existent");
}
// 18. Return resultDesc.
desc.flags.enumerable = resultDesc.enumerable;
desc.flags.configurable = resultDesc.configurable;
desc.flags.writable = resultDesc.writable;
if (resultDesc.setGetter || resultDesc.setSetter) {
desc.flags.accessor = true;
}
if (valueOrAccessor) {
*valueOrAccessor = std::move(resultValueOrAccessor);
}
return true;
}
CallResult<bool> JSProxy::defineOwnProperty(
Handle<JSObject> selfHandle,
Runtime *runtime,
Handle<> nameValHandle,
DefinePropertyFlags dpFlags,
Handle<> valueOrAccessor,
PropOpFlags opFlags) {
GCScope gcScope{runtime};
ScopedNativeDepthTracker depthTracker(runtime);
if (LLVM_UNLIKELY(depthTracker.overflowed())) {
return runtime->raiseStackOverflow(Runtime::StackOverflowKind::NativeStack);
}
Handle<JSObject> target =
runtime->makeHandle(detail::slots(*selfHandle).target);
CallResult<Handle<Callable>> trapRes =
detail::findTrap(selfHandle, runtime, Predefined::defineProperty);
if (trapRes == ExecutionStatus::EXCEPTION) {
return ExecutionStatus::EXCEPTION;
}
// 7. If trap is undefined, then
if (!*trapRes) {
// a. Return ? target.[[GetOwnProperty]](P).
return JSObject::defineOwnComputedPrimitive(
target, runtime, nameValHandle, dpFlags, valueOrAccessor, opFlags);
}
// 8. Let descObj be FromPropertyDescriptor(Desc).
ComputedPropertyDescriptor desc;
desc.flags.accessor = dpFlags.setGetter || dpFlags.setSetter;
desc.flags.writable = dpFlags.setWritable && dpFlags.writable;
desc.flags.enumerable = dpFlags.setEnumerable && dpFlags.enumerable;
desc.flags.configurable = dpFlags.setConfigurable && dpFlags.configurable;
CallResult<HermesValue> descObjRes =
objectFromPropertyDescriptor(runtime, desc, valueOrAccessor);
if (descObjRes == ExecutionStatus::EXCEPTION) {
return ExecutionStatus::EXCEPTION;
}
// 9. Let booleanTrapResult be ToBoolean(? Call(trap, handler, « target, P,
// descObj »)).
CallResult<PseudoHandle<>> trapResultRes = Callable::executeCall3(
*trapRes,
runtime,
runtime->makeHandle(detail::slots(*selfHandle).handler),
target.getHermesValue(),
nameValHandle.getHermesValue(),
*descObjRes);
if (trapResultRes == ExecutionStatus::EXCEPTION) {
return ExecutionStatus::EXCEPTION;
}
bool trapResult = toBoolean(trapResultRes->get());
// 10. If booleanTrapResult is false, return false.
if (!trapResult) {
if (opFlags.getThrowOnError()) {
return runtime->raiseTypeError(
"defineProperty proxy trap returned false");
} else {
return false;
}
}
// 11. Let targetDesc be ? target.[[GetOwnProperty]](P).
ComputedPropertyDescriptor targetDesc;
MutableHandle<> targetDescValueOrAccessor{runtime};
MutableHandle<SymbolID> tmpPropNameStorage{runtime};
CallResult<bool> targetDescRes = JSObject::getOwnComputedDescriptor(
target,
runtime,
nameValHandle,
tmpPropNameStorage,
targetDesc,
targetDescValueOrAccessor);
if (targetDescRes == ExecutionStatus::EXCEPTION) {
return ExecutionStatus::EXCEPTION;
}
// 12. Let extensibleTarget be ? IsExtensible(target).
CallResult<bool> extensibleRes = JSObject::isExtensible(target, runtime);
if (extensibleRes == ExecutionStatus::EXCEPTION) {
return ExecutionStatus::EXCEPTION;
}
// 13. If Desc has a [[Configurable]] field and if Desc.[[Configurable]] is
// false, then
// a. Let settingConfigFalse be true.
// 14. Else, let settingConfigFalse be false.
bool settingConfigFalse = dpFlags.setConfigurable && !dpFlags.configurable;
// 15. If targetDesc is undefined, then
if (!*targetDescRes) {
// a. If extensibleTarget is false, throw a TypeError exception.
if (!*extensibleRes) {
return runtime->raiseTypeError(
"defineProperty trap called for non-existent property on non-extensible target");
}
// b. If settingConfigFalse is true, throw a TypeError exception.
if (settingConfigFalse) {
return runtime->raiseTypeError(
"defineProperty trap attempted to define non-configurable property for non-existent property in the target");
}
} else {
// 16. Else targetDesc is not undefined,
// a. If IsCompatiblePropertyDescriptor(extensibleTarget, Desc,
// targetDesc) is false, throw a TypeError exception.
if (LLVM_UNLIKELY(
isCompatiblePropertyDescriptor(
runtime,
dpFlags,
valueOrAccessor,
targetDesc,
targetDescValueOrAccessor) == ExecutionStatus::EXCEPTION)) {
return ExecutionStatus::EXCEPTION;
}
// b. If settingConfigFalse is true and targetDesc.[[Configurable]] is
// true, throw a TypeError exception.
if (settingConfigFalse && targetDesc.flags.configurable) {
return runtime->raiseTypeError(
"defineProperty trap attempted to define non-configurable property for configurable property in the target");
}
}
// 17. Return true.
return true;
}
namespace {
/// Common parts of hasNamed/hasComputed
CallResult<bool> hasWithTrap(
Runtime *runtime,
Handle<> nameValHandle,
Handle<Callable> trap,
Handle<JSObject> handler,
Handle<JSObject> target) {
// 1. Assert: IsPropertyKey(P) is true.
assert(isPropertyKey(nameValHandle) && "key is not a String or Symbol");
// 8. Let booleanTrapResult be ToBoolean(? Call(trap, handler, « target, P
// »)).
CallResult<PseudoHandle<>> trapResultRes = Callable::executeCall2(
trap,
runtime,
handler,
target.getHermesValue(),
nameValHandle.getHermesValue());
if (trapResultRes == ExecutionStatus::EXCEPTION) {
return ExecutionStatus::EXCEPTION;
}
bool trapResult = toBoolean(trapResultRes->get());
// 9. If booleanTrapResult is false, then
if (!trapResult) {
// a. Let targetDesc be ? target.[[GetOwnProperty]](P).
ComputedPropertyDescriptor targetDesc;
MutableHandle<SymbolID> tmpPropNameStorage{runtime};
CallResult<bool> targetDescRes = JSObject::getOwnComputedDescriptor(
target, runtime, nameValHandle, tmpPropNameStorage, targetDesc);
if (targetDescRes == ExecutionStatus::EXCEPTION) {
return ExecutionStatus::EXCEPTION;
}
// b. If targetDesc is not undefined, then
if (*targetDescRes) {
// i. If targetDesc.[[Configurable]] is false, throw a TypeError
// exception.
if (!targetDesc.flags.configurable) {
return runtime->raiseTypeError(
"HasProperty trap result is not configurable");
}
// ii. Let extensibleTarget be ? IsExtensible(target).
CallResult<bool> extensibleRes = JSObject::isExtensible(target, runtime);
if (extensibleRes == ExecutionStatus::EXCEPTION) {
return ExecutionStatus::EXCEPTION;
}
// iii. If extensibleTarget is false, throw a TypeError exception.
if (!*extensibleRes) {
return runtime->raiseTypeError(
"HasProperty proxy target is not extensible");
}
}
}
// 11. Return trapResult.
return trapResult;
}
} // namespace
CallResult<bool> JSProxy::hasNamed(
Handle<JSObject> selfHandle,
Runtime *runtime,
SymbolID name) {
GCScope gcScope{runtime};
ScopedNativeDepthTracker depthTracker(runtime);
if (LLVM_UNLIKELY(depthTracker.overflowed())) {
return runtime->raiseStackOverflow(Runtime::StackOverflowKind::NativeStack);
}
Handle<JSObject> target =
runtime->makeHandle(detail::slots(*selfHandle).target);
CallResult<Handle<Callable>> trapRes =
detail::findTrap(selfHandle, runtime, Predefined::has);
if (trapRes == ExecutionStatus::EXCEPTION) {
return ExecutionStatus::EXCEPTION;
}
// 7. If trap is undefined, then
if (!*trapRes) {
// a. Return ? target.[[HasProperty]](P, Receiver).
return JSObject::hasNamed(target, runtime, name);
}
return hasWithTrap(
runtime,
runtime->makeHandle(HermesValue::encodeStringValue(
runtime->getStringPrimFromSymbolID(name))),
*trapRes,
runtime->makeHandle(detail::slots(*selfHandle).handler),
target);
}
CallResult<bool> JSProxy::hasComputed(
Handle<JSObject> selfHandle,
Runtime *runtime,
Handle<> nameValHandle) {
GCScope gcScope{runtime};
ScopedNativeDepthTracker depthTracker(runtime);
if (LLVM_UNLIKELY(depthTracker.overflowed())) {
return runtime->raiseStackOverflow(Runtime::StackOverflowKind::NativeStack);
}
Handle<JSObject> target =
runtime->makeHandle(detail::slots(*selfHandle).target);
CallResult<Handle<Callable>> trapRes =
detail::findTrap(selfHandle, runtime, Predefined::has);
if (trapRes == ExecutionStatus::EXCEPTION) {
return ExecutionStatus::EXCEPTION;
}
if (!*trapRes) {
// 7. If trap is undefined, then
// a. Return ? target.[[HasProperty]](P, Receiver).
return JSObject::hasComputed(target, runtime, nameValHandle);
}
return hasWithTrap(
runtime,
nameValHandle,
*trapRes,
runtime->makeHandle(detail::slots(*selfHandle).handler),
target);
}
namespace {
/// Common parts of getNamed/getComputed
CallResult<PseudoHandle<>> getWithTrap(
Runtime *runtime,
Handle<> nameValHandle,
Handle<Callable> trap,
Handle<JSObject> handler,
Handle<JSObject> target,
Handle<> receiver) {
// 1. Assert: IsPropertyKey(P) is true.
assert(isPropertyKey(nameValHandle) && "key is not a String or Symbol");
// 8. Let trapResult be ? Call(trap, handler, « target, P, Receiver »).
CallResult<PseudoHandle<>> trapResultRes = Callable::executeCall3(
trap,
runtime,
handler,
target.getHermesValue(),
nameValHandle.getHermesValue(),
receiver.getHermesValue());
if (trapResultRes == ExecutionStatus::EXCEPTION) {
return ExecutionStatus::EXCEPTION;
}
Handle<> trapResult = runtime->makeHandle(std::move(*trapResultRes));
// 9. Let targetDesc be ? target.[[GetOwnProperty]](P).
ComputedPropertyDescriptor targetDesc;
MutableHandle<> targetValueOrAccessor{runtime};
MutableHandle<SymbolID> tmpPropNameStorage{runtime};
CallResult<bool> targetDescRes = JSObject::getOwnComputedDescriptor(
target,
runtime,
nameValHandle,
tmpPropNameStorage,
targetDesc,
targetValueOrAccessor);
if (targetDescRes == ExecutionStatus::EXCEPTION) {
return ExecutionStatus::EXCEPTION;
}
// 10. If targetDesc is not undefined and targetDesc.[[Configurable]] is
// false, then
if (*targetDescRes && !targetDesc.flags.configurable) {
// a. If IsDataDescriptor(targetDesc) is true and targetDesc.[[Writable]]
// is false, then
if (!targetDesc.flags.accessor && !targetDesc.flags.writable) {
// i. If SameValue(trapResult, targetDesc.[[Value]]) is false, throw a
// TypeError exception.
if (!isSameValue(*trapResult, targetValueOrAccessor.getHermesValue())) {
return runtime->raiseTypeError(
"target property is non-configurable and non-writable, and get trap result differs from target property value");
}
}
// b. If IsAccessorDescriptor(targetDesc) is true and targetDesc.[[Get]]
// is undefined, then
// i. If trapResult is not undefined, throw a TypeError exception.
if (targetDesc.flags.accessor &&
!vmcast<PropertyAccessor>(*targetValueOrAccessor)->getter &&
!trapResult->isUndefined()) {
return runtime->raiseTypeError(
"target property is non-configurable accessor with no getter, but get trap returned not undefined");
}
}
// 11. Return trapResult.
return {trapResult};
}
} // namespace
CallResult<PseudoHandle<>> JSProxy::getNamed(
Handle<JSObject> selfHandle,
Runtime *runtime,
SymbolID name,
Handle<> receiver) {
GCScope gcScope{runtime};
ScopedNativeDepthTracker depthTracker(runtime);
if (LLVM_UNLIKELY(depthTracker.overflowed())) {
return runtime->raiseStackOverflow(Runtime::StackOverflowKind::NativeStack);
}
Handle<JSObject> target =
runtime->makeHandle(detail::slots(*selfHandle).target);
CallResult<Handle<Callable>> trapRes =
detail::findTrap(selfHandle, runtime, Predefined::get);
if (trapRes == ExecutionStatus::EXCEPTION) {
return ExecutionStatus::EXCEPTION;
}
// 7. If trap is undefined, then
if (!*trapRes) {
// a. Return ? target.[[Get]](P, Receiver).
return JSObject::getNamedWithReceiver_RJS(target, runtime, name, receiver);
}
return getWithTrap(
runtime,
name.isUniqued() ? runtime->makeHandle(HermesValue::encodeStringValue(
runtime->getStringPrimFromSymbolID(name)))
: runtime->makeHandle(name),
*trapRes,
runtime->makeHandle(detail::slots(*selfHandle).handler),
target,
receiver);
}
CallResult<PseudoHandle<>> JSProxy::getComputed(
Handle<JSObject> selfHandle,
Runtime *runtime,
Handle<> nameValHandle,
Handle<> receiver) {
GCScope gcScope{runtime};
ScopedNativeDepthTracker depthTracker(runtime);
if (LLVM_UNLIKELY(depthTracker.overflowed())) {
return runtime->raiseStackOverflow(Runtime::StackOverflowKind::NativeStack);
}
Handle<JSObject> target =
runtime->makeHandle(detail::slots(*selfHandle).target);
CallResult<Handle<Callable>> trapRes =
detail::findTrap(selfHandle, runtime, Predefined::get);
if (trapRes == ExecutionStatus::EXCEPTION) {
return ExecutionStatus::EXCEPTION;
}
// 7. If trap is undefined, then
if (!*trapRes) {
// a. Return ? target.[[Get]](P, Receiver).
return JSObject::getComputedWithReceiver_RJS(
target, runtime, nameValHandle, receiver);
}
return getWithTrap(
runtime,
nameValHandle,
*trapRes,
runtime->makeHandle(detail::slots(*selfHandle).handler),
target,
receiver);
}
namespace {
/// Common parts of setNamed/setComputed
CallResult<bool> setWithTrap(
Runtime *runtime,
Handle<> nameValHandle,
Handle<> valueHandle,
Handle<Callable> trap,
Handle<JSObject> handler,
Handle<JSObject> target,
Handle<> receiver) {
// 1. Assert: IsPropertyKey(P) is true.
assert(isPropertyKey(nameValHandle) && "key is not a String or Symbol");
// 8. Let booleanTrapResult be ToBoolean(? Call(trap, handler, « target, P, V,
// Receiver »)).
CallResult<PseudoHandle<>> trapResultRes = Callable::executeCall4(
trap,
runtime,
handler,
target.getHermesValue(),
nameValHandle.getHermesValue(),
valueHandle.getHermesValue(),
receiver.getHermesValue());
if (trapResultRes == ExecutionStatus::EXCEPTION) {
return ExecutionStatus::EXCEPTION;
}
// 9. If booleanTrapResult is false, return false.
if (!toBoolean(trapResultRes->get())) {
return false;
}
// 10. Let targetDesc be ? target.[[GetOwnProperty]](P).
ComputedPropertyDescriptor targetDesc;
MutableHandle<> targetValueOrAccessor{runtime};
MutableHandle<SymbolID> tmpPropNameStorage{runtime};
CallResult<bool> targetDescRes = JSObject::getOwnComputedDescriptor(
target,
runtime,
nameValHandle,
tmpPropNameStorage,
targetDesc,
targetValueOrAccessor);
if (targetDescRes == ExecutionStatus::EXCEPTION) {
return ExecutionStatus::EXCEPTION;
}
// 11. If targetDesc is not undefined and targetDesc.[[Configurable]] is
// false, then
if (*targetDescRes && !targetDesc.flags.configurable) {
// a. If IsDataDescriptor(targetDesc) is true and targetDesc.[[Writable]]
// is false, then
if (!targetDesc.flags.accessor && !targetDesc.flags.writable) {
// i. If SameValue(V, targetDesc.[[Value]]) is false, throw a
// TypeError exception.
if (!isSameValue(
valueHandle.getHermesValue(),
targetValueOrAccessor.getHermesValue())) {
return runtime->raiseTypeError(
"target property is non-configurable and non-writable, and set trap value differs from target property value");
}
}
// b. If IsAccessorDescriptor(targetDesc) is true, then
// i. If targetDesc.[[Set]] is undefined, throw a TypeError exception.
if (targetDesc.flags.accessor &&
!vmcast<PropertyAccessor>(*targetValueOrAccessor)->setter) {
return runtime->raiseTypeError(
"set trap called, but target property is non-configurable accessor with no setter");
}
}
// 12. Return true.
return true;
}
} // namespace
CallResult<bool> JSProxy::setNamed(
Handle<JSObject> selfHandle,
Runtime *runtime,
SymbolID name,
Handle<> valueHandle,
// TODO could be HermesValue
Handle<> receiver) {
GCScope gcScope{runtime};
ScopedNativeDepthTracker depthTracker(runtime);
if (LLVM_UNLIKELY(depthTracker.overflowed())) {
return runtime->raiseStackOverflow(Runtime::StackOverflowKind::NativeStack);
}
Handle<JSObject> target =
runtime->makeHandle(detail::slots(*selfHandle).target);
CallResult<Handle<Callable>> trapRes =
detail::findTrap(selfHandle, runtime, Predefined::set);
if (trapRes == ExecutionStatus::EXCEPTION) {
return ExecutionStatus::EXCEPTION;
}
// 7. If trap is undefined, then
if (!*trapRes) {
// a. Return ? target.[[Set]](P, V, Receiver).
return JSObject::putNamedWithReceiver_RJS(
target, runtime, name, valueHandle, receiver);
}
return setWithTrap(
runtime,
name.isUniqued() ? runtime->makeHandle(HermesValue::encodeStringValue(
runtime->getStringPrimFromSymbolID(name)))
: runtime->makeHandle(name),
valueHandle,
*trapRes,
runtime->makeHandle(detail::slots(*selfHandle).handler),
target,
receiver);
}
CallResult<bool> JSProxy::setComputed(
Handle<JSObject> selfHandle,
Runtime *runtime,
Handle<> nameValHandle,
Handle<> valueHandle,
// TODO could be HermesValue
Handle<> receiver) {
GCScope gcScope{runtime};
ScopedNativeDepthTracker depthTracker(runtime);
if (LLVM_UNLIKELY(depthTracker.overflowed())) {
return runtime->raiseStackOverflow(Runtime::StackOverflowKind::NativeStack);
}
Handle<JSObject> target =
runtime->makeHandle(detail::slots(*selfHandle).target);
CallResult<Handle<Callable>> trapRes =
detail::findTrap(selfHandle, runtime, Predefined::set);
if (trapRes == ExecutionStatus::EXCEPTION) {
return ExecutionStatus::EXCEPTION;
}
// 7. If trap is undefined, then
if (!*trapRes) {
// a. Return ? target.[[Set]](P, V, Receiver).
return JSObject::putComputedWithReceiver_RJS(
target, runtime, nameValHandle, valueHandle, receiver);
}
return setWithTrap(
runtime,
nameValHandle,
valueHandle,
*trapRes,
runtime->makeHandle(detail::slots(*selfHandle).handler),
target,
receiver);
}
namespace {
/// Common parts of deleteNamed/deleteComputed
CallResult<bool> deleteWithTrap(
Runtime *runtime,
Handle<> nameValHandle,
Handle<Callable> trap,
Handle<JSObject> handler,
Handle<JSObject> target) {
// 1. Assert: IsPropertyKey(P) is true.
assert(isPropertyKey(nameValHandle) && "key is not a String or Symbol");
// 8. Let booleanTrapResult be ToBoolean(? Call(trap, handler, « target, P
// »)).
CallResult<PseudoHandle<>> trapResultRes = Callable::executeCall2(
trap,
runtime,
handler,
target.getHermesValue(),
nameValHandle.getHermesValue());
if (trapResultRes == ExecutionStatus::EXCEPTION) {
return ExecutionStatus::EXCEPTION;
}
bool trapResult = toBoolean(trapResultRes->getHermesValue());
// 9. If booleanTrapResult is false, return false.
if (!trapResult) {
return false;
}
// 10. Let targetDesc be ? target.[[GetOwnProperty]](P).
ComputedPropertyDescriptor targetDesc;
MutableHandle<> targetValueOrAccessor{runtime};
MutableHandle<SymbolID> tmpPropNameStorage{runtime};
CallResult<bool> targetDescRes = JSObject::getOwnComputedDescriptor(
target,
runtime,
nameValHandle,
tmpPropNameStorage,
targetDesc,
targetValueOrAccessor);
if (targetDescRes == ExecutionStatus::EXCEPTION) {
return ExecutionStatus::EXCEPTION;
}
// 11. If targetDesc is undefined, return true.
if (!*targetDescRes) {
return true;
}
// 12. If targetDesc.[[Configurable]] is false, throw a TypeError exception.
if (!targetDesc.flags.configurable) {
return runtime->raiseTypeError(
"Delete trap target called, but target property is non-configurable");
}
// 13. Return true.
return true;
}
} // namespace
CallResult<bool> JSProxy::deleteNamed(
Handle<JSObject> selfHandle,
Runtime *runtime,
SymbolID name) {
GCScope gcScope{runtime};
ScopedNativeDepthTracker depthTracker(runtime);
if (LLVM_UNLIKELY(depthTracker.overflowed())) {
return runtime->raiseStackOverflow(Runtime::StackOverflowKind::NativeStack);
}
Handle<JSObject> target =
runtime->makeHandle(detail::slots(*selfHandle).target);
CallResult<Handle<Callable>> trapRes =
detail::findTrap(selfHandle, runtime, Predefined::deleteProperty);
if (trapRes == ExecutionStatus::EXCEPTION) {
return ExecutionStatus::EXCEPTION;
}
// 7. If trap is undefined, then
if (!*trapRes) {
// a. Return ? target.[[Delete]](P, Receiver).
return JSObject::deleteNamed(target, runtime, name);
}
return deleteWithTrap(
runtime,
runtime->makeHandle(HermesValue::encodeStringValue(
runtime->getStringPrimFromSymbolID(name))),
*trapRes,
runtime->makeHandle(detail::slots(*selfHandle).handler),
target);
}
CallResult<bool> JSProxy::deleteComputed(
Handle<JSObject> selfHandle,
Runtime *runtime,
Handle<> nameValHandle) {
GCScope gcScope{runtime};
ScopedNativeDepthTracker depthTracker(runtime);
if (LLVM_UNLIKELY(depthTracker.overflowed())) {
return runtime->raiseStackOverflow(Runtime::StackOverflowKind::NativeStack);
}
Handle<JSObject> target =
runtime->makeHandle(detail::slots(*selfHandle).target);
CallResult<Handle<Callable>> trapRes =
detail::findTrap(selfHandle, runtime, Predefined::deleteProperty);
if (trapRes == ExecutionStatus::EXCEPTION) {
return ExecutionStatus::EXCEPTION;
}
// 7. If trap is undefined, then
if (!*trapRes) {
// a. Return ? target.[[Delete]](P, Receiver).
return JSObject::deleteComputed(target, runtime, nameValHandle);
}
return deleteWithTrap(
runtime,
nameValHandle,
*trapRes,
runtime->makeHandle(detail::slots(*selfHandle).handler),
target);
}
namespace {
CallResult<PseudoHandle<JSArray>> filterKeys(
Handle<JSObject> selfHandle,
Handle<JSArray> keys,
Runtime *runtime,
OwnKeysFlags okFlags) {
assert(
(okFlags.getIncludeNonSymbols() || okFlags.getIncludeSymbols()) &&
"Can't exclude symbols and strings");
// If nothing is excluded, just return the array as-is.
if (okFlags.getIncludeNonSymbols() && okFlags.getIncludeSymbols() &&
okFlags.getIncludeNonEnumerable()) {
return createPseudoHandle(*keys);
}
// Count number of matching elements by type.
assert(
((okFlags.getIncludeSymbols() ? 0 : 1) +
(okFlags.getIncludeNonSymbols() ? 0 : 1)) == 1 &&
"Exactly one of Symbols or non-Symbols is included here");
bool onlySymbols = okFlags.getIncludeSymbols();
uint32_t len = JSArray::getLength(*keys, runtime);
uint32_t count = 0;
// Verify this loop is alloc-free
{
NoAllocScope noAlloc(runtime);
for (uint32_t i = 0; i < len; ++i) {
if (keys->at(runtime, i).isSymbol() == onlySymbols) {
++count;
}
}
}
// If everything in the array matches the filter by type, return
// the list as-is.
if (len == count && okFlags.getIncludeNonEnumerable()) {
return createPseudoHandle(*keys);
}
// Filter the desired elements we want into the result
auto resultRes = JSArray::create(runtime, count, count);
if (LLVM_UNLIKELY(resultRes == ExecutionStatus::EXCEPTION)) {
return ExecutionStatus::EXCEPTION;
}
Handle<JSArray> resultHandle = *resultRes;
MutableHandle<> elemHandle{runtime};
uint32_t resultIndex = 0;
GCScopeMarkerRAII marker{runtime};
for (uint32_t i = 0; i < len; ++i) {
marker.flush();
HermesValue elem = keys->at(runtime, i);
if (elem.isSymbol() ? !okFlags.getIncludeSymbols()
: !okFlags.getIncludeNonSymbols()) {
continue;
}
elemHandle = elem;
if (!okFlags.getIncludeNonEnumerable()) {
ComputedPropertyDescriptor desc;
CallResult<bool> propRes = JSProxy::getOwnProperty(
selfHandle, runtime, elemHandle, desc, nullptr);
if (LLVM_UNLIKELY(propRes == ExecutionStatus::EXCEPTION)) {
return ExecutionStatus::EXCEPTION;
}
if (!*propRes || !desc.flags.enumerable) {
continue;
}
}
JSArray::setElementAt(resultHandle, runtime, resultIndex++, elemHandle);
}
assert(
(!okFlags.getIncludeNonEnumerable() || resultIndex == count) &&
"Expected count was not correct");
CallResult<bool> setLenRes =
JSArray::setLengthProperty(resultHandle, runtime, resultIndex);
if (LLVM_UNLIKELY(setLenRes == ExecutionStatus::EXCEPTION)) {
return ExecutionStatus::EXCEPTION;
}
return createPseudoHandle(*resultHandle);
}
} // namespace
CallResult<PseudoHandle<JSArray>> JSProxy::ownPropertyKeys(
Handle<JSObject> selfHandle,
Runtime *runtime,
OwnKeysFlags okFlags) {
GCScope gcScope{runtime};
ScopedNativeDepthTracker depthTracker(runtime);
if (LLVM_UNLIKELY(depthTracker.overflowed())) {
return runtime->raiseStackOverflow(Runtime::StackOverflowKind::NativeStack);
}
Handle<JSObject> target =
runtime->makeHandle(detail::slots(*selfHandle).target);
CallResult<Handle<Callable>> trapRes =
detail::findTrap(selfHandle, runtime, Predefined::ownKeys);
if (trapRes == ExecutionStatus::EXCEPTION) {
return ExecutionStatus::EXCEPTION;
}
// 6. If trap is undefined, then
if (!*trapRes) {
// a. Return ? target.[[OwnPropertyKeys]]().
CallResult<Handle<JSArray>> targetRes =
// Include everything here, so that filterKeys has a chance to
// make observable trap calls.
JSObject::getOwnPropertyKeys(
target,
runtime,
OwnKeysFlags()
.plusIncludeSymbols()
.plusIncludeNonSymbols()
.plusIncludeNonEnumerable());
if (targetRes == ExecutionStatus::EXCEPTION) {
return ExecutionStatus::EXCEPTION;
}
return filterKeys(selfHandle, *targetRes, runtime, okFlags);
}
// 7. Let trapResultArray be ? Call(trap, handler, « target »).
CallResult<PseudoHandle<>> trapResultArrayRes = Callable::executeCall1(
*trapRes,
runtime,
runtime->makeHandle(detail::slots(*selfHandle).handler),
target.getHermesValue());
if (trapResultArrayRes == ExecutionStatus::EXCEPTION) {
return ExecutionStatus::EXCEPTION;
}
if (!vmisa<JSObject>(trapResultArrayRes->get())) {
return runtime->raiseTypeErrorForValue(
runtime->makeHandle(std::move(*trapResultArrayRes)),
" ownKeys trap result is not an Object");
}
auto trapResultArray =
runtime->makeHandle<JSObject>(std::move(trapResultArrayRes->get()));
// 8. Let trapResult be ? CreateListFromArrayLike(trapResultArray, « String,
// Symbol »)
// 9. If trapResult contains any duplicate entries, throw a TypeError
// exception.
CallResult<uint64_t> countRes = getArrayLikeLength(trapResultArray, runtime);
if (LLVM_UNLIKELY(countRes == ExecutionStatus::EXCEPTION)) {
return ExecutionStatus::EXCEPTION;
}
if (*countRes > UINT32_MAX) {
return runtime->raiseRangeError(
"Too many elements returned from ownKeys trap");
}
uint32_t count = static_cast<uint32_t>(*countRes);
auto trapResultRes = JSArray::create(runtime, count, count);
if (LLVM_UNLIKELY(trapResultRes == ExecutionStatus::EXCEPTION)) {
return ExecutionStatus::EXCEPTION;
}
Handle<JSArray> trapResult = *trapResultRes;
CallResult<PseudoHandle<OrderedHashMap>> dupcheckRes =
OrderedHashMap::create(runtime);
if (LLVM_UNLIKELY(dupcheckRes == ExecutionStatus::EXCEPTION)) {
return ExecutionStatus::EXCEPTION;
}
Handle<OrderedHashMap> dupcheck =
runtime->makeHandle(std::move(*dupcheckRes));
if (LLVM_UNLIKELY(
createListFromArrayLike(
trapResultArray,
runtime,
count,
[&dupcheck, &trapResult](
Runtime *runtime, uint64_t index, PseudoHandle<> value) {
Handle<> valHandle = runtime->makeHandle(std::move(value));
if (!valHandle->isString() && !valHandle->isSymbol()) {
return runtime->raiseTypeErrorForValue(
valHandle,
" ownKeys trap result element is not String or Symbol");
}
if (OrderedHashMap::has(dupcheck, runtime, valHandle)) {
return runtime->raiseTypeErrorForValue(
"ownKeys trap result has duplicate ", valHandle, "");
}
if (LLVM_UNLIKELY(
OrderedHashMap::insert(
dupcheck, runtime, valHandle, valHandle) ==
ExecutionStatus::EXCEPTION))
return ExecutionStatus::RETURNED;
JSArray::setElementAt(trapResult, runtime, index, valHandle);
return ExecutionStatus::RETURNED;
}) == ExecutionStatus::EXCEPTION)) {
return ExecutionStatus::EXCEPTION;
}
// 10. Let extensibleTarget be ? IsExtensible(target).
CallResult<bool> extensibleRes = JSObject::isExtensible(target, runtime);
if (extensibleRes == ExecutionStatus::EXCEPTION) {
return ExecutionStatus::EXCEPTION;
}
// 11. Let targetKeys be ? target.[[OwnPropertyKeys]]().
CallResult<Handle<JSArray>> targetKeysRes = JSObject::getOwnPropertyKeys(
target,
runtime,
OwnKeysFlags()
.plusIncludeSymbols()
.plusIncludeNonSymbols()
.plusIncludeNonEnumerable());
if (targetKeysRes == ExecutionStatus::EXCEPTION) {
return ExecutionStatus::EXCEPTION;
}
Handle<JSArray> targetKeys = *targetKeysRes;
// 12. Assert: targetKeys is a List containing only String and Symbol values.
// 13. Assert: targetKeys contains no duplicate entries.
// 14. Let targetConfigurableKeys be a new empty List.
// 15. Let targetNonconfigurableKeys be a new empty List.
llvh::SmallSet<uint32_t, 8> nonConfigurable;
MutableHandle<SymbolID> tmpPropNameStorage{runtime};
// 16. For each element key of targetKeys, do
auto marker2 = runtime->getTopGCScope()->createMarker();
for (uint32_t i = 0, len = JSArray::getLength(*targetKeys, runtime); i < len;
++i) {
// a. Let desc be ? target.[[GetOwnProperty]](key).
ComputedPropertyDescriptor desc;
CallResult<bool> descRes = JSObject::getOwnComputedDescriptor(
target,
runtime,
runtime->makeHandle(targetKeys->at(runtime, i)),
tmpPropNameStorage,
desc);
if (descRes == ExecutionStatus::EXCEPTION) {
return ExecutionStatus::EXCEPTION;
}
// b. If desc is not undefined and desc.[[Configurable]] is false, then
// i. Append key as an element of targetNonconfigurableKeys.
// c. Else,
// i. Append key as an element of targetConfigurableKeys.
if (*descRes && !desc.flags.configurable) {
nonConfigurable.insert(i);
}
runtime->getTopGCScope()->flushToMarker(marker2);
}
// 17. If extensibleTarget is true and targetNonconfigurableKeys is empty,
// then
if (*extensibleRes && nonConfigurable.empty()) {
// a. Return trapResult.
return filterKeys(selfHandle, trapResult, runtime, okFlags);
}
// 18. Let uncheckedResultKeys be a new List which is a copy of trapResult.
// 19. For each key that is an element of targetNonconfigurableKeys, do
// a. If key is not an element of uncheckedResultKeys, throw a TypeError
// exception. b. Remove key from uncheckedResultKeys.
auto inTrapResult = [&runtime, &trapResult](HermesValue value) {
for (uint32_t j = 0, len = JSArray::getLength(*trapResult, runtime);
j < len;
++j) {
if (isSameValue(value, trapResult->at(runtime, j))) {
return true;
}
}
return false;
};
for (auto i : nonConfigurable) {
if (!inTrapResult(targetKeys->at(runtime, i))) {
return runtime->raiseTypeError(
"ownKeys target key is non-configurable but not present in trap result");
}
}
// 20. If extensibleTarget is true, return trapResult.
if (*extensibleRes) {
return filterKeys(selfHandle, trapResult, runtime, okFlags);
}
// 21. For each key that is an element of targetConfigurableKeys, do
// a. If key is not an element of uncheckedResultKeys, throw a TypeError
// exception. b. Remove key from uncheckedResultKeys.
for (uint32_t i = 0, len = JSArray::getLength(*targetKeys, runtime); i < len;
++i) {
if (nonConfigurable.count(i) > 0) {
continue;
}
if (!inTrapResult(targetKeys->at(runtime, i))) {
return runtime->raiseTypeError(
"ownKeys target is non-extensible but key is missing from trap result");
}
}
// 22. If uncheckedResultKeys is not empty, throw a TypeError exception.
if (JSArray::getLength(*targetKeys, runtime) !=
JSArray::getLength(*trapResult, runtime)) {
return runtime->raiseTypeError(
"ownKeys target is non-extensible but trap result keys differ from target keys");
}
// 23. Return trapResult.
return filterKeys(selfHandle, trapResult, runtime, okFlags);
}
} // namespace vm
} // namespace hermes
| 37.171685 | 124 | 0.683912 | [
"object"
] |
11efda8faa869451586414509875e69199000f3a | 91,517 | cc | C++ | components/autofill/core/browser/form_structure_unittest.cc | justremotephone/android_external_chromium_org | 246856e61da7acf5494076c74198f2aea894a721 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 2 | 2020-01-25T10:18:18.000Z | 2021-01-23T15:29:56.000Z | components/autofill/core/browser/form_structure_unittest.cc | justremotephone/android_external_chromium_org | 246856e61da7acf5494076c74198f2aea894a721 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | components/autofill/core/browser/form_structure_unittest.cc | justremotephone/android_external_chromium_org | 246856e61da7acf5494076c74198f2aea894a721 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 2 | 2015-04-17T13:19:09.000Z | 2021-10-21T12:55:15.000Z | // Copyright 2013 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 "components/autofill/core/browser/form_structure.h"
#include "base/memory/scoped_ptr.h"
#include "base/strings/string_util.h"
#include "base/strings/utf_string_conversions.h"
#include "components/autofill/core/browser/autofill_metrics.h"
#include "components/autofill/core/common/form_data.h"
#include "components/autofill/core/common/form_field_data.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "url/gurl.h"
using base::ASCIIToUTF16;
namespace autofill {
namespace {
// Unlike the base AutofillMetrics, exposes copy and assignment constructors,
// which are handy for briefer test code. The AutofillMetrics class is
// stateless, so this is safe.
class TestAutofillMetrics : public AutofillMetrics {
public:
TestAutofillMetrics() {}
virtual ~TestAutofillMetrics() {}
};
} // anonymous namespace
namespace content {
std::ostream& operator<<(std::ostream& os, const FormData& form) {
os << base::UTF16ToUTF8(form.name)
<< " "
<< base::UTF16ToUTF8(form.method)
<< " "
<< form.origin.spec()
<< " "
<< form.action.spec()
<< " ";
for (std::vector<FormFieldData>::const_iterator iter =
form.fields.begin();
iter != form.fields.end(); ++iter) {
os << *iter
<< " ";
}
return os;
}
} // namespace content
class FormStructureTest {
public:
static std::string Hash64Bit(const std::string& str) {
return FormStructure::Hash64Bit(str);
}
};
TEST(FormStructureTest, FieldCount) {
scoped_ptr<FormStructure> form_structure;
FormData form;
form.method = ASCIIToUTF16("post");
FormFieldData field;
field.label = ASCIIToUTF16("username");
field.name = ASCIIToUTF16("username");
field.form_control_type = "text";
form.fields.push_back(field);
field.label = ASCIIToUTF16("password");
field.name = ASCIIToUTF16("password");
field.form_control_type = "password";
form.fields.push_back(field);
field.label = base::string16();
field.name = ASCIIToUTF16("Submit");
field.form_control_type = "submit";
form.fields.push_back(field);
field.label = ASCIIToUTF16("address1");
field.name = ASCIIToUTF16("address1");
field.form_control_type = "text";
field.should_autocomplete = false;
form.fields.push_back(field);
// The render process sends all fields to browser including fields with
// autocomplete=off
form_structure.reset(new FormStructure(form));
EXPECT_EQ(4U, form_structure->field_count());
}
TEST(FormStructureTest, AutofillCount) {
scoped_ptr<FormStructure> form_structure;
FormData form;
form.method = ASCIIToUTF16("post");
FormFieldData field;
field.label = ASCIIToUTF16("username");
field.name = ASCIIToUTF16("username");
field.form_control_type = "text";
form.fields.push_back(field);
field.label = ASCIIToUTF16("password");
field.name = ASCIIToUTF16("password");
field.form_control_type = "password";
form.fields.push_back(field);
field.label = ASCIIToUTF16("state");
field.name = ASCIIToUTF16("state");
field.form_control_type = "select-one";
form.fields.push_back(field);
field.label = base::string16();
field.name = ASCIIToUTF16("Submit");
field.form_control_type = "submit";
form.fields.push_back(field);
// Only text and select fields that are heuristically matched are counted.
form_structure.reset(new FormStructure(form));
form_structure->DetermineHeuristicTypes(TestAutofillMetrics());
EXPECT_EQ(1U, form_structure->autofill_count());
// Add a field with should_autocomplete=false. This should not be considered a
// fillable field.
field.label = ASCIIToUTF16("address1");
field.name = ASCIIToUTF16("address1");
field.form_control_type = "text";
field.should_autocomplete = false;
form.fields.push_back(field);
form_structure.reset(new FormStructure(form));
form_structure->DetermineHeuristicTypes(TestAutofillMetrics());
EXPECT_EQ(1U, form_structure->autofill_count());
}
TEST(FormStructureTest, SourceURL) {
FormData form;
form.origin = GURL("http://www.foo.com/");
form.method = ASCIIToUTF16("post");
FormStructure form_structure(form);
EXPECT_EQ(form.origin, form_structure.source_url());
}
TEST(FormStructureTest, IsAutofillable) {
scoped_ptr<FormStructure> form_structure;
FormData form;
// We need at least three text fields to be auto-fillable.
form.method = ASCIIToUTF16("post");
FormFieldData field;
field.label = ASCIIToUTF16("username");
field.name = ASCIIToUTF16("username");
field.form_control_type = "text";
form.fields.push_back(field);
field.label = ASCIIToUTF16("password");
field.name = ASCIIToUTF16("password");
field.form_control_type = "password";
form.fields.push_back(field);
field.label = base::string16();
field.name = ASCIIToUTF16("Submit");
field.form_control_type = "submit";
form.fields.push_back(field);
form_structure.reset(new FormStructure(form));
form_structure->DetermineHeuristicTypes(TestAutofillMetrics());
EXPECT_FALSE(form_structure->IsAutofillable(true));
// We now have three text fields, but only two auto-fillable fields.
field.label = ASCIIToUTF16("First Name");
field.name = ASCIIToUTF16("firstname");
field.form_control_type = "text";
form.fields.push_back(field);
field.label = ASCIIToUTF16("Last Name");
field.name = ASCIIToUTF16("lastname");
field.form_control_type = "text";
form.fields.push_back(field);
form_structure.reset(new FormStructure(form));
form_structure->DetermineHeuristicTypes(TestAutofillMetrics());
EXPECT_FALSE(form_structure->IsAutofillable(true));
// We now have three auto-fillable fields.
field.label = ASCIIToUTF16("Email");
field.name = ASCIIToUTF16("email");
field.form_control_type = "email";
form.fields.push_back(field);
form_structure.reset(new FormStructure(form));
form_structure->DetermineHeuristicTypes(TestAutofillMetrics());
EXPECT_TRUE(form_structure->IsAutofillable(true));
// The method must be 'post', though we can intentionally ignore this
// criterion for the sake of providing a helpful warning message to the user.
form.method = ASCIIToUTF16("get");
form_structure.reset(new FormStructure(form));
form_structure->DetermineHeuristicTypes(TestAutofillMetrics());
EXPECT_FALSE(form_structure->IsAutofillable(true));
EXPECT_TRUE(form_structure->IsAutofillable(false));
// The target cannot include http(s)://*/search...
form.method = ASCIIToUTF16("post");
form.action = GURL("http://google.com/search?q=hello");
form_structure.reset(new FormStructure(form));
form_structure->DetermineHeuristicTypes(TestAutofillMetrics());
EXPECT_FALSE(form_structure->IsAutofillable(true));
// But search can be in the URL.
form.action = GURL("http://search.com/?q=hello");
form_structure.reset(new FormStructure(form));
form_structure->DetermineHeuristicTypes(TestAutofillMetrics());
EXPECT_TRUE(form_structure->IsAutofillable(true));
}
TEST(FormStructureTest, ShouldBeParsed) {
scoped_ptr<FormStructure> form_structure;
FormData form;
// We need at least three text fields to be parseable.
form.method = ASCIIToUTF16("post");
FormFieldData field;
field.label = ASCIIToUTF16("username");
field.name = ASCIIToUTF16("username");
field.form_control_type = "text";
form.fields.push_back(field);
FormFieldData checkable_field;
checkable_field.is_checkable = true;
checkable_field.name = ASCIIToUTF16("radiobtn");
checkable_field.form_control_type = "radio";
form.fields.push_back(checkable_field);
checkable_field.name = ASCIIToUTF16("checkbox");
checkable_field.form_control_type = "checkbox";
form.fields.push_back(checkable_field);
// We have only one text field, should not be parsed.
form_structure.reset(new FormStructure(form));
EXPECT_FALSE(form_structure->ShouldBeParsed(true));
// We now have three text fields, though only two are auto-fillable.
field.label = ASCIIToUTF16("First Name");
field.name = ASCIIToUTF16("firstname");
field.form_control_type = "text";
form.fields.push_back(field);
field.label = ASCIIToUTF16("Last Name");
field.name = ASCIIToUTF16("lastname");
field.form_control_type = "text";
form.fields.push_back(field);
form_structure.reset(new FormStructure(form));
EXPECT_TRUE(form_structure->ShouldBeParsed(true));
// The method must be 'post', though we can intentionally ignore this
// criterion for the sake of providing a helpful warning message to the user.
form.method = ASCIIToUTF16("get");
form_structure.reset(new FormStructure(form));
EXPECT_FALSE(form_structure->IsAutofillable(true));
EXPECT_TRUE(form_structure->ShouldBeParsed(false));
// The target cannot include http(s)://*/search...
form.method = ASCIIToUTF16("post");
form.action = GURL("http://google.com/search?q=hello");
form_structure.reset(new FormStructure(form));
EXPECT_FALSE(form_structure->ShouldBeParsed(true));
// But search can be in the URL.
form.action = GURL("http://search.com/?q=hello");
form_structure.reset(new FormStructure(form));
EXPECT_TRUE(form_structure->ShouldBeParsed(true));
// The form need only have three fields, but at least one must be a text
// field.
form.fields.clear();
field.label = ASCIIToUTF16("Email");
field.name = ASCIIToUTF16("email");
field.form_control_type = "email";
form.fields.push_back(field);
field.label = ASCIIToUTF16("State");
field.name = ASCIIToUTF16("state");
field.form_control_type = "select-one";
form.fields.push_back(field);
field.label = ASCIIToUTF16("Country");
field.name = ASCIIToUTF16("country");
field.form_control_type = "select-one";
form.fields.push_back(field);
form_structure.reset(new FormStructure(form));
EXPECT_TRUE(form_structure->ShouldBeParsed(true));
form.fields[0].form_control_type = "select-one";
// Now, no text fields.
form_structure.reset(new FormStructure(form));
EXPECT_FALSE(form_structure->ShouldBeParsed(true));
}
TEST(FormStructureTest, HeuristicsContactInfo) {
scoped_ptr<FormStructure> form_structure;
FormData form;
form.method = ASCIIToUTF16("post");
FormFieldData field;
field.form_control_type = "text";
field.label = ASCIIToUTF16("First Name");
field.name = ASCIIToUTF16("firstname");
form.fields.push_back(field);
field.label = ASCIIToUTF16("Last Name");
field.name = ASCIIToUTF16("lastname");
form.fields.push_back(field);
field.label = ASCIIToUTF16("Email");
field.name = ASCIIToUTF16("email");
form.fields.push_back(field);
field.label = ASCIIToUTF16("Phone");
field.name = ASCIIToUTF16("phone");
form.fields.push_back(field);
field.label = ASCIIToUTF16("Address");
field.name = ASCIIToUTF16("address");
form.fields.push_back(field);
field.label = ASCIIToUTF16("City");
field.name = ASCIIToUTF16("city");
form.fields.push_back(field);
field.label = ASCIIToUTF16("Zip code");
field.name = ASCIIToUTF16("zipcode");
form.fields.push_back(field);
field.label = base::string16();
field.name = ASCIIToUTF16("Submit");
field.form_control_type = "submit";
form.fields.push_back(field);
form_structure.reset(new FormStructure(form));
form_structure->DetermineHeuristicTypes(TestAutofillMetrics());
EXPECT_TRUE(form_structure->IsAutofillable(true));
// Expect the correct number of fields.
ASSERT_EQ(8U, form_structure->field_count());
ASSERT_EQ(7U, form_structure->autofill_count());
// First name.
EXPECT_EQ(NAME_FIRST, form_structure->field(0)->heuristic_type());
// Last name.
EXPECT_EQ(NAME_LAST, form_structure->field(1)->heuristic_type());
// Email.
EXPECT_EQ(EMAIL_ADDRESS, form_structure->field(2)->heuristic_type());
// Phone.
EXPECT_EQ(PHONE_HOME_WHOLE_NUMBER,
form_structure->field(3)->heuristic_type());
// Address.
EXPECT_EQ(ADDRESS_HOME_LINE1, form_structure->field(4)->heuristic_type());
// City.
EXPECT_EQ(ADDRESS_HOME_CITY, form_structure->field(5)->heuristic_type());
// Zip.
EXPECT_EQ(ADDRESS_HOME_ZIP, form_structure->field(6)->heuristic_type());
// Submit.
EXPECT_EQ(UNKNOWN_TYPE, form_structure->field(7)->heuristic_type());
}
// Verify that we can correctly process the |autocomplete| attribute.
TEST(FormStructureTest, HeuristicsAutocompleteAttribute) {
scoped_ptr<FormStructure> form_structure;
FormData form;
form.method = ASCIIToUTF16("post");
FormFieldData field;
field.form_control_type = "text";
field.label = base::string16();
field.name = ASCIIToUTF16("field1");
field.autocomplete_attribute = "given-name";
form.fields.push_back(field);
field.label = base::string16();
field.name = ASCIIToUTF16("field2");
field.autocomplete_attribute = "family-name";
form.fields.push_back(field);
field.label = base::string16();
field.name = ASCIIToUTF16("field3");
field.autocomplete_attribute = "email";
form.fields.push_back(field);
form_structure.reset(new FormStructure(form));
form_structure->DetermineHeuristicTypes(TestAutofillMetrics());
EXPECT_TRUE(form_structure->IsAutofillable(true));
// Expect the correct number of fields.
ASSERT_EQ(3U, form_structure->field_count());
ASSERT_EQ(3U, form_structure->autofill_count());
EXPECT_EQ(HTML_TYPE_GIVEN_NAME, form_structure->field(0)->html_type());
EXPECT_EQ(HTML_TYPE_FAMILY_NAME, form_structure->field(1)->html_type());
EXPECT_EQ(HTML_TYPE_EMAIL, form_structure->field(2)->html_type());
EXPECT_EQ(UNKNOWN_TYPE, form_structure->field(0)->heuristic_type());
EXPECT_EQ(UNKNOWN_TYPE, form_structure->field(1)->heuristic_type());
EXPECT_EQ(UNKNOWN_TYPE, form_structure->field(2)->heuristic_type());
}
// Verify that we can correctly process the 'autocomplete' attribute for phone
// number types (especially phone prefixes and suffixes).
TEST(FormStructureTest, HeuristicsAutocompleteAttributePhoneTypes) {
scoped_ptr<FormStructure> form_structure;
FormData form;
form.method = ASCIIToUTF16("post");
FormFieldData field;
field.form_control_type = "text";
field.label = base::string16();
field.name = ASCIIToUTF16("field1");
field.autocomplete_attribute = "tel-local";
form.fields.push_back(field);
field.label = base::string16();
field.name = ASCIIToUTF16("field2");
field.autocomplete_attribute = "tel-local-prefix";
form.fields.push_back(field);
field.label = base::string16();
field.name = ASCIIToUTF16("field3");
field.autocomplete_attribute = "tel-local-suffix";
form.fields.push_back(field);
form_structure.reset(new FormStructure(form));
form_structure->DetermineHeuristicTypes(TestAutofillMetrics());
EXPECT_TRUE(form_structure->IsAutofillable(true));
// Expect the correct number of fields.
ASSERT_EQ(3U, form_structure->field_count());
EXPECT_EQ(3U, form_structure->autofill_count());
EXPECT_EQ(HTML_TYPE_TEL_LOCAL, form_structure->field(0)->html_type());
EXPECT_EQ(AutofillField::IGNORED, form_structure->field(0)->phone_part());
EXPECT_EQ(HTML_TYPE_TEL_LOCAL_PREFIX, form_structure->field(1)->html_type());
EXPECT_EQ(AutofillField::PHONE_PREFIX,
form_structure->field(1)->phone_part());
EXPECT_EQ(HTML_TYPE_TEL_LOCAL_SUFFIX, form_structure->field(2)->html_type());
EXPECT_EQ(AutofillField::PHONE_SUFFIX,
form_structure->field(2)->phone_part());
}
// If at least one field includes type hints in the 'autocomplete' attribute, we
// should not try to apply any other heuristics.
TEST(FormStructureTest, AutocompleteAttributeOverridesOtherHeuristics) {
scoped_ptr<FormStructure> form_structure;
FormData form;
form.method = ASCIIToUTF16("post");
// Start with a regular contact form.
FormFieldData field;
field.form_control_type = "text";
field.label = ASCIIToUTF16("First Name");
field.name = ASCIIToUTF16("firstname");
form.fields.push_back(field);
field.label = ASCIIToUTF16("Last Name");
field.name = ASCIIToUTF16("lastname");
form.fields.push_back(field);
field.label = ASCIIToUTF16("Email");
field.name = ASCIIToUTF16("email");
form.fields.push_back(field);
form_structure.reset(new FormStructure(form));
form_structure->DetermineHeuristicTypes(TestAutofillMetrics());
EXPECT_TRUE(form_structure->IsAutofillable(true));
EXPECT_TRUE(form_structure->ShouldBeCrowdsourced());
ASSERT_EQ(3U, form_structure->field_count());
ASSERT_EQ(3U, form_structure->autofill_count());
EXPECT_EQ(NAME_FIRST, form_structure->field(0)->heuristic_type());
EXPECT_EQ(NAME_LAST, form_structure->field(1)->heuristic_type());
EXPECT_EQ(EMAIL_ADDRESS, form_structure->field(2)->heuristic_type());
// Now update the first form field to include an 'autocomplete' attribute.
form.fields.front().autocomplete_attribute = "x-other";
form_structure.reset(new FormStructure(form));
form_structure->DetermineHeuristicTypes(TestAutofillMetrics());
EXPECT_FALSE(form_structure->IsAutofillable(true));
EXPECT_FALSE(form_structure->ShouldBeCrowdsourced());
ASSERT_EQ(3U, form_structure->field_count());
ASSERT_EQ(0U, form_structure->autofill_count());
EXPECT_EQ(UNKNOWN_TYPE, form_structure->field(0)->heuristic_type());
EXPECT_EQ(UNKNOWN_TYPE, form_structure->field(1)->heuristic_type());
EXPECT_EQ(UNKNOWN_TYPE, form_structure->field(2)->heuristic_type());
}
// Verify that we can correctly process sections listed in the |autocomplete|
// attribute.
TEST(FormStructureTest, HeuristicsAutocompleteAttributeWithSections) {
FormData form;
form.method = ASCIIToUTF16("post");
FormFieldData field;
field.form_control_type = "text";
// Some fields will have no section specified. These fall into the default
// section.
field.autocomplete_attribute = "email";
form.fields.push_back(field);
// We allow arbitrary section names.
field.autocomplete_attribute = "section-foo email";
form.fields.push_back(field);
// "shipping" and "billing" are special section tokens that don't require the
// "section-" prefix.
field.autocomplete_attribute = "shipping email";
form.fields.push_back(field);
field.autocomplete_attribute = "billing email";
form.fields.push_back(field);
// "shipping" and "billing" can be combined with other section names.
field.autocomplete_attribute = "section-foo shipping email";
form.fields.push_back(field);
field.autocomplete_attribute = "section-foo billing email";
form.fields.push_back(field);
// We don't do anything clever to try to coalesce sections; it's up to site
// authors to avoid typos.
field.autocomplete_attribute = "section--foo email";
form.fields.push_back(field);
// "shipping email" and "section--shipping" email should be parsed as
// different sections. This is only an interesting test due to how we
// implement implicit section names from attributes like "shipping email"; see
// the implementation for more details.
field.autocomplete_attribute = "section--shipping email";
form.fields.push_back(field);
// Credit card fields are implicitly in a separate section from other fields.
field.autocomplete_attribute = "section-foo cc-number";
form.fields.push_back(field);
FormStructure form_structure(form);
form_structure.DetermineHeuristicTypes(TestAutofillMetrics());
EXPECT_TRUE(form_structure.IsAutofillable(true));
// Expect the correct number of fields.
ASSERT_EQ(9U, form_structure.field_count());
EXPECT_EQ(9U, form_structure.autofill_count());
// All of the fields in this form should be parsed as belonging to different
// sections.
std::set<std::string> section_names;
for (size_t i = 0; i < 9; ++i) {
section_names.insert(form_structure.field(i)->section());
}
EXPECT_EQ(9U, section_names.size());
}
// Verify that we can correctly process a degenerate section listed in the
// |autocomplete| attribute.
TEST(FormStructureTest, HeuristicsAutocompleteAttributeWithSectionsDegenerate) {
FormData form;
form.method = ASCIIToUTF16("post");
FormFieldData field;
field.form_control_type = "text";
// Some fields will have no section specified. These fall into the default
// section.
field.autocomplete_attribute = "email";
form.fields.push_back(field);
// Specifying "section-" is equivalent to not specifying a section.
field.autocomplete_attribute = "section- email";
form.fields.push_back(field);
// Invalid tokens should prevent us from setting a section name.
field.autocomplete_attribute = "garbage section-foo email";
form.fields.push_back(field);
field.autocomplete_attribute = "garbage section-bar email";
form.fields.push_back(field);
field.autocomplete_attribute = "garbage shipping email";
form.fields.push_back(field);
field.autocomplete_attribute = "garbage billing email";
form.fields.push_back(field);
FormStructure form_structure(form);
form_structure.DetermineHeuristicTypes(TestAutofillMetrics());
// Expect the correct number of fields.
ASSERT_EQ(6U, form_structure.field_count());
EXPECT_EQ(2U, form_structure.autofill_count());
// All of the fields in this form should be parsed as belonging to the same
// section.
std::set<std::string> section_names;
for (size_t i = 0; i < 6; ++i) {
section_names.insert(form_structure.field(i)->section());
}
EXPECT_EQ(1U, section_names.size());
}
// Verify that we can correctly process repeated sections listed in the
// |autocomplete| attribute.
TEST(FormStructureTest, HeuristicsAutocompleteAttributeWithSectionsRepeated) {
FormData form;
form.method = ASCIIToUTF16("post");
FormFieldData field;
field.form_control_type = "text";
field.autocomplete_attribute = "section-foo email";
form.fields.push_back(field);
field.autocomplete_attribute = "section-foo address-line1";
form.fields.push_back(field);
FormStructure form_structure(form);
form_structure.DetermineHeuristicTypes(TestAutofillMetrics());
// Expect the correct number of fields.
ASSERT_EQ(2U, form_structure.field_count());
EXPECT_EQ(2U, form_structure.autofill_count());
// All of the fields in this form should be parsed as belonging to the same
// section.
std::set<std::string> section_names;
for (size_t i = 0; i < 2; ++i) {
section_names.insert(form_structure.field(i)->section());
}
EXPECT_EQ(1U, section_names.size());
}
// Verify that we do not override the author-specified sections from a form with
// local heuristics.
TEST(FormStructureTest, HeuristicsDontOverrideAutocompleteAttributeSections) {
FormData form;
form.method = ASCIIToUTF16("post");
FormFieldData field;
field.form_control_type = "text";
field.name = ASCIIToUTF16("one");
field.autocomplete_attribute = "address-line1";
form.fields.push_back(field);
field.name = base::string16();
field.autocomplete_attribute = "section-foo email";
form.fields.push_back(field);
field.name = base::string16();
field.autocomplete_attribute = "name";
form.fields.push_back(field);
field.name = ASCIIToUTF16("two");
field.autocomplete_attribute = "address-line1";
form.fields.push_back(field);
FormStructure form_structure(form);
form_structure.DetermineHeuristicTypes(TestAutofillMetrics());
// Expect the correct number of fields.
ASSERT_EQ(4U, form_structure.field_count());
EXPECT_EQ(4U, form_structure.autofill_count());
// Normally, the two separate address fields would cause us to detect two
// separate sections; but because there is an author-specified section in this
// form, we do not apply these usual heuristics.
EXPECT_EQ(ASCIIToUTF16("one"), form_structure.field(0)->name);
EXPECT_EQ(ASCIIToUTF16("two"), form_structure.field(3)->name);
EXPECT_EQ(form_structure.field(0)->section(),
form_structure.field(3)->section());
}
TEST(FormStructureTest, HeuristicsSample8) {
scoped_ptr<FormStructure> form_structure;
FormData form;
form.method = ASCIIToUTF16("post");
FormFieldData field;
field.form_control_type = "text";
field.label = ASCIIToUTF16("Your First Name:");
field.name = ASCIIToUTF16("bill.first");
form.fields.push_back(field);
field.label = ASCIIToUTF16("Your Last Name:");
field.name = ASCIIToUTF16("bill.last");
form.fields.push_back(field);
field.label = ASCIIToUTF16("Street Address Line 1:");
field.name = ASCIIToUTF16("bill.street1");
form.fields.push_back(field);
field.label = ASCIIToUTF16("Street Address Line 2:");
field.name = ASCIIToUTF16("bill.street2");
form.fields.push_back(field);
field.label = ASCIIToUTF16("City");
field.name = ASCIIToUTF16("bill.city");
form.fields.push_back(field);
field.label = ASCIIToUTF16("State (U.S.):");
field.name = ASCIIToUTF16("bill.state");
form.fields.push_back(field);
field.label = ASCIIToUTF16("Zip/Postal Code:");
field.name = ASCIIToUTF16("BillTo.PostalCode");
form.fields.push_back(field);
field.label = ASCIIToUTF16("Country:");
field.name = ASCIIToUTF16("bill.country");
form.fields.push_back(field);
field.label = ASCIIToUTF16("Phone Number:");
field.name = ASCIIToUTF16("BillTo.Phone");
form.fields.push_back(field);
field.label = base::string16();
field.name = ASCIIToUTF16("Submit");
field.form_control_type = "submit";
form.fields.push_back(field);
form_structure.reset(new FormStructure(form));
form_structure->DetermineHeuristicTypes(TestAutofillMetrics());
EXPECT_TRUE(form_structure->IsAutofillable(true));
ASSERT_EQ(10U, form_structure->field_count());
ASSERT_EQ(9U, form_structure->autofill_count());
// First name.
EXPECT_EQ(NAME_FIRST, form_structure->field(0)->heuristic_type());
// Last name.
EXPECT_EQ(NAME_LAST, form_structure->field(1)->heuristic_type());
// Address.
EXPECT_EQ(ADDRESS_HOME_LINE1, form_structure->field(2)->heuristic_type());
// Address.
EXPECT_EQ(ADDRESS_HOME_LINE2, form_structure->field(3)->heuristic_type());
// City.
EXPECT_EQ(ADDRESS_HOME_CITY, form_structure->field(4)->heuristic_type());
// State.
EXPECT_EQ(ADDRESS_HOME_STATE, form_structure->field(5)->heuristic_type());
// Zip.
EXPECT_EQ(ADDRESS_HOME_ZIP, form_structure->field(6)->heuristic_type());
// Country.
EXPECT_EQ(ADDRESS_HOME_COUNTRY, form_structure->field(7)->heuristic_type());
// Phone.
EXPECT_EQ(PHONE_HOME_WHOLE_NUMBER,
form_structure->field(8)->heuristic_type());
// Submit.
EXPECT_EQ(UNKNOWN_TYPE, form_structure->field(9)->heuristic_type());
}
TEST(FormStructureTest, HeuristicsSample6) {
scoped_ptr<FormStructure> form_structure;
FormData form;
form.method = ASCIIToUTF16("post");
FormFieldData field;
field.form_control_type = "text";
field.label = ASCIIToUTF16("E-mail address");
field.name = ASCIIToUTF16("email");
form.fields.push_back(field);
field.label = ASCIIToUTF16("Full name");
field.name = ASCIIToUTF16("name");
form.fields.push_back(field);
field.label = ASCIIToUTF16("Company");
field.name = ASCIIToUTF16("company");
form.fields.push_back(field);
field.label = ASCIIToUTF16("Address");
field.name = ASCIIToUTF16("address");
form.fields.push_back(field);
field.label = ASCIIToUTF16("City");
field.name = ASCIIToUTF16("city");
form.fields.push_back(field);
field.label = ASCIIToUTF16("Zip Code");
field.name = ASCIIToUTF16("Home.PostalCode");
form.fields.push_back(field);
field.label = base::string16();
field.name = ASCIIToUTF16("Submit");
field.value = ASCIIToUTF16("continue");
field.form_control_type = "submit";
form.fields.push_back(field);
form_structure.reset(new FormStructure(form));
form_structure->DetermineHeuristicTypes(TestAutofillMetrics());
EXPECT_TRUE(form_structure->IsAutofillable(true));
ASSERT_EQ(7U, form_structure->field_count());
ASSERT_EQ(6U, form_structure->autofill_count());
// Email.
EXPECT_EQ(EMAIL_ADDRESS, form_structure->field(0)->heuristic_type());
// Full name.
EXPECT_EQ(NAME_FULL, form_structure->field(1)->heuristic_type());
// Company
EXPECT_EQ(COMPANY_NAME, form_structure->field(2)->heuristic_type());
// Address.
EXPECT_EQ(ADDRESS_HOME_LINE1, form_structure->field(3)->heuristic_type());
// City.
EXPECT_EQ(ADDRESS_HOME_CITY, form_structure->field(4)->heuristic_type());
// Zip.
EXPECT_EQ(ADDRESS_HOME_ZIP, form_structure->field(5)->heuristic_type());
// Submit.
EXPECT_EQ(UNKNOWN_TYPE, form_structure->field(6)->heuristic_type());
}
// Tests a sequence of FormFields where only labels are supplied to heuristics
// for matching. This works because FormFieldData labels are matched in the
// case that input element ids (or |name| fields) are missing.
TEST(FormStructureTest, HeuristicsLabelsOnly) {
scoped_ptr<FormStructure> form_structure;
FormData form;
form.method = ASCIIToUTF16("post");
FormFieldData field;
field.form_control_type = "text";
field.label = ASCIIToUTF16("First Name");
field.name = base::string16();
form.fields.push_back(field);
field.label = ASCIIToUTF16("Last Name");
field.name = base::string16();
form.fields.push_back(field);
field.label = ASCIIToUTF16("Email");
field.name = base::string16();
form.fields.push_back(field);
field.label = ASCIIToUTF16("Phone");
field.name = base::string16();
form.fields.push_back(field);
field.label = ASCIIToUTF16("Address");
field.name = base::string16();
form.fields.push_back(field);
field.label = ASCIIToUTF16("Address");
field.name = base::string16();
form.fields.push_back(field);
field.label = ASCIIToUTF16("Zip code");
field.name = base::string16();
form.fields.push_back(field);
field.label = base::string16();
field.name = ASCIIToUTF16("Submit");
field.form_control_type = "submit";
form.fields.push_back(field);
form_structure.reset(new FormStructure(form));
form_structure->DetermineHeuristicTypes(TestAutofillMetrics());
EXPECT_TRUE(form_structure->IsAutofillable(true));
ASSERT_EQ(8U, form_structure->field_count());
ASSERT_EQ(7U, form_structure->autofill_count());
// First name.
EXPECT_EQ(NAME_FIRST, form_structure->field(0)->heuristic_type());
// Last name.
EXPECT_EQ(NAME_LAST, form_structure->field(1)->heuristic_type());
// Email.
EXPECT_EQ(EMAIL_ADDRESS, form_structure->field(2)->heuristic_type());
// Phone.
EXPECT_EQ(PHONE_HOME_WHOLE_NUMBER,
form_structure->field(3)->heuristic_type());
// Address.
EXPECT_EQ(ADDRESS_HOME_LINE1, form_structure->field(4)->heuristic_type());
// Address Line 2.
EXPECT_EQ(ADDRESS_HOME_LINE2, form_structure->field(5)->heuristic_type());
// Zip.
EXPECT_EQ(ADDRESS_HOME_ZIP, form_structure->field(6)->heuristic_type());
// Submit.
EXPECT_EQ(UNKNOWN_TYPE, form_structure->field(7)->heuristic_type());
}
TEST(FormStructureTest, HeuristicsCreditCardInfo) {
scoped_ptr<FormStructure> form_structure;
FormData form;
form.method = ASCIIToUTF16("post");
FormFieldData field;
field.form_control_type = "text";
field.label = ASCIIToUTF16("Name on Card");
field.name = ASCIIToUTF16("name_on_card");
form.fields.push_back(field);
field.label = ASCIIToUTF16("Card Number");
field.name = ASCIIToUTF16("card_number");
form.fields.push_back(field);
field.label = ASCIIToUTF16("Exp Month");
field.name = ASCIIToUTF16("ccmonth");
form.fields.push_back(field);
field.label = ASCIIToUTF16("Exp Year");
field.name = ASCIIToUTF16("ccyear");
form.fields.push_back(field);
field.label = ASCIIToUTF16("Verification");
field.name = ASCIIToUTF16("verification");
form.fields.push_back(field);
field.label = base::string16();
field.name = ASCIIToUTF16("Submit");
field.form_control_type = "submit";
form.fields.push_back(field);
form_structure.reset(new FormStructure(form));
form_structure->DetermineHeuristicTypes(TestAutofillMetrics());
EXPECT_TRUE(form_structure->IsAutofillable(true));
ASSERT_EQ(6U, form_structure->field_count());
ASSERT_EQ(5U, form_structure->autofill_count());
// Credit card name.
EXPECT_EQ(CREDIT_CARD_NAME, form_structure->field(0)->heuristic_type());
// Credit card number.
EXPECT_EQ(CREDIT_CARD_NUMBER, form_structure->field(1)->heuristic_type());
// Credit card expiration month.
EXPECT_EQ(CREDIT_CARD_EXP_MONTH, form_structure->field(2)->heuristic_type());
// Credit card expiration year.
EXPECT_EQ(CREDIT_CARD_EXP_4_DIGIT_YEAR,
form_structure->field(3)->heuristic_type());
// CVV.
EXPECT_EQ(CREDIT_CARD_VERIFICATION_CODE,
form_structure->field(4)->heuristic_type());
// Submit.
EXPECT_EQ(UNKNOWN_TYPE, form_structure->field(5)->heuristic_type());
}
TEST(FormStructureTest, HeuristicsCreditCardInfoWithUnknownCardField) {
scoped_ptr<FormStructure> form_structure;
FormData form;
form.method = ASCIIToUTF16("post");
FormFieldData field;
field.form_control_type = "text";
field.label = ASCIIToUTF16("Name on Card");
field.name = ASCIIToUTF16("name_on_card");
form.fields.push_back(field);
// This is not a field we know how to process. But we should skip over it
// and process the other fields in the card block.
field.label = ASCIIToUTF16("Card image");
field.name = ASCIIToUTF16("card_image");
form.fields.push_back(field);
field.label = ASCIIToUTF16("Card Number");
field.name = ASCIIToUTF16("card_number");
form.fields.push_back(field);
field.label = ASCIIToUTF16("Exp Month");
field.name = ASCIIToUTF16("ccmonth");
form.fields.push_back(field);
field.label = ASCIIToUTF16("Exp Year");
field.name = ASCIIToUTF16("ccyear");
form.fields.push_back(field);
field.label = ASCIIToUTF16("Verification");
field.name = ASCIIToUTF16("verification");
form.fields.push_back(field);
field.label = base::string16();
field.name = ASCIIToUTF16("Submit");
field.form_control_type = "submit";
form.fields.push_back(field);
form_structure.reset(new FormStructure(form));
form_structure->DetermineHeuristicTypes(TestAutofillMetrics());
EXPECT_TRUE(form_structure->IsAutofillable(true));
ASSERT_EQ(7U, form_structure->field_count());
ASSERT_EQ(5U, form_structure->autofill_count());
// Credit card name.
EXPECT_EQ(CREDIT_CARD_NAME, form_structure->field(0)->heuristic_type());
// Credit card type. This is an unknown type but related to the credit card.
EXPECT_EQ(UNKNOWN_TYPE, form_structure->field(1)->heuristic_type());
// Credit card number.
EXPECT_EQ(CREDIT_CARD_NUMBER, form_structure->field(2)->heuristic_type());
// Credit card expiration month.
EXPECT_EQ(CREDIT_CARD_EXP_MONTH, form_structure->field(3)->heuristic_type());
// Credit card expiration year.
EXPECT_EQ(CREDIT_CARD_EXP_4_DIGIT_YEAR,
form_structure->field(4)->heuristic_type());
// CVV.
EXPECT_EQ(CREDIT_CARD_VERIFICATION_CODE,
form_structure->field(5)->heuristic_type());
// Submit.
EXPECT_EQ(UNKNOWN_TYPE, form_structure->field(6)->heuristic_type());
}
TEST(FormStructureTest, ThreeAddressLines) {
scoped_ptr<FormStructure> form_structure;
FormData form;
form.method = ASCIIToUTF16("post");
FormFieldData field;
field.form_control_type = "text";
field.label = ASCIIToUTF16("Address Line1");
field.name = ASCIIToUTF16("Address");
form.fields.push_back(field);
field.label = ASCIIToUTF16("Address Line2");
field.name = ASCIIToUTF16("Address");
form.fields.push_back(field);
field.label = ASCIIToUTF16("Address Line3");
field.name = ASCIIToUTF16("Address");
form.fields.push_back(field);
field.label = ASCIIToUTF16("City");
field.name = ASCIIToUTF16("city");
form.fields.push_back(field);
form_structure.reset(new FormStructure(form));
form_structure->DetermineHeuristicTypes(TestAutofillMetrics());
EXPECT_TRUE(form_structure->IsAutofillable(true));
ASSERT_EQ(4U, form_structure->field_count());
ASSERT_EQ(3U, form_structure->autofill_count());
// Address Line 1.
EXPECT_EQ(ADDRESS_HOME_LINE1, form_structure->field(0)->heuristic_type());
// Address Line 2.
EXPECT_EQ(ADDRESS_HOME_LINE2, form_structure->field(1)->heuristic_type());
// Address Line 3.
EXPECT_EQ(UNKNOWN_TYPE, form_structure->field(2)->heuristic_type());
// City.
EXPECT_EQ(ADDRESS_HOME_CITY, form_structure->field(3)->heuristic_type());
}
// Numbered address lines after line two are ignored.
TEST(FormStructureTest, SurplusAddressLinesIgnored) {
scoped_ptr<FormStructure> form_structure;
FormData form;
form.method = ASCIIToUTF16("post");
FormFieldData field;
field.form_control_type = "text";
field.label = ASCIIToUTF16("Address Line1");
field.name = ASCIIToUTF16("shipping.address.addressLine1");
form.fields.push_back(field);
field.label = ASCIIToUTF16("Address Line2");
field.name = ASCIIToUTF16("shipping.address.addressLine2");
form.fields.push_back(field);
field.label = ASCIIToUTF16("Address Line3");
field.name = ASCIIToUTF16("billing.address.addressLine3");
form.fields.push_back(field);
field.label = ASCIIToUTF16("Address Line4");
field.name = ASCIIToUTF16("billing.address.addressLine4");
form.fields.push_back(field);
form_structure.reset(new FormStructure(form));
form_structure->DetermineHeuristicTypes(TestAutofillMetrics());
ASSERT_EQ(4U, form_structure->field_count());
ASSERT_EQ(2U, form_structure->autofill_count());
// Address Line 1.
EXPECT_EQ(ADDRESS_HOME_LINE1, form_structure->field(0)->heuristic_type());
// Address Line 2.
EXPECT_EQ(ADDRESS_HOME_LINE2, form_structure->field(1)->heuristic_type());
// Address Line 3 (ignored).
EXPECT_EQ(UNKNOWN_TYPE, form_structure->field(2)->heuristic_type());
// Address Line 4 (ignored).
EXPECT_EQ(UNKNOWN_TYPE, form_structure->field(3)->heuristic_type());
}
// This example comes from expedia.com where they use a "Suite" label to
// indicate a suite or apartment number. We interpret this as address line 2.
// And the following "Street address second line" we interpret as address line
// 3 and discard.
// See http://crbug.com/48197 for details.
TEST(FormStructureTest, ThreeAddressLinesExpedia) {
scoped_ptr<FormStructure> form_structure;
FormData form;
form.method = ASCIIToUTF16("post");
FormFieldData field;
field.form_control_type = "text";
field.label = ASCIIToUTF16("Street:");
field.name = ASCIIToUTF16("FOPIH_RgWebCC_0_IHAddress_ads1");
form.fields.push_back(field);
field.label = ASCIIToUTF16("Suite or Apt:");
field.name = ASCIIToUTF16("FOPIH_RgWebCC_0_IHAddress_adap");
form.fields.push_back(field);
field.label = ASCIIToUTF16("Street address second line");
field.name = ASCIIToUTF16("FOPIH_RgWebCC_0_IHAddress_ads2");
form.fields.push_back(field);
field.label = ASCIIToUTF16("City:");
field.name = ASCIIToUTF16("FOPIH_RgWebCC_0_IHAddress_adct");
form.fields.push_back(field);
form_structure.reset(new FormStructure(form));
form_structure->DetermineHeuristicTypes(TestAutofillMetrics());
EXPECT_TRUE(form_structure->IsAutofillable(true));
ASSERT_EQ(4U, form_structure->field_count());
EXPECT_EQ(3U, form_structure->autofill_count());
// Address Line 1.
EXPECT_EQ(ADDRESS_HOME_LINE1, form_structure->field(0)->heuristic_type());
// Suite / Apt.
EXPECT_EQ(ADDRESS_HOME_LINE2, form_structure->field(1)->heuristic_type());
// Address Line 3.
EXPECT_EQ(UNKNOWN_TYPE, form_structure->field(2)->heuristic_type());
// City.
EXPECT_EQ(ADDRESS_HOME_CITY, form_structure->field(3)->heuristic_type());
}
// This example comes from ebay.com where the word "suite" appears in the label
// and the name "address2" clearly indicates that this is the address line 2.
// See http://crbug.com/48197 for details.
TEST(FormStructureTest, TwoAddressLinesEbay) {
scoped_ptr<FormStructure> form_structure;
FormData form;
form.method = ASCIIToUTF16("post");
FormFieldData field;
field.form_control_type = "text";
field.label = ASCIIToUTF16("Address Line1");
field.name = ASCIIToUTF16("address1");
form.fields.push_back(field);
field.label = ASCIIToUTF16("Floor number, suite number, etc");
field.name = ASCIIToUTF16("address2");
form.fields.push_back(field);
field.label = ASCIIToUTF16("City:");
field.name = ASCIIToUTF16("city");
form.fields.push_back(field);
form_structure.reset(new FormStructure(form));
form_structure->DetermineHeuristicTypes(TestAutofillMetrics());
EXPECT_TRUE(form_structure->IsAutofillable(true));
ASSERT_EQ(3U, form_structure->field_count());
ASSERT_EQ(3U, form_structure->autofill_count());
// Address Line 1.
EXPECT_EQ(ADDRESS_HOME_LINE1, form_structure->field(0)->heuristic_type());
// Address Line 2.
EXPECT_EQ(ADDRESS_HOME_LINE2, form_structure->field(1)->heuristic_type());
// City.
EXPECT_EQ(ADDRESS_HOME_CITY, form_structure->field(2)->heuristic_type());
}
TEST(FormStructureTest, HeuristicsStateWithProvince) {
scoped_ptr<FormStructure> form_structure;
FormData form;
form.method = ASCIIToUTF16("post");
FormFieldData field;
field.form_control_type = "text";
field.label = ASCIIToUTF16("Address Line1");
field.name = ASCIIToUTF16("Address");
form.fields.push_back(field);
field.label = ASCIIToUTF16("Address Line2");
field.name = ASCIIToUTF16("Address");
form.fields.push_back(field);
field.label = ASCIIToUTF16("State/Province/Region");
field.name = ASCIIToUTF16("State");
form.fields.push_back(field);
form_structure.reset(new FormStructure(form));
form_structure->DetermineHeuristicTypes(TestAutofillMetrics());
EXPECT_TRUE(form_structure->IsAutofillable(true));
ASSERT_EQ(3U, form_structure->field_count());
ASSERT_EQ(3U, form_structure->autofill_count());
// Address Line 1.
EXPECT_EQ(ADDRESS_HOME_LINE1, form_structure->field(0)->heuristic_type());
// Address Line 2.
EXPECT_EQ(ADDRESS_HOME_LINE2, form_structure->field(1)->heuristic_type());
// State.
EXPECT_EQ(ADDRESS_HOME_STATE, form_structure->field(2)->heuristic_type());
}
// This example comes from lego.com's checkout page.
TEST(FormStructureTest, HeuristicsWithBilling) {
scoped_ptr<FormStructure> form_structure;
FormData form;
form.method = ASCIIToUTF16("post");
FormFieldData field;
field.form_control_type = "text";
field.label = ASCIIToUTF16("First Name*:");
field.name = ASCIIToUTF16("editBillingAddress$firstNameBox");
form.fields.push_back(field);
field.label = ASCIIToUTF16("Last Name*:");
field.name = ASCIIToUTF16("editBillingAddress$lastNameBox");
form.fields.push_back(field);
field.label = ASCIIToUTF16("Company Name:");
field.name = ASCIIToUTF16("editBillingAddress$companyBox");
form.fields.push_back(field);
field.label = ASCIIToUTF16("Address*:");
field.name = ASCIIToUTF16("editBillingAddress$addressLine1Box");
form.fields.push_back(field);
field.label = ASCIIToUTF16("Apt/Suite :");
field.name = ASCIIToUTF16("editBillingAddress$addressLine2Box");
form.fields.push_back(field);
field.label = ASCIIToUTF16("City*:");
field.name = ASCIIToUTF16("editBillingAddress$cityBox");
form.fields.push_back(field);
field.label = ASCIIToUTF16("State/Province*:");
field.name = ASCIIToUTF16("editBillingAddress$stateDropDown");
form.fields.push_back(field);
field.label = ASCIIToUTF16("Country*:");
field.name = ASCIIToUTF16("editBillingAddress$countryDropDown");
form.fields.push_back(field);
field.label = ASCIIToUTF16("Postal Code*:");
field.name = ASCIIToUTF16("editBillingAddress$zipCodeBox");
form.fields.push_back(field);
field.label = ASCIIToUTF16("Phone*:");
field.name = ASCIIToUTF16("editBillingAddress$phoneBox");
form.fields.push_back(field);
field.label = ASCIIToUTF16("Email Address*:");
field.name = ASCIIToUTF16("email$emailBox");
form.fields.push_back(field);
form_structure.reset(new FormStructure(form));
form_structure->DetermineHeuristicTypes(TestAutofillMetrics());
EXPECT_TRUE(form_structure->IsAutofillable(true));
ASSERT_EQ(11U, form_structure->field_count());
ASSERT_EQ(11U, form_structure->autofill_count());
EXPECT_EQ(NAME_FIRST, form_structure->field(0)->heuristic_type());
EXPECT_EQ(NAME_LAST, form_structure->field(1)->heuristic_type());
EXPECT_EQ(COMPANY_NAME, form_structure->field(2)->heuristic_type());
EXPECT_EQ(ADDRESS_HOME_LINE1, form_structure->field(3)->heuristic_type());
EXPECT_EQ(ADDRESS_HOME_LINE2, form_structure->field(4)->heuristic_type());
EXPECT_EQ(ADDRESS_HOME_CITY, form_structure->field(5)->heuristic_type());
EXPECT_EQ(ADDRESS_HOME_STATE, form_structure->field(6)->heuristic_type());
EXPECT_EQ(ADDRESS_HOME_COUNTRY, form_structure->field(7)->heuristic_type());
EXPECT_EQ(ADDRESS_HOME_ZIP, form_structure->field(8)->heuristic_type());
EXPECT_EQ(PHONE_HOME_WHOLE_NUMBER,
form_structure->field(9)->heuristic_type());
EXPECT_EQ(EMAIL_ADDRESS, form_structure->field(10)->heuristic_type());
}
TEST(FormStructureTest, ThreePartPhoneNumber) {
scoped_ptr<FormStructure> form_structure;
FormData form;
form.method = ASCIIToUTF16("post");
FormFieldData field;
field.form_control_type = "text";
field.label = ASCIIToUTF16("Phone:");
field.name = ASCIIToUTF16("dayphone1");
field.max_length = 0;
form.fields.push_back(field);
field.label = ASCIIToUTF16("-");
field.name = ASCIIToUTF16("dayphone2");
field.max_length = 3; // Size of prefix is 3.
form.fields.push_back(field);
field.label = ASCIIToUTF16("-");
field.name = ASCIIToUTF16("dayphone3");
field.max_length = 4; // Size of suffix is 4. If unlimited size is
// passed, phone will be parsed as
// <country code> - <area code> - <phone>.
form.fields.push_back(field);
field.label = ASCIIToUTF16("ext.:");
field.name = ASCIIToUTF16("dayphone4");
field.max_length = 0;
form.fields.push_back(field);
form_structure.reset(new FormStructure(form));
form_structure->DetermineHeuristicTypes(TestAutofillMetrics());
EXPECT_TRUE(form_structure->IsAutofillable(true));
ASSERT_EQ(4U, form_structure->field_count());
ASSERT_EQ(3U, form_structure->autofill_count());
// Area code.
EXPECT_EQ(PHONE_HOME_CITY_CODE, form_structure->field(0)->heuristic_type());
// Phone number suffix.
EXPECT_EQ(PHONE_HOME_NUMBER,
form_structure->field(1)->heuristic_type());
// Phone number suffix.
EXPECT_EQ(PHONE_HOME_NUMBER,
form_structure->field(2)->heuristic_type());
// Unknown.
EXPECT_EQ(UNKNOWN_TYPE, form_structure->field(3)->heuristic_type());
}
TEST(FormStructureTest, HeuristicsInfernoCC) {
scoped_ptr<FormStructure> form_structure;
FormData form;
form.method = ASCIIToUTF16("post");
FormFieldData field;
field.form_control_type = "text";
field.label = ASCIIToUTF16("Name on Card");
field.name = ASCIIToUTF16("name_on_card");
form.fields.push_back(field);
field.label = ASCIIToUTF16("Address");
field.name = ASCIIToUTF16("billing_address");
form.fields.push_back(field);
field.label = ASCIIToUTF16("Card Number");
field.name = ASCIIToUTF16("card_number");
form.fields.push_back(field);
field.label = ASCIIToUTF16("Expiration Date");
field.name = ASCIIToUTF16("expiration_month");
form.fields.push_back(field);
field.label = ASCIIToUTF16("Expiration Year");
field.name = ASCIIToUTF16("expiration_year");
form.fields.push_back(field);
form_structure.reset(new FormStructure(form));
form_structure->DetermineHeuristicTypes(TestAutofillMetrics());
EXPECT_TRUE(form_structure->IsAutofillable(true));
// Expect the correct number of fields.
ASSERT_EQ(5U, form_structure->field_count());
EXPECT_EQ(5U, form_structure->autofill_count());
// Name on Card.
EXPECT_EQ(CREDIT_CARD_NAME, form_structure->field(0)->heuristic_type());
// Address.
EXPECT_EQ(ADDRESS_HOME_LINE1, form_structure->field(1)->heuristic_type());
// Card Number.
EXPECT_EQ(CREDIT_CARD_NUMBER, form_structure->field(2)->heuristic_type());
// Expiration Date.
EXPECT_EQ(CREDIT_CARD_EXP_MONTH, form_structure->field(3)->heuristic_type());
// Expiration Year.
EXPECT_EQ(CREDIT_CARD_EXP_4_DIGIT_YEAR,
form_structure->field(4)->heuristic_type());
}
TEST(FormStructureTest, CVCCodeClash) {
scoped_ptr<FormStructure> form_structure;
FormData form;
form.method = ASCIIToUTF16("post");
FormFieldData field;
field.form_control_type = "text";
field.label = ASCIIToUTF16("Card number");
field.name = ASCIIToUTF16("ccnumber");
form.fields.push_back(field);
field.label = ASCIIToUTF16("First name");
field.name = ASCIIToUTF16("first_name");
form.fields.push_back(field);
field.label = ASCIIToUTF16("Last name");
field.name = ASCIIToUTF16("last_name");
form.fields.push_back(field);
field.label = ASCIIToUTF16("Expiration date");
field.name = ASCIIToUTF16("ccexpiresmonth");
form.fields.push_back(field);
field.label = base::string16();
field.name = ASCIIToUTF16("ccexpiresyear");
form.fields.push_back(field);
field.label = ASCIIToUTF16("cvc number");
field.name = ASCIIToUTF16("csc");
form.fields.push_back(field);
form_structure.reset(new FormStructure(form));
form_structure->DetermineHeuristicTypes(TestAutofillMetrics());
EXPECT_TRUE(form_structure->IsAutofillable(true));
// Expect the correct number of fields.
ASSERT_EQ(6U, form_structure->field_count());
ASSERT_EQ(5U, form_structure->autofill_count());
// Card Number.
EXPECT_EQ(CREDIT_CARD_NUMBER, form_structure->field(0)->heuristic_type());
// First name, taken as name on card.
EXPECT_EQ(CREDIT_CARD_NAME, form_structure->field(1)->heuristic_type());
// Last name is not merged.
EXPECT_EQ(UNKNOWN_TYPE, form_structure->field(2)->heuristic_type());
// Expiration Date.
EXPECT_EQ(CREDIT_CARD_EXP_MONTH, form_structure->field(3)->heuristic_type());
// Expiration Year.
EXPECT_EQ(CREDIT_CARD_EXP_4_DIGIT_YEAR,
form_structure->field(4)->heuristic_type());
// CVC code.
EXPECT_EQ(CREDIT_CARD_VERIFICATION_CODE,
form_structure->field(5)->heuristic_type());
}
TEST(FormStructureTest, EncodeQueryRequest) {
FormData form;
form.method = ASCIIToUTF16("post");
FormFieldData field;
field.form_control_type = "text";
field.label = ASCIIToUTF16("Name on Card");
field.name = ASCIIToUTF16("name_on_card");
form.fields.push_back(field);
field.label = ASCIIToUTF16("Address");
field.name = ASCIIToUTF16("billing_address");
form.fields.push_back(field);
field.label = ASCIIToUTF16("Card Number");
field.name = ASCIIToUTF16("card_number");
form.fields.push_back(field);
field.label = ASCIIToUTF16("Expiration Date");
field.name = ASCIIToUTF16("expiration_month");
form.fields.push_back(field);
field.label = ASCIIToUTF16("Expiration Year");
field.name = ASCIIToUTF16("expiration_year");
form.fields.push_back(field);
// Add checkable field.
FormFieldData checkable_field;
checkable_field.is_checkable = true;
checkable_field.label = ASCIIToUTF16("Checkable1");
checkable_field.name = ASCIIToUTF16("Checkable1");
form.fields.push_back(checkable_field);
ScopedVector<FormStructure> forms;
forms.push_back(new FormStructure(form));
std::vector<std::string> encoded_signatures;
std::string encoded_xml;
const char kSignature1[] = "11337937696949187602";
const char kResponse1[] =
"<\?xml version=\"1.0\" encoding=\"UTF-8\"\?>"
"<autofillquery clientversion=\"6.1.1715.1442/en (GGLL)\">"
"<form signature=\"11337937696949187602\">"
"<field signature=\"412125936\"/>"
"<field signature=\"1917667676\"/>"
"<field signature=\"2226358947\"/>"
"<field signature=\"747221617\"/>"
"<field signature=\"4108155786\"/>"
"</form>"
"</autofillquery>";
ASSERT_TRUE(FormStructure::EncodeQueryRequest(forms.get(),
&encoded_signatures,
&encoded_xml));
ASSERT_EQ(1U, encoded_signatures.size());
EXPECT_EQ(kSignature1, encoded_signatures[0]);
EXPECT_EQ(kResponse1, encoded_xml);
// Add the same form, only one will be encoded, so EncodeQueryRequest() should
// return the same data.
forms.push_back(new FormStructure(form));
ASSERT_TRUE(FormStructure::EncodeQueryRequest(forms.get(),
&encoded_signatures,
&encoded_xml));
ASSERT_EQ(1U, encoded_signatures.size());
EXPECT_EQ(kSignature1, encoded_signatures[0]);
EXPECT_EQ(kResponse1, encoded_xml);
// Add 5 address fields - this should be still a valid form.
for (size_t i = 0; i < 5; ++i) {
field.label = ASCIIToUTF16("Address");
field.name = ASCIIToUTF16("address");
form.fields.push_back(field);
}
forms.push_back(new FormStructure(form));
ASSERT_TRUE(FormStructure::EncodeQueryRequest(forms.get(),
&encoded_signatures,
&encoded_xml));
ASSERT_EQ(2U, encoded_signatures.size());
EXPECT_EQ(kSignature1, encoded_signatures[0]);
const char kSignature2[] = "8308881815906226214";
EXPECT_EQ(kSignature2, encoded_signatures[1]);
const char kResponse2[] =
"<\?xml version=\"1.0\" encoding=\"UTF-8\"\?>"
"<autofillquery clientversion=\"6.1.1715.1442/en (GGLL)\">"
"<form signature=\"11337937696949187602\">"
"<field signature=\"412125936\"/>"
"<field signature=\"1917667676\"/>"
"<field signature=\"2226358947\"/>"
"<field signature=\"747221617\"/>"
"<field signature=\"4108155786\"/>"
"</form>"
"<form signature=\"8308881815906226214\">"
"<field signature=\"412125936\"/>"
"<field signature=\"1917667676\"/>"
"<field signature=\"2226358947\"/>"
"<field signature=\"747221617\"/>"
"<field signature=\"4108155786\"/>"
"<field signature=\"509334676\"/>"
"<field signature=\"509334676\"/>"
"<field signature=\"509334676\"/>"
"<field signature=\"509334676\"/>"
"<field signature=\"509334676\"/>"
"</form>"
"</autofillquery>";
EXPECT_EQ(kResponse2, encoded_xml);
FormData malformed_form(form);
// Add 50 address fields - the form is not valid anymore, but previous ones
// are. The result should be the same as in previous test.
for (size_t i = 0; i < 50; ++i) {
field.label = ASCIIToUTF16("Address");
field.name = ASCIIToUTF16("address");
malformed_form.fields.push_back(field);
}
forms.push_back(new FormStructure(malformed_form));
ASSERT_TRUE(FormStructure::EncodeQueryRequest(forms.get(),
&encoded_signatures,
&encoded_xml));
ASSERT_EQ(2U, encoded_signatures.size());
EXPECT_EQ(kSignature1, encoded_signatures[0]);
EXPECT_EQ(kSignature2, encoded_signatures[1]);
EXPECT_EQ(kResponse2, encoded_xml);
// Check that we fail if there are only bad form(s).
ScopedVector<FormStructure> bad_forms;
bad_forms.push_back(new FormStructure(malformed_form));
EXPECT_FALSE(FormStructure::EncodeQueryRequest(bad_forms.get(),
&encoded_signatures,
&encoded_xml));
EXPECT_EQ(0U, encoded_signatures.size());
EXPECT_EQ("", encoded_xml);
}
TEST(FormStructureTest, EncodeUploadRequest) {
scoped_ptr<FormStructure> form_structure;
std::vector<ServerFieldTypeSet> possible_field_types;
FormData form;
form.method = ASCIIToUTF16("post");
form_structure.reset(new FormStructure(form));
form_structure->DetermineHeuristicTypes(TestAutofillMetrics());
FormFieldData field;
field.form_control_type = "text";
field.label = ASCIIToUTF16("First Name");
field.name = ASCIIToUTF16("firstname");
form.fields.push_back(field);
possible_field_types.push_back(ServerFieldTypeSet());
possible_field_types.back().insert(NAME_FIRST);
field.label = ASCIIToUTF16("Last Name");
field.name = ASCIIToUTF16("lastname");
form.fields.push_back(field);
possible_field_types.push_back(ServerFieldTypeSet());
possible_field_types.back().insert(NAME_LAST);
field.label = ASCIIToUTF16("Email");
field.name = ASCIIToUTF16("email");
field.form_control_type = "email";
form.fields.push_back(field);
possible_field_types.push_back(ServerFieldTypeSet());
possible_field_types.back().insert(EMAIL_ADDRESS);
field.label = ASCIIToUTF16("Phone");
field.name = ASCIIToUTF16("phone");
field.form_control_type = "number";
form.fields.push_back(field);
possible_field_types.push_back(ServerFieldTypeSet());
possible_field_types.back().insert(PHONE_HOME_WHOLE_NUMBER);
field.label = ASCIIToUTF16("Country");
field.name = ASCIIToUTF16("country");
field.form_control_type = "select-one";
form.fields.push_back(field);
possible_field_types.push_back(ServerFieldTypeSet());
possible_field_types.back().insert(ADDRESS_HOME_COUNTRY);
// Add checkable field.
FormFieldData checkable_field;
checkable_field.is_checkable = true;
checkable_field.label = ASCIIToUTF16("Checkable1");
checkable_field.name = ASCIIToUTF16("Checkable1");
form.fields.push_back(checkable_field);
possible_field_types.push_back(ServerFieldTypeSet());
possible_field_types.back().insert(ADDRESS_HOME_COUNTRY);
form_structure.reset(new FormStructure(form));
ASSERT_EQ(form_structure->field_count(), possible_field_types.size());
for (size_t i = 0; i < form_structure->field_count(); ++i)
form_structure->field(i)->set_possible_types(possible_field_types[i]);
ServerFieldTypeSet available_field_types;
available_field_types.insert(NAME_FIRST);
available_field_types.insert(NAME_LAST);
available_field_types.insert(ADDRESS_HOME_LINE1);
available_field_types.insert(ADDRESS_HOME_LINE2);
available_field_types.insert(ADDRESS_HOME_COUNTRY);
available_field_types.insert(ADDRESS_BILLING_LINE1);
available_field_types.insert(ADDRESS_BILLING_LINE2);
available_field_types.insert(EMAIL_ADDRESS);
available_field_types.insert(PHONE_HOME_WHOLE_NUMBER);
std::string encoded_xml;
EXPECT_TRUE(form_structure->EncodeUploadRequest(available_field_types, false,
&encoded_xml));
EXPECT_EQ("<\?xml version=\"1.0\" encoding=\"UTF-8\"\?>"
"<autofillupload clientversion=\"6.1.1715.1442/en (GGLL)\" "
"formsignature=\"8736493185895608956\" autofillused=\"false\" "
"datapresent=\"144200030e\">"
"<field signature=\"3763331450\" autofilltype=\"3\"/>"
"<field signature=\"3494530716\" autofilltype=\"5\"/>"
"<field signature=\"1029417091\" autofilltype=\"9\"/>"
"<field signature=\"466116101\" autofilltype=\"14\"/>"
"<field signature=\"2799270304\" autofilltype=\"36\"/>"
"</autofillupload>",
encoded_xml);
EXPECT_TRUE(form_structure->EncodeUploadRequest(available_field_types, true,
&encoded_xml));
EXPECT_EQ("<\?xml version=\"1.0\" encoding=\"UTF-8\"\?>"
"<autofillupload clientversion=\"6.1.1715.1442/en (GGLL)\" "
"formsignature=\"8736493185895608956\" autofillused=\"true\" "
"datapresent=\"144200030e\">"
"<field signature=\"3763331450\" autofilltype=\"3\"/>"
"<field signature=\"3494530716\" autofilltype=\"5\"/>"
"<field signature=\"1029417091\" autofilltype=\"9\"/>"
"<field signature=\"466116101\" autofilltype=\"14\"/>"
"<field signature=\"2799270304\" autofilltype=\"36\"/>"
"</autofillupload>",
encoded_xml);
// Add 2 address fields - this should be still a valid form.
for (size_t i = 0; i < 2; ++i) {
field.label = ASCIIToUTF16("Address");
field.name = ASCIIToUTF16("address");
field.form_control_type = "text";
form.fields.push_back(field);
possible_field_types.push_back(ServerFieldTypeSet());
possible_field_types.back().insert(ADDRESS_HOME_LINE1);
possible_field_types.back().insert(ADDRESS_HOME_LINE2);
possible_field_types.back().insert(ADDRESS_BILLING_LINE1);
possible_field_types.back().insert(ADDRESS_BILLING_LINE2);
}
form_structure.reset(new FormStructure(form));
ASSERT_EQ(form_structure->field_count(), possible_field_types.size());
for (size_t i = 0; i < form_structure->field_count(); ++i)
form_structure->field(i)->set_possible_types(possible_field_types[i]);
EXPECT_TRUE(form_structure->EncodeUploadRequest(available_field_types, false,
&encoded_xml));
EXPECT_EQ("<\?xml version=\"1.0\" encoding=\"UTF-8\"\?>"
"<autofillupload clientversion=\"6.1.1715.1442/en (GGLL)\" "
"formsignature=\"7816485729218079147\" autofillused=\"false\" "
"datapresent=\"144200030e\">"
"<field signature=\"3763331450\" autofilltype=\"3\"/>"
"<field signature=\"3494530716\" autofilltype=\"5\"/>"
"<field signature=\"1029417091\" autofilltype=\"9\"/>"
"<field signature=\"466116101\" autofilltype=\"14\"/>"
"<field signature=\"2799270304\" autofilltype=\"36\"/>"
"<field signature=\"509334676\" autofilltype=\"30\"/>"
"<field signature=\"509334676\" autofilltype=\"31\"/>"
"<field signature=\"509334676\" autofilltype=\"37\"/>"
"<field signature=\"509334676\" autofilltype=\"38\"/>"
"<field signature=\"509334676\" autofilltype=\"30\"/>"
"<field signature=\"509334676\" autofilltype=\"31\"/>"
"<field signature=\"509334676\" autofilltype=\"37\"/>"
"<field signature=\"509334676\" autofilltype=\"38\"/>"
"</autofillupload>",
encoded_xml);
// Add 50 address fields - now the form is invalid, as it has too many fields.
for (size_t i = 0; i < 50; ++i) {
field.label = ASCIIToUTF16("Address");
field.name = ASCIIToUTF16("address");
field.form_control_type = "text";
form.fields.push_back(field);
possible_field_types.push_back(ServerFieldTypeSet());
possible_field_types.back().insert(ADDRESS_HOME_LINE1);
possible_field_types.back().insert(ADDRESS_HOME_LINE2);
possible_field_types.back().insert(ADDRESS_BILLING_LINE1);
possible_field_types.back().insert(ADDRESS_BILLING_LINE2);
}
form_structure.reset(new FormStructure(form));
ASSERT_EQ(form_structure->field_count(), possible_field_types.size());
for (size_t i = 0; i < form_structure->field_count(); ++i)
form_structure->field(i)->set_possible_types(possible_field_types[i]);
EXPECT_FALSE(form_structure->EncodeUploadRequest(available_field_types, false,
&encoded_xml));
}
TEST(FormStructureTest, EncodeFieldAssignments) {
scoped_ptr<FormStructure> form_structure;
std::vector<ServerFieldTypeSet> possible_field_types;
FormData form;
form.method = ASCIIToUTF16("post");
form_structure.reset(new FormStructure(form));
form_structure->DetermineHeuristicTypes(TestAutofillMetrics());
FormFieldData field;
field.form_control_type = "text";
field.label = ASCIIToUTF16("First Name");
field.name = ASCIIToUTF16("firstname");
form.fields.push_back(field);
possible_field_types.push_back(ServerFieldTypeSet());
possible_field_types.back().insert(NAME_FIRST);
field.label = ASCIIToUTF16("Last Name");
field.name = ASCIIToUTF16("lastname");
form.fields.push_back(field);
possible_field_types.push_back(ServerFieldTypeSet());
possible_field_types.back().insert(NAME_LAST);
field.label = ASCIIToUTF16("Email");
field.name = ASCIIToUTF16("email");
field.form_control_type = "email";
form.fields.push_back(field);
possible_field_types.push_back(ServerFieldTypeSet());
possible_field_types.back().insert(EMAIL_ADDRESS);
field.label = ASCIIToUTF16("Phone");
field.name = ASCIIToUTF16("phone");
field.form_control_type = "number";
form.fields.push_back(field);
possible_field_types.push_back(ServerFieldTypeSet());
possible_field_types.back().insert(PHONE_HOME_WHOLE_NUMBER);
field.label = ASCIIToUTF16("Country");
field.name = ASCIIToUTF16("country");
field.form_control_type = "select-one";
form.fields.push_back(field);
possible_field_types.push_back(ServerFieldTypeSet());
possible_field_types.back().insert(ADDRESS_HOME_COUNTRY);
// Add checkable field.
FormFieldData checkable_field;
checkable_field.is_checkable = true;
checkable_field.label = ASCIIToUTF16("Checkable1");
checkable_field.name = ASCIIToUTF16("Checkable1");
form.fields.push_back(checkable_field);
possible_field_types.push_back(ServerFieldTypeSet());
possible_field_types.back().insert(ADDRESS_HOME_COUNTRY);
form_structure.reset(new FormStructure(form));
ASSERT_EQ(form_structure->field_count(), possible_field_types.size());
for (size_t i = 0; i < form_structure->field_count(); ++i)
form_structure->field(i)->set_possible_types(possible_field_types[i]);
ServerFieldTypeSet available_field_types;
available_field_types.insert(NAME_FIRST);
available_field_types.insert(NAME_LAST);
available_field_types.insert(ADDRESS_HOME_LINE1);
available_field_types.insert(ADDRESS_HOME_LINE2);
available_field_types.insert(ADDRESS_HOME_COUNTRY);
available_field_types.insert(ADDRESS_BILLING_LINE1);
available_field_types.insert(ADDRESS_BILLING_LINE2);
available_field_types.insert(EMAIL_ADDRESS);
available_field_types.insert(PHONE_HOME_WHOLE_NUMBER);
std::string encoded_xml;
EXPECT_TRUE(form_structure->EncodeFieldAssignments(
available_field_types, &encoded_xml));
EXPECT_EQ(
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
"<fieldassignments formsignature=\"8736493185895608956\">"
"<fields fieldid=\"3763331450\" fieldtype=\"3\" name=\"firstname\"/>"
"<fields fieldid=\"3494530716\" fieldtype=\"5\" name=\"lastname\"/>"
"<fields fieldid=\"1029417091\" fieldtype=\"9\" name=\"email\"/>"
"<fields fieldid=\"466116101\" fieldtype=\"14\" name=\"phone\"/>"
"<fields fieldid=\"2799270304\" fieldtype=\"36\" name=\"country\"/>"
"<fields fieldid=\"3410250678\" fieldtype=\"36\" name=\"Checkable1\"/>"
"</fieldassignments>",
encoded_xml);
// Add 2 address fields - this should be still a valid form.
for (size_t i = 0; i < 2; ++i) {
field.label = ASCIIToUTF16("Address");
field.name = ASCIIToUTF16("address");
field.form_control_type = "text";
form.fields.push_back(field);
possible_field_types.push_back(ServerFieldTypeSet());
possible_field_types.back().insert(ADDRESS_HOME_LINE1);
possible_field_types.back().insert(ADDRESS_HOME_LINE2);
possible_field_types.back().insert(ADDRESS_BILLING_LINE1);
possible_field_types.back().insert(ADDRESS_BILLING_LINE2);
}
form_structure.reset(new FormStructure(form));
ASSERT_EQ(form_structure->field_count(), possible_field_types.size());
for (size_t i = 0; i < form_structure->field_count(); ++i)
form_structure->field(i)->set_possible_types(possible_field_types[i]);
EXPECT_TRUE(form_structure->EncodeFieldAssignments(
available_field_types, &encoded_xml));
EXPECT_EQ(
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
"<fieldassignments formsignature=\"7816485729218079147\">"
"<fields fieldid=\"3763331450\" fieldtype=\"3\" name=\"firstname\"/>"
"<fields fieldid=\"3494530716\" fieldtype=\"5\" name=\"lastname\"/>"
"<fields fieldid=\"1029417091\" fieldtype=\"9\" name=\"email\"/>"
"<fields fieldid=\"466116101\" fieldtype=\"14\" name=\"phone\"/>"
"<fields fieldid=\"2799270304\" fieldtype=\"36\" name=\"country\"/>"
"<fields fieldid=\"3410250678\" fieldtype=\"36\" name=\"Checkable1\"/>"
"<fields fieldid=\"509334676\" fieldtype=\"30\" name=\"address\"/>"
"<fields fieldid=\"509334676\" fieldtype=\"31\" name=\"address\"/>"
"<fields fieldid=\"509334676\" fieldtype=\"37\" name=\"address\"/>"
"<fields fieldid=\"509334676\" fieldtype=\"38\" name=\"address\"/>"
"<fields fieldid=\"509334676\" fieldtype=\"30\" name=\"address\"/>"
"<fields fieldid=\"509334676\" fieldtype=\"31\" name=\"address\"/>"
"<fields fieldid=\"509334676\" fieldtype=\"37\" name=\"address\"/>"
"<fields fieldid=\"509334676\" fieldtype=\"38\" name=\"address\"/>"
"</fieldassignments>",
encoded_xml);
}
// Check that we compute the "datapresent" string correctly for the given
// |available_types|.
TEST(FormStructureTest, CheckDataPresence) {
FormData form;
form.method = ASCIIToUTF16("post");
FormFieldData field;
field.form_control_type = "text";
field.label = ASCIIToUTF16("First Name");
field.name = ASCIIToUTF16("first");
form.fields.push_back(field);
field.label = ASCIIToUTF16("Last Name");
field.name = ASCIIToUTF16("last");
form.fields.push_back(field);
field.label = ASCIIToUTF16("Email");
field.name = ASCIIToUTF16("email");
form.fields.push_back(field);
FormStructure form_structure(form);
ServerFieldTypeSet unknown_type;
unknown_type.insert(UNKNOWN_TYPE);
for (size_t i = 0; i < form_structure.field_count(); ++i)
form_structure.field(i)->set_possible_types(unknown_type);
// No available types.
// datapresent should be "" == trimmmed(0x0000000000000000) ==
// 0b0000000000000000000000000000000000000000000000000000000000000000
ServerFieldTypeSet available_field_types;
std::string encoded_xml;
EXPECT_TRUE(form_structure.EncodeUploadRequest(available_field_types, false,
&encoded_xml));
EXPECT_EQ("<\?xml version=\"1.0\" encoding=\"UTF-8\"\?>"
"<autofillupload clientversion=\"6.1.1715.1442/en (GGLL)\""
" formsignature=\"6402244543831589061\" autofillused=\"false\""
" datapresent=\"\">"
"<field signature=\"1089846351\" autofilltype=\"1\"/>"
"<field signature=\"2404144663\" autofilltype=\"1\"/>"
"<field signature=\"420638584\" autofilltype=\"1\"/>"
"</autofillupload>",
encoded_xml);
// Only a few types available.
// datapresent should be "1540000240" == trimmmed(0x1540000240000000) ==
// 0b0001010101000000000000000000001001000000000000000000000000000000
// The set bits are:
// 3 == NAME_FIRST
// 5 == NAME_LAST
// 7 == NAME_FULL
// 9 == EMAIL_ADDRESS
// 30 == ADDRESS_HOME_LINE1
// 33 == ADDRESS_HOME_CITY
available_field_types.clear();
available_field_types.insert(NAME_FIRST);
available_field_types.insert(NAME_LAST);
available_field_types.insert(NAME_FULL);
available_field_types.insert(EMAIL_ADDRESS);
available_field_types.insert(ADDRESS_HOME_LINE1);
available_field_types.insert(ADDRESS_HOME_CITY);
EXPECT_TRUE(form_structure.EncodeUploadRequest(available_field_types, false,
&encoded_xml));
EXPECT_EQ("<\?xml version=\"1.0\" encoding=\"UTF-8\"\?>"
"<autofillupload clientversion=\"6.1.1715.1442/en (GGLL)\""
" formsignature=\"6402244543831589061\" autofillused=\"false\""
" datapresent=\"1540000240\">"
"<field signature=\"1089846351\" autofilltype=\"1\"/>"
"<field signature=\"2404144663\" autofilltype=\"1\"/>"
"<field signature=\"420638584\" autofilltype=\"1\"/>"
"</autofillupload>",
encoded_xml);
// All supported non-credit card types available.
// datapresent should be "1f7e000378000008" == trimmmed(0x1f7e000378000008) ==
// 0b0001111101111110000000000000001101111000000000000000000000001000
// The set bits are:
// 3 == NAME_FIRST
// 4 == NAME_MIDDLE
// 5 == NAME_LAST
// 6 == NAME_MIDDLE_INITIAL
// 7 == NAME_FULL
// 9 == EMAIL_ADDRESS
// 10 == PHONE_HOME_NUMBER,
// 11 == PHONE_HOME_CITY_CODE,
// 12 == PHONE_HOME_COUNTRY_CODE,
// 13 == PHONE_HOME_CITY_AND_NUMBER,
// 14 == PHONE_HOME_WHOLE_NUMBER,
// 30 == ADDRESS_HOME_LINE1
// 31 == ADDRESS_HOME_LINE2
// 33 == ADDRESS_HOME_CITY
// 34 == ADDRESS_HOME_STATE
// 35 == ADDRESS_HOME_ZIP
// 36 == ADDRESS_HOME_COUNTRY
// 60 == COMPANY_NAME
available_field_types.clear();
available_field_types.insert(NAME_FIRST);
available_field_types.insert(NAME_MIDDLE);
available_field_types.insert(NAME_LAST);
available_field_types.insert(NAME_MIDDLE_INITIAL);
available_field_types.insert(NAME_FULL);
available_field_types.insert(EMAIL_ADDRESS);
available_field_types.insert(PHONE_HOME_NUMBER);
available_field_types.insert(PHONE_HOME_CITY_CODE);
available_field_types.insert(PHONE_HOME_COUNTRY_CODE);
available_field_types.insert(PHONE_HOME_CITY_AND_NUMBER);
available_field_types.insert(PHONE_HOME_WHOLE_NUMBER);
available_field_types.insert(ADDRESS_HOME_LINE1);
available_field_types.insert(ADDRESS_HOME_LINE2);
available_field_types.insert(ADDRESS_HOME_CITY);
available_field_types.insert(ADDRESS_HOME_STATE);
available_field_types.insert(ADDRESS_HOME_ZIP);
available_field_types.insert(ADDRESS_HOME_COUNTRY);
available_field_types.insert(COMPANY_NAME);
EXPECT_TRUE(form_structure.EncodeUploadRequest(available_field_types, false,
&encoded_xml));
EXPECT_EQ("<\?xml version=\"1.0\" encoding=\"UTF-8\"\?>"
"<autofillupload clientversion=\"6.1.1715.1442/en (GGLL)\""
" formsignature=\"6402244543831589061\" autofillused=\"false\""
" datapresent=\"1f7e000378000008\">"
"<field signature=\"1089846351\" autofilltype=\"1\"/>"
"<field signature=\"2404144663\" autofilltype=\"1\"/>"
"<field signature=\"420638584\" autofilltype=\"1\"/>"
"</autofillupload>",
encoded_xml);
// All supported credit card types available.
// datapresent should be "0000000000001fc0" == trimmmed(0x0000000000001fc0) ==
// 0b0000000000000000000000000000000000000000000000000001111111000000
// The set bits are:
// 51 == CREDIT_CARD_NAME
// 52 == CREDIT_CARD_NUMBER
// 53 == CREDIT_CARD_EXP_MONTH
// 54 == CREDIT_CARD_EXP_2_DIGIT_YEAR
// 55 == CREDIT_CARD_EXP_4_DIGIT_YEAR
// 56 == CREDIT_CARD_EXP_DATE_2_DIGIT_YEAR
// 57 == CREDIT_CARD_EXP_DATE_4_DIGIT_YEAR
available_field_types.clear();
available_field_types.insert(CREDIT_CARD_NAME);
available_field_types.insert(CREDIT_CARD_NUMBER);
available_field_types.insert(CREDIT_CARD_EXP_MONTH);
available_field_types.insert(CREDIT_CARD_EXP_2_DIGIT_YEAR);
available_field_types.insert(CREDIT_CARD_EXP_4_DIGIT_YEAR);
available_field_types.insert(CREDIT_CARD_EXP_DATE_2_DIGIT_YEAR);
available_field_types.insert(CREDIT_CARD_EXP_DATE_4_DIGIT_YEAR);
EXPECT_TRUE(form_structure.EncodeUploadRequest(available_field_types, false,
&encoded_xml));
EXPECT_EQ("<\?xml version=\"1.0\" encoding=\"UTF-8\"\?>"
"<autofillupload clientversion=\"6.1.1715.1442/en (GGLL)\""
" formsignature=\"6402244543831589061\" autofillused=\"false\""
" datapresent=\"0000000000001fc0\">"
"<field signature=\"1089846351\" autofilltype=\"1\"/>"
"<field signature=\"2404144663\" autofilltype=\"1\"/>"
"<field signature=\"420638584\" autofilltype=\"1\"/>"
"</autofillupload>",
encoded_xml);
// All supported types available.
// datapresent should be "1f7e000378001fc8" == trimmmed(0x1f7e000378001fc8) ==
// 0b0001111101111110000000000000001101111000000000000001111111001000
// The set bits are:
// 3 == NAME_FIRST
// 4 == NAME_MIDDLE
// 5 == NAME_LAST
// 6 == NAME_MIDDLE_INITIAL
// 7 == NAME_FULL
// 9 == EMAIL_ADDRESS
// 10 == PHONE_HOME_NUMBER,
// 11 == PHONE_HOME_CITY_CODE,
// 12 == PHONE_HOME_COUNTRY_CODE,
// 13 == PHONE_HOME_CITY_AND_NUMBER,
// 14 == PHONE_HOME_WHOLE_NUMBER,
// 30 == ADDRESS_HOME_LINE1
// 31 == ADDRESS_HOME_LINE2
// 33 == ADDRESS_HOME_CITY
// 34 == ADDRESS_HOME_STATE
// 35 == ADDRESS_HOME_ZIP
// 36 == ADDRESS_HOME_COUNTRY
// 51 == CREDIT_CARD_NAME
// 52 == CREDIT_CARD_NUMBER
// 53 == CREDIT_CARD_EXP_MONTH
// 54 == CREDIT_CARD_EXP_2_DIGIT_YEAR
// 55 == CREDIT_CARD_EXP_4_DIGIT_YEAR
// 56 == CREDIT_CARD_EXP_DATE_2_DIGIT_YEAR
// 57 == CREDIT_CARD_EXP_DATE_4_DIGIT_YEAR
// 60 == COMPANY_NAME
available_field_types.clear();
available_field_types.insert(NAME_FIRST);
available_field_types.insert(NAME_MIDDLE);
available_field_types.insert(NAME_LAST);
available_field_types.insert(NAME_MIDDLE_INITIAL);
available_field_types.insert(NAME_FULL);
available_field_types.insert(EMAIL_ADDRESS);
available_field_types.insert(PHONE_HOME_NUMBER);
available_field_types.insert(PHONE_HOME_CITY_CODE);
available_field_types.insert(PHONE_HOME_COUNTRY_CODE);
available_field_types.insert(PHONE_HOME_CITY_AND_NUMBER);
available_field_types.insert(PHONE_HOME_WHOLE_NUMBER);
available_field_types.insert(ADDRESS_HOME_LINE1);
available_field_types.insert(ADDRESS_HOME_LINE2);
available_field_types.insert(ADDRESS_HOME_CITY);
available_field_types.insert(ADDRESS_HOME_STATE);
available_field_types.insert(ADDRESS_HOME_ZIP);
available_field_types.insert(ADDRESS_HOME_COUNTRY);
available_field_types.insert(CREDIT_CARD_NAME);
available_field_types.insert(CREDIT_CARD_NUMBER);
available_field_types.insert(CREDIT_CARD_EXP_MONTH);
available_field_types.insert(CREDIT_CARD_EXP_2_DIGIT_YEAR);
available_field_types.insert(CREDIT_CARD_EXP_4_DIGIT_YEAR);
available_field_types.insert(CREDIT_CARD_EXP_DATE_2_DIGIT_YEAR);
available_field_types.insert(CREDIT_CARD_EXP_DATE_4_DIGIT_YEAR);
available_field_types.insert(COMPANY_NAME);
EXPECT_TRUE(form_structure.EncodeUploadRequest(available_field_types, false,
&encoded_xml));
EXPECT_EQ("<\?xml version=\"1.0\" encoding=\"UTF-8\"\?>"
"<autofillupload clientversion=\"6.1.1715.1442/en (GGLL)\""
" formsignature=\"6402244543831589061\" autofillused=\"false\""
" datapresent=\"1f7e000378001fc8\">"
"<field signature=\"1089846351\" autofilltype=\"1\"/>"
"<field signature=\"2404144663\" autofilltype=\"1\"/>"
"<field signature=\"420638584\" autofilltype=\"1\"/>"
"</autofillupload>",
encoded_xml);
}
TEST(FormStructureTest, CheckMultipleTypes) {
// Throughout this test, datapresent should be
// 0x1440000360000008 ==
// 0b0001010001000000000000000000001101100000000000000000000000001000
// The set bits are:
// 3 == NAME_FIRST
// 5 == NAME_LAST
// 9 == EMAIL_ADDRESS
// 30 == ADDRESS_HOME_LINE1
// 31 == ADDRESS_HOME_LINE2
// 33 == ADDRESS_HOME_CITY
// 34 == ADDRESS_HOME_STATE
// 60 == COMPANY_NAME
ServerFieldTypeSet available_field_types;
available_field_types.insert(NAME_FIRST);
available_field_types.insert(NAME_LAST);
available_field_types.insert(EMAIL_ADDRESS);
available_field_types.insert(ADDRESS_HOME_LINE1);
available_field_types.insert(ADDRESS_HOME_LINE2);
available_field_types.insert(ADDRESS_HOME_CITY);
available_field_types.insert(ADDRESS_HOME_STATE);
available_field_types.insert(COMPANY_NAME);
// Check that multiple types for the field are processed correctly.
scoped_ptr<FormStructure> form_structure;
std::vector<ServerFieldTypeSet> possible_field_types;
FormData form;
form.method = ASCIIToUTF16("post");
FormFieldData field;
field.form_control_type = "text";
field.label = ASCIIToUTF16("email");
field.name = ASCIIToUTF16("email");
form.fields.push_back(field);
possible_field_types.push_back(ServerFieldTypeSet());
possible_field_types.back().insert(EMAIL_ADDRESS);
field.label = ASCIIToUTF16("First Name");
field.name = ASCIIToUTF16("first");
form.fields.push_back(field);
possible_field_types.push_back(ServerFieldTypeSet());
possible_field_types.back().insert(NAME_FIRST);
field.label = ASCIIToUTF16("Last Name");
field.name = ASCIIToUTF16("last");
form.fields.push_back(field);
possible_field_types.push_back(ServerFieldTypeSet());
possible_field_types.back().insert(NAME_LAST);
field.label = ASCIIToUTF16("Address");
field.name = ASCIIToUTF16("address");
form.fields.push_back(field);
possible_field_types.push_back(ServerFieldTypeSet());
possible_field_types.back().insert(ADDRESS_HOME_LINE1);
form_structure.reset(new FormStructure(form));
for (size_t i = 0; i < form_structure->field_count(); ++i)
form_structure->field(i)->set_possible_types(possible_field_types[i]);
std::string encoded_xml;
// Now we matched both fields singularly.
EXPECT_TRUE(form_structure->EncodeUploadRequest(available_field_types, false,
&encoded_xml));
EXPECT_EQ("<\?xml version=\"1.0\" encoding=\"UTF-8\"\?>"
"<autofillupload clientversion=\"6.1.1715.1442/en (GGLL)\""
" formsignature=\"18062476096658145866\" autofillused=\"false\""
" datapresent=\"1440000360000008\">"
"<field signature=\"420638584\" autofilltype=\"9\"/>"
"<field signature=\"1089846351\" autofilltype=\"3\"/>"
"<field signature=\"2404144663\" autofilltype=\"5\"/>"
"<field signature=\"509334676\" autofilltype=\"30\"/>"
"</autofillupload>",
encoded_xml);
// Match third field as both first and last.
possible_field_types[2].insert(NAME_FIRST);
form_structure->field(2)->set_possible_types(possible_field_types[2]);
EXPECT_TRUE(form_structure->EncodeUploadRequest(available_field_types, false,
&encoded_xml));
EXPECT_EQ("<\?xml version=\"1.0\" encoding=\"UTF-8\"\?>"
"<autofillupload clientversion=\"6.1.1715.1442/en (GGLL)\""
" formsignature=\"18062476096658145866\" autofillused=\"false\""
" datapresent=\"1440000360000008\">"
"<field signature=\"420638584\" autofilltype=\"9\"/>"
"<field signature=\"1089846351\" autofilltype=\"3\"/>"
"<field signature=\"2404144663\" autofilltype=\"3\"/>"
"<field signature=\"2404144663\" autofilltype=\"5\"/>"
"<field signature=\"509334676\" autofilltype=\"30\"/>"
"</autofillupload>",
encoded_xml);
possible_field_types[3].insert(ADDRESS_HOME_LINE2);
form_structure->field(form_structure->field_count() - 1)->set_possible_types(
possible_field_types[form_structure->field_count() - 1]);
EXPECT_TRUE(form_structure->EncodeUploadRequest(available_field_types, false,
&encoded_xml));
EXPECT_EQ("<\?xml version=\"1.0\" encoding=\"UTF-8\"\?>"
"<autofillupload clientversion=\"6.1.1715.1442/en (GGLL)\""
" formsignature=\"18062476096658145866\" autofillused=\"false\""
" datapresent=\"1440000360000008\">"
"<field signature=\"420638584\" autofilltype=\"9\"/>"
"<field signature=\"1089846351\" autofilltype=\"3\"/>"
"<field signature=\"2404144663\" autofilltype=\"3\"/>"
"<field signature=\"2404144663\" autofilltype=\"5\"/>"
"<field signature=\"509334676\" autofilltype=\"30\"/>"
"<field signature=\"509334676\" autofilltype=\"31\"/>"
"</autofillupload>",
encoded_xml);
possible_field_types[3].clear();
possible_field_types[3].insert(ADDRESS_HOME_LINE1);
possible_field_types[3].insert(COMPANY_NAME);
form_structure->field(form_structure->field_count() - 1)->set_possible_types(
possible_field_types[form_structure->field_count() - 1]);
EXPECT_TRUE(form_structure->EncodeUploadRequest(available_field_types, false,
&encoded_xml));
EXPECT_EQ("<\?xml version=\"1.0\" encoding=\"UTF-8\"\?>"
"<autofillupload clientversion=\"6.1.1715.1442/en (GGLL)\""
" formsignature=\"18062476096658145866\" autofillused=\"false\""
" datapresent=\"1440000360000008\">"
"<field signature=\"420638584\" autofilltype=\"9\"/>"
"<field signature=\"1089846351\" autofilltype=\"3\"/>"
"<field signature=\"2404144663\" autofilltype=\"3\"/>"
"<field signature=\"2404144663\" autofilltype=\"5\"/>"
"<field signature=\"509334676\" autofilltype=\"30\"/>"
"<field signature=\"509334676\" autofilltype=\"60\"/>"
"</autofillupload>",
encoded_xml);
}
TEST(FormStructureTest, CheckFormSignature) {
// Check that form signature is created correctly.
scoped_ptr<FormStructure> form_structure;
FormData form;
form.method = ASCIIToUTF16("post");
FormFieldData field;
field.form_control_type = "text";
field.label = ASCIIToUTF16("email");
field.name = ASCIIToUTF16("email");
form.fields.push_back(field);
field.label = ASCIIToUTF16("First Name");
field.name = ASCIIToUTF16("first");
form.fields.push_back(field);
// Checkable fields shouldn't affect the signature.
field.label = ASCIIToUTF16("Select");
field.name = ASCIIToUTF16("Select");
field.form_control_type = "checkbox";
field.is_checkable = true;
form.fields.push_back(field);
form_structure.reset(new FormStructure(form));
EXPECT_EQ(FormStructureTest::Hash64Bit(
std::string("://&&email&first")),
form_structure->FormSignature());
form.origin = GURL(std::string("http://www.facebook.com"));
form_structure.reset(new FormStructure(form));
EXPECT_EQ(FormStructureTest::Hash64Bit(
std::string("http://www.facebook.com&&email&first")),
form_structure->FormSignature());
form.action = GURL(std::string("https://login.facebook.com/path"));
form_structure.reset(new FormStructure(form));
EXPECT_EQ(FormStructureTest::Hash64Bit(
std::string("https://login.facebook.com&&email&first")),
form_structure->FormSignature());
form.name = ASCIIToUTF16("login_form");
form_structure.reset(new FormStructure(form));
EXPECT_EQ(FormStructureTest::Hash64Bit(
std::string("https://login.facebook.com&login_form&email&first")),
form_structure->FormSignature());
field.is_checkable = false;
field.label = ASCIIToUTF16("Random Field label");
field.name = ASCIIToUTF16("random1234");
field.form_control_type = "text";
form.fields.push_back(field);
field.label = ASCIIToUTF16("Random Field label2");
field.name = ASCIIToUTF16("random12345");
form.fields.push_back(field);
field.label = ASCIIToUTF16("Random Field label3");
field.name = ASCIIToUTF16("1random12345678");
form.fields.push_back(field);
field.label = ASCIIToUTF16("Random Field label3");
field.name = ASCIIToUTF16("12345random");
form.fields.push_back(field);
form_structure.reset(new FormStructure(form));
EXPECT_EQ(FormStructureTest::Hash64Bit(
std::string("https://login.facebook.com&login_form&email&first&"
"random1234&random&1random&random")),
form_structure->FormSignature());
}
TEST(FormStructureTest, ToFormData) {
FormData form;
form.name = ASCIIToUTF16("the-name");
form.method = ASCIIToUTF16("POST");
form.origin = GURL("http://cool.com");
form.action = form.origin.Resolve("/login");
FormFieldData field;
field.label = ASCIIToUTF16("username");
field.name = ASCIIToUTF16("username");
field.form_control_type = "text";
form.fields.push_back(field);
field.label = ASCIIToUTF16("password");
field.name = ASCIIToUTF16("password");
field.form_control_type = "password";
form.fields.push_back(field);
field.label = base::string16();
field.name = ASCIIToUTF16("Submit");
field.form_control_type = "submit";
form.fields.push_back(field);
EXPECT_EQ(form, FormStructure(form).ToFormData());
// Currently |FormStructure(form_data)ToFormData().user_submitted| is always
// false. This forces a future author that changes this to update this test.
form.user_submitted = true;
EXPECT_NE(form, FormStructure(form).ToFormData());
}
TEST(FormStructureTest, SkipFieldTest) {
FormData form;
form.name = ASCIIToUTF16("the-name");
form.method = ASCIIToUTF16("POST");
form.origin = GURL("http://cool.com");
form.action = form.origin.Resolve("/login");
FormFieldData field;
field.label = ASCIIToUTF16("username");
field.name = ASCIIToUTF16("username");
field.form_control_type = "text";
form.fields.push_back(field);
field.label = ASCIIToUTF16("select");
field.name = ASCIIToUTF16("select");
field.form_control_type = "checkbox";
field.is_checkable = true;
form.fields.push_back(field);
field.label = base::string16();
field.name = ASCIIToUTF16("email");
field.form_control_type = "text";
field.is_checkable = false;
form.fields.push_back(field);
ScopedVector<FormStructure> forms;
forms.push_back(new FormStructure(form));
std::vector<std::string> encoded_signatures;
std::string encoded_xml;
const char kSignature[] = "18006745212084723782";
const char kResponse[] =
"<\?xml version=\"1.0\" encoding=\"UTF-8\"?>"
"<autofillquery clientversion=\"6.1.1715.1442/en (GGLL)\">"
"<form signature=\"18006745212084723782\">"
"<field signature=\"239111655\"/>"
"<field signature=\"420638584\"/>"
"</form>"
"</autofillquery>";
ASSERT_TRUE(FormStructure::EncodeQueryRequest(forms.get(),
&encoded_signatures,
&encoded_xml));
ASSERT_EQ(1U, encoded_signatures.size());
EXPECT_EQ(kSignature, encoded_signatures[0]);
EXPECT_EQ(kResponse, encoded_xml);
}
TEST(FormStructureTest, PossibleValues) {
FormData form_data;
FormFieldData field;
field.autocomplete_attribute = "billing country";
field.option_contents.push_back(ASCIIToUTF16("Down Under"));
field.option_values.push_back(ASCIIToUTF16("AU"));
field.option_contents.push_back(ASCIIToUTF16("Fr"));
field.option_values.push_back(ASCIIToUTF16(""));
field.option_contents.push_back(ASCIIToUTF16("Germany"));
field.option_values.push_back(ASCIIToUTF16("GRMNY"));
form_data.fields.push_back(field);
FormStructure form_structure(form_data);
bool unused;
form_structure.ParseFieldTypesFromAutocompleteAttributes(&unused, &unused);
// All values in <option> value= or contents are returned, set to upper case.
std::set<base::string16> possible_values =
form_structure.PossibleValues(ADDRESS_BILLING_COUNTRY);
EXPECT_EQ(5U, possible_values.size());
EXPECT_EQ(1U, possible_values.count(ASCIIToUTF16("AU")));
EXPECT_EQ(1U, possible_values.count(ASCIIToUTF16("FR")));
EXPECT_EQ(1U, possible_values.count(ASCIIToUTF16("DOWN UNDER")));
EXPECT_EQ(1U, possible_values.count(ASCIIToUTF16("GERMANY")));
EXPECT_EQ(1U, possible_values.count(ASCIIToUTF16("GRMNY")));
EXPECT_EQ(0U, possible_values.count(ASCIIToUTF16("Fr")));
EXPECT_EQ(0U, possible_values.count(ASCIIToUTF16("DE")));
// No field for the given type; empty value set.
EXPECT_EQ(0U, form_structure.PossibleValues(ADDRESS_HOME_COUNTRY).size());
// A freeform input (<input>) allows any value (overriding other <select>s).
FormFieldData freeform_field;
freeform_field.autocomplete_attribute = "billing country";
form_data.fields.push_back(freeform_field);
FormStructure form_structure2(form_data);
form_structure2.ParseFieldTypesFromAutocompleteAttributes(&unused, &unused);
EXPECT_EQ(0U, form_structure2.PossibleValues(ADDRESS_BILLING_COUNTRY).size());
}
} // namespace autofill
| 38.084478 | 80 | 0.717266 | [
"render",
"vector"
] |
11f5da39ad07ddd012f1df4fc117a2c0abcbb54f | 21,379 | hpp | C++ | include/nana/filesystem/filesystem.hpp | SteffenL/nana | 6156acf068d392b9d19fca7ec685443fa9dd1dcc | [
"BSL-1.0"
] | 2,316 | 2015-01-02T02:40:34.000Z | 2022-03-30T01:13:21.000Z | include/nana/filesystem/filesystem.hpp | SteffenL/nana | 6156acf068d392b9d19fca7ec685443fa9dd1dcc | [
"BSL-1.0"
] | 563 | 2015-01-02T19:53:56.000Z | 2022-03-29T17:16:19.000Z | include/nana/filesystem/filesystem.hpp | SteffenL/nana | 6156acf068d392b9d19fca7ec685443fa9dd1dcc | [
"BSL-1.0"
] | 519 | 2015-01-09T21:26:19.000Z | 2022-03-30T17:00:19.000Z | /**
* A ISO C++ filesystem Implementation
* Nana C++ Library(http://www.nanapro.org)
* Copyright(C) 2003-2019 Jinhao(cnjinhao@hotmail.com)
*
* 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 nana/filesystem/filesystem.hpp
* @author Ariel Vina-Rodriguez, Jinhao
* @brief Mimic std::filesystem
* and need VC2015 or a C++11 compiler. With a few correction can be compiler by VC2013
*/
// http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2014/n4100.pdf --- pdf of std draft N4100 <filesystem> 2014-07-04
// http://en.cppreference.com/w/cpp/experimental/fs
// http://cpprocks.com/introduction-to-tr2-filesystem-library-in-vs2012/ --- TR2 filesystem in VS2012
// https://msdn.microsoft.com/en-us/library/hh874694%28v=vs.140%29.aspx --- C++ 14, the <filesystem> header VS2015
// https://msdn.microsoft.com/en-us/library/hh874694%28v=vs.120%29.aspx --- <filesystem> header VS2013
// http://cplusplus.github.io/filesystem-ts/working-draft.html --- in html format
// http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2014/n4099.html --- in html format
// http://article.gmane.org/gmane.comp.lib.boost.devel/256220 --- The filesystem TS unanimously approved by ISO.
// http://theboostcpplibraries.com/boost.filesystem --- Boost docs
// http://www.boost.org/doc/libs/1_58_0/libs/filesystem/doc/index.htm ---
// http://www.boost.org/doc/libs/1_34_0/libs/filesystem/doc/index.htm
// http://www.boost.org/doc/libs/1_58_0/boost/filesystem.hpp
// https://gcc.gnu.org/onlinedocs/libstdc++/manual/status.html#status.iso.200x --- Table 1.4. g++ C++ Technical Specifications Implementation Status
#ifndef NANA_FILESYSTEM_HPP
#define NANA_FILESYSTEM_HPP
#include <nana/push_ignore_diagnostic>
//Filesystem Selection
#include <nana/config.hpp>
#define NANA_USING_NANA_FILESYSTEM 0
#define NANA_USING_STD_FILESYSTEM 0
#define NANA_USING_BOOST_FILESYSTEM 0
//#define NANA_FILESYSTEM_FORCE 1
#if (defined(NANA_FILESYSTEM_FORCE) || ( (defined(STD_FILESYSTEM_NOT_SUPPORTED) && !defined(BOOST_FILESYSTEM_AVAILABLE)) && !(defined(BOOST_FILESYSTEM_FORCE) || defined(STD_FILESYSTEM_FORCE)) ) )
#undef NANA_USING_NANA_FILESYSTEM
#define NANA_USING_NANA_FILESYSTEM 1
#elif (defined(BOOST_FILESYSTEM_AVAILABLE) && ( defined(BOOST_FILESYSTEM_FORCE) || ( defined(STD_FILESYSTEM_NOT_SUPPORTED) && !defined(STD_FILESYSTEM_FORCE) ) ))
#undef NANA_USING_BOOST_FILESYSTEM
#define NANA_USING_BOOST_FILESYSTEM 1
# include <chrono>
# include <boost/filesystem.hpp>
// inline boost::filesystem into std::filesystem
namespace std {
namespace filesystem {
inline namespace boost_filesystem {
using namespace boost::filesystem;
using file_time_type = std::chrono::time_point<std::chrono::system_clock>;
enum class file_type {
none = boost::filesystem::file_type::status_unknown,
not_found = boost::filesystem::file_type::file_not_found,
regular = boost::filesystem::file_type::regular_file,
directory = boost::filesystem::file_type::directory_file,
symlink = boost::filesystem::file_type::symlink_file,
block = boost::filesystem::file_type::block_file,
character = boost::filesystem::file_type::character_file,
fifo = boost::filesystem::file_type::fifo_file,
socket = boost::filesystem::file_type::socket_file,
unknown = boost::filesystem::file_type::type_unknown,
};
// Boost dont include generic_u8string
// http://www.boost.org/doc/libs/1_66_0/boost/filesystem/path.hpp
//
// Boost versions: 1.67.0, 1.66.0, ... 1.56.0 enable directory_iterator C++11 range-base for
// http://www.boost.org/doc/libs/1_66_0/boost/filesystem/operations.hpp
// but travis come with an oooold version of boost
// 1.55.0 NOT enable directory_iterator C++11 range-base for
// http://www.boost.org/doc/libs/1_54_0/boost/filesystem/operations.hpp
#if BOOST_VERSION < 105600
namespace boost { // todo ??
// enable directory_iterator C++11 range-base for statement use --------------------//
// begin() and end() are only used by a range-based for statement in the context of
// auto - thus the top-level const is stripped - so returning const is harmless and
// emphasizes begin() is just a pass through.
inline const directory_iterator& begin(const directory_iterator& iter) BOOST_NOEXCEPT
{
return iter;
}
inline directory_iterator end(const directory_iterator&) BOOST_NOEXCEPT
{
return directory_iterator();
}
}
#endif
} // boost_filesystem
} // filesystem
} // std
#else
# undef NANA_USING_STD_FILESYSTEM
# define NANA_USING_STD_FILESYSTEM 1
//Detects whether the compiler supports std::filesystem under current options
# if ((defined(_MSC_VER) && (_MSC_VER >= 1912) && defined(_MSVC_LANG) && _MSVC_LANG >= 201703)) || \
((__cplusplus >= 201703L) && \
(defined(__clang__) && (__clang_major__ >= 7) || \
(!defined(__clang__) && defined(__GNUC__) && (__GNUC__ >= 8))) )
# include <filesystem>
# else
# include <experimental/filesystem>
namespace std{
namespace filesystem{
using namespace std::experimental::filesystem;
}
}
# undef NANA_USING_STD_EXPERIMENTAL_FILESYSTEM
# define NANA_USING_STD_EXPERIMENTAL_FILESYSTEM
# endif
#endif // BOOST_FILESYSTEM and NANA_FILESYSTEM
#if NANA_USING_NANA_FILESYSTEM
#include <string>
#include <system_error>
#include <iterator>
#include <memory>
#include <chrono>
#include <cstddef>
#include <cstdint>
#include <algorithm>
#include <nana/deploy.hpp>
namespace nana {
namespace filesystem {
enum class file_type
{
none = 0, ///< has not been determined or an error occurred while trying to determine
not_found = -1, ///< Pseudo-type: file was not found. Is not considered an error
regular = 1,
directory = 2,
symlink = 3, ///< Symbolic link file
block = 4, ///< Block special file
character = 5, ///< Character special file
fifo = 6, ///< FIFO or pipe file
socket = 7,
unknown = 8 ///< The file does exist, but is of an operating system dependent type not covered by any of the other
};
enum class perms
{
none = 0, ///< There are no permissions set for the file.
all = 0x1FF, ///< owner_all | group_all | others_all
mask = 0xFFF, ///< all | set_uid | set_gid | sticky_bit.
unknown = 0xFFFF ///< not known, such as when a file_status object is created without specifying the permissions
};
//enum class copy_options;
enum class directory_options
{
none,
follow_directory_symlink,
skip_permission_denied
};
struct space_info
{
uintmax_t capacity;
uintmax_t free;
uintmax_t available;
};
using file_time_type = std::chrono::time_point<std::chrono::system_clock>; ///< trivial-clock> ;
class file_status
{
file_type m_ft = file_type::none;
perms m_prms = perms::unknown;
public:
explicit file_status(file_type ft = file_type::none, perms prms = perms::unknown);
// observers
file_type type() const;
perms permissions() const;
// modifiers
void type(file_type ft);
void permissions(perms prms);
private:
file_type value_;
perms perms_;
};
/// concerned only with lexical and syntactic aspects and does not necessarily exist in
/// external storage, and the pathname is not necessarily valid for the current operating system
/// or for a particular file system
/// A sequence of elements that identify the location of a file within a filesystem.
/// The elements are the:
/// rootname (opt), root-directory (opt), and an optional sequence of filenames.
/// The maximum number of elements in the sequence is operating system dependent.
class path
{
public:
#if defined(NANA_WINDOWS)
using value_type = wchar_t;
const static value_type preferred_separator = L'\\';
#else
using value_type = char;
const static value_type preferred_separator = '/';
#endif
using string_type = std::basic_string<value_type>;
path() = default;
template<typename Source>
path(const Source &source)
{
_m_assign(source);
}
// modifiers
void clear() noexcept;
path &make_preferred();
path &remove_filename();
//path& replace_filename(const path& replacement);
//path& replace_extension(const path& replacement = path());
//void swap(path& rhs) noexcept;
// decomposition
path root_name() const;
path root_directory() const;
path root_path() const;
path relative_path() const;
path parent_path() const;
path filename() const;
path stem() const;
path extension() const;
// query
bool empty() const noexcept;
bool has_root_name() const
{ return !root_name().empty(); }
bool has_root_directory() const
{ return !root_directory().empty(); }
bool has_root_path() const
{ return !root_path().empty(); }
bool has_relative_path() const
{ return !relative_path().empty(); }
bool has_parent_path() const
{ return !parent_path().empty(); }; // temp;;
bool has_filename() const
{ return !filename().empty(); }; // temp;
//bool has_stem() const;
bool has_extension() const
{ return !extension().empty(); }; // temp
bool is_absolute() const;
bool is_relative() const;
int compare(const path &other) const;
file_type what() const;
const value_type *c_str() const;
const string_type &native() const;
operator string_type() const;
std::string string() const;
std::wstring wstring() const;
// std::string u8string() const;
// std::u16string u16string() const;
// std::u32string u32string() const;
std::string generic_string() const;
std::wstring generic_wstring() const;
// std::string generic_u8string() const;
// std::u16string generic_u16string() const;
// std::u32string generic_u32string() const;
path lexically_normal() const;
//appends
path &operator/=(const path &other);
template<typename Source>
path &operator/=(const Source &source)
{
path other(source);
return this->operator/=(other);
}
template<typename Source>
path &append(const Source &source)
{
path other(source);
return this->operator/=(other);
}
private:
void _m_assign(const std::string &source_utf8);
void _m_assign(const std::wstring &source);
private:
string_type pathstr_;
};
bool operator==(const path &lhs, const path &rhs);
bool operator!=(const path &lhs, const path &rhs);
bool operator<(const path &lhs, const path &rhs);
bool operator>(const path &lhs, const path &rhs);
path operator/(const path &lhs, const path &rhs);
class filesystem_error
: public std::system_error
{
public:
explicit filesystem_error(const std::string &msg, std::error_code);
filesystem_error(const std::string &msg, const path &path1, std::error_code err);
filesystem_error(const std::string &msg, const path &path1, const path &path2, std::error_code err);
const path &path1() const noexcept;
const path &path2() const noexcept;
// const char* what() const noexcept;
private:
path path1_;
path path2_;
};
class directory_entry
{
public:
directory_entry() = default;
explicit directory_entry(const filesystem::path &);
//modifiers
void assign(const filesystem::path &);
void replace_filename(const filesystem::path &);
//observers
file_status status() const;
operator const filesystem::path &() const
{ return path_; };
const filesystem::path &path() const;
private:
filesystem::path path_;
};
/// InputIterator that iterate over the sequence of directory_entry elements representing the files in a directory, not an recursive_directory_iterator
class directory_iterator : public std::iterator<std::input_iterator_tag, directory_entry>
{
using find_handle = void *;
public:
directory_iterator() noexcept;
explicit directory_iterator(const path &p);
directory_iterator(const path &p, directory_options opt);
const value_type &operator*() const;
const value_type *operator->() const;
directory_iterator &operator++();
directory_iterator operator++(int); ///< extention
bool equal(const directory_iterator &x) const;
private:
template<typename Char>
static bool _m_ignore(const Char *p)
{
while (*p == '.')
++p;
return (*p == 0);
}
void _m_prepare(const path &file_path);
void _m_read();
private:
bool end_{false};
path::string_type path_;
directory_options option_{directory_options::none};
std::shared_ptr<find_handle> find_ptr_;
find_handle handle_{nullptr};
value_type value_;
};
/// enable directory_iterator range-based for statements
inline directory_iterator begin(directory_iterator iter) noexcept
{
return iter;
}
inline directory_iterator end(const directory_iterator &) noexcept
{
return {};
}
//class recursive_directory_iterator;
//// enable recursive_directory_iterator range-based for statements
//recursive_directory_iterator begin(recursive_directory_iterator iter) noexcept;
//recursive_directory_iterator end(const recursive_directory_iterator&) noexcept;
//template<typename Value_Type>
inline bool operator==(const directory_iterator/*<Value_Type>*/ &x, const directory_iterator/*<Value_Type>*/ &y)
{
return x.equal(y);
}
//template<typename Value_Type>
inline bool operator!=(const directory_iterator/*<Value_Type>*/ &x, const directory_iterator/*<Value_Type>*/ &y)
{
return !x.equal(y);
}
file_status status(const path &p);
file_status status(const path &p, std::error_code &);
std::uintmax_t file_size(const path &p);
std::uintmax_t file_size(const path &p, std::error_code &ec) noexcept;
inline bool is_directory(file_status s) noexcept
{ return s.type() == file_type::directory; }
bool is_directory(const path &p);
bool is_directory(const path &p, std::error_code &ec) noexcept;
inline bool is_regular_file(file_status s) noexcept
{
return s.type() == file_type::regular;
}
inline bool is_regular_file(const path &p)
{
return is_regular_file(status(p));
}
// bool is_regular_file(const path& p, error_code& ec) noexcept; // todo:
// Returns: is_regular_file(status(p, ec)).Returns false if an error occurs. // todo:
inline bool is_empty(const path &p)
{
auto fs = status(p);
if (is_directory(fs))
return (directory_iterator() == directory_iterator(p));
return (file_size(p) == 0);
}
// bool is_empty(const path& p, error_code& ec) noexcept;
bool create_directories(const path &p);
//bool create_directories(const path& p, error_code& ec) noexcept;
bool create_directory(const path &p);
//bool create_directory(const path& p, error_code& ec) noexcept;
bool create_directory(const path &p, const path &attributes);
//bool create_directory(const path& p, const path& attributes, error_code& ec) noexcept;
/// The time of last data modification of p, determined as if by the value of the POSIX
/// stat structure member st_mtime obtained as if by POSIX stat().
file_time_type last_write_time(const path &p);
/// returns file_time_type::min() if an error occurs
//file_time_type last_write_time(const path& p, error_code& ec) noexcept;
path current_path();
//path current_path(error_code& ec);
void current_path(const path &p); ///< chdir
//void current_path(const path& p, error_code& ec) noexcept;
bool remove(const path &p);
bool remove(const path &p, std::error_code &ec); // noexcept;
//uintmax_t remove_all(const path& p);
//uintmax_t remove_all(const path& p, error_code& ec) noexcept;
template<typename CharType>
std::basic_string<CharType> parent_path(const std::basic_string<CharType> &path)
{
auto index = path.size();
if (index)
{
auto str = path.c_str();
for (--index; index > 0; --index)
{
auto c = str[index];
if (c != '\\' && c != '/')
break;
}
for (--index; index > 0; --index)
{
auto c = str[index];
if (c == '\\' || c == '/')
break;
}
}
return index ? path.substr(0, index + 1) : std::basic_string<CharType>();
}
path absolute(const path& p);
path absolute(const path& p, std::error_code& err);
path canonical(const path& p);
path canonical(const path& p, std::error_code& err);
path weakly_canonical(const path& p);
path weakly_canonical(const path& p, std::error_code& err);
bool exists( file_status s ) noexcept;
bool exists( const path& p );
bool exists( const path& p, std::error_code& ec ) noexcept;
} //end namespace filesystem
} //end namespace nana
namespace std
{
namespace filesystem
{
#if defined(_MSC_VER) && ((!defined(_MSVC_LANG)) || _MSVC_LANG < 201703)
using namespace ::nana::filesystem;
#else
inline namespace nana_filesystem
{
using namespace ::nana::filesystem;
}
#endif
}
}
#else // not #if NANA_USING_NANA_FILESYSTEM and not BOOST_FILESYSTEM, also incomplete STD_FILESYSTEM
//Implements the missing functions for various version of experimental/filesystem
namespace std
{
namespace filesystem
{
#if defined(_MSC_VER) && ((!defined(_MSVC_LANG)) || (_MSVC_LANG < 201703))
path absolute(const path& p);
path absolute(const path& p, std::error_code& err);
path canonical(const path& p);
path canonical(const path& p, std::error_code& err);
path weakly_canonical(const path& p);
path weakly_canonical(const path& p, std::error_code& err);
#endif
/*
#if defined(NANA_MINGW) // todo ??
bool exists( std::filesystem::file_status s ) noexcept;
bool exists( const std::filesystem::path& p );
bool exists( const std::filesystem::path& p, std::error_code& ec ) noexcept;
#endif
*/
//Visual Studio 2017
#if (defined(NANA_USING_STD_EXPERIMENTAL_FILESYSTEM) && defined(_MSC_VER) && (_MSC_VER > 1912)) || \
(!defined(__clang__) && defined(__GNUC__) && (__cplusplus < 201603 || (__GNUC__* 100 + __GNUC_MINOR__ < 801)))
path weakly_canonical(const path& p);
path weakly_canonical(const path& p, std::error_code& err);
#endif
} // namespace filesystem
} // namespace std
#endif // incomplete STD_FILESYSTEM
#include <nana/pop_ignore_diagnostic>
#endif //NANA_FILESYSTEM_HPP
| 34.042994 | 195 | 0.599093 | [
"object"
] |
11f8ea818df954a6cdd3f3428a3c12ced8e752e3 | 2,679 | hpp | C++ | inference-engine/src/hetero_plugin/hetero_executable_network.hpp | jhajducz/openvino | 083302dfb68d8e7f9ffdf119ca2f6df81819bd5c | [
"Apache-2.0"
] | null | null | null | inference-engine/src/hetero_plugin/hetero_executable_network.hpp | jhajducz/openvino | 083302dfb68d8e7f9ffdf119ca2f6df81819bd5c | [
"Apache-2.0"
] | 29 | 2020-11-18T10:58:28.000Z | 2022-02-21T13:03:28.000Z | inference-engine/src/hetero_plugin/hetero_executable_network.hpp | jhajducz/openvino | 083302dfb68d8e7f9ffdf119ca2f6df81819bd5c | [
"Apache-2.0"
] | null | null | null | // Copyright (C) 2018-2020 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
//
/**
* @brief a header file for ExecutableNetwork
* @file hetero_executable_network.hpp
*/
#pragma once
#include <memory>
#include <string>
#include <vector>
#include <map>
#include <unordered_map>
#include <unordered_set>
#include <ie_common.h>
#include <cpp_interfaces/impl/ie_executable_network_thread_safe_default.hpp>
#include "hetero_infer_request.hpp"
#include "ie_icore.hpp"
#include <legacy/cnn_network_impl.hpp>
#include "hetero_async_infer_request.hpp"
namespace HeteroPlugin {
class Engine;
/**
* @class ExecutableNetwork
* @brief Interface of executable network
*/
class HeteroExecutableNetwork : public InferenceEngine::ExecutableNetworkThreadSafeDefault {
public:
typedef std::shared_ptr<HeteroExecutableNetwork> Ptr;
/**
* @brief constructor
*/
HeteroExecutableNetwork(const InferenceEngine::CNNNetwork& network,
const std::map<std::string, std::string>& config,
Engine* plugin);
/**
* @brief Import from opened file constructor
*/
HeteroExecutableNetwork(std::istream& heteroModel,
const std::map<std::string, std::string>& config,
Engine* plugin);
~HeteroExecutableNetwork() override = default;
InferenceEngine::InferRequestInternal::Ptr CreateInferRequestImpl(InferenceEngine::InputsDataMap networkInputs,
InferenceEngine::OutputsDataMap networkOutputs) override;
InferenceEngine::IInferRequest::Ptr CreateInferRequest() override;
InferenceEngine::Parameter GetConfig(const std::string &name) const override;
InferenceEngine::Parameter GetMetric(const std::string &name) const override;
void ExportImpl(std::ostream& modelFile) override;
private:
void InitCNNImpl(const InferenceEngine::CNNNetwork& network);
void InitNgraph(const InferenceEngine::CNNNetwork& network);
struct NetworkDesc {
std::string _device;
InferenceEngine::CNNNetwork _clonedNetwork;
InferenceEngine::ExecutableNetwork _network;
};
std::vector<NetworkDesc> networks;
Engine* _heteroPlugin;
std::string _name;
std::map<std::string, std::string> _config;
std::unordered_map<std::string, std::string> _blobNameMap;
};
} // namespace HeteroPlugin
| 32.670732 | 127 | 0.634938 | [
"vector"
] |
11fa2289751ea9a3891fa4f0faf7a3c3bb5424c3 | 27,069 | cpp | C++ | grasp_generation/graspitmodified_lm/Coin-3.1.3/src/nodes/SoSelection.cpp | KraftOreo/EBM_Hand | 9ab1722c196b7eb99b4c3ecc85cef6e8b1887053 | [
"MIT"
] | null | null | null | grasp_generation/graspitmodified_lm/Coin-3.1.3/src/nodes/SoSelection.cpp | KraftOreo/EBM_Hand | 9ab1722c196b7eb99b4c3ecc85cef6e8b1887053 | [
"MIT"
] | null | null | null | grasp_generation/graspitmodified_lm/Coin-3.1.3/src/nodes/SoSelection.cpp | KraftOreo/EBM_Hand | 9ab1722c196b7eb99b4c3ecc85cef6e8b1887053 | [
"MIT"
] | null | null | null | /**************************************************************************\
*
* This file is part of the Coin 3D visualization library.
* Copyright (C) by Kongsberg Oil & Gas Technologies.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* ("GPL") version 2 as published by the Free Software Foundation.
* See the file LICENSE.GPL at the root directory of this source
* distribution for additional information about the GNU GPL.
*
* For using Coin with software that can not be combined with the GNU
* GPL, and for taking advantage of the additional benefits of our
* support services, please contact Kongsberg Oil & Gas Technologies
* about acquiring a Coin Professional Edition License.
*
* See http://www.coin3d.org/ for more information.
*
* Kongsberg Oil & Gas Technologies, Bygdoy Alle 5, 0257 Oslo, NORWAY.
* http://www.sim.no/ sales@sim.no coin-support@coin3d.org
*
\**************************************************************************/
/*!
\class SoSelection SoSelection.h Inventor/nodes/SoSelection.h
\brief The SoSelection class manages a list of selected nodes.
\ingroup nodes
Inserting an SoSelection node in your scene graph enables you to let
the user "pick" with the left mousebutton to select/deselect objects
below the SoSelection node.
Using an SoBoxHighlightRenderAction or an
SoLineHighlightRenderAction to render scenegraphs containing
SoSelection nodes provides a convenient way of providing visual
feedback about the selections to the application user.
Beware that one common faulty assumption which is made about the
node is that the scene will automatically be re-rendered whenever
the user pick objects. This is not the case, the application
programmer must himself schedule a redraw. A straightforward way to
accomplish this is to SoNode::touch() the SoSelection node in the
selection / deselection callback.
A "skeleton" for basic use of SoSelection nodes is given below:
\code
extern SoSeparator * make_scenegraph( void );
static SoSelection * selection = NULL;
// Callback function triggered for selection / deselection.
void made_selection( void * userdata, SoPath * path )
{
(void)fprintf( stdout, "%sselected %s\n",
userdata == (void *)1L ? "" : "de",
path->getTail()->getTypeId().getName().getString() );
selection->touch(); // to redraw
}
// *************************************************************************
// Print a quick instructions notice on stdout.
void show_instructions( void )
{
(void)fprintf( stdout, "\nThis example program demonstrates the use of the SoSelection node type.\n" );
(void)fprintf( stdout, "\nQuick instructions:\n\n" );
(void)fprintf( stdout, " * pick with left mouse button\n" );
(void)fprintf( stdout, " * hold SHIFT to select multiple objects\n" );
(void)fprintf( stdout, " * hit ESC to toggle back and forth to view mode\n" );
(void)fprintf( stdout, "\n" );
}
// *************************************************************************
int main( int argc, char ** argv )
{
QWidget * window = SoQt::init( argv[0] );
show_instructions();
selection = new SoSelection;
selection->policy = SoSelection::SHIFT;
selection->ref();
selection->addChild( make_scenegraph() );
selection->addSelectionCallback( made_selection, (void *)1L );
selection->addDeselectionCallback( made_selection, (void *)0L );
SoQtExaminerViewer * examinerviewer = new SoQtExaminerViewer( window );
examinerviewer->setSceneGraph( selection );
examinerviewer->setGLRenderAction( new SoBoxHighlightRenderAction );
examinerviewer->setViewing( FALSE );
examinerviewer->show();
SoQt::show( window );
SoQt::mainLoop();
delete examinerviewer;
selection->unref();
return 0;
}
\endcode
This node is not initialized in SoDB::init(), since it is part of
the interaction kit "add-on". Before using this node, you should
therefore call SoInteraction::init(). If you're using one of the
standard GUI-toolkits (SoXt / SoQt / SoWin) SoInteraction::init()
will be called for you from the So[Xt|Qt|Win]::init() method and you
don't have to worry about it.
With regard to using multiple SoSelection nodes at the same time in
the same scene graph: this is possible, but it is not
straightforward. The standard viewers provided by SoQt, SoWin, et
al, will only snoop on one SoSelection node (part of the the legacy
API from SGI's InventorXt), so selection changes on the others
doesn't trigger redraws. You don't necessarily see what's happening
in other words. You'll have to hook up manually and trigger redraws
yourself.
Also be aware that when having multiple SoSelection nodes in the
scene graph active at the same time, the SoHandleEventAction
traversals that you intend for selection-change on one SoSelection
node will also affect all the other SoSelection nodes in the scene
-- usually delesecting everything below them since you will be
clicking outside the selectable objects. You'll therefore also have
to manually override that behaviour, if you want selection change on
one SoSelection node to not affect the others.
<b>FILE FORMAT/DEFAULTS:</b>
\code
Selection {
renderCaching AUTO
boundingBoxCaching AUTO
renderCulling AUTO
pickCulling AUTO
policy SHIFT
}
\endcode
*/
// *************************************************************************
#include <Inventor/nodes/SoSelection.h>
#include <Inventor/actions/SoSearchAction.h>
#include <Inventor/actions/SoHandleEventAction.h>
#include <Inventor/lists/SoCallbackList.h>
#include <Inventor/SoPickedPoint.h>
#include <Inventor/events/SoMouseButtonEvent.h>
#include "tidbitsp.h"
#include "nodes/SoSubNodeP.h"
// *************************************************************************
// FIXME: this doesn't seem to end up in the Doxygen-generated
// documentation anywhere, with Doxygen version 1.2.18, at least.
// Find out why. There are also many other typedefs like this in Coin,
// which are not within the scope of a class declaration. 20040707 mortene.
/*!
\typedef SoPath * SoSelectionPickCB(void * data, const SoPickedPoint * pick)
Callback functions for the
SoSelection::setPickFilterCallbacksetPassCallback() method need to
be of this type.
See documentation of that method for more information.
*/
// FIXME: document these:
//
// typedef void SoSelectionPathCB(void * data, SoPath * path);
// typedef void SoSelectionClassCB(void * data, SoSelection * sel);
//
// 20040707 mortene.
// *************************************************************************
/*!
\enum SoSelection::Policy
Enum for different pick policies.
*/
/*!
\var SoSelection::Policy SoSelection::SINGLE
Only one object can be selected at any time. When the user picks a
new object, the previous selection will be unselected. If the user
picks on nothing, the current selection will be unselected.
Note that if a new selection matches one already present in the
selection list, neither a deselect nor a select notification
callback will be made about that selection path.
*/
/*!
\var SoSelection::Policy SoSelection::TOGGLE
Picking an object toggles its selection state.
*/
/*!
\var SoSelection::Policy SoSelection::SHIFT
Same as SINGLE, but when shift key is pressed the selection policy
will be changed to TOGGLE.
*/
/*!
\var SoSFEnum SoSelection::policy
Field for selection policy. Default value is SHIFT.
*/
/*!
\var SoPathList SoSelection::selectionList
\COININTERNAL
*/
/*!
\var SoCallbackList * SoSelection::selCBList
\COININTERNAL
*/
/*!
\var SoCallbackList * SoSelection::deselCBList
\COININTERNAL
*/
/*!
\var SoCallbackList * SoSelection::startCBList
\COININTERNAL
*/
/*!
\var SoCallbackList * SoSelection::finishCBList
\COININTERNAL
*/
/*!
\var SoSelectionPickCB * SoSelection::pickCBFunc
\COININTERNAL
*/
/*!
\var void * SoSelection::pickCBData
\COININTERNAL
*/
/*!
\var SbBool SoSelection::callPickCBOnlyIfSelectable
\COININTERNAL
*/
/*!
\var SoCallbackList * SoSelection::changeCBList
\COININTERNAL
*/
/*!
\var SoPath * SoSelection::mouseDownPickPath
\COININTERNAL
*/
/*!
\var SbBool SoSelection::pickMatching
\COININTERNAL
*/
// *************************************************************************
// Used to search for nodes. Just use one static action to avoid
// allocating a new action every time we need to search for a node.
static SoSearchAction * soselection_searchAction;
static void
soselection_cleanup(void)
{
delete soselection_searchAction;
soselection_searchAction = NULL;
}
// *************************************************************************
SO_NODE_SOURCE(SoSelection);
// *************************************************************************
/*!
Default constructor.
*/
SoSelection::SoSelection(void)
{
this->init();
}
/*!
Constructor.
The argument should be the approximate number of children which is
expected to be inserted below this node. The number need not be
exact, as it is only used as a hint for better memory resource
allocation.
*/
SoSelection::SoSelection(const int nChildren)
: inherited(nChildren)
{
this->init();
}
/*!
Destructor.
*/
SoSelection::~SoSelection()
{
delete this->selCBList;
delete this->deselCBList;
delete this->startCBList;
delete this->finishCBList;
delete this->changeCBList;
if (this->mouseDownPickPath) this->mouseDownPickPath->unref();
}
// doc in parent
void
SoSelection::initClass(void)
{
SO_NODE_INTERNAL_INIT_CLASS(SoSelection, SO_FROM_INVENTOR_1);
}
//
// common code for both constructors
//
void
SoSelection::init(void)
{
SO_NODE_INTERNAL_CONSTRUCTOR(SoSelection);
SO_NODE_ADD_FIELD(policy, (SoSelection::SHIFT));
SO_NODE_DEFINE_ENUM_VALUE(Policy, SINGLE);
SO_NODE_DEFINE_ENUM_VALUE(Policy, TOGGLE);
SO_NODE_DEFINE_ENUM_VALUE(Policy, SHIFT);
SO_NODE_SET_SF_ENUM_TYPE(policy, Policy);
this->selCBList = new SoCallbackList;
this->deselCBList = new SoCallbackList;
this->startCBList = new SoCallbackList;
this->finishCBList = new SoCallbackList;
this->changeCBList = new SoCallbackList;
this->pickCBFunc = NULL;
this->pickCBData = NULL;
this->callPickCBOnlyIfSelectable = FALSE;
this->mouseDownPickPath = NULL;
this->pickMatching = TRUE;
}
/*!
Adds \a path to the list of selected objects.
*/
void
SoSelection::select(const SoPath * path)
{
SoPath * newpath = this->copyFromThis(path);
// FIXME: memleak if path already stored in list. 20050107 mortene.
if (newpath && this->findPath(newpath) < 0) {
newpath->ref();
this->addPath(newpath);
newpath->unrefNoDelete();
}
}
/*!
Adds \a node to the list of selected objects. The scene graph
below the Selection node will be searched, and the path to
\a node will be added if found.
*/
void
SoSelection::select(SoNode * node)
{
SoPath * path = this->searchNode(node);
if (path) {
// don't ref() the path. searchNode() will ref it before returning
if (this->findPath(path) < 0) this->addPath(path);
path->unref();
}
}
/*!
Remove \a path from the list of selected objects.
*/
void
SoSelection::deselect(const SoPath * path)
{
int idx = this->findPath(path);
if (idx >= 0) this->removePath(idx);
}
/*!
Remove objects \a which from the list of selected objects.
*/
void
SoSelection::deselect(const int which)
{
this->removePath(which);
}
/*!
Remove \a node from the list of selected objects. The scene graph
below the Selection node will be searched, and the path to
\a node will be removed if found.
*/
void
SoSelection::deselect(SoNode * node)
{
SoPath * path = this->searchNode(node);
if (path) {
// don't ref() the path. searchNode() will ref it before returning
this->deselect(path);
path->unref();
}
}
/*!
If \a path is not already selected, add \a path to the list of selected
objects. Otherwise remove \a path from the list of selected objects.
*/
void
SoSelection::toggle(const SoPath * path)
{
int idx = this->findPath(path);
if (idx >= 0) this->removePath(idx);
else this->select(path); // call select instead of addPath to copy path before adding
}
/*!
If \a node is not already selected, add \a path to the list of selected
objects. Otherwise remove \a node from the list of selected objects.
*/
void
SoSelection::toggle(SoNode * node)
{
SoPath * path = this->searchNode(node);
if (path) {
// don't ref() the path. searchNode() will ref it before returning
this->toggle(path);
path->unref();
}
}
/*!
Return \e TRUE if \a path is in the list of selected objects.
*/
SbBool
SoSelection::isSelected(const SoPath * path) const
{
return this->findPath(path) >= 0;
}
/*!
Return \e TRUE if the path to \a node is in the list of selected objects.
*/
SbBool
SoSelection::isSelected(SoNode * node) const
{
SoPath * path = this->searchNode(node);
SbBool ret = FALSE;
if (path) {
// don't ref() the path. searchNode() will ref it before returning
ret = this->isSelected(path);
path->unref();
}
return ret;
}
/*!
Clears the selection list.
*/
void
SoSelection::deselectAll(void)
{
while (this->getNumSelected())
this->removePath(this->getNumSelected()-1);
}
/*!
Returns the number of selected objects.
*/
int
SoSelection::getNumSelected(void) const
{
return this->selectionList.getLength();
}
/*!
Returns the list of selected objects.
*/
const SoPathList *
SoSelection::getList(void) const
{
return &this->selectionList;
}
/*!
Returns the \a index'th selected objects.
*/
SoPath *
SoSelection::getPath(const int index) const
{
return this->selectionList[index];
}
/*!
Operator for accessing selected objects.
*/
SoPath *
SoSelection::operator[](const int i) const
{
return this->selectionList[i];
}
/*!
Adds a callback which will be called every time an
object is selected.
\sa removeSelectionCallback()
*/
void
SoSelection::addSelectionCallback(SoSelectionPathCB * f, void * userData)
{
this->selCBList->addCallback((SoCallbackListCB *)f, userData);
}
/*!
Removes one of the selection callbacks.
\sa addSelectionCallback()
*/
void
SoSelection::removeSelectionCallback(SoSelectionPathCB * f, void * userData)
{
this->selCBList->removeCallback((SoCallbackListCB *)f, userData);
}
/*!
Adds a callback which will be called every time an
object is deselected.
\sa removeDeselectionCallback()
*/
void
SoSelection::addDeselectionCallback(SoSelectionPathCB * f, void * userData)
{
this->deselCBList->addCallback((SoCallbackListCB *)f, userData);
}
/*!
Removes one of the deselection callbacks.
\sa addDeselctionCallback()
*/
void
SoSelection::removeDeselectionCallback(SoSelectionPathCB * f, void * userData)
{
this->deselCBList->removeCallback((SoCallbackListCB *)f, userData);
}
/*!
Adds a callback which will be invoked when the user start an interactive
change to the list of selected objects.
This callback is useful for storing the old selection list for undo/redo
functionality.
\sa addFinishCallback()
*/
void
SoSelection::addStartCallback(SoSelectionClassCB * f, void * userData)
{
this->startCBList->addCallback((SoCallbackListCB *)f, userData);
}
/*!
Removes \a f from the list of start callbacks.
\sa addStartCallback()
*/
void
SoSelection::removeStartCallback(SoSelectionClassCB * f, void * userData)
{
this->startCBList->removeCallback((SoCallbackListCB *)f, userData);
}
/*!
Adds a callback which will be invoked when the user has finished
an interactive change to the list of selected objects.
\sa addStartCallback()
*/
void
SoSelection::addFinishCallback(SoSelectionClassCB * f, void * userData)
{
this->finishCBList->addCallback((SoCallbackListCB *)f, userData);
}
/*!
Removes \a f from the list og finish callbacks.
\sa addFinishCallback()
*/
void
SoSelection::removeFinishCallback(SoSelectionClassCB * f, void * userData)
{
this->finishCBList->removeCallback((SoCallbackListCB *)f, userData);
}
/*!
Sets the pick filter callback. This callback will be called when a
path is about to be added to or removed from the list of selected
objects. The callback function should return a replacement path that
should be used instead of the picked path. The returned path will
be ref'ed, copied, and then unref'ed again by the SoSelection node.
If no callback is set (the default), the picked path will be used
for selecting/deselecting.
Possible return values from the callback:
<ul>
<li> NULL: simulate that nothing was picked. This will clear the
selection for the SINGLE policy. The handle event action will be
halted.</li>
<li> A path: the path will be selected/deselected. The handle event
action will be halted. </li>
<li> A path containing only the Selection node: as NULL, but action
will not be halted. </li>
<li> An empty path or a path not containing the Selection node: the
pick will be ignored. </li>
</ul>
if \a callOnlyIfSelectable is \c TRUE, the callback will only be
called if the Selection node is in the picked path.
*/
void
SoSelection::setPickFilterCallback(SoSelectionPickCB * f,
void * userData,
const SbBool callOnlyIfSelectable)
{
this->pickCBFunc = f;
this->pickCBData = userData;
this->callPickCBOnlyIfSelectable = callOnlyIfSelectable;
}
/*!
When \a pickmatchflag is \c TRUE (the default), the mouse button
release pick must match the mouse button press pick before object is
selected/deselected.
This flag should normally not be of interest to application
programmers.
*/
void
SoSelection::setPickMatching(const SbBool pickmatchflag)
{
this->pickMatching = pickmatchflag;
}
/*!
Returns \e TRUE if pick matching is enabled.
\sa setPickMatching()
*/
SbBool
SoSelection::isPickMatching(void) const
{
return this->pickMatching;
}
/*!
Returns \e TRUE if pick matching is enabled.
\sa setPickMatching()
*/
SbBool
SoSelection::getPickMatching(void) const
{
return this->pickMatching;
}
/*!
\COININTERNAL.
Used by render area to receive notification when the selection list changes.
*/
void
SoSelection::addChangeCallback(SoSelectionClassCB * f, void * userData)
{
this->changeCBList->addCallback((SoCallbackListCB *)f, userData);
}
/*!
\COININTERNAL
Used by render area to receive notification when the selection list changes.
*/
void
SoSelection::removeChangeCallback(SoSelectionClassCB * f, void * userData)
{
this->changeCBList->removeCallback((SoCallbackListCB *)f, userData);
}
/*!
\COININTERNAL
*/
void
SoSelection::invokeSelectionPolicy(SoPath * path,
SbBool shiftdown)
{
SbBool toggle = this->policy.getValue() == SoSelection::TOGGLE ||
(this->policy.getValue() == SoSelection::SHIFT && shiftdown);
if (toggle)
this->performToggleSelection(path);
else
this->performSingleSelection(path);
}
/*!
\COININTERNAL
*/
void
SoSelection::performSingleSelection(SoPath * path)
{
// Make a copy of the path from the selection node down, to use for
// comparisons versus already selected paths.
SoPath * cmppath = path ? this->copyFromThis(path) : NULL;
if (cmppath) { cmppath->ref(); }
const int nrsel = this->getNumSelected();
SbBool alreadyselected = FALSE;
// Remove all selected paths already present, *except* if one of
// them matches the new selection path -- then we'll just keep it.
for (int i = (nrsel - 1); i >= 0; i--) {
SoPath * selp = this->getPath(i);
// If selection happened on an already selected path, just keep it
// in and don't trigger a "deselect + select" pair of
// notifications.
if (cmppath && (*selp == *cmppath)) { alreadyselected = TRUE; }
else { this->removePath(i); }
}
// If path was not already selected, then add it to selection
// list. (And since this is SINGLE mode selection, it will now be
// the only selected path.)
if (path && !alreadyselected) { this->select(path); }
if (cmppath) { cmppath->unref(); }
}
/*!
\COININTERNAL
*/
void
SoSelection::performToggleSelection(SoPath * path)
{
if (path) {
int idx = this->findPath(path);
if (idx >= 0) {
this->removePath(idx);
}
else if (path->findNode(this) >= 0) {
this->select(path);
}
}
}
/*!
\COININTERNAL
*/
SoPath *
SoSelection::copyFromThis(const SoPath * path) const
{
SoPath * newpath = NULL;
path->ref();
int i = path->findNode(this);
if (i >= 0) {
newpath = path->copy(i);
}
path->unrefNoDelete();
return newpath;
}
/*!
\COININTERNAL
*/
void
SoSelection::addPath(SoPath * path)
{
this->selectionList.append(path);
this->selCBList->invokeCallbacks(path);
this->changeCBList->invokeCallbacks(this);
}
/*!
\COININTERNAL
*/
void
SoSelection::removePath(const int which)
{
SoPath * path = this->selectionList[which];
path->ref();
this->selectionList.remove(which);
this->deselCBList->invokeCallbacks(path);
this->changeCBList->invokeCallbacks(this);
path->unref();
}
/*!
\COININTERNAL
*/
int
SoSelection::findPath(const SoPath * path) const
{
int idx = -1;
// make copy only if necessary
if (path->getHead() != (SoNode *)this) {
SoPath * newpath = this->copyFromThis(path);
if (newpath) {
newpath->ref();
idx = this->selectionList.findPath(*newpath);
newpath->unref();
}
else idx = -1;
}
else idx = this->selectionList.findPath(*path);
return idx;
}
// Documented in superclass.
void
SoSelection::handleEvent(SoHandleEventAction * action)
{
// Overridden to do selection picking.
inherited::handleEvent(action);
const SoEvent * event = action->getEvent();
SbBool haltaction = FALSE;
if (SO_MOUSE_PRESS_EVENT(event, BUTTON1)) {
if (this->mouseDownPickPath) {
this->mouseDownPickPath->unref();
this->mouseDownPickPath = NULL;
}
const SoPickedPoint * pp = action->getPickedPoint();
if (pp) {
SoPath * selectionpath = pp->getPath();
// call pick filter callback also for mouse down events
if (this->pickCBFunc && (!this->callPickCBOnlyIfSelectable ||
selectionpath->findNode(this) >= 0)) {
selectionpath = this->pickCBFunc(this->pickCBData, pp);
}
if (selectionpath) {
this->mouseDownPickPath = selectionpath;
this->mouseDownPickPath->ref();
action->setHandled();
}
}
}
else if (SO_MOUSE_RELEASE_EVENT(event, BUTTON1)) {
SbBool ignorepick = FALSE;
// call pick filter callback (called from getSelectionPath()) even
// if the event was handled by a child node.
SoPath * selpath = this->getSelectionPath(action, ignorepick, haltaction);
if (action->isHandled()) {
// if the event was handled by a child node we should not invoke
// the selection policy
if (selpath) {
selpath->ref();
selpath->unref();
}
}
else {
if (haltaction) action->setHandled();
if (!ignorepick) {
if (selpath) selpath->ref();
this->startCBList->invokeCallbacks(this);
this->invokeSelectionPolicy(selpath, event->wasShiftDown());
this->finishCBList->invokeCallbacks(this);
if (selpath) selpath->unref();
}
}
if (this->mouseDownPickPath) {
this->mouseDownPickPath->unref();
this->mouseDownPickPath = NULL;
}
}
}
// Uses a static search action to find path to node from this. If the
// node is found, the returned path will be ref'ed. It's the caller's
// responsibility to unref the returned path when != NULL.
SoPath *
SoSelection::searchNode(SoNode * node) const
{
if (soselection_searchAction == NULL) {
soselection_searchAction = new SoSearchAction;
soselection_searchAction->setInterest(SoSearchAction::FIRST);
coin_atexit((coin_atexit_f*) soselection_cleanup, CC_ATEXIT_NORMAL);
}
soselection_searchAction->setNode(node);
soselection_searchAction->apply((SoNode *)this);
SoPath * path = soselection_searchAction->getPath();
if (path) path->ref();
// reset action before returning
soselection_searchAction->reset();
return path;
}
//
// Returns the pick selection path. Considers pick filter callback.
//
SoPath *
SoSelection::getSelectionPath(SoHandleEventAction * action, SbBool & ignorepick,
SbBool & haltaction)
{
//
// handled like described in the man-pages for SoSelection
//
haltaction = FALSE;
ignorepick = FALSE;
if (this->pickMatching && this->mouseDownPickPath == NULL) {
return NULL;
}
const SoPickedPoint * pp = action->getPickedPoint();
SoPath * selectionpath = NULL;
if (pp) {
selectionpath = pp->getPath();
// if there's no pickCBFunc we can just test against
// mouseDownPickPath and (possibly) return here.
if (this->pickMatching && !this->pickCBFunc) {
if (*(this->mouseDownPickPath) != *selectionpath) {
ignorepick = TRUE;
return NULL;
}
}
// if we have a pickCBFunc we have to get the pick filter path
// before comparing the mouse press and mouse release paths
if (this->pickCBFunc && (!this->callPickCBOnlyIfSelectable ||
selectionpath->findNode(this) >= 0)) {
selectionpath = this->pickCBFunc(this->pickCBData, pp);
// From the SoSelection man-pages:
// Possible return values from pickCBFunc:
// 1) NULL - behave as if nothing was picked, halt action
// 2) path through the selection node - select/deselect path
// 3) path containing only the selection node - as 1, but do not halt action
// 4) path not through the selection node - ignore event
if (selectionpath) {
if (selectionpath->getLength() == 1 &&
selectionpath->getNode(0) == this) {
selectionpath->ref();
selectionpath->unref();
selectionpath = NULL;
}
else if (selectionpath->findNode(this) >= 0) {
if (*(this->mouseDownPickPath) == *selectionpath) {
// pick matched
haltaction = TRUE;
}
else {
// mouse release didn't match mouse down
selectionpath->ref();
selectionpath->unref();
selectionpath = NULL;
ignorepick = TRUE;
}
}
else { // path with this not in the path (most probably an empty path)
selectionpath->ref();
selectionpath->unref();
selectionpath = NULL;
ignorepick = TRUE;
}
}
else { // pickCBFunc returned NULL
haltaction = TRUE;
}
}
else { // no pickCBFunc or not a valid path
haltaction = FALSE;
}
}
else if (this->mouseDownPickPath) {
ignorepick = TRUE;
}
return selectionpath;
}
| 27.150451 | 107 | 0.671876 | [
"render",
"object",
"3d"
] |
11fb50422f2f1067ebf7191ca75b875b190330e6 | 16,285 | cpp | C++ | rs_bag2image/realsense.cpp | yuki-inaho/rs_bag2image | 195c340dcc5c31b9df6287f99327a333f675a003 | [
"MIT"
] | 70 | 2018-05-02T09:34:15.000Z | 2022-03-25T23:05:40.000Z | rs_bag2image/realsense.cpp | yuki-inaho/rs_bag2image | 195c340dcc5c31b9df6287f99327a333f675a003 | [
"MIT"
] | 16 | 2018-05-29T17:13:44.000Z | 2021-06-21T14:17:24.000Z | rs_bag2image/realsense.cpp | yuki-inaho/rs_bag2image | 195c340dcc5c31b9df6287f99327a333f675a003 | [
"MIT"
] | 16 | 2018-10-12T15:05:10.000Z | 2022-01-30T14:04:59.000Z | #include "realsense.h"
#include "version.h"
#include <sstream>
#include <iomanip>
#include <limits>
// Constructor
RealSense::RealSense( int argc, char* argv[] )
{
std::cout << "rs_bag2image " << RS_BAG2IMAGE_VERSION << std::endl;
// Initialize
initialize( argc, argv );
}
// Destructor
RealSense::~RealSense()
{
// Finalize
finalize();
}
// Processing
void RealSense::run()
{
// Retrieve Last Position
uint64_t last_position = pipeline_profile.get_device().as<rs2::playback>().get_position();
// Main Loop
while( true ){
// Update Data
update();
// Draw Data
draw();
// Show Data
if( display ){
show();
}
// Save Data
save();
// Key Check
const int32_t key = cv::waitKey( 1 );
if( key == 'q' ){
break;
}
// End of Position
const uint64_t current_position = pipeline_profile.get_device().as<rs2::playback>().get_position();
if( static_cast<int64_t>( current_position - last_position ) < 0 ){
break;
}
last_position = current_position;
}
}
// Initialize
void RealSense::initialize( int argc, char * argv[] )
{
cv::setUseOptimized( true );
// Initialize Parameter
initializeParameter( argc, argv );
// Initialize Sensor
initializeSensor();
// Initialize Save
initializeSave();
}
// Initialize Parameter
inline void RealSense::initializeParameter( int argc, char * argv[] )
{
// Create Command Line Parser
const std::string keys =
"{ help h | | print this message. }"
"{ bag b | | path to input bag file. (required) }"
"{ scaling s | false | enable depth scaling for visualization. false is raw 16bit image. (bool) }"
"{ quality q | 95 | jpeg encoding quality for color and infrared. [0-100] }"
"{ display d | false | display each stream images on window. false is not display. (bool) }";
cv::CommandLineParser parser( argc, argv, keys );
if( parser.has( "help" ) ){
parser.printMessage();
std::exit( EXIT_SUCCESS );
}
// Check Parsing Error
if( !parser.check() ){
parser.printErrors();
throw std::runtime_error( "failed command arguments" );
}
// Retrieve Bag File Path (Required)
if( !parser.has( "bag" ) ){
throw std::runtime_error( "failed can't find input bag file" );
}
else{
bag_file = parser.get<cv::String>( "bag" ).c_str();
if( !filesystem::is_regular_file( bag_file ) || bag_file.extension() != ".bag" ){
throw std::runtime_error( "failed can't find input bag file" );
}
}
// Retrieve Scaling Flag (Option)
if( !parser.has( "scaling" ) ){
scaling = false;
}
else{
scaling = parser.get<bool>( "scaling" );
}
// Retrieve JPEG Quality (Option)
if( !parser.has( "quality" ) ){
params = { cv::IMWRITE_JPEG_QUALITY, 95 };
}
else{
params = { cv::IMWRITE_JPEG_QUALITY, std::min( std::max( 0, parser.get<int32_t>( "quality" ) ), 100 ) };
}
// Retrieve Display Flag (Option)
if( !parser.has( "display" ) ){
display = false;
}
else{
display = parser.get<bool>( "display" );
}
}
// Initialize Sensor
inline void RealSense::initializeSensor()
{
// Retrieve Each Streams that contain in File
rs2::config config;
rs2::context context;
const rs2::playback playback = context.load_device( bag_file.string() );
const std::vector<rs2::sensor> sensors = playback.query_sensors();
for( const rs2::sensor& sensor : sensors ){
const std::vector<rs2::stream_profile> stream_profiles = sensor.get_stream_profiles();
for( const rs2::stream_profile& stream_profile : stream_profiles ){
config.enable_stream( stream_profile.stream_type(), stream_profile.stream_index() );
}
}
// Start Pipeline
config.enable_device_from_file( playback.file_name() );
pipeline_profile = pipeline.start( config );
// Set Non Real Time Playback
pipeline_profile.get_device().as<rs2::playback>().set_real_time( false );
// Show Enable Streams
const std::vector<rs2::stream_profile> stream_profiles = pipeline_profile.get_streams();
for( const rs2::stream_profile stream_profile : stream_profiles ){
std::cout << stream_profile.stream_name() << std::endl;
}
}
// Initialize Save
inline void RealSense::initializeSave()
{
// Create Root Directory (Bag File Name)
directory = bag_file.parent_path().generic_string() + "/" + bag_file.stem().string();
if( !filesystem::create_directories( directory ) ){
throw std::runtime_error( "failed can't create root directory" );
}
// Create Sub Directory for Each Streams (Stream Name)
const std::vector<rs2::stream_profile> stream_profiles = pipeline_profile.get_streams();
for( const rs2::stream_profile stream_profile : stream_profiles ){
filesystem::path sub_directory = directory.generic_string() + "/" + stream_profile.stream_name();
filesystem::create_directories( sub_directory );
}
}
// Finalize
void RealSense::finalize()
{
// Close Windows
cv::destroyAllWindows();
// Stop Pipline
pipeline.stop();
}
// Update Data
void RealSense::update()
{
// Update Frame
updateFrame();
// Update Color
updateColor();
// Update Depth
updateDepth();
// Update Infrared
updateInfrared();
}
// Update Frame
inline void RealSense::updateFrame()
{
// Update Frame
frameset = pipeline.wait_for_frames();
}
// Update Color
inline void RealSense::updateColor()
{
// Retrieve Color Flame
color_frame = frameset.get_color_frame();
if( !color_frame ){
return;
}
// Retrive Frame Size
color_width = color_frame.as<rs2::video_frame>().get_width();
color_height = color_frame.as<rs2::video_frame>().get_height();
}
// Update Depth
inline void RealSense::updateDepth()
{
// Retrieve Depth Flame
depth_frame = frameset.get_depth_frame();
if( !depth_frame ){
return;
}
// Retrive Frame Size
depth_width = depth_frame.as<rs2::video_frame>().get_width();
depth_height = depth_frame.as<rs2::video_frame>().get_height();
}
// Update Infrared
inline void RealSense::updateInfrared()
{
// Retrieve Infrared Flames
#if 29 < RS2_API_MINOR_VERSION
frameset.foreach_rs( [this]( const rs2::frame& frame ){
#else
frameset.foreach( [this]( const rs2::frame& frame ){
#endif
if( frame.get_profile().stream_type() == rs2_stream::RS2_STREAM_INFRARED ){
const int32_t infrared_stream_index = frame.get_profile().stream_index();
const int32_t infrared_frame_index = ( infrared_stream_index != 0 ) ? infrared_stream_index - 1 : 0;
infrared_frames[infrared_frame_index] = frame;
}
} );
const rs2::frame& infrared_frame = infrared_frames.front();
if( !infrared_frame ){
return;
}
// Retrive Frame Size
infrared_width = infrared_frame.as<rs2::video_frame>().get_width();
infrared_height = infrared_frame.as<rs2::video_frame>().get_height();
}
// Draw Data
void RealSense::draw()
{
// Draw Color
drawColor();
// Draw Depth
drawDepth();
// Draw Infrared
drawInfrared();
}
// Draw Color
inline void RealSense::drawColor()
{
if( !color_frame ){
return;
}
// Create cv::Mat form Color Frame
const rs2_format color_format = color_frame.get_profile().format();
switch( color_format ){
// RGB8
case rs2_format::RS2_FORMAT_RGB8:
{
color_mat = cv::Mat( color_height, color_width, CV_8UC3, const_cast<void*>( color_frame.get_data() ) ).clone();
cv::cvtColor( color_mat, color_mat, cv::COLOR_RGB2BGR );
break;
}
// RGBA8
case rs2_format::RS2_FORMAT_RGBA8:
{
color_mat = cv::Mat( color_height, color_width, CV_8UC4, const_cast<void*>( color_frame.get_data() ) ).clone();
cv::cvtColor( color_mat, color_mat, cv::COLOR_RGBA2BGRA );
break;
}
// BGR8
case rs2_format::RS2_FORMAT_BGR8:
{
color_mat = cv::Mat( color_height, color_width, CV_8UC3, const_cast<void*>( color_frame.get_data() ) ).clone();
break;
}
// BGRA8
case rs2_format::RS2_FORMAT_BGRA8:
{
color_mat = cv::Mat( color_height, color_width, CV_8UC4, const_cast<void*>( color_frame.get_data() ) ).clone();
break;
}
// Y16 (GrayScale)
case rs2_format::RS2_FORMAT_Y16:
{
color_mat = cv::Mat( color_height, color_width, CV_16UC1, const_cast<void*>( color_frame.get_data() ) ).clone();
constexpr double scaling = static_cast<double>( std::numeric_limits<uint8_t>::max() ) / static_cast<double>( std::numeric_limits<uint16_t>::max() );
color_mat.convertTo( color_mat, CV_8U, scaling );
break;
}
// YUYV
case rs2_format::RS2_FORMAT_YUYV:
{
color_mat = cv::Mat( color_height, color_width, CV_8UC2, const_cast<void*>( color_frame.get_data() ) ).clone();
cv::cvtColor( color_mat, color_mat, cv::COLOR_YUV2BGR_YUYV );
break;
}
default:
throw std::runtime_error( "unknown color format" );
break;
}
}
// Draw Depth
inline void RealSense::drawDepth()
{
if( !depth_frame ){
return;
}
// Create cv::Mat form Depth Frame
depth_mat = cv::Mat( depth_height, depth_width, CV_16UC1, const_cast<void*>( depth_frame.get_data() ) ).clone();
}
// Draw Infrared
inline void RealSense::drawInfrared()
{
// Create cv::Mat form Infrared Frame
for( const rs2::frame& infrared_frame : infrared_frames ){
if( !infrared_frame ){
continue;
}
const uint8_t infrared_stream_index = infrared_frame.get_profile().stream_index();
const uint8_t infrared_mat_index = ( infrared_stream_index != 0 ) ? infrared_stream_index - 1 : 0;
const rs2_format infrared_format = infrared_frame.get_profile().format();
switch( infrared_format ){
// RGB8 (Color)
case rs2_format::RS2_FORMAT_RGB8:
{
infrared_mats[infrared_mat_index] = cv::Mat( infrared_height, infrared_width, CV_8UC3, const_cast<void*>( infrared_frame.get_data() ) ).clone();
cv::cvtColor( infrared_mats[infrared_mat_index], infrared_mats[infrared_mat_index], cv::COLOR_RGB2BGR );
break;
}
// RGBA8 (Color)
case rs2_format::RS2_FORMAT_RGBA8:
{
infrared_mats[infrared_mat_index] = cv::Mat( infrared_height, infrared_width, CV_8UC4, const_cast<void*>( infrared_frame.get_data() ) ).clone();
cv::cvtColor( infrared_mats[infrared_mat_index], infrared_mats[infrared_mat_index], cv::COLOR_RGBA2BGRA );
break;
}
// BGR8 (Color)
case rs2_format::RS2_FORMAT_BGR8:
{
infrared_mats[infrared_mat_index] = cv::Mat( infrared_height, infrared_width, CV_8UC3, const_cast<void*>( infrared_frame.get_data() ) ).clone();
break;
}
// BGRA8 (Color)
case rs2_format::RS2_FORMAT_BGRA8:
{
infrared_mats[infrared_mat_index] = cv::Mat( infrared_height, infrared_width, CV_8UC4, const_cast<void*>( infrared_frame.get_data() ) ).clone();
break;
}
// Y8
case rs2_format::RS2_FORMAT_Y8:
{
infrared_mats[infrared_mat_index] = cv::Mat( infrared_height, infrared_width, CV_8UC1, const_cast<void*>( infrared_frame.get_data() ) ).clone();
break;
}
// UYVY
case rs2_format::RS2_FORMAT_UYVY:
{
infrared_mats[infrared_mat_index] = cv::Mat( infrared_height, infrared_width, CV_8UC2, const_cast<void*>( infrared_frame.get_data() ) ).clone();
cv::cvtColor( infrared_mats[infrared_mat_index], infrared_mats[infrared_mat_index], cv::COLOR_YUV2GRAY_UYVY );
break;
}
default:
throw std::runtime_error( "unknown infrared format" );
break;
}
}
}
// Show Data
void RealSense::show()
{
// Show Color
showColor();
// Show Depth
showDepth();
// Show Infrared
showInfrared();
}
// Show Color
inline void RealSense::showColor()
{
if( !color_frame ){
return;
}
if( color_mat.empty() ){
return;
}
// Show Color Image
cv::imshow( "Color", color_mat );
}
// Show Depth
inline void RealSense::showDepth()
{
if( !depth_frame ){
return;
}
if( depth_mat.empty() ){
return;
}
// Scaling
cv::Mat scale_mat;
depth_mat.convertTo( scale_mat, CV_8U, -255.0 / 10000.0, 255.0 ); // 0-10000 -> 255(white)-0(black)
// Show Depth Image
cv::imshow( "Depth", scale_mat );
}
// Show Infrared
inline void RealSense::showInfrared()
{
for( const rs2::frame& infrared_frame : infrared_frames ){
if( !infrared_frame ){
continue;
}
const uint8_t infrared_stream_index = infrared_frame.get_profile().stream_index();
const uint8_t infrared_mat_index = ( infrared_stream_index != 0 ) ? infrared_stream_index - 1 : 0;
if( infrared_mats[infrared_mat_index].empty() ){
continue;
}
// Show Infrared Image
cv::imshow( "Infrared " + std::to_string( infrared_stream_index ), infrared_mats[infrared_mat_index] );
}
}
// Save Data
void RealSense::save()
{
// Save Color
saveColor();
// Save Depth
saveDepth();
// Save Infrared
saveInfrared();
}
// Save Color
inline void RealSense::saveColor()
{
if( !color_frame ){
return;
}
if( color_mat.empty() ){
return;
}
// Create Save Directory and File Name
std::ostringstream oss;
oss << directory.generic_string() << "/Color/";
oss << std::setfill( '0' ) << std::setw( 6 ) << color_frame.get_frame_number() << ".jpg";
// Write Color Image
cv::imwrite( oss.str(), color_mat, params );
}
// Save Depth
inline void RealSense::saveDepth()
{
if( !depth_frame ){
return;
}
if( depth_mat.empty() ){
return;
}
// Create Save Directory and File Name
std::ostringstream oss;
oss << directory.generic_string() << "/Depth/";
oss << std::setfill( '0' ) << std::setw( 6 ) << depth_frame.get_frame_number() << ".png";
// Scaling
cv::Mat scale_mat = depth_mat;
if( scaling ){
depth_mat.convertTo( scale_mat, CV_8U, -255.0 / 10000.0, 255.0 ); // 0-10000 -> 255(white)-0(black)
}
// Write Depth Image
cv::imwrite( oss.str(), scale_mat );
}
// Save Infrared
inline void RealSense::saveInfrared()
{
for( const rs2::frame& infrared_frame : infrared_frames ){
if( !infrared_frame ){
continue;
}
const uint8_t infrared_stream_index = infrared_frame.get_profile().stream_index();
const uint8_t infrared_mat_index = ( infrared_stream_index != 0 ) ? infrared_stream_index - 1 : 0;
if( infrared_mats[infrared_mat_index].empty() ){
continue;
}
// Create Save Directory and File Name
std::ostringstream oss;
if( infrared_stream_index != 0 ){
oss << directory.generic_string() << "/Infrared " << std::to_string( infrared_stream_index ) << "/";
}
else{
oss << directory.generic_string() << "/Infrared" << "/";
}
oss << std::setfill( '0' ) << std::setw( 6 ) << infrared_frame.get_frame_number() << ".jpg";
// Write Infrared Image
cv::imwrite( oss.str(), infrared_mats[infrared_mat_index], params );
}
}
| 29.02852 | 160 | 0.598895 | [
"vector"
] |
11fedd384246f1206a25e61421503d72896898a6 | 8,718 | cc | C++ | content/browser/file_system/file_system_operation_runner_unittest.cc | sarang-apps/darshan_browser | 173649bb8a7c656dc60784d19e7bb73e07c20daa | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 575 | 2015-06-18T23:58:20.000Z | 2022-03-23T09:32:39.000Z | content/browser/file_system/file_system_operation_runner_unittest.cc | sarang-apps/darshan_browser | 173649bb8a7c656dc60784d19e7bb73e07c20daa | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 113 | 2015-05-04T09:58:14.000Z | 2022-01-31T19:35:03.000Z | content/browser/file_system/file_system_operation_runner_unittest.cc | sarang-apps/darshan_browser | 173649bb8a7c656dc60784d19e7bb73e07c20daa | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 52 | 2015-07-14T10:40:50.000Z | 2022-03-15T01:11:49.000Z | // Copyright 2013 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 <utility>
#include "base/bind.h"
#include "base/files/file_path.h"
#include "base/files/scoped_temp_dir.h"
#include "base/macros.h"
#include "base/memory/scoped_refptr.h"
#include "base/run_loop.h"
#include "base/task/post_task.h"
#include "base/task/task_traits.h"
#include "base/task/thread_pool.h"
#include "base/task/thread_pool/thread_pool_instance.h"
#include "base/test/task_environment.h"
#include "base/threading/thread_restrictions.h"
#include "base/threading/thread_task_runner_handle.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/test/browser_task_environment.h"
#include "storage/browser/file_system/external_mount_points.h"
#include "storage/browser/file_system/file_system_backend.h"
#include "storage/browser/file_system/file_system_context.h"
#include "storage/browser/file_system/file_system_operation_runner.h"
#include "storage/browser/test/mock_special_storage_policy.h"
#include "storage/browser/test/test_file_system_context.h"
#include "storage/browser/test/test_file_system_options.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "url/gurl.h"
#include "url/origin.h"
using storage::FileSystemContext;
using storage::FileSystemOperationRunner;
using storage::FileSystemType;
using storage::FileSystemURL;
namespace content {
namespace {
void GetStatus(bool* done,
base::File::Error* status_out,
base::File::Error status) {
ASSERT_FALSE(*done);
*done = true;
*status_out = status;
}
void GetCancelStatus(bool* operation_done,
bool* cancel_done,
base::File::Error* status_out,
base::File::Error status) {
// Cancel callback must be always called after the operation's callback.
ASSERT_TRUE(*operation_done);
ASSERT_FALSE(*cancel_done);
*cancel_done = true;
*status_out = status;
}
void DidOpenFile(base::File file, base::OnceClosure on_close_callback) {}
} // namespace
class FileSystemOperationRunnerTest : public testing::Test {
protected:
FileSystemOperationRunnerTest() {}
~FileSystemOperationRunnerTest() override {}
void SetUp() override {
ASSERT_TRUE(base_.CreateUniqueTempDir());
base::FilePath base_dir = base_.GetPath();
file_system_context_ =
storage::CreateFileSystemContextForTesting(nullptr, base_dir);
}
void TearDown() override {
file_system_context_ = nullptr;
base::RunLoop().RunUntilIdle();
}
FileSystemURL URL(const std::string& path) {
return file_system_context_->CreateCrackedFileSystemURL(
url::Origin::Create(GURL("http://example.com")),
storage::kFileSystemTypeTemporary,
base::FilePath::FromUTF8Unsafe(path));
}
FileSystemOperationRunner* operation_runner() {
return file_system_context_->operation_runner();
}
private:
base::ScopedTempDir base_;
base::test::SingleThreadTaskEnvironment task_environment_;
scoped_refptr<FileSystemContext> file_system_context_;
DISALLOW_COPY_AND_ASSIGN(FileSystemOperationRunnerTest);
};
TEST_F(FileSystemOperationRunnerTest, NotFoundError) {
bool done = false;
base::File::Error status = base::File::FILE_ERROR_FAILED;
// Regular NOT_FOUND error, which is called asynchronously.
operation_runner()->Truncate(URL("foo"), 0,
base::BindOnce(&GetStatus, &done, &status));
ASSERT_FALSE(done);
base::RunLoop().RunUntilIdle();
ASSERT_TRUE(done);
ASSERT_EQ(base::File::FILE_ERROR_NOT_FOUND, status);
}
TEST_F(FileSystemOperationRunnerTest, InvalidURLError) {
bool done = false;
base::File::Error status = base::File::FILE_ERROR_FAILED;
// Invalid URL error, which calls DidFinish synchronously.
operation_runner()->Truncate(FileSystemURL(), 0,
base::BindOnce(&GetStatus, &done, &status));
// The error call back shouldn't be fired synchronously.
ASSERT_FALSE(done);
base::RunLoop().RunUntilIdle();
ASSERT_TRUE(done);
ASSERT_EQ(base::File::FILE_ERROR_INVALID_URL, status);
}
TEST_F(FileSystemOperationRunnerTest, NotFoundErrorAndCancel) {
bool done = false;
bool cancel_done = false;
base::File::Error status = base::File::FILE_ERROR_FAILED;
base::File::Error cancel_status = base::File::FILE_ERROR_FAILED;
// Call Truncate with non-existent URL, and try to cancel it immediately
// after that (before its callback is fired).
FileSystemOperationRunner::OperationID id = operation_runner()->Truncate(
URL("foo"), 0, base::BindOnce(&GetStatus, &done, &status));
operation_runner()->Cancel(id, base::BindOnce(&GetCancelStatus, &done,
&cancel_done, &cancel_status));
ASSERT_FALSE(done);
ASSERT_FALSE(cancel_done);
base::RunLoop().RunUntilIdle();
ASSERT_TRUE(done);
ASSERT_TRUE(cancel_done);
ASSERT_EQ(base::File::FILE_ERROR_NOT_FOUND, status);
ASSERT_EQ(base::File::FILE_ERROR_INVALID_OPERATION, cancel_status);
}
TEST_F(FileSystemOperationRunnerTest, InvalidURLErrorAndCancel) {
bool done = false;
bool cancel_done = false;
base::File::Error status = base::File::FILE_ERROR_FAILED;
base::File::Error cancel_status = base::File::FILE_ERROR_FAILED;
// Call Truncate with invalid URL, and try to cancel it immediately
// after that (before its callback is fired).
FileSystemOperationRunner::OperationID id = operation_runner()->Truncate(
FileSystemURL(), 0, base::BindOnce(&GetStatus, &done, &status));
operation_runner()->Cancel(id, base::BindOnce(&GetCancelStatus, &done,
&cancel_done, &cancel_status));
ASSERT_FALSE(done);
ASSERT_FALSE(cancel_done);
base::RunLoop().RunUntilIdle();
ASSERT_TRUE(done);
ASSERT_TRUE(cancel_done);
ASSERT_EQ(base::File::FILE_ERROR_INVALID_URL, status);
ASSERT_EQ(base::File::FILE_ERROR_INVALID_OPERATION, cancel_status);
}
TEST_F(FileSystemOperationRunnerTest, CancelWithInvalidId) {
const FileSystemOperationRunner::OperationID kInvalidId = -1;
bool done = true; // The operation is not running.
bool cancel_done = false;
base::File::Error cancel_status = base::File::FILE_ERROR_FAILED;
operation_runner()->Cancel(
kInvalidId,
base::BindOnce(&GetCancelStatus, &done, &cancel_done, &cancel_status));
ASSERT_TRUE(cancel_done);
ASSERT_EQ(base::File::FILE_ERROR_INVALID_OPERATION, cancel_status);
}
class MultiThreadFileSystemOperationRunnerTest : public testing::Test {
public:
MultiThreadFileSystemOperationRunnerTest()
: task_environment_(content::BrowserTaskEnvironment::IO_MAINLOOP) {}
void SetUp() override {
ASSERT_TRUE(base_.CreateUniqueTempDir());
base::FilePath base_dir = base_.GetPath();
file_system_context_ = base::MakeRefCounted<FileSystemContext>(
base::ThreadTaskRunnerHandle::Get().get(),
base::ThreadPool::CreateSequencedTaskRunner({base::MayBlock()}).get(),
storage::ExternalMountPoints::CreateRefCounted().get(),
base::MakeRefCounted<storage::MockSpecialStoragePolicy>().get(),
nullptr, std::vector<std::unique_ptr<storage::FileSystemBackend>>(),
std::vector<storage::URLRequestAutoMountHandler>(), base_dir,
storage::CreateAllowFileAccessOptions());
// Disallow IO on the main loop.
base::ThreadRestrictions::SetIOAllowed(false);
}
void TearDown() override {
base::ThreadRestrictions::SetIOAllowed(true);
file_system_context_ = nullptr;
}
FileSystemURL URL(const std::string& path) {
return file_system_context_->CreateCrackedFileSystemURL(
url::Origin::Create(GURL("http://example.com")),
storage::kFileSystemTypeTemporary,
base::FilePath::FromUTF8Unsafe(path));
}
FileSystemOperationRunner* operation_runner() {
return file_system_context_->operation_runner();
}
private:
base::ScopedTempDir base_;
content::BrowserTaskEnvironment task_environment_;
scoped_refptr<FileSystemContext> file_system_context_;
DISALLOW_COPY_AND_ASSIGN(MultiThreadFileSystemOperationRunnerTest);
};
TEST_F(MultiThreadFileSystemOperationRunnerTest, OpenAndShutdown) {
// Call OpenFile and immediately shutdown the runner.
operation_runner()->OpenFile(
URL("foo"), base::File::FLAG_CREATE_ALWAYS | base::File::FLAG_WRITE,
base::BindOnce(&DidOpenFile));
operation_runner()->Shutdown();
// Wait until the task posted on the blocking thread is done.
base::ThreadPoolInstance::Get()->FlushForTesting();
// This should finish without thread assertion failure on debug build.
}
} // namespace content
| 35.295547 | 79 | 0.732507 | [
"vector"
] |
11fef225324cf80a5a6db4bc262fcd809d35a98e | 1,512 | hpp | C++ | src/org/apache/poi/hssf/record/SSTSerializer.hpp | pebble2015/cpoi | 6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6 | [
"Apache-2.0"
] | null | null | null | src/org/apache/poi/hssf/record/SSTSerializer.hpp | pebble2015/cpoi | 6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6 | [
"Apache-2.0"
] | null | null | null | src/org/apache/poi/hssf/record/SSTSerializer.hpp | pebble2015/cpoi | 6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6 | [
"Apache-2.0"
] | null | null | null | // Generated from /POI/java/org/apache/poi/hssf/record/SSTSerializer.java
#pragma once
#include <fwd-POI.hpp>
#include <org/apache/poi/hssf/record/fwd-POI.hpp>
#include <org/apache/poi/hssf/record/common/fwd-POI.hpp>
#include <org/apache/poi/hssf/record/cont/fwd-POI.hpp>
#include <org/apache/poi/util/fwd-POI.hpp>
#include <java/lang/Object.hpp>
struct default_init_tag;
class poi::hssf::record::SSTSerializer final
: public ::java::lang::Object
{
public:
typedef ::java::lang::Object super;
private:
int32_t _numStrings { };
int32_t _numUniqueStrings { };
::poi::util::IntMapper* strings { };
::int32_tArray* bucketAbsoluteOffsets { };
::int32_tArray* bucketRelativeOffsets { };
protected:
void ctor(::poi::util::IntMapper* strings, int32_t numStrings, int32_t numUniqueStrings);
public:
void serialize(::poi::hssf::record::cont::ContinuableRecordOutput* out);
private:
::poi::hssf::record::common::UnicodeString* getUnicodeString(int32_t index);
static ::poi::hssf::record::common::UnicodeString* getUnicodeString(::poi::util::IntMapper* strings, int32_t index);
public:
::int32_tArray* getBucketAbsoluteOffsets();
::int32_tArray* getBucketRelativeOffsets();
// Generated
SSTSerializer(::poi::util::IntMapper* strings, int32_t numStrings, int32_t numUniqueStrings);
protected:
SSTSerializer(const ::default_init_tag&);
public:
static ::java::lang::Class *class_();
private:
virtual ::java::lang::Class* getClass0();
};
| 28.528302 | 120 | 0.716931 | [
"object"
] |
f50193bb97bb2a971cdc802d37fe830c13ba9055 | 20,302 | cpp | C++ | 01_Develop/libXMFFmpeg/Source/libavcodec/ivi_dsp.cpp | mcodegeeks/OpenKODE-Framework | d4382d781da7f488a0e7667362a89e8e389468dd | [
"MIT"
] | 2 | 2017-08-03T07:15:00.000Z | 2018-06-18T10:32:53.000Z | 01_Develop/libXMFFmpeg/Source/libavcodec/ivi_dsp.cpp | mcodegeeks/OpenKODE-Framework | d4382d781da7f488a0e7667362a89e8e389468dd | [
"MIT"
] | null | null | null | 01_Develop/libXMFFmpeg/Source/libavcodec/ivi_dsp.cpp | mcodegeeks/OpenKODE-Framework | d4382d781da7f488a0e7667362a89e8e389468dd | [
"MIT"
] | 2 | 2019-03-04T22:57:42.000Z | 2020-03-06T01:32:26.000Z | /*
* DSP functions for Indeo Video Interactive codecs (Indeo4 and Indeo5)
*
* Copyright (c) 2009-2011 Maxim Poliakovski
*
* This file is part of FFmpeg.
*
* FFmpeg 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.
*
* FFmpeg 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 FFmpeg; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
/**
* @file
* DSP functions (inverse transforms, motion compensation, wavelet recompostions)
* for Indeo Video Interactive codecs.
*/
#include "internal.h"
#include "dsputil.h"
#include "dwt.h"
#include "ivi_common.h"
#include "ivi_dsp.h"
void ff_ivi_recompose53(const IVIPlaneDesc *plane, uint8_t *dst,
const int dst_pitch, const int num_bands)
{
int x, y, indx;
int32_t p0, p1, p2, p3, tmp0, tmp1, tmp2;
int32_t b0_1, b0_2, b1_1, b1_2, b1_3, b2_1, b2_2, b2_3, b2_4, b2_5, b2_6;
int32_t b3_1, b3_2, b3_3, b3_4, b3_5, b3_6, b3_7, b3_8, b3_9;
int32_t pitch, back_pitch;
const IDWTELEM *b0_ptr, *b1_ptr, *b2_ptr, *b3_ptr;
/* all bands should have the same pitch */
pitch = plane->bands[0].pitch;
/* pixels at the position "y-1" will be set to pixels at the "y" for the 1st iteration */
back_pitch = 0;
/* get pointers to the wavelet bands */
b0_ptr = plane->bands[0].buf;
b1_ptr = plane->bands[1].buf;
b2_ptr = plane->bands[2].buf;
b3_ptr = plane->bands[3].buf;
for (y = 0; y < plane->height; y += 2) {
/* load storage variables with values */
if (num_bands > 0) {
b0_1 = b0_ptr[0];
b0_2 = b0_ptr[pitch];
}
if (num_bands > 1) {
b1_1 = b1_ptr[back_pitch];
b1_2 = b1_ptr[0];
b1_3 = b1_1 - b1_2*6 + b1_ptr[pitch];
}
if (num_bands > 2) {
b2_2 = b2_ptr[0]; // b2[x, y ]
b2_3 = b2_2; // b2[x+1,y ] = b2[x,y]
b2_5 = b2_ptr[pitch]; // b2[x ,y+1]
b2_6 = b2_5; // b2[x+1,y+1] = b2[x,y+1]
}
if (num_bands > 3) {
b3_2 = b3_ptr[back_pitch]; // b3[x ,y-1]
b3_3 = b3_2; // b3[x+1,y-1] = b3[x ,y-1]
b3_5 = b3_ptr[0]; // b3[x ,y ]
b3_6 = b3_5; // b3[x+1,y ] = b3[x ,y ]
b3_8 = b3_2 - b3_5*6 + b3_ptr[pitch];
b3_9 = b3_8;
}
for (x = 0, indx = 0; x < plane->width; x+=2, indx++) {
/* some values calculated in the previous iterations can */
/* be reused in the next ones, so do appropriate copying */
b2_1 = b2_2; // b2[x-1,y ] = b2[x, y ]
b2_2 = b2_3; // b2[x ,y ] = b2[x+1,y ]
b2_4 = b2_5; // b2[x-1,y+1] = b2[x ,y+1]
b2_5 = b2_6; // b2[x ,y+1] = b2[x+1,y+1]
b3_1 = b3_2; // b3[x-1,y-1] = b3[x ,y-1]
b3_2 = b3_3; // b3[x ,y-1] = b3[x+1,y-1]
b3_4 = b3_5; // b3[x-1,y ] = b3[x ,y ]
b3_5 = b3_6; // b3[x ,y ] = b3[x+1,y ]
b3_7 = b3_8; // vert_HPF(x-1)
b3_8 = b3_9; // vert_HPF(x )
p0 = p1 = p2 = p3 = 0;
/* process the LL-band by applying LPF both vertically and horizontally */
if (num_bands > 0) {
tmp0 = b0_1;
tmp2 = b0_2;
b0_1 = b0_ptr[indx+1];
b0_2 = b0_ptr[pitch+indx+1];
tmp1 = tmp0 + b0_1;
p0 = tmp0 << 4;
p1 = tmp1 << 3;
p2 = (tmp0 + tmp2) << 3;
p3 = (tmp1 + tmp2 + b0_2) << 2;
}
/* process the HL-band by applying HPF vertically and LPF horizontally */
if (num_bands > 1) {
tmp0 = b1_2;
tmp1 = b1_1;
b1_2 = b1_ptr[indx+1];
b1_1 = b1_ptr[back_pitch+indx+1];
tmp2 = tmp1 - tmp0*6 + b1_3;
b1_3 = b1_1 - b1_2*6 + b1_ptr[pitch+indx+1];
p0 += (tmp0 + tmp1) << 3;
p1 += (tmp0 + tmp1 + b1_1 + b1_2) << 2;
p2 += tmp2 << 2;
p3 += (tmp2 + b1_3) << 1;
}
/* process the LH-band by applying LPF vertically and HPF horizontally */
if (num_bands > 2) {
b2_3 = b2_ptr[indx+1];
b2_6 = b2_ptr[pitch+indx+1];
tmp0 = b2_1 + b2_2;
tmp1 = b2_1 - b2_2*6 + b2_3;
p0 += tmp0 << 3;
p1 += tmp1 << 2;
p2 += (tmp0 + b2_4 + b2_5) << 2;
p3 += (tmp1 + b2_4 - b2_5*6 + b2_6) << 1;
}
/* process the HH-band by applying HPF both vertically and horizontally */
if (num_bands > 3) {
b3_6 = b3_ptr[indx+1]; // b3[x+1,y ]
b3_3 = b3_ptr[back_pitch+indx+1]; // b3[x+1,y-1]
tmp0 = b3_1 + b3_4;
tmp1 = b3_2 + b3_5;
tmp2 = b3_3 + b3_6;
b3_9 = b3_3 - b3_6*6 + b3_ptr[pitch+indx+1];
p0 += (tmp0 + tmp1) << 2;
p1 += (tmp0 - tmp1*6 + tmp2) << 1;
p2 += (b3_7 + b3_8) << 1;
p3 += b3_7 - b3_8*6 + b3_9;
}
/* output four pixels */
dst[x] = av_clip_uint8((p0 >> 6) + 128);
dst[x+1] = av_clip_uint8((p1 >> 6) + 128);
dst[dst_pitch+x] = av_clip_uint8((p2 >> 6) + 128);
dst[dst_pitch+x+1] = av_clip_uint8((p3 >> 6) + 128);
}// for x
dst += dst_pitch << 1;
back_pitch = -pitch;
b0_ptr += pitch;
b1_ptr += pitch;
b2_ptr += pitch;
b3_ptr += pitch;
}
}
void ff_ivi_recompose_haar(const IVIPlaneDesc *plane, uint8_t *dst,
const int dst_pitch, const int num_bands)
{
int x, y, indx, b0, b1, b2, b3, p0, p1, p2, p3;
const IDWTELEM *b0_ptr, *b1_ptr, *b2_ptr, *b3_ptr;
int32_t pitch;
/* all bands should have the same pitch */
pitch = plane->bands[0].pitch;
/* get pointers to the wavelet bands */
b0_ptr = plane->bands[0].buf;
b1_ptr = plane->bands[1].buf;
b2_ptr = plane->bands[2].buf;
b3_ptr = plane->bands[3].buf;
for (y = 0; y < plane->height; y += 2) {
for (x = 0, indx = 0; x < plane->width; x += 2, indx++) {
/* load coefficients */
b0 = b0_ptr[indx]; //should be: b0 = (num_bands > 0) ? b0_ptr[indx] : 0;
b1 = b1_ptr[indx]; //should be: b1 = (num_bands > 1) ? b1_ptr[indx] : 0;
b2 = b2_ptr[indx]; //should be: b2 = (num_bands > 2) ? b2_ptr[indx] : 0;
b3 = b3_ptr[indx]; //should be: b3 = (num_bands > 3) ? b3_ptr[indx] : 0;
/* haar wavelet recomposition */
p0 = (b0 + b1 + b2 + b3 + 2) >> 2;
p1 = (b0 + b1 - b2 - b3 + 2) >> 2;
p2 = (b0 - b1 + b2 - b3 + 2) >> 2;
p3 = (b0 - b1 - b2 + b3 + 2) >> 2;
/* bias, convert and output four pixels */
dst[x] = av_clip_uint8(p0 + 128);
dst[x + 1] = av_clip_uint8(p1 + 128);
dst[dst_pitch + x] = av_clip_uint8(p2 + 128);
dst[dst_pitch + x + 1] = av_clip_uint8(p3 + 128);
}// for x
dst += dst_pitch << 1;
b0_ptr += pitch;
b1_ptr += pitch;
b2_ptr += pitch;
b3_ptr += pitch;
}// for y
}
/** butterfly operation for the inverse Haar transform */
#define IVI_HAAR_BFLY(s1, s2, o1, o2, t) \
t = (s1 - s2) >> 1;\
o1 = (s1 + s2) >> 1;\
o2 = t;\
/** inverse 8-point Haar transform */
#define INV_HAAR8(s1, s5, s3, s7, s2, s4, s6, s8,\
d1, d2, d3, d4, d5, d6, d7, d8,\
t0, t1, t2, t3, t4, t5, t6, t7, t8) {\
t1 = s1 << 1; t5 = s5 << 1;\
IVI_HAAR_BFLY(t1, t5, t1, t5, t0); IVI_HAAR_BFLY(t1, s3, t1, t3, t0);\
IVI_HAAR_BFLY(t5, s7, t5, t7, t0); IVI_HAAR_BFLY(t1, s2, t1, t2, t0);\
IVI_HAAR_BFLY(t3, s4, t3, t4, t0); IVI_HAAR_BFLY(t5, s6, t5, t6, t0);\
IVI_HAAR_BFLY(t7, s8, t7, t8, t0);\
d1 = COMPENSATE(t1);\
d2 = COMPENSATE(t2);\
d3 = COMPENSATE(t3);\
d4 = COMPENSATE(t4);\
d5 = COMPENSATE(t5);\
d6 = COMPENSATE(t6);\
d7 = COMPENSATE(t7);\
d8 = COMPENSATE(t8); }
/** inverse 4-point Haar transform */
#define INV_HAAR4(s1, s3, s5, s7) {\
HAAR_BFLY(s1, s5); HAAR_BFLY(s1, s3); HAAR_BFLY(s5, s7);\
s1 = COMPENSATE(s1);\
s3 = COMPENSATE(s3);\
s5 = COMPENSATE(s5);\
s7 = COMPENSATE(s7); }
void ff_ivi_inverse_haar_8x8(const int32_t *in, int16_t *out, uint32_t pitch,
const uint8_t *flags)
{
int i, shift, sp1, sp2, sp3, sp4;
const int32_t *src;
int32_t *dst;
int32_t tmp[64];
int t0, t1, t2, t3, t4, t5, t6, t7, t8;
/* apply the InvHaar8 to all columns */
#define COMPENSATE(x) (x)
src = in;
dst = tmp;
for (i = 0; i < 8; i++) {
if (flags[i]) {
/* pre-scaling */
shift = !(i & 4);
sp1 = src[ 0] << shift;
sp2 = src[ 8] << shift;
sp3 = src[16] << shift;
sp4 = src[24] << shift;
INV_HAAR8( sp1, sp2, sp3, sp4,
src[32], src[40], src[48], src[56],
dst[ 0], dst[ 8], dst[16], dst[24],
dst[32], dst[40], dst[48], dst[56],
t0, t1, t2, t3, t4, t5, t6, t7, t8);
} else
dst[ 0] = dst[ 8] = dst[16] = dst[24] =
dst[32] = dst[40] = dst[48] = dst[56] = 0;
src++;
dst++;
}
#undef COMPENSATE
/* apply the InvHaar8 to all rows */
#define COMPENSATE(x) (x)
src = tmp;
for (i = 0; i < 8; i++) {
if ( !src[0] && !src[1] && !src[2] && !src[3]
&& !src[4] && !src[5] && !src[6] && !src[7]) {
memset(out, 0, 8 * sizeof(out[0]));
} else {
INV_HAAR8(src[0], src[1], src[2], src[3],
src[4], src[5], src[6], src[7],
out[0], out[1], out[2], out[3],
out[4], out[5], out[6], out[7],
t0, t1, t2, t3, t4, t5, t6, t7, t8);
}
src += 8;
out += pitch;
}
#undef COMPENSATE
}
void ff_ivi_dc_haar_2d(const int32_t *in, int16_t *out, uint32_t pitch,
int blk_size)
{
int x, y;
int16_t dc_coeff;
dc_coeff = (*in + 0) >> 3;
for (y = 0; y < blk_size; out += pitch, y++) {
for (x = 0; x < blk_size; x++)
out[x] = dc_coeff;
}
}
/** butterfly operation for the inverse slant transform */
#define IVI_SLANT_BFLY(s1, s2, o1, o2, t) \
t = s1 - s2;\
o1 = s1 + s2;\
o2 = t;\
/** This is a reflection a,b = 1/2, 5/4 for the inverse slant transform */
#define IVI_IREFLECT(s1, s2, o1, o2, t) \
t = ((s1 + s2*2 + 2) >> 2) + s1;\
o2 = ((s1*2 - s2 + 2) >> 2) - s2;\
o1 = t;\
/** This is a reflection a,b = 1/2, 7/8 for the inverse slant transform */
#define IVI_SLANT_PART4(s1, s2, o1, o2, t) \
t = s2 + ((s1*4 - s2 + 4) >> 3);\
o2 = s1 + ((-s1 - s2*4 + 4) >> 3);\
o1 = t;\
/** inverse slant8 transform */
#define IVI_INV_SLANT8(s1, s4, s8, s5, s2, s6, s3, s7,\
d1, d2, d3, d4, d5, d6, d7, d8,\
t0, t1, t2, t3, t4, t5, t6, t7, t8) {\
IVI_SLANT_PART4(s4, s5, t4, t5, t0);\
\
IVI_SLANT_BFLY(s1, t5, t1, t5, t0); IVI_SLANT_BFLY(s2, s6, t2, t6, t0);\
IVI_SLANT_BFLY(s7, s3, t7, t3, t0); IVI_SLANT_BFLY(t4, s8, t4, t8, t0);\
\
IVI_SLANT_BFLY(t1, t2, t1, t2, t0); IVI_IREFLECT (t4, t3, t4, t3, t0);\
IVI_SLANT_BFLY(t5, t6, t5, t6, t0); IVI_IREFLECT (t8, t7, t8, t7, t0);\
IVI_SLANT_BFLY(t1, t4, t1, t4, t0); IVI_SLANT_BFLY(t2, t3, t2, t3, t0);\
IVI_SLANT_BFLY(t5, t8, t5, t8, t0); IVI_SLANT_BFLY(t6, t7, t6, t7, t0);\
d1 = COMPENSATE(t1);\
d2 = COMPENSATE(t2);\
d3 = COMPENSATE(t3);\
d4 = COMPENSATE(t4);\
d5 = COMPENSATE(t5);\
d6 = COMPENSATE(t6);\
d7 = COMPENSATE(t7);\
d8 = COMPENSATE(t8);}
/** inverse slant4 transform */
#define IVI_INV_SLANT4(s1, s4, s2, s3, d1, d2, d3, d4, t0, t1, t2, t3, t4) {\
IVI_SLANT_BFLY(s1, s2, t1, t2, t0); IVI_IREFLECT (s4, s3, t4, t3, t0);\
\
IVI_SLANT_BFLY(t1, t4, t1, t4, t0); IVI_SLANT_BFLY(t2, t3, t2, t3, t0);\
d1 = COMPENSATE(t1);\
d2 = COMPENSATE(t2);\
d3 = COMPENSATE(t3);\
d4 = COMPENSATE(t4);}
void ff_ivi_inverse_slant_8x8(const int32_t *in, int16_t *out, uint32_t pitch, const uint8_t *flags)
{
int i;
const int32_t *src;
int32_t *dst;
int32_t tmp[64];
int t0, t1, t2, t3, t4, t5, t6, t7, t8;
#define COMPENSATE(x) (x)
src = in;
dst = tmp;
for (i = 0; i < 8; i++) {
if (flags[i]) {
IVI_INV_SLANT8(src[0], src[8], src[16], src[24], src[32], src[40], src[48], src[56],
dst[0], dst[8], dst[16], dst[24], dst[32], dst[40], dst[48], dst[56],
t0, t1, t2, t3, t4, t5, t6, t7, t8);
} else
dst[0] = dst[8] = dst[16] = dst[24] = dst[32] = dst[40] = dst[48] = dst[56] = 0;
src++;
dst++;
}
#undef COMPENSATE
#define COMPENSATE(x) ((x + 1)>>1)
src = tmp;
for (i = 0; i < 8; i++) {
if (!src[0] && !src[1] && !src[2] && !src[3] && !src[4] && !src[5] && !src[6] && !src[7]) {
memset(out, 0, 8*sizeof(out[0]));
} else {
IVI_INV_SLANT8(src[0], src[1], src[2], src[3], src[4], src[5], src[6], src[7],
out[0], out[1], out[2], out[3], out[4], out[5], out[6], out[7],
t0, t1, t2, t3, t4, t5, t6, t7, t8);
}
src += 8;
out += pitch;
}
#undef COMPENSATE
}
void ff_ivi_inverse_slant_4x4(const int32_t *in, int16_t *out, uint32_t pitch, const uint8_t *flags)
{
int i;
const int32_t *src;
int32_t *dst;
int32_t tmp[16];
int t0, t1, t2, t3, t4;
#define COMPENSATE(x) (x)
src = in;
dst = tmp;
for (i = 0; i < 4; i++) {
if (flags[i]) {
IVI_INV_SLANT4(src[0], src[4], src[8], src[12],
dst[0], dst[4], dst[8], dst[12],
t0, t1, t2, t3, t4);
} else
dst[0] = dst[4] = dst[8] = dst[12] = 0;
src++;
dst++;
}
#undef COMPENSATE
#define COMPENSATE(x) ((x + 1)>>1)
src = tmp;
for (i = 0; i < 4; i++) {
if (!src[0] && !src[1] && !src[2] && !src[3]) {
out[0] = out[1] = out[2] = out[3] = 0;
} else {
IVI_INV_SLANT4(src[0], src[1], src[2], src[3],
out[0], out[1], out[2], out[3],
t0, t1, t2, t3, t4);
}
src += 4;
out += pitch;
}
#undef COMPENSATE
}
void ff_ivi_dc_slant_2d(const int32_t *in, int16_t *out, uint32_t pitch, int blk_size)
{
int x, y;
int16_t dc_coeff;
dc_coeff = (*in + 1) >> 1;
for (y = 0; y < blk_size; out += pitch, y++) {
for (x = 0; x < blk_size; x++)
out[x] = dc_coeff;
}
}
void ff_ivi_row_slant8(const int32_t *in, int16_t *out, uint32_t pitch, const uint8_t *flags)
{
int i;
int t0, t1, t2, t3, t4, t5, t6, t7, t8;
#define COMPENSATE(x) ((x + 1)>>1)
for (i = 0; i < 8; i++) {
if (!in[0] && !in[1] && !in[2] && !in[3] && !in[4] && !in[5] && !in[6] && !in[7]) {
memset(out, 0, 8*sizeof(out[0]));
} else {
IVI_INV_SLANT8( in[0], in[1], in[2], in[3], in[4], in[5], in[6], in[7],
out[0], out[1], out[2], out[3], out[4], out[5], out[6], out[7],
t0, t1, t2, t3, t4, t5, t6, t7, t8);
}
in += 8;
out += pitch;
}
#undef COMPENSATE
}
void ff_ivi_dc_row_slant(const int32_t *in, int16_t *out, uint32_t pitch, int blk_size)
{
int x, y;
int16_t dc_coeff;
dc_coeff = (*in + 1) >> 1;
for (x = 0; x < blk_size; x++)
out[x] = dc_coeff;
out += pitch;
for (y = 1; y < blk_size; out += pitch, y++) {
for (x = 0; x < blk_size; x++)
out[x] = 0;
}
}
void ff_ivi_col_slant8(const int32_t *in, int16_t *out, uint32_t pitch, const uint8_t *flags)
{
int i, row2, row4, row8;
int t0, t1, t2, t3, t4, t5, t6, t7, t8;
row2 = pitch << 1;
row4 = pitch << 2;
row8 = pitch << 3;
#define COMPENSATE(x) ((x + 1)>>1)
for (i = 0; i < 8; i++) {
if (flags[i]) {
IVI_INV_SLANT8(in[0], in[8], in[16], in[24], in[32], in[40], in[48], in[56],
out[0], out[pitch], out[row2], out[row2 + pitch], out[row4],
out[row4 + pitch], out[row4 + row2], out[row8 - pitch],
t0, t1, t2, t3, t4, t5, t6, t7, t8);
} else {
out[0] = out[pitch] = out[row2] = out[row2 + pitch] = out[row4] =
out[row4 + pitch] = out[row4 + row2] = out[row8 - pitch] = 0;
}
in++;
out++;
}
#undef COMPENSATE
}
void ff_ivi_dc_col_slant(const int32_t *in, int16_t *out, uint32_t pitch, int blk_size)
{
int x, y;
int16_t dc_coeff;
dc_coeff = (*in + 1) >> 1;
for (y = 0; y < blk_size; out += pitch, y++) {
out[0] = dc_coeff;
for (x = 1; x < blk_size; x++)
out[x] = 0;
}
}
void ff_ivi_put_pixels_8x8(const int32_t *in, int16_t *out, uint32_t pitch,
const uint8_t *flags)
{
int x, y;
for (y = 0; y < 8; out += pitch, in += 8, y++)
for (x = 0; x < 8; x++)
out[x] = in[x];
}
void ff_ivi_put_dc_pixel_8x8(const int32_t *in, int16_t *out, uint32_t pitch,
int blk_size)
{
int y;
out[0] = in[0];
memset(out + 1, 0, 7*sizeof(out[0]));
out += pitch;
for (y = 1; y < 8; out += pitch, y++)
memset(out, 0, 8*sizeof(out[0]));
}
#define IVI_MC_TEMPLATE(size, suffix, OP) \
void ff_ivi_mc_ ## size ##x## size ## suffix (int16_t *buf, const int16_t *ref_buf, \
uint32_t pitch, int mc_type) \
{ \
int i, j; \
const int16_t *wptr; \
\
switch (mc_type) { \
case 0: /* fullpel (no interpolation) */ \
for (i = 0; i < size; i++, buf += pitch, ref_buf += pitch) { \
for (j = 0; j < size; j++) {\
OP(buf[j], ref_buf[j]); \
} \
} \
break; \
case 1: /* horizontal halfpel interpolation */ \
for (i = 0; i < size; i++, buf += pitch, ref_buf += pitch) \
for (j = 0; j < size; j++) \
OP(buf[j], (ref_buf[j] + ref_buf[j+1]) >> 1); \
break; \
case 2: /* vertical halfpel interpolation */ \
wptr = ref_buf + pitch; \
for (i = 0; i < size; i++, buf += pitch, wptr += pitch, ref_buf += pitch) \
for (j = 0; j < size; j++) \
OP(buf[j], (ref_buf[j] + wptr[j]) >> 1); \
break; \
case 3: /* vertical and horizontal halfpel interpolation */ \
wptr = ref_buf + pitch; \
for (i = 0; i < size; i++, buf += pitch, wptr += pitch, ref_buf += pitch) \
for (j = 0; j < size; j++) \
OP(buf[j], (ref_buf[j] + ref_buf[j+1] + wptr[j] + wptr[j+1]) >> 2); \
break; \
} \
} \
#define OP_PUT(a, b) (a) = (b)
#define OP_ADD(a, b) (a) += (b)
IVI_MC_TEMPLATE(8, _no_delta, OP_PUT)
IVI_MC_TEMPLATE(8, _delta, OP_ADD)
IVI_MC_TEMPLATE(4, _no_delta, OP_PUT)
IVI_MC_TEMPLATE(4, _delta, OP_ADD)
| 33.011382 | 100 | 0.472022 | [
"transform"
] |
f505c13fb12f32c294219f862edb2678e22ea298 | 6,312 | cpp | C++ | src/modules/math/wrap_BezierCurve.cpp | prepare/lualove | 22e6969ebbc2e57030aef05421f740b229c0f50c | [
"BSD-3-Clause"
] | 20 | 2019-10-16T22:24:49.000Z | 2020-07-23T00:37:05.000Z | src/love/src/modules/math/wrap_BezierCurve.cpp | MikuAuahDark/livesim4 | 76860f58d81c44da2f4c5f2a2f32ab7ab73e1155 | [
"Zlib"
] | 8 | 2021-01-27T01:02:47.000Z | 2022-03-09T16:41:48.000Z | src/modules/math/wrap_BezierCurve.cpp | aaronbolyard/love2d | 2a5424931c53ec887e1280e4031a28c5d36de0e6 | [
"Apache-2.0"
] | 2 | 2016-08-23T03:52:28.000Z | 2019-10-29T19:03:08.000Z | /**
* Copyright (c) 2006-2018 LOVE Development Team
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
**/
#include "common/Exception.h"
#include "wrap_BezierCurve.h"
#include <cmath>
namespace love
{
namespace math
{
BezierCurve *luax_checkbeziercurve(lua_State *L, int idx)
{
return luax_checktype<BezierCurve>(L, idx);
}
int w_BezierCurve_getDegree(lua_State *L)
{
BezierCurve *curve = luax_checkbeziercurve(L, 1);
lua_pushnumber(L, curve->getDegree());
return 1;
}
int w_BezierCurve_getDerivative(lua_State *L)
{
BezierCurve *curve = luax_checkbeziercurve(L, 1);
BezierCurve *deriv = new BezierCurve(curve->getDerivative());
luax_pushtype(L, deriv);
deriv->release();
return 1;
}
int w_BezierCurve_getControlPoint(lua_State *L)
{
BezierCurve *curve = luax_checkbeziercurve(L, 1);
int idx = (int) luaL_checkinteger(L, 2);
if (idx > 0) // 1-indexing
idx--;
luax_catchexcept(L, [&]() {
Vector2 v = curve->getControlPoint(idx);
lua_pushnumber(L, v.x);
lua_pushnumber(L, v.y);
});
return 2;
}
int w_BezierCurve_setControlPoint(lua_State *L)
{
BezierCurve *curve = luax_checkbeziercurve(L, 1);
int idx = (int) luaL_checkinteger(L, 2);
float vx = (float) luaL_checknumber(L, 3);
float vy = (float) luaL_checknumber(L, 4);
if (idx > 0) // 1-indexing
idx--;
luax_catchexcept(L, [&](){ curve->setControlPoint(idx, Vector2(vx,vy)); });
return 0;
}
int w_BezierCurve_insertControlPoint(lua_State *L)
{
BezierCurve *curve = luax_checkbeziercurve(L, 1);
float vx = (float) luaL_checknumber(L, 2);
float vy = (float) luaL_checknumber(L, 3);
int idx = (int) luaL_optinteger(L, 4, -1);
if (idx > 0) // 1-indexing
idx--;
luax_catchexcept(L, [&](){ curve->insertControlPoint(Vector2(vx,vy), idx); });
return 0;
}
int w_BezierCurve_removeControlPoint(lua_State *L)
{
BezierCurve *curve = luax_checkbeziercurve(L, 1);
int idx = (int) luaL_checkinteger(L, 2);
if (idx > 0) // 1-indexing
idx--;
luax_catchexcept(L, [&](){ curve->removeControlPoint(idx); });
return 0;
}
int w_BezierCurve_getControlPointCount(lua_State *L)
{
BezierCurve *curve = luax_checkbeziercurve(L, 1);
lua_pushinteger(L, curve->getControlPointCount());
return 1;
}
int w_BezierCurve_translate(lua_State *L)
{
BezierCurve *curve = luax_checkbeziercurve(L, 1);
float dx = (float) luaL_checknumber(L, 2);
float dy = (float) luaL_checknumber(L, 3);
curve->translate(Vector2(dx,dy));
return 0;
}
int w_BezierCurve_rotate(lua_State *L)
{
BezierCurve *curve = luax_checkbeziercurve(L, 1);
double phi = luaL_checknumber(L, 2);
float ox = (float) luaL_optnumber(L, 3, 0);
float oy = (float) luaL_optnumber(L, 4, 0);
curve->rotate(phi, Vector2(ox,oy));
return 0;
}
int w_BezierCurve_scale(lua_State *L)
{
BezierCurve *curve = luax_checkbeziercurve(L, 1);
double s = luaL_checknumber(L, 2);
float ox = (float) luaL_optnumber(L, 3, 0);
float oy = (float) luaL_optnumber(L, 4, 0);
curve->scale(s, Vector2(ox,oy));
return 0;
}
int w_BezierCurve_evaluate(lua_State *L)
{
BezierCurve *curve = luax_checkbeziercurve(L, 1);
double t = luaL_checknumber(L, 2);
luax_catchexcept(L, [&]() {
Vector2 v = curve->evaluate(t);
lua_pushnumber(L, v.x);
lua_pushnumber(L, v.y);
});
return 2;
}
int w_BezierCurve_getSegment(lua_State *L)
{
BezierCurve *curve = luax_checkbeziercurve(L, 1);
double t1 = luaL_checknumber(L, 2);
double t2 = luaL_checknumber(L, 3);
BezierCurve *segment;
luax_catchexcept(L, [&](){ segment = curve->getSegment(t1, t2); });
luax_pushtype(L, segment);
segment->release();
return 1;
}
int w_BezierCurve_render(lua_State *L)
{
BezierCurve *curve = luax_checkbeziercurve(L, 1);
int accuracy = (int) luaL_optinteger(L, 2, 5);
std::vector<Vector2> points;
luax_catchexcept(L, [&](){ points = curve->render(accuracy); });
lua_createtable(L, (int) points.size() * 2, 0);
for (int i = 0; i < (int) points.size(); ++i)
{
lua_pushnumber(L, points[i].x);
lua_rawseti(L, -2, 2*i+1);
lua_pushnumber(L, points[i].y);
lua_rawseti(L, -2, 2*i+2);
}
return 1;
}
int w_BezierCurve_renderSegment(lua_State *L)
{
BezierCurve *curve = luax_checkbeziercurve(L, 1);
double start = luaL_checknumber(L, 2);
double end = luaL_checknumber(L, 3);
int accuracy = (int) luaL_optinteger(L, 4, 5);
std::vector<Vector2> points;
luax_catchexcept(L, [&](){ points = curve->renderSegment(start, end, accuracy); });
lua_createtable(L, (int) points.size() * 2, 0);
for (int i = 0; i < (int) points.size(); ++i)
{
lua_pushnumber(L, points[i].x);
lua_rawseti(L, -2, 2*i+1);
lua_pushnumber(L, points[i].y);
lua_rawseti(L, -2, 2*i+2);
}
return 1;
}
static const luaL_Reg w_BezierCurve_functions[] =
{
{"getDegree", w_BezierCurve_getDegree},
{"getDerivative", w_BezierCurve_getDerivative},
{"getControlPoint", w_BezierCurve_getControlPoint},
{"setControlPoint", w_BezierCurve_setControlPoint},
{"insertControlPoint", w_BezierCurve_insertControlPoint},
{"removeControlPoint", w_BezierCurve_removeControlPoint},
{"getControlPointCount", w_BezierCurve_getControlPointCount},
{"translate", w_BezierCurve_translate},
{"rotate", w_BezierCurve_rotate},
{"scale", w_BezierCurve_scale},
{"evaluate", w_BezierCurve_evaluate},
{"getSegment", w_BezierCurve_getSegment},
{"render", w_BezierCurve_render},
{"renderSegment", w_BezierCurve_renderSegment},
{ 0, 0 }
};
extern "C" int luaopen_beziercurve(lua_State *L)
{
return luax_register_type(L, &BezierCurve::type, w_BezierCurve_functions, nullptr);
}
} // math
} // love
| 26.082645 | 84 | 0.71071 | [
"render",
"vector"
] |
f506374a4d1c263ff426a2291dd55c565004e6e2 | 37,597 | cpp | C++ | Source/Utility/MythForest/Component/Sky/AtmosphereModel.cpp | paintdream/paintsnow | 3a1cbc9e571eaa2e62a3a2d60f75817b45f0c781 | [
"MIT"
] | null | null | null | Source/Utility/MythForest/Component/Sky/AtmosphereModel.cpp | paintdream/paintsnow | 3a1cbc9e571eaa2e62a3a2d60f75817b45f0c781 | [
"MIT"
] | null | null | null | Source/Utility/MythForest/Component/Sky/AtmosphereModel.cpp | paintdream/paintsnow | 3a1cbc9e571eaa2e62a3a2d60f75817b45f0c781 | [
"MIT"
] | null | null | null | #include "AtmosphereModel.h"
#include "../../Engine.h"
#include "../../../SnowyStream/SnowyStream.h"
#include "../../../SnowyStream/Manager/RenderResourceManager.h"
#include <cassert>
#include <cmath>
#include <iostream>
#include <memory>
// [Precomputed Atmospheric Scattering](https://hal.inria.fr/inria-00288758/en)
// https://ebruneton.github.io/precomputed_atmospheric_scattering/demo.html
/**
* Copyright (c) 2017 Eric Bruneton
* 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 holders 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.
*/
namespace Atmosphere {
using namespace PaintsNow;
static const double kLambdaR = 680.0;
static const double kLambdaG = 550.0;
static const double kLambdaB = 440.0;
static const int TRANSMITTANCE_TEXTURE_WIDTH = 256;
static const int TRANSMITTANCE_TEXTURE_HEIGHT = 64;
static const int SCATTERING_TEXTURE_R_SIZE = 32;
static const int SCATTERING_TEXTURE_MU_SIZE = 128;
static const int SCATTERING_TEXTURE_MU_S_SIZE = 32;
static const int SCATTERING_TEXTURE_NU_SIZE = 8;
static const int SCATTERING_TEXTURE_WIDTH =
SCATTERING_TEXTURE_NU_SIZE * SCATTERING_TEXTURE_MU_S_SIZE;
static const int SCATTERING_TEXTURE_HEIGHT = SCATTERING_TEXTURE_MU_SIZE;
static const int SCATTERING_TEXTURE_DEPTH = SCATTERING_TEXTURE_R_SIZE;
static const int IRRADIANCE_TEXTURE_WIDTH = 64;
static const int IRRADIANCE_TEXTURE_HEIGHT = 16;
// The conversion factor between watts and lumens.
const double MAX_LUMINOUS_EFFICACY = 683.0;
// Values from "CIE (1931) 2-deg color matching functions", see
// "http://web.archive.org/web/20081228084047/
// http://www.cvrl.org/database/data/cmfs/ciexyz31.txt".
static const double CIE_2_DEG_COLOR_MATCHING_FUNCTIONS[380] = {
360, 0.000129900000, 0.000003917000, 0.000606100000,
365, 0.000232100000, 0.000006965000, 0.001086000000,
370, 0.000414900000, 0.000012390000, 0.001946000000,
375, 0.000741600000, 0.000022020000, 0.003486000000,
380, 0.001368000000, 0.000039000000, 0.006450001000,
385, 0.002236000000, 0.000064000000, 0.010549990000,
390, 0.004243000000, 0.000120000000, 0.020050010000,
395, 0.007650000000, 0.000217000000, 0.036210000000,
400, 0.014310000000, 0.000396000000, 0.067850010000,
405, 0.023190000000, 0.000640000000, 0.110200000000,
410, 0.043510000000, 0.001210000000, 0.207400000000,
415, 0.077630000000, 0.002180000000, 0.371300000000,
420, 0.134380000000, 0.004000000000, 0.645600000000,
425, 0.214770000000, 0.007300000000, 1.039050100000,
430, 0.283900000000, 0.011600000000, 1.385600000000,
435, 0.328500000000, 0.016840000000, 1.622960000000,
440, 0.348280000000, 0.023000000000, 1.747060000000,
445, 0.348060000000, 0.029800000000, 1.782600000000,
450, 0.336200000000, 0.038000000000, 1.772110000000,
455, 0.318700000000, 0.048000000000, 1.744100000000,
460, 0.290800000000, 0.060000000000, 1.669200000000,
465, 0.251100000000, 0.073900000000, 1.528100000000,
470, 0.195360000000, 0.090980000000, 1.287640000000,
475, 0.142100000000, 0.112600000000, 1.041900000000,
480, 0.095640000000, 0.139020000000, 0.812950100000,
485, 0.057950010000, 0.169300000000, 0.616200000000,
490, 0.032010000000, 0.208020000000, 0.465180000000,
495, 0.014700000000, 0.258600000000, 0.353300000000,
500, 0.004900000000, 0.323000000000, 0.272000000000,
505, 0.002400000000, 0.407300000000, 0.212300000000,
510, 0.009300000000, 0.503000000000, 0.158200000000,
515, 0.029100000000, 0.608200000000, 0.111700000000,
520, 0.063270000000, 0.710000000000, 0.078249990000,
525, 0.109600000000, 0.793200000000, 0.057250010000,
530, 0.165500000000, 0.862000000000, 0.042160000000,
535, 0.225749900000, 0.914850100000, 0.029840000000,
540, 0.290400000000, 0.954000000000, 0.020300000000,
545, 0.359700000000, 0.980300000000, 0.013400000000,
550, 0.433449900000, 0.994950100000, 0.008749999000,
555, 0.512050100000, 1.000000000000, 0.005749999000,
560, 0.594500000000, 0.995000000000, 0.003900000000,
565, 0.678400000000, 0.978600000000, 0.002749999000,
570, 0.762100000000, 0.952000000000, 0.002100000000,
575, 0.842500000000, 0.915400000000, 0.001800000000,
580, 0.916300000000, 0.870000000000, 0.001650001000,
585, 0.978600000000, 0.816300000000, 0.001400000000,
590, 1.026300000000, 0.757000000000, 0.001100000000,
595, 1.056700000000, 0.694900000000, 0.001000000000,
600, 1.062200000000, 0.631000000000, 0.000800000000,
605, 1.045600000000, 0.566800000000, 0.000600000000,
610, 1.002600000000, 0.503000000000, 0.000340000000,
615, 0.938400000000, 0.441200000000, 0.000240000000,
620, 0.854449900000, 0.381000000000, 0.000190000000,
625, 0.751400000000, 0.321000000000, 0.000100000000,
630, 0.642400000000, 0.265000000000, 0.000049999990,
635, 0.541900000000, 0.217000000000, 0.000030000000,
640, 0.447900000000, 0.175000000000, 0.000020000000,
645, 0.360800000000, 0.138200000000, 0.000010000000,
650, 0.283500000000, 0.107000000000, 0.000000000000,
655, 0.218700000000, 0.081600000000, 0.000000000000,
660, 0.164900000000, 0.061000000000, 0.000000000000,
665, 0.121200000000, 0.044580000000, 0.000000000000,
670, 0.087400000000, 0.032000000000, 0.000000000000,
675, 0.063600000000, 0.023200000000, 0.000000000000,
680, 0.046770000000, 0.017000000000, 0.000000000000,
685, 0.032900000000, 0.011920000000, 0.000000000000,
690, 0.022700000000, 0.008210000000, 0.000000000000,
695, 0.015840000000, 0.005723000000, 0.000000000000,
700, 0.011359160000, 0.004102000000, 0.000000000000,
705, 0.008110916000, 0.002929000000, 0.000000000000,
710, 0.005790346000, 0.002091000000, 0.000000000000,
715, 0.004109457000, 0.001484000000, 0.000000000000,
720, 0.002899327000, 0.001047000000, 0.000000000000,
725, 0.002049190000, 0.000740000000, 0.000000000000,
730, 0.001439971000, 0.000520000000, 0.000000000000,
735, 0.000999949300, 0.000361100000, 0.000000000000,
740, 0.000690078600, 0.000249200000, 0.000000000000,
745, 0.000476021300, 0.000171900000, 0.000000000000,
750, 0.000332301100, 0.000120000000, 0.000000000000,
755, 0.000234826100, 0.000084800000, 0.000000000000,
760, 0.000166150500, 0.000060000000, 0.000000000000,
765, 0.000117413000, 0.000042400000, 0.000000000000,
770, 0.000083075270, 0.000030000000, 0.000000000000,
775, 0.000058706520, 0.000021200000, 0.000000000000,
780, 0.000041509940, 0.000014990000, 0.000000000000,
785, 0.000029353260, 0.000010600000, 0.000000000000,
790, 0.000020673830, 0.000007465700, 0.000000000000,
795, 0.000014559770, 0.000005257800, 0.000000000000,
800, 0.000010253980, 0.000003702900, 0.000000000000,
805, 0.000007221456, 0.000002607800, 0.000000000000,
810, 0.000005085868, 0.000001836600, 0.000000000000,
815, 0.000003581652, 0.000001293400, 0.000000000000,
820, 0.000002522525, 0.000000910930, 0.000000000000,
825, 0.000001776509, 0.000000641530, 0.000000000000,
830, 0.000001251141, 0.000000451810, 0.000000000000,
};
// The conversion matrix from XYZ to linear sRGB color spaces.
// Values from https://en.wikipedia.org/wiki/SRGB.
static const double XYZ_TO_SRGB[9] = {
+3.2406, -1.5372, -0.4986,
-0.9689, +1.8758, +0.0415,
+0.0557, -0.2040, +1.0570
};
static const int kLambdaMin = 360;
static const int kLambdaMax = 830;
static double CieColorMatchingFunctionTableValue(double wavelength, int column) {
if (wavelength <= kLambdaMin || wavelength >= kLambdaMax) {
return 0.0;
}
double u = (wavelength - kLambdaMin) / 5.0;
int row = static_cast<int>(floor(u));
assert(row >= 0 && row + 1 < 95);
assert(CIE_2_DEG_COLOR_MATCHING_FUNCTIONS[4 * row] <= wavelength &&
CIE_2_DEG_COLOR_MATCHING_FUNCTIONS[4 * (row + 1)] >= wavelength);
u -= row;
return CIE_2_DEG_COLOR_MATCHING_FUNCTIONS[4 * row + column] * (1.0 - u) +
CIE_2_DEG_COLOR_MATCHING_FUNCTIONS[4 * (row + 1) + column] * u;
}
static double Interpolate(
const std::vector<double>& wavelengths,
const std::vector<double>& wavelength_function,
double wavelength) {
assert(wavelength_function.size() == wavelengths.size());
if (wavelength < wavelengths[0]) {
return wavelength_function[0];
}
for (unsigned int i = 0; i < wavelengths.size() - 1; ++i) {
if (wavelength < wavelengths[i + 1]) {
double u =
(wavelength - wavelengths[i]) / (wavelengths[i + 1] - wavelengths[i]);
return
wavelength_function[i] * (1.0 - u) + wavelength_function[i + 1] * u;
}
}
return wavelength_function[wavelength_function.size() - 1];
}
/*
<p>We can then implement a utility function to compute the "spectral radiance to
luminance" conversion constants (see Section 14.3 in <a
href="https://arxiv.org/pdf/1612.04336.pdf">A Qualitative and Quantitative
Evaluation of 8 Clear Sky Models</a> for their definitions):
*/
// The returned constants are in lumen.nm / watt.
static void ComputeSpectralRadianceToLuminanceFactors(
const std::vector<double>& wavelengths,
const std::vector<double>& solar_irradiance,
double lambda_power, double* k_r, double* k_g, double* k_b) {
*k_r = 0.0;
*k_g = 0.0;
*k_b = 0.0;
double solar_r = Interpolate(wavelengths, solar_irradiance, kLambdaR);
double solar_g = Interpolate(wavelengths, solar_irradiance, kLambdaG);
double solar_b = Interpolate(wavelengths, solar_irradiance, kLambdaB);
int dlambda = 1;
for (int lambda = kLambdaMin; lambda < kLambdaMax; lambda += dlambda) {
double x_bar = CieColorMatchingFunctionTableValue(lambda, 1);
double y_bar = CieColorMatchingFunctionTableValue(lambda, 2);
double z_bar = CieColorMatchingFunctionTableValue(lambda, 3);
const double* xyz2srgb = XYZ_TO_SRGB;
double r_bar =
xyz2srgb[0] * x_bar + xyz2srgb[1] * y_bar + xyz2srgb[2] * z_bar;
double g_bar =
xyz2srgb[3] * x_bar + xyz2srgb[4] * y_bar + xyz2srgb[5] * z_bar;
double b_bar =
xyz2srgb[6] * x_bar + xyz2srgb[7] * y_bar + xyz2srgb[8] * z_bar;
double irradiance = Interpolate(wavelengths, solar_irradiance, lambda);
*k_r += r_bar * irradiance / solar_r *
pow(lambda / kLambdaR, lambda_power);
*k_g += g_bar * irradiance / solar_g *
pow(lambda / kLambdaG, lambda_power);
*k_b += b_bar * irradiance / solar_b *
pow(lambda / kLambdaB, lambda_power);
}
*k_r *= MAX_LUMINOUS_EFFICACY * dlambda;
*k_g *= MAX_LUMINOUS_EFFICACY * dlambda;
*k_b *= MAX_LUMINOUS_EFFICACY * dlambda;
}
static TShared<TextureResource> NewTexture2d(Engine& engine, int width, int height) {
IRender::Queue* resourceQueue = engine.snowyStream.GetRenderResourceManager()->GetWarpResourceQueue();
TShared<TextureResource> texture = engine.snowyStream.CreateReflectedResource(UniqueType<TextureResource>(), "", false, ResourceBase::RESOURCE_VIRTUAL);
IRender::Resource::TextureDescription::State& state = texture->description.state;
state.addressU = state.addressV = state.addressW = IRender::Resource::TextureDescription::CLAMP;
state.sample = IRender::Resource::TextureDescription::LINEAR;
state.format = IRender::Resource::TextureDescription::FLOAT;
state.layout = IRender::Resource::TextureDescription::RGBA;
state.attachment = 1;
UShort3& dimension = texture->description.dimension;
dimension.x() = width;
dimension.y() = height;
texture->Flag().fetch_or(Tiny::TINY_MODIFIED, std::memory_order_relaxed);
texture->GetResourceManager().InvokeUpload(texture(), resourceQueue);
return texture;
}
static TShared<TextureResource> NewTexture3d(Engine& engine, int width, int height, int depth, bool half_precision) {
IRender::Queue* resourceQueue = engine.snowyStream.GetRenderResourceManager()->GetWarpResourceQueue();
TShared<TextureResource> texture = engine.snowyStream.CreateReflectedResource(UniqueType<TextureResource>(), "", false, ResourceBase::RESOURCE_VIRTUAL);
IRender::Resource::TextureDescription::State& state = texture->description.state;
state.type = IRender::Resource::TextureDescription::TEXTURE_3D;
state.addressU = state.addressV = state.addressW = IRender::Resource::TextureDescription::CLAMP;
state.sample = IRender::Resource::TextureDescription::LINEAR;
state.format = half_precision ? IRender::Resource::TextureDescription::HALF : IRender::Resource::TextureDescription::FLOAT;
state.layout = IRender::Resource::TextureDescription::RGBA;
state.attachment = 1;
UShort3& dimension = texture->description.dimension;
dimension.x() = width;
dimension.y() = height;
dimension.z() = depth;
texture->Flag().fetch_or(Tiny::TINY_MODIFIED, std::memory_order_relaxed);
texture->GetResourceManager().InvokeUpload(texture(), resourceQueue);
return texture;
}
/*<h3 id="implementation">Model implementation</h3>
<p>Using the above utility functions and classes, we can now implement the
constructor of the <code>Model</code> class. This constructor generates a piece
of GLSL code that defines an <code>ATMOSPHERE</code> constant containing the
atmosphere parameters (we use constants instead of uniforms to enable constant
folding and propagation optimizations in the GLSL compiler), concatenated with
<a href="functions.glsl.html">functions.glsl</a>, and with
<code>kAtmosphereShader</code>, to get the shader exposed by our API in
<code>GetShader</code>. It also allocates the precomputed textures (but does not
initialize them), as well as a vertex buffer object to render a full screen quad
(used to render into the precomputed textures).
*/
Model::Model(
Engine& engine,
const std::vector<double>& wavelengths,
const std::vector<double>& solar_irradiance,
const double sun_angular_radius,
double bottom_radius,
double top_radius,
const std::vector<DensityProfileLayer>& rayleigh_density,
const std::vector<double>& rayleigh_scattering,
const std::vector<DensityProfileLayer>& mie_density,
const std::vector<double>& mie_scattering,
const std::vector<double>& mie_extinction,
double mie_phase_function_g,
const std::vector<DensityProfileLayer>& absorption_density,
const std::vector<double>& absorption_extinction,
const std::vector<double>& ground_albedo,
double max_sun_zenith_angle,
double length_unit_in_meters,
unsigned int num_precomputed_wavelengths,
bool combine_scattering_textures,
bool half_precision) :
num_precomputed_wavelengths_(num_precomputed_wavelengths),
half_precision_(half_precision) {
// Compute the values for the SKY_RADIANCE_TO_LUMINANCE constant. In theory
// this should be 1 in precomputed illuminance mode (because the precomputed
// textures already contain illuminance values). In practice, however, storing
// true illuminance values in half precision textures yields artefacts
// (because the values are too large), so we store illuminance values divided
// by MAX_LUMINOUS_EFFICACY instead. This is why, in precomputed illuminance
// mode, we set SKY_RADIANCE_TO_LUMINANCE to MAX_LUMINOUS_EFFICACY.
bool precompute_illuminance = num_precomputed_wavelengths > 3;
double sky_k_r, sky_k_g, sky_k_b;
if (precompute_illuminance) {
sky_k_r = sky_k_g = sky_k_b = MAX_LUMINOUS_EFFICACY;
}
else {
ComputeSpectralRadianceToLuminanceFactors(wavelengths, solar_irradiance,
-3 /* lambda_power */, &sky_k_r, &sky_k_g, &sky_k_b);
}
// Compute the values for the SUN_RADIANCE_TO_LUMINANCE constant.
double sun_k_r, sun_k_g, sun_k_b;
ComputeSpectralRadianceToLuminanceFactors(wavelengths, solar_irradiance,
0 /* lambda_power */, &sun_k_r, &sun_k_g, &sun_k_b);
// Allocate the precomputed textures, but don't precompute them yet.
transmittance_texture_ = NewTexture2d(engine,
TRANSMITTANCE_TEXTURE_WIDTH, TRANSMITTANCE_TEXTURE_HEIGHT);
scattering_texture_ = NewTexture3d(engine,
SCATTERING_TEXTURE_WIDTH,
SCATTERING_TEXTURE_HEIGHT,
SCATTERING_TEXTURE_DEPTH,
half_precision);
if (combine_scattering_textures) {
optional_single_mie_scattering_texture_ = 0;
}
else {
optional_single_mie_scattering_texture_ = NewTexture3d(
engine,
SCATTERING_TEXTURE_WIDTH,
SCATTERING_TEXTURE_HEIGHT,
SCATTERING_TEXTURE_DEPTH,
half_precision);
}
irradiance_texture_ = NewTexture2d(engine,
IRRADIANCE_TEXTURE_WIDTH, IRRADIANCE_TEXTURE_HEIGHT);
// Create and compile the shader providing our API.
/*
std::string shader =
glsl_header_factory_({ kLambdaR, kLambdaG, kLambdaB }) +
(precompute_illuminance ? "" : "#define RADIANCE_API_ENABLED\n") +
kAtmosphereShader;
const char* source = shader.c_str();
atmosphere_shader_ = glCreateShader(GL_FRAGMENT_SHADER);
glShaderSource(atmosphere_shader_, 1, &source, NULL);
glCompileShader(atmosphere_shader_);
// Create a full screen quad vertex array and vertex buffer objects.
glGenVertexArrays(1, &full_screen_quad_vao_);
glBindVertexArray(full_screen_quad_vao_);
glGenBuffers(1, &full_screen_quad_vbo_);
glBindBuffer(GL_ARRAY_BUFFER, full_screen_quad_vbo_);
const GLfloat vertices[] = {
-1.0, -1.0,
+1.0, -1.0,
-1.0, +1.0,
+1.0, +1.0,
};
const int kCoordsPerVertex = 2;
glBufferData(GL_ARRAY_BUFFER, sizeof vertices, vertices, GL_STATIC_DRAW);
const uint32_t kAttribIndex = 0;
glVertexAttribPointer(kAttribIndex, kCoordsPerVertex, GL_FLOAT, false, 0, 0);
glEnableVertexAttribArray(kAttribIndex);
glBindVertexArray(0);
*/
}
/*
<p>The destructor is trivial:
*/
Model::~Model() {}
/*
<p>The Init method precomputes the atmosphere textures. It first allocates the
temporary resources it needs, then calls <code>Precompute</code> to do the
actual precomputations, and finally destroys the temporary resources.
<p>Note that there are two precomputation modes here, depending on whether we
want to store precomputed irradiance or illuminance values:
<ul>
<li>In precomputed irradiance mode, we simply need to call
<code>Precompute</code> with the 3 wavelengths for which we want to precompute
irradiance, namely <code>kLambdaR</code>, <code>kLambdaG</code>,
<code>kLambdaB</code> (with the identity matrix for
<code>luminance_from_radiance</code>, since we don't want any conversion from
radiance to luminance)</li>
<li>In precomputed illuminance mode, we need to precompute irradiance for
<code>num_precomputed_wavelengths_</code>, and then integrate the results,
multiplied with the 3 CIE xyz color matching functions and the XYZ to sRGB
matrix to get sRGB illuminance values.
<p>A naive solution would be to allocate temporary textures for the
intermediate irradiance results, then perform the integration from irradiance
to illuminance and store the result in the final precomputed texture. In
pseudo-code (and assuming one wavelength per texture instead of 3):
<pre>
create n temporary irradiance textures
for each wavelength lambda in the n wavelengths:
precompute irradiance at lambda into one of the temporary textures
initializes the final illuminance texture with zeros
for each wavelength lambda in the n wavelengths:
accumulate in the final illuminance texture the product of the
precomputed irradiance at lambda (read from the temporary textures)
with the value of the 3 sRGB color matching functions at lambda (i.e.
the product of the XYZ to sRGB matrix with the CIE xyz color matching
functions).
</pre>
<p>However, this be would waste GPU memory. Instead, we can avoid allocating
temporary irradiance textures, by merging the two above loops:
<pre>
for each wavelength lambda in the n wavelengths:
accumulate in the final illuminance texture (or, for the first
iteration, set this texture to) the product of the precomputed
irradiance at lambda (computed on the fly) with the value of the 3
sRGB color matching functions at lambda.
</pre>
<p>This is the method we use below, with 3 wavelengths per iteration instead
of 1, using <code>Precompute</code> to compute 3 irradiances values per
iteration, and <code>luminance_from_radiance</code> to multiply 3 irradiances
with the values of the 3 sRGB color matching functions at 3 different
wavelengths (yielding a 3x3 matrix).</li>
</ul>
<p>This yields the following implementation:
*/
void Model::Init(unsigned int num_scattering_orders) {
// The precomputations require temporary textures, in particular to store the
// contribution of one scattering order, which is needed to compute the next
// order of scattering (the final precomputed textures store the sum of all
// the scattering orders). We allocate them here, and destroy them at the end
// of this method.
/*
uint32_t delta_irradiance_texture = NewTexture2d(
IRRADIANCE_TEXTURE_WIDTH, IRRADIANCE_TEXTURE_HEIGHT);
uint32_t delta_rayleigh_scattering_texture = NewTexture3d(
SCATTERING_TEXTURE_WIDTH,
SCATTERING_TEXTURE_HEIGHT,
SCATTERING_TEXTURE_DEPTH,
rgb_format_supported_ ? GL_RGB : GL_RGBA,
half_precision_);
uint32_t delta_mie_scattering_texture = NewTexture3d(
SCATTERING_TEXTURE_WIDTH,
SCATTERING_TEXTURE_HEIGHT,
SCATTERING_TEXTURE_DEPTH,
rgb_format_supported_ ? GL_RGB : GL_RGBA,
half_precision_);
uint32_t delta_scattering_density_texture = NewTexture3d(
SCATTERING_TEXTURE_WIDTH,
SCATTERING_TEXTURE_HEIGHT,
SCATTERING_TEXTURE_DEPTH,
rgb_format_supported_ ? GL_RGB : GL_RGBA,
half_precision_);
// delta_multiple_scattering_texture is only needed to compute scattering
// order 3 or more, while delta_rayleigh_scattering_texture and
// delta_mie_scattering_texture are only needed to compute double scattering.
// Therefore, to save memory, we can store delta_rayleigh_scattering_texture
// and delta_multiple_scattering_texture in the same GPU texture.
uint32_t delta_multiple_scattering_texture = delta_rayleigh_scattering_texture;
// The precomputations also require a temporary framebuffer object, created
// here (and destroyed at the end of this method).
uint32_t fbo;
glGenFramebuffers(1, &fbo);
glBindFramebuffer(GL_FRAMEBUFFER, fbo);
// The actual precomputations depend on whether we want to store precomputed
// irradiance or illuminance values.
if (num_precomputed_wavelengths_ <= 3) {
vec3 lambdas{ kLambdaR, kLambdaG, kLambdaB };
mat3 luminance_from_radiance{ 1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0 };
Precompute(fbo, delta_irradiance_texture, delta_rayleigh_scattering_texture,
delta_mie_scattering_texture, delta_scattering_density_texture,
delta_multiple_scattering_texture, lambdas, luminance_from_radiance,
false, num_scattering_orders);
}
else {
const double kLambdaMin = 360.0;
const double kLambdaMax = 830.0;
int num_iterations = (num_precomputed_wavelengths_ + 2) / 3;
double dlambda = (kLambdaMax - kLambdaMin) / (3 * num_iterations);
for (int i = 0; i < num_iterations; ++i) {
vec3 lambdas{
kLambdaMin + (3 * i + 0.5) * dlambda,
kLambdaMin + (3 * i + 1.5) * dlambda,
kLambdaMin + (3 * i + 2.5) * dlambda
};
auto coeff = [dlambda](double lambda, int component) {
// Note that we don't include MAX_LUMINOUS_EFFICACY here, to avoid
// artefacts due to too large values when using half precision on GPU.
// We add this term back in kAtmosphereShader, via
// SKY_SPECTRAL_RADIANCE_TO_LUMINANCE (see also the comments in the
// Model constructor).
double x = CieColorMatchingFunctionTableValue(lambda, 1);
double y = CieColorMatchingFunctionTableValue(lambda, 2);
double z = CieColorMatchingFunctionTableValue(lambda, 3);
return static_cast<float>((
XYZ_TO_SRGB[component * 3] * x +
XYZ_TO_SRGB[component * 3 + 1] * y +
XYZ_TO_SRGB[component * 3 + 2] * z) * dlambda);
};
mat3 luminance_from_radiance{
coeff(lambdas[0], 0), coeff(lambdas[1], 0), coeff(lambdas[2], 0),
coeff(lambdas[0], 1), coeff(lambdas[1], 1), coeff(lambdas[2], 1),
coeff(lambdas[0], 2), coeff(lambdas[1], 2), coeff(lambdas[2], 2)
};
Precompute(fbo, delta_irradiance_texture,
delta_rayleigh_scattering_texture, delta_mie_scattering_texture,
delta_scattering_density_texture, delta_multiple_scattering_texture,
lambdas, luminance_from_radiance, i > 0,
num_scattering_orders);
}
// After the above iterations, the transmittance texture contains the
// transmittance for the 3 wavelengths used at the last iteration. But we
// want the transmittance at kLambdaR, kLambdaG, kLambdaB instead, so we
// must recompute it here for these 3 wavelengths:
std::string header = glsl_header_factory_({ kLambdaR, kLambdaG, kLambdaB });
Program compute_transmittance(
kVertexShader, header + kComputeTransmittanceShader);
glFramebufferTexture(
GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, transmittance_texture_, 0);
glDrawBuffer(GL_COLOR_ATTACHMENT0);
glViewport(0, 0, TRANSMITTANCE_TEXTURE_WIDTH, TRANSMITTANCE_TEXTURE_HEIGHT);
compute_transmittance.Use();
DrawQuad({}, full_screen_quad_vao_);
}
// Delete the temporary resources allocated at the begining of this method.
glUseProgram(0);
glBindFramebuffer(GL_FRAMEBUFFER, 0);
glDeleteFramebuffers(1, &fbo);
glDeleteTextures(1, &delta_scattering_density_texture);
glDeleteTextures(1, &delta_mie_scattering_texture);
glDeleteTextures(1, &delta_rayleigh_scattering_texture);
glDeleteTextures(1, &delta_irradiance_texture);
assert(glGetError() == 0);
*/
}
/*
<p>The <code>SetProgramUniforms</code> method is straightforward: it simply
binds the precomputed textures to the specified texture units, and then sets
the corresponding uniforms in the user provided program to the index of these
texture units.
*/
void Model::SetProgramUniforms(
uint32_t program,
uint32_t transmittance_texture_unit,
uint32_t scattering_texture_unit,
uint32_t irradiance_texture_unit,
uint32_t single_mie_scattering_texture_unit) const {
/*
glActiveTexture(GL_TEXTURE0 + transmittance_texture_unit);
glBindTexture(GL_TEXTURE_2D, transmittance_texture_);
glUniform1i(glGetUniformLocation(program, "transmittance_texture"),
transmittance_texture_unit);
glActiveTexture(GL_TEXTURE0 + scattering_texture_unit);
glBindTexture(GL_TEXTURE_3D, scattering_texture_);
glUniform1i(glGetUniformLocation(program, "scattering_texture"),
scattering_texture_unit);
glActiveTexture(GL_TEXTURE0 + irradiance_texture_unit);
glBindTexture(GL_TEXTURE_2D, irradiance_texture_);
glUniform1i(glGetUniformLocation(program, "irradiance_texture"),
irradiance_texture_unit);
if (optional_single_mie_scattering_texture_ != 0) {
glActiveTexture(GL_TEXTURE0 + single_mie_scattering_texture_unit);
glBindTexture(GL_TEXTURE_3D, optional_single_mie_scattering_texture_);
glUniform1i(glGetUniformLocation(program, "single_mie_scattering_texture"),
single_mie_scattering_texture_unit);
}
*/
}
/*
<p>The utility method <code>ConvertSpectrumToLinearSrgb</code> is implemented
with a simple numerical integration of the given function, times the CIE color
matching funtions (with an integration step of 1nm), followed by a matrix
multiplication:
*/
void Model::ConvertSpectrumToLinearSrgb(
const std::vector<double>& wavelengths,
const std::vector<double>& spectrum,
double* r, double* g, double* b) {
double x = 0.0;
double y = 0.0;
double z = 0.0;
const int dlambda = 1;
for (int lambda = kLambdaMin; lambda < kLambdaMax; lambda += dlambda) {
double value = Interpolate(wavelengths, spectrum, lambda);
x += CieColorMatchingFunctionTableValue(lambda, 1) * value;
y += CieColorMatchingFunctionTableValue(lambda, 2) * value;
z += CieColorMatchingFunctionTableValue(lambda, 3) * value;
}
*r = MAX_LUMINOUS_EFFICACY *
(XYZ_TO_SRGB[0] * x + XYZ_TO_SRGB[1] * y + XYZ_TO_SRGB[2] * z) * dlambda;
*g = MAX_LUMINOUS_EFFICACY *
(XYZ_TO_SRGB[3] * x + XYZ_TO_SRGB[4] * y + XYZ_TO_SRGB[5] * z) * dlambda;
*b = MAX_LUMINOUS_EFFICACY *
(XYZ_TO_SRGB[6] * x + XYZ_TO_SRGB[7] * y + XYZ_TO_SRGB[8] * z) * dlambda;
}
/*
<p>Finally, we provide the actual implementation of the precomputation algorithm
described in Algorithm 4.1 of
<a href="https://hal.inria.fr/inria-00288758/en">our paper</a>. Each step is
explained by the inline comments below.
*/
void Model::Precompute(
const TShared<TextureResource>& delta_irradiance_texture,
const TShared<TextureResource>& delta_rayleigh_scattering_texture,
const TShared<TextureResource>& delta_mie_scattering_texture,
const TShared<TextureResource>& delta_scattering_density_texture,
const TShared<TextureResource>& delta_multiple_scattering_texture,
const Float3& lambdas,
const MatrixFloat3x3& luminance_from_radiance,
bool blend,
unsigned int num_scattering_orders) {
/*
// The precomputations require specific GLSL programs, for each precomputation
// step. We create and compile them here (they are automatically destroyed
// when this method returns, via the Program destructor).
std::string header = glsl_header_factory_(lambdas);
Program compute_transmittance(
kVertexShader, header + kComputeTransmittanceShader);
Program compute_direct_irradiance(
kVertexShader, header + kComputeDirectIrradianceShader);
Program compute_single_scattering(kVertexShader, kGeometryShader,
header + kComputeSingleScatteringShader);
Program compute_scattering_density(kVertexShader, kGeometryShader,
header + kComputeScatteringDensityShader);
Program compute_indirect_irradiance(
kVertexShader, header + kComputeIndirectIrradianceShader);
Program compute_multiple_scattering(kVertexShader, kGeometryShader,
header + kComputeMultipleScatteringShader);
const uint32_t kDrawBuffers[4] = {
GL_COLOR_ATTACHMENT0,
GL_COLOR_ATTACHMENT1,
GL_COLOR_ATTACHMENT2,
GL_COLOR_ATTACHMENT3
};
glBlendEquationSeparate(GL_FUNC_ADD, GL_FUNC_ADD);
glBlendFuncSeparate(GL_ONE, GL_ONE, GL_ONE, GL_ONE);
// Compute the transmittance, and store it in transmittance_texture_.
glFramebufferTexture(
GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, transmittance_texture_, 0);
glDrawBuffer(GL_COLOR_ATTACHMENT0);
glViewport(0, 0, TRANSMITTANCE_TEXTURE_WIDTH, TRANSMITTANCE_TEXTURE_HEIGHT);
compute_transmittance.Use();
DrawQuad({}, full_screen_quad_vao_);
// Compute the direct irradiance, store it in delta_irradiance_texture and,
// depending on 'blend', either initialize irradiance_texture_ with zeros or
// leave it unchanged (we don't want the direct irradiance in
// irradiance_texture_, but only the irradiance from the sky).
glFramebufferTexture(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0,
delta_irradiance_texture, 0);
glFramebufferTexture(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT1,
irradiance_texture_, 0);
glDrawBuffers(2, kDrawBuffers);
glViewport(0, 0, IRRADIANCE_TEXTURE_WIDTH, IRRADIANCE_TEXTURE_HEIGHT);
compute_direct_irradiance.Use();
compute_direct_irradiance.BindTexture2d(
"transmittance_texture", transmittance_texture_, 0);
DrawQuad({ false, blend }, full_screen_quad_vao_);
// Compute the rayleigh and mie single scattering, store them in
// delta_rayleigh_scattering_texture and delta_mie_scattering_texture, and
// either store them or accumulate them in scattering_texture_ and
// optional_single_mie_scattering_texture_.
glFramebufferTexture(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0,
delta_rayleigh_scattering_texture, 0);
glFramebufferTexture(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT1,
delta_mie_scattering_texture, 0);
glFramebufferTexture(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT2,
scattering_texture_, 0);
if (optional_single_mie_scattering_texture_ != 0) {
glFramebufferTexture(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT3,
optional_single_mie_scattering_texture_, 0);
glDrawBuffers(4, kDrawBuffers);
}
else {
glDrawBuffers(3, kDrawBuffers);
}
glViewport(0, 0, SCATTERING_TEXTURE_WIDTH, SCATTERING_TEXTURE_HEIGHT);
compute_single_scattering.Use();
compute_single_scattering.BindMat3(
"luminance_from_radiance", luminance_from_radiance);
compute_single_scattering.BindTexture2d(
"transmittance_texture", transmittance_texture_, 0);
for (unsigned int layer = 0; layer < SCATTERING_TEXTURE_DEPTH; ++layer) {
compute_single_scattering.BindInt("layer", layer);
DrawQuad({ false, false, blend, blend }, full_screen_quad_vao_);
}
// Compute the 2nd, 3rd and 4th order of scattering, in sequence.
for (unsigned int scattering_order = 2;
scattering_order <= num_scattering_orders;
++scattering_order) {
// Compute the scattering density, and store it in
// delta_scattering_density_texture.
glFramebufferTexture(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0,
delta_scattering_density_texture, 0);
glFramebufferTexture(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT1, 0, 0);
glFramebufferTexture(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT2, 0, 0);
glFramebufferTexture(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT3, 0, 0);
glDrawBuffer(GL_COLOR_ATTACHMENT0);
glViewport(0, 0, SCATTERING_TEXTURE_WIDTH, SCATTERING_TEXTURE_HEIGHT);
compute_scattering_density.Use();
compute_scattering_density.BindTexture2d(
"transmittance_texture", transmittance_texture_, 0);
compute_scattering_density.BindTexture3d(
"single_rayleigh_scattering_texture",
delta_rayleigh_scattering_texture,
1);
compute_scattering_density.BindTexture3d(
"single_mie_scattering_texture", delta_mie_scattering_texture, 2);
compute_scattering_density.BindTexture3d(
"multiple_scattering_texture", delta_multiple_scattering_texture, 3);
compute_scattering_density.BindTexture2d(
"irradiance_texture", delta_irradiance_texture, 4);
compute_scattering_density.BindInt("scattering_order", scattering_order);
for (unsigned int layer = 0; layer < SCATTERING_TEXTURE_DEPTH; ++layer) {
compute_scattering_density.BindInt("layer", layer);
DrawQuad({}, full_screen_quad_vao_);
}
// Compute the indirect irradiance, store it in delta_irradiance_texture and
// accumulate it in irradiance_texture_.
glFramebufferTexture(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0,
delta_irradiance_texture, 0);
glFramebufferTexture(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT1,
irradiance_texture_, 0);
glDrawBuffers(2, kDrawBuffers);
glViewport(0, 0, IRRADIANCE_TEXTURE_WIDTH, IRRADIANCE_TEXTURE_HEIGHT);
compute_indirect_irradiance.Use();
compute_indirect_irradiance.BindMat3(
"luminance_from_radiance", luminance_from_radiance);
compute_indirect_irradiance.BindTexture3d(
"single_rayleigh_scattering_texture",
delta_rayleigh_scattering_texture,
0);
compute_indirect_irradiance.BindTexture3d(
"single_mie_scattering_texture", delta_mie_scattering_texture, 1);
compute_indirect_irradiance.BindTexture3d(
"multiple_scattering_texture", delta_multiple_scattering_texture, 2);
compute_indirect_irradiance.BindInt("scattering_order",
scattering_order - 1);
DrawQuad({ false, true }, full_screen_quad_vao_);
// Compute the multiple scattering, store it in
// delta_multiple_scattering_texture, and accumulate it in
// scattering_texture_.
glFramebufferTexture(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0,
delta_multiple_scattering_texture, 0);
glFramebufferTexture(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT1,
scattering_texture_, 0);
glDrawBuffers(2, kDrawBuffers);
glViewport(0, 0, SCATTERING_TEXTURE_WIDTH, SCATTERING_TEXTURE_HEIGHT);
compute_multiple_scattering.Use();
compute_multiple_scattering.BindMat3(
"luminance_from_radiance", luminance_from_radiance);
compute_multiple_scattering.BindTexture2d(
"transmittance_texture", transmittance_texture_, 0);
compute_multiple_scattering.BindTexture3d(
"scattering_density_texture", delta_scattering_density_texture, 1);
for (unsigned int layer = 0; layer < SCATTERING_TEXTURE_DEPTH; ++layer) {
compute_multiple_scattering.BindInt("layer", layer);
DrawQuad({ false, true }, full_screen_quad_vao_);
}
}
glFramebufferTexture(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT1, 0, 0);
glFramebufferTexture(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT2, 0, 0);
glFramebufferTexture(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT3, 0, 0);
*/
}
} // namespace atmosphere
| 45.516949 | 154 | 0.763545 | [
"render",
"object",
"vector",
"model"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.