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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
2d71e53ef0fe60bfaf3f27660ba5cb7856a5c0d2 | 2,108 | cpp | C++ | tests/cpp/test_quiver_cpu.cpp | jakeKonrad/torch-quiver | 16e01b8b61459ae41b7386b6a57ef9d20dfb6606 | [
"Apache-2.0"
] | 196 | 2021-10-30T23:40:27.000Z | 2022-03-28T03:43:18.000Z | tests/cpp/test_quiver_cpu.cpp | jakeKonrad/torch-quiver | 16e01b8b61459ae41b7386b6a57ef9d20dfb6606 | [
"Apache-2.0"
] | 32 | 2021-11-03T15:07:50.000Z | 2022-03-07T09:03:33.000Z | tests/cpp/test_quiver_cpu.cpp | jakeKonrad/torch-quiver | 16e01b8b61459ae41b7386b6a57ef9d20dfb6606 | [
"Apache-2.0"
] | 24 | 2021-10-31T12:28:34.000Z | 2022-03-19T03:03:13.000Z | #include <algorithm>
#include <unordered_set>
#include <vector>
#include <quiver/quiver.cpu.hpp>
#include "testing.hpp"
class simple_graph
{
int nodes_;
int neighbor_;
std::vector<std::pair<int64_t, int64_t>> edges_;
public:
simple_graph(int N, int neighbor)
: nodes_(N), neighbor_(neighbor), edges_(N * neighbor)
{
for (int i = 0; i < N; i++) {
size_t index = i * neighbor;
for (int j = 0; j < neighbor; j++) {
int64_t src = i;
int64_t dst = (j + 1) * N + i;
edges_[index + j] = std::make_pair(src, dst);
}
}
}
std::vector<std::pair<int64_t, int64_t>> get_edges() { return edges_; }
};
bool is_sample_valid(int N, int num_neighbor, std::vector<int64_t> outputs,
std::vector<int64_t> output_counts)
{
size_t index = 0;
if (output_counts.size() != N) { return false; }
for (int i = 0; i < N; i++) {
int cnt = output_counts[i];
std::unordered_set<int64_t> neighbors;
for (int k = 0; k < num_neighbor; k++) {
neighbors.insert((k + 1) * N + i);
}
for (int j = 0; j < cnt; j++) {
int64_t neighbor = outputs[index++];
if (neighbors.find(neighbor) == neighbors.end()) { return false; }
neighbors.erase(neighbor);
}
}
if (outputs.size() != index) { return false; }
return true;
}
using V = int64_t;
using Quiver = quiver::quiver<V, quiver::CPU>;
void test_sample_kernel(int N, int neighbor, int k)
{
auto g = simple_graph(N, neighbor);
Quiver q(N, g.get_edges());
std::vector<V> inputs(N);
std::iota(inputs.begin(), inputs.end(), 0);
auto res = q.sample_kernel(inputs, k);
std::vector<V> outputs = std::get<0>(res);
std::vector<V> output_counts = std::get<1>(res);
bool ok = is_sample_valid(N, neighbor, outputs, output_counts);
ASSERT_TRUE(ok);
}
TEST(test_quiver_cpu, test_1)
{
test_sample_kernel(10, 5, 10);
test_sample_kernel(100, 10, 5);
test_sample_kernel(1000, 10, 10);
}
| 27.736842 | 78 | 0.569734 | [
"vector"
] |
2d7201b11826f8ff797293f970cd3085e7cde6cf | 5,964 | hpp | C++ | iceoryx_hoofs/include/iceoryx_hoofs/internal/relocatable_pointer/relocatable_ptr.hpp | sloretz/iceoryx | 6ca4d0ad7122bda725c697b7b9cf3fd8ae73b51d | [
"Apache-2.0"
] | 560 | 2021-01-09T11:09:16.000Z | 2022-03-29T15:55:08.000Z | iceoryx_hoofs/include/iceoryx_hoofs/internal/relocatable_pointer/relocatable_ptr.hpp | sloretz/iceoryx | 6ca4d0ad7122bda725c697b7b9cf3fd8ae73b51d | [
"Apache-2.0"
] | 779 | 2021-01-05T08:46:43.000Z | 2022-03-31T17:45:11.000Z | iceoryx_hoofs/include/iceoryx_hoofs/internal/relocatable_pointer/relocatable_ptr.hpp | sloretz/iceoryx | 6ca4d0ad7122bda725c697b7b9cf3fd8ae73b51d | [
"Apache-2.0"
] | 122 | 2021-01-11T02:06:26.000Z | 2022-03-31T20:00:26.000Z | // Copyright (c) 2021 by Apex.AI Inc. 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.
//
// SPDX-License-Identifier: Apache-2.0
#ifndef IOX_HOOFS_RELOCATABLE_POINTER_RELOCATABLE_PTR_HPP
#define IOX_HOOFS_RELOCATABLE_POINTER_RELOCATABLE_PTR_HPP
#include <cstdint>
#include <type_traits>
namespace iox
{
namespace rp
{
/// @brief Smart pointer type that allows objects using it to able to be copied by memcpy
/// without invalidating the pointer.
/// This applies only if it points to memory owned by the object itself
/// (i.e. not to memory outside of the object).
/// This is useful to improve copy-efficiency and allow the types build with relocatable
/// pointers only to be stored in shared memory.
/// It is useable like a raw pointer of the corresponding type and can be implicily
/// converted to one.
///
/// @tparam T the native type wrapped by the relocatable_ptr, i.e. relocatable_ptr<T>
/// has native type T and corresponds to a raw pointer of type T*.
///
/// @note It is advisable to use relocatable_ptr only for storage (e.g. member variables),
/// not to pass them around as function arguments or as return value.
/// There should be no need for this, since as pass-around type
/// regular pointers do the job just fine and do not incur
/// the slight runtime overhead of a relocatable_ptr.
/// There should be no memory overhead on 64 bit systems.
/// @note relocatable_ptr is not trivially copyable since in general the copy constructor
/// requires additional logic. Hence obects that contain it re not trivially
/// copyable in the C++ sense. However, if the pointees of a host object containing the
/// relocatable ptr are all located inside the object and the obect is otherwise trivially
/// copyable it can be safely copied by memcpy.
/// @todo specialize for another pointer class for this use case once it is fully defined/understood
template <typename T>
class relocatable_ptr
{
public:
using ptr_t = T*;
/// @brief Construct from raw pointer.
relocatable_ptr(T* ptr = nullptr) noexcept;
/// @brief Construct from other relocatable pointer.
relocatable_ptr(const relocatable_ptr& other) noexcept;
/// @brief Move construct from other relocatable pointer.
relocatable_ptr(relocatable_ptr&& other);
/// @brief Assign from relocatable pointer rhs.
relocatable_ptr& operator=(const relocatable_ptr& rhs) noexcept;
/// @brief Move assign from relocatable pointer rhs.
relocatable_ptr& operator=(relocatable_ptr&& rhs) noexcept;
/// @brief Get the corresponding raw pointer.
/// @return corresponding raw pointer
T* get() noexcept;
/// @brief Get the corresponding raw pointer from const relocatable_ptr
/// @return corresponding raw pointer
const T* get() const noexcept;
/// @brief Dereference a relocatable_ptr.
/// @return reference to the pointee
/// @note not available for T=void
template <typename S = T>
S& operator*() noexcept;
/// @brief Dereference a const relocatable_ptr.
/// @return reference to the pointee
/// @note not available for T=void
template <typename S = T>
const S& operator*() const noexcept;
/// @brief Get the corresponding raw pointer with arrow operator syntax.
/// @return corresponding raw pointer
T* operator->() noexcept;
/// @brief Get the corresponding raw pointer with arrow operator syntax
/// from a const relocatable_ptr.
/// @return corresponding raw pointer
const T* operator->() const noexcept;
/// @brief Convert to the corresponding raw pointer.
/// @return corresponding raw pointer
operator T*() noexcept;
/// @brief Convert to the corresponding const raw pointer.
/// @return corresponding const raw pointer
operator const T*() const noexcept;
private:
using offset_t = uint64_t;
offset_t self() const noexcept;
offset_t to_offset(const void* ptr) const noexcept;
T* from_offset(offset_t offset) const noexcept;
private:
// This is safe since it is equivalent to point to the relocatable pointer
// second byte of the relocatable pointer itself which we define to be illegal.
// (it is no reasonable use-case)
// Note that 0 is equivalent to point to the relocatable pointer itself.
// This is needed if say the relocatable ptr is the first member in some class like
// struct Foo {
// relocatable_ptr<Foo> rp;
// }
// Since Foo and rp have the same address (this), we need the 0 offset to allow
// rp to point to Foo itself.
static constexpr offset_t NULL_POINTER_OFFSET = 1;
offset_t m_offset;
};
/// @brief Compare relocatable_ptr with respect to logical equality.
/// @return true if rhs and lhs point to the same location, false otherwise
template <typename T>
bool operator==(const relocatable_ptr<T>& lhs, const relocatable_ptr<T>& rhs) noexcept;
/// @brief Compare relocatable_ptr with respect to logical inequality.
/// @return true if rhs and lhs point to a different location, false otherwise
template <typename T>
bool operator!=(const relocatable_ptr<T>& lhs, const relocatable_ptr<T>& rhs) noexcept;
} // namespace rp
} // namespace iox
#include "iceoryx_hoofs/internal/relocatable_pointer/relocatable_ptr.inl"
#endif // IOX_HOOFS_RELOCATABLE_POINTER_RELOCATABLE_PTR_HPP | 40.026846 | 100 | 0.715292 | [
"object"
] |
2d749a350732005cbcd0dcf9d7fd7d1c5992826c | 4,866 | cc | C++ | vpc/src/model/DescribeRouteTableListRequest.cc | iamzken/aliyun-openapi-cpp-sdk | 3c991c9ca949b6003c8f498ce7a672ea88162bf1 | [
"Apache-2.0"
] | 89 | 2018-02-02T03:54:39.000Z | 2021-12-13T01:32:55.000Z | vpc/src/model/DescribeRouteTableListRequest.cc | iamzken/aliyun-openapi-cpp-sdk | 3c991c9ca949b6003c8f498ce7a672ea88162bf1 | [
"Apache-2.0"
] | 89 | 2018-03-14T07:44:54.000Z | 2021-11-26T07:43:25.000Z | vpc/src/model/DescribeRouteTableListRequest.cc | aliyun/aliyun-openapi-cpp-sdk | 0cf5861ece17dfb0bb251f13bf3fbdb39c0c6e36 | [
"Apache-2.0"
] | 69 | 2018-01-22T09:45:52.000Z | 2022-03-28T07:58:38.000Z | /*
* Copyright 2009-2017 Alibaba Cloud All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <alibabacloud/vpc/model/DescribeRouteTableListRequest.h>
using AlibabaCloud::Vpc::Model::DescribeRouteTableListRequest;
DescribeRouteTableListRequest::DescribeRouteTableListRequest() :
RpcServiceRequest("vpc", "2016-04-28", "DescribeRouteTableList")
{
setMethod(HttpRequest::Method::Post);
}
DescribeRouteTableListRequest::~DescribeRouteTableListRequest()
{}
long DescribeRouteTableListRequest::getResourceOwnerId()const
{
return resourceOwnerId_;
}
void DescribeRouteTableListRequest::setResourceOwnerId(long resourceOwnerId)
{
resourceOwnerId_ = resourceOwnerId;
setParameter("ResourceOwnerId", std::to_string(resourceOwnerId));
}
int DescribeRouteTableListRequest::getPageNumber()const
{
return pageNumber_;
}
void DescribeRouteTableListRequest::setPageNumber(int pageNumber)
{
pageNumber_ = pageNumber;
setParameter("PageNumber", std::to_string(pageNumber));
}
std::string DescribeRouteTableListRequest::getResourceGroupId()const
{
return resourceGroupId_;
}
void DescribeRouteTableListRequest::setResourceGroupId(const std::string& resourceGroupId)
{
resourceGroupId_ = resourceGroupId;
setParameter("ResourceGroupId", resourceGroupId);
}
std::string DescribeRouteTableListRequest::getRouteTableName()const
{
return routeTableName_;
}
void DescribeRouteTableListRequest::setRouteTableName(const std::string& routeTableName)
{
routeTableName_ = routeTableName;
setParameter("RouteTableName", routeTableName);
}
std::string DescribeRouteTableListRequest::getRegionId()const
{
return regionId_;
}
void DescribeRouteTableListRequest::setRegionId(const std::string& regionId)
{
regionId_ = regionId;
setParameter("RegionId", regionId);
}
int DescribeRouteTableListRequest::getPageSize()const
{
return pageSize_;
}
void DescribeRouteTableListRequest::setPageSize(int pageSize)
{
pageSize_ = pageSize;
setParameter("PageSize", std::to_string(pageSize));
}
std::vector<DescribeRouteTableListRequest::Tag> DescribeRouteTableListRequest::getTag()const
{
return tag_;
}
void DescribeRouteTableListRequest::setTag(const std::vector<Tag>& tag)
{
tag_ = tag;
for(int dep1 = 0; dep1!= tag.size(); dep1++) {
auto tagObj = tag.at(dep1);
std::string tagObjStr = "Tag." + std::to_string(dep1 + 1);
setParameter(tagObjStr + ".Value", tagObj.value);
setParameter(tagObjStr + ".Key", tagObj.key);
}
}
std::string DescribeRouteTableListRequest::getRouteTableId()const
{
return routeTableId_;
}
void DescribeRouteTableListRequest::setRouteTableId(const std::string& routeTableId)
{
routeTableId_ = routeTableId;
setParameter("RouteTableId", routeTableId);
}
std::string DescribeRouteTableListRequest::getResourceOwnerAccount()const
{
return resourceOwnerAccount_;
}
void DescribeRouteTableListRequest::setResourceOwnerAccount(const std::string& resourceOwnerAccount)
{
resourceOwnerAccount_ = resourceOwnerAccount;
setParameter("ResourceOwnerAccount", resourceOwnerAccount);
}
std::string DescribeRouteTableListRequest::getOwnerAccount()const
{
return ownerAccount_;
}
void DescribeRouteTableListRequest::setOwnerAccount(const std::string& ownerAccount)
{
ownerAccount_ = ownerAccount;
setParameter("OwnerAccount", ownerAccount);
}
long DescribeRouteTableListRequest::getOwnerId()const
{
return ownerId_;
}
void DescribeRouteTableListRequest::setOwnerId(long ownerId)
{
ownerId_ = ownerId;
setParameter("OwnerId", std::to_string(ownerId));
}
std::string DescribeRouteTableListRequest::getRouterType()const
{
return routerType_;
}
void DescribeRouteTableListRequest::setRouterType(const std::string& routerType)
{
routerType_ = routerType;
setParameter("RouterType", routerType);
}
std::string DescribeRouteTableListRequest::getRouterId()const
{
return routerId_;
}
void DescribeRouteTableListRequest::setRouterId(const std::string& routerId)
{
routerId_ = routerId;
setParameter("RouterId", routerId);
}
std::string DescribeRouteTableListRequest::getVpcId()const
{
return vpcId_;
}
void DescribeRouteTableListRequest::setVpcId(const std::string& vpcId)
{
vpcId_ = vpcId;
setParameter("VpcId", vpcId);
}
| 25.746032 | 101 | 0.765105 | [
"vector",
"model"
] |
2d7ce26c49302255425762cbb477404155cf9dff | 1,781 | cpp | C++ | Leetcode/Hot100/208_Implement_Trie_(Prefix_Tree).cpp | ZR-Huang/AlgorithmPractices | 226cecde136531341ce23cdf88529345be1912fc | [
"BSD-3-Clause"
] | 1 | 2019-11-26T11:52:25.000Z | 2019-11-26T11:52:25.000Z | Leetcode/Hot100/208_Implement_Trie_(Prefix_Tree).cpp | ZR-Huang/AlgorithmPractices | 226cecde136531341ce23cdf88529345be1912fc | [
"BSD-3-Clause"
] | null | null | null | Leetcode/Hot100/208_Implement_Trie_(Prefix_Tree).cpp | ZR-Huang/AlgorithmPractices | 226cecde136531341ce23cdf88529345be1912fc | [
"BSD-3-Clause"
] | null | null | null | /*
Implement a trie with insert, search, and startsWith methods.
Example:
Trie trie = new Trie();
trie.insert("apple");
trie.search("apple"); // returns true
trie.search("app"); // returns false
trie.startsWith("app"); // returns true
trie.insert("app");
trie.search("app"); // returns true
Note:
You may assume that all inputs are consist of lowercase letters a-z.
All inputs are guaranteed to be non-empty strings.
*/
#include <vector>
#include <string>
using namespace std;
struct TrieNode {
bool isEnd = false;
TrieNode *links[26];
};
class Trie {
public:
TrieNode *root;
/** Initialize your data structure here. */
Trie() {
root = new TrieNode();
}
/** Inserts a word into the trie. */
void insert(string word) {
TrieNode *node = root;
for(auto c : word){
if(node->links[c-'a']==NULL)
node->links[c-'a'] = new TrieNode();
node = node->links[c-'a'];
}
node->isEnd = true;
}
/** Returns if the word is in the trie. */
bool search(string word) {
TrieNode *node = root;
for(auto c : word){
node = node->links[c-'a'];
if (!node) return false;
}
return node->isEnd;
}
/** Returns if there is any word in the trie that starts with the given prefix. */
bool startsWith(string prefix) {
TrieNode *node = root;
for(auto c : prefix){
node = node->links[c-'a'];
if (!node) return false;
}
return true;
}
};
/**
* Your Trie object will be instantiated and called as such:
* Trie* obj = new Trie();
* obj->insert(word);
* bool param_2 = obj->search(word);
* bool param_3 = obj->startsWith(prefix);
*/ | 25.084507 | 86 | 0.56822 | [
"object",
"vector"
] |
2d7f42ab0cf45cec2de45b0c0daf91ee88b2aa15 | 1,162 | hpp | C++ | Source/Object/Item/Damage/damage.hpp | weenchvd/Wasteland3 | e1d9b96f73b9d1901dfee61ec2d468e00560cb00 | [
"BSL-1.0"
] | null | null | null | Source/Object/Item/Damage/damage.hpp | weenchvd/Wasteland3 | e1d9b96f73b9d1901dfee61ec2d468e00560cb00 | [
"BSL-1.0"
] | null | null | null | Source/Object/Item/Damage/damage.hpp | weenchvd/Wasteland3 | e1d9b96f73b9d1901dfee61ec2d468e00560cb00 | [
"BSL-1.0"
] | null | null | null |
// Copyright (c) 2021 Vitaly Dikov
//
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE or copy at https://www.boost.org/LICENSE_1_0.txt)
#ifndef DAMAGE_HPP
#define DAMAGE_HPP
#include"damageCommon.hpp"
#include"damageReference.hpp"
#include"damageText.hpp"
namespace game {
namespace object {
class Damage {
public:
using Type = Damage__Type;
public:
static void initialize();
static bool isInitialized();
public:
static const DamageReferenceContainer& damageReferenceContainer() noexcept {
return ref_;
}
static const DamageText& damageText() noexcept {
return text_;
}
private:
static const DamageReferenceContainer ref_;
static const DamageText text_;
};
///************************************************************************************************
inline void Damage::initialize()
{
ref_.initialize();
text_.initialize();
}
inline bool Damage::isInitialized()
{
return ref_.isInitialized()
&& text_.isInitialized();
}
} // namespace object
} // namespace game
#endif // !DAMAGE_HPP
| 20.034483 | 99 | 0.623064 | [
"object"
] |
2d80b14571b5f737f8651c41152112056f3ccae5 | 24,552 | cpp | C++ | src/corgi/corgi_adapter.cpp | google/scene_lab | 3f68e1cf48479ee6507b81092c392736e11085d5 | [
"Apache-2.0"
] | 65 | 2015-11-19T05:01:04.000Z | 2021-10-12T12:50:29.000Z | src/corgi/corgi_adapter.cpp | google/scene_lab | 3f68e1cf48479ee6507b81092c392736e11085d5 | [
"Apache-2.0"
] | null | null | null | src/corgi/corgi_adapter.cpp | google/scene_lab | 3f68e1cf48479ee6507b81092c392736e11085d5 | [
"Apache-2.0"
] | 20 | 2015-11-19T10:07:28.000Z | 2021-09-05T08:52:43.000Z | // Copyright 2016 Google Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "scene_lab/corgi/corgi_adapter.h"
#include <string>
#include "corgi_component_library/common_services.h"
#include "corgi_component_library/meta.h"
#include "corgi_component_library/physics.h"
#include "corgi_component_library/rendermesh.h"
#include "corgi_component_library/transform.h"
#include "mathfu/glsl_mappings.h"
#include "scene_lab/basic_camera.h"
#include "scene_lab/corgi/edit_options.h"
namespace scene_lab_corgi {
using corgi::component_library::CommonServicesComponent;
using corgi::component_library::MetaComponent;
using corgi::component_library::MetaData;
using corgi::component_library::PhysicsComponent;
using corgi::component_library::PhysicsData;
using corgi::component_library::TransformComponent;
using corgi::component_library::TransformData;
using corgi::component_library::RenderMeshComponent;
using corgi::component_library::RenderMeshData;
using scene_lab::SceneLab;
using scene_lab::GenericEntityId;
using scene_lab::GenericComponentId;
CorgiAdapter::CorgiAdapter(SceneLab* scene_lab,
corgi::EntityManager* entity_manager)
: scene_lab_(scene_lab),
entity_manager_(entity_manager),
entity_cycler_(entity_manager->begin()) {
auto services = entity_manager_->GetComponent<CommonServicesComponent>();
renderer_ = services->renderer();
entity_factory_ = services->entity_factory();
rendermesh_culling_distance_squared_ = 0;
auto edit_options = entity_manager_->GetComponent<EditOptionsComponent>();
if (edit_options) {
edit_options->SetSceneLabCallbacks(this);
}
const char* schema_file_text =
scene_lab_->config()->schema_file_text()->c_str();
const char* schema_file_binary =
scene_lab_->config()->schema_file_binary()->c_str();
if (!fplbase::LoadFile(schema_file_binary, &schema_data_)) {
fplbase::LogError("CorgiAdapter: Failed to open binary schema file: %s",
schema_file_binary);
}
auto schema = reflection::GetSchema(schema_data_.c_str());
if (schema != nullptr) {
fplbase::LogInfo("CorgiAdapter: Binary schema %s loaded",
schema_file_binary);
}
if (fplbase::LoadFile(schema_file_text, &schema_text_)) {
fplbase::LogInfo("CorgiAdapter: Text schema %s loaded", schema_file_text);
}
scene_lab_->gui()->SetShowComponentDataView(
GetGenericComponentId(MetaComponent::GetComponentId()), true);
scene_lab_->gui()->SetShowComponentDataView(
GetGenericComponentId(TransformComponent::GetComponentId()), true);
AddComponentToUpdate(TransformComponent::GetComponentId());
}
void CorgiAdapter::AdvanceFrame(double delta_seconds) {
corgi::WorldTime delta_time = static_cast<corgi::WorldTime>(
delta_seconds * corgi::kMillisecondsPerSecond);
(void)delta_time;
auto transform_component =
entity_manager_->GetComponent<TransformComponent>();
transform_component->PostLoadFixup();
// Any components we specifically still want to update should be updated here.
for (size_t i = 0; i < components_to_update_.size(); i++) {
entity_manager_->GetComponent(components_to_update_[i])
->UpdateAllEntities(0);
}
entity_manager_->DeleteMarkedEntities();
}
void CorgiAdapter::OnActivate() {
if (camera_ == nullptr) {
CreateDefaultCamera();
}
// Disable distance culling, if enabled.
auto render_mesh_component =
entity_manager_->GetComponent<RenderMeshComponent>();
if (render_mesh_component != nullptr) {
rendermesh_culling_distance_squared_ =
render_mesh_component->culling_distance_squared();
// Only cull past the far clipping plane.
render_mesh_component->set_culling_distance_squared(
camera_->viewport_far_plane() * camera_->viewport_far_plane());
}
}
void CorgiAdapter::OnDeactivate() {
// Restore previous distance culling setting.
auto render_mesh_component =
entity_manager_->GetComponent<RenderMeshComponent>();
if (render_mesh_component != nullptr) {
render_mesh_component->set_culling_distance_squared(
rendermesh_culling_distance_squared_);
}
auto physics_component = entity_manager_->GetComponent<PhysicsComponent>();
if (physics_component != nullptr) {
physics_component->AwakenAllEntities();
}
}
bool CorgiAdapter::EntityExists(const GenericEntityId& id) {
return GetEntityRef(id);
}
bool CorgiAdapter::GetEntityTransform(const GenericEntityId& id,
GenericTransform* transform) {
if (!EntityExists(id)) return false;
auto transform_data =
entity_manager_->GetComponentData<TransformData>(GetEntityRef(id));
if (transform_data == nullptr) {
return false;
}
transform->position = transform_data->position;
transform->orientation = transform_data->orientation;
transform->scale = transform_data->scale;
return true;
}
bool CorgiAdapter::SetEntityTransform(const GenericEntityId& id,
const GenericTransform& transform) {
if (!EntityExists(id)) return false;
auto transform_component =
entity_manager_->GetComponent<TransformComponent>();
corgi::EntityRef entity = GetEntityRef(id);
// Get the transform assigned to this entity, adding one if needed.
auto transform_data = transform_component->AddEntity(entity);
if (transform_data == nullptr) {
// Failed to add the transform to the entity.
return false;
}
transform_data->position = transform.position;
transform_data->orientation = transform.orientation;
transform_data->scale = transform.scale;
if (entity_manager_->GetComponentData<PhysicsData>(entity)) {
PhysicsComponent* physics =
entity_manager_->GetComponent<PhysicsComponent>();
physics->UpdatePhysicsFromTransform(entity);
// Workaround for an issue with the physics library where modifying
// a raycast physics volume causes raycasts to stop working on it.
physics->DisablePhysics(entity);
physics->EnablePhysics(entity);
}
return true;
}
bool CorgiAdapter::GetEntityChildren(
const GenericEntityId& id, std::vector<GenericEntityId>* children_out) {
if (!EntityExists(id)) return false;
auto transform_data =
entity_manager_->GetComponentData<TransformData>(GetEntityRef(id));
if (transform_data == nullptr) {
return false;
}
for (auto iter = transform_data->children.begin();
iter != transform_data->children.end(); ++iter) {
if (children_out != nullptr)
children_out->push_back(GetEntityId(iter->owner));
}
return true;
}
bool CorgiAdapter::GetEntityParent(const GenericEntityId& id,
GenericEntityId* parent_out) {
if (!EntityExists(id)) return false;
auto transform_data =
entity_manager_->GetComponentData<TransformData>(GetEntityRef(id));
if (transform_data == nullptr) {
return false;
}
if (parent_out != nullptr) {
if (transform_data->parent) {
*parent_out = GetEntityId(transform_data->parent);
} else {
*parent_out = kNoEntityId;
}
}
return true;
}
bool CorgiAdapter::SetEntityParent(const GenericEntityId& child,
const GenericEntityId& parent) {
if (!EntityExists(child)) return false;
corgi::EntityRef child_entity = GetEntityRef(child);
auto transform_component =
entity_manager_->GetComponent<TransformComponent>();
if (transform_component->GetComponentData(child_entity) == nullptr)
return false;
if (parent == kNoEntityId) {
// No parent specified, just remove the current parent, if any.
GenericEntityId current_parent = kNoEntityId;
GetEntityParent(child, ¤t_parent);
if (current_parent != kNoEntityId) {
transform_component->RemoveChild(child_entity);
}
} else {
// parent is an entity, check if valid.
if (!EntityExists(parent)) return false;
corgi::EntityRef parent_entity = GetEntityRef(parent);
if (transform_component->GetComponentData(parent_entity) == nullptr)
return false;
transform_component->AddChild(child_entity, parent_entity);
}
return true;
}
bool CorgiAdapter::GetCamera(GenericCamera* camera_out) {
if (camera_ == nullptr) {
CreateDefaultCamera();
}
if (camera_out != nullptr) {
camera_out->position = camera_->position();
camera_out->facing = camera_->facing();
camera_out->up = camera_->up();
}
return true;
}
bool CorgiAdapter::SetCamera(const GenericCamera& camera_in) {
if (camera_ == nullptr) {
CreateDefaultCamera();
}
camera_->set_position(camera_in.position);
if (camera_in.facing.LengthSquared() != 0) {
camera_->set_facing(camera_in.facing);
}
if (camera_in.up.LengthSquared() != 0) {
camera_->set_up(camera_in.up);
}
return true;
}
bool CorgiAdapter::GetViewportSettings(ViewportSettings* viewport_out) {
if (camera_ == nullptr) {
CreateDefaultCamera();
}
if (viewport_out != nullptr) {
viewport_out->vertical_angle = camera_->viewport_angle();
viewport_out->aspect_ratio =
camera_->viewport_resolution().x / camera_->viewport_resolution().y;
}
return true;
}
bool CorgiAdapter::DuplicateEntity(const GenericEntityId& id,
GenericEntityId* new_id) {
corgi::EntityRef entity = GetEntityRef(id);
std::vector<uint8_t> entity_serialized;
if (!entity_factory_->SerializeEntity(entity, entity_manager_,
&entity_serialized)) {
fplbase::LogError("DuplicateEntity: Couldn't serialize entity");
return false;
}
std::vector<std::vector<uint8_t>> entity_defs;
entity_defs.push_back(entity_serialized);
std::vector<uint8_t> entity_list;
if (!entity_factory_->SerializeEntityList(entity_defs, &entity_list)) {
fplbase::LogError("DuplicateEntity: Couldn't create entity list");
return false;
}
std::vector<corgi::EntityRef> entities_created;
if (entity_factory_->LoadEntityListFromMemory(
entity_list.data(), entity_manager_, &entities_created) > 0) {
// We created some new duplicate entities! (most likely exactly one.) We
// need to remove their entity IDs since otherwise they will have
// duplicate entity IDs to the one we created. We also need to make sure
// the new entity IDs are marked with the same source file as the old.
for (size_t i = 0; i < entities_created.size(); i++) {
corgi::EntityRef& new_entity = entities_created[i];
MetaData* old_editor_data =
entity_manager_->GetComponentData<MetaData>(entity);
MetaData* editor_data =
entity_manager_->GetComponentData<MetaData>(new_entity);
if (editor_data != nullptr) {
editor_data->entity_id = "";
if (old_editor_data != nullptr)
editor_data->source_file = old_editor_data->source_file;
}
}
entity_manager_->GetComponent<TransformComponent>()->PostLoadFixup();
for (size_t i = 0; i < entities_created.size(); i++) {
scene_lab_->NotifyCreateEntity(GetEntityId(entities_created[i]));
}
*new_id = GetEntityId(entities_created[0]);
return true;
}
return false;
}
bool CorgiAdapter::CreateEntity(GenericEntityId* new_id_output) {
corgi::EntityRef new_entity = entity_manager_->AllocateNewEntity();
if (new_entity) {
if (new_id_output != nullptr) {
*new_id_output = GetEntityId(new_entity);
}
return true;
} else {
return false;
}
}
bool CorgiAdapter::CreateEntityFromPrototype(
const GenericPrototypeId& prototype, GenericEntityId* new_id_output) {
std::string prototype_str = static_cast<std::string>(prototype);
corgi::EntityRef new_entity = entity_factory_->CreateEntityFromPrototype(
prototype_str.c_str(), entity_manager_);
if (new_entity) {
if (new_id_output != nullptr) {
*new_id_output = GetEntityId(new_entity);
}
return true;
} else {
return false; // Couldn't create.
}
}
bool CorgiAdapter::DeleteEntity(const GenericEntityId& id) {
if (!EntityExists(id)) return false;
corgi::EntityRef entity = GetEntityRef(id);
entity_manager_->DeleteEntity(entity);
return true;
}
bool CorgiAdapter::SetEntityHighlighted(const GenericEntityId& id,
bool is_highlighted) {
if (!EntityExists(id)) return false;
return HighlightEntity(GetEntityRef(id), is_highlighted ? 2.0f : 1.0f);
}
bool CorgiAdapter::DebugDrawPhysics(const GenericEntityId& id) {
if (EntityExists(id)) {
corgi::EntityRef entity = GetEntityRef(id);
if (entity) {
auto physics = entity_manager_->GetComponent<PhysicsComponent>();
mathfu::mat4 cam = camera_->GetTransformMatrix();
physics->DebugDrawObject(renderer_, cam, entity,
mathfu::vec3(1.0f, 0.5f, 0.5f));
return true;
}
}
return false;
}
bool CorgiAdapter::GetRayIntersection(const mathfu::vec3& start_point,
const mathfu::vec3& direction,
GenericEntityId* entity_output,
mathfu::vec3* intersection_point_output) {
if (camera_ == nullptr) return false;
mathfu::vec3 intersection_point;
mathfu::vec3 start = start_point;
float distance = camera_->viewport_far_plane();
mathfu::vec3 end = start + distance * direction;
corgi::EntityRef result =
entity_manager_->GetComponent<PhysicsComponent>()->RaycastSingle(
start, end, &intersection_point);
if (result) {
if (entity_output != nullptr) *entity_output = GetEntityId(result);
if (intersection_point_output != nullptr)
*intersection_point_output = intersection_point;
return true;
}
return false;
}
bool CorgiAdapter::CycleEntities(int direction, GenericEntityId* next_entity) {
corgi::EntityRef current = entity_cycler_.ToReference();
if (!current) entity_cycler_ = entity_manager_->begin();
if (direction == 0) {
// Reset to the beginning, ignoring current_entity.
entity_cycler_ = entity_manager_->begin();
} else if (direction > 0) {
// Cycle forward N entities.
for (int i = 0; i < direction; i++) {
if (entity_cycler_ != entity_manager_->end()) {
entity_cycler_++;
}
if (entity_cycler_ == entity_manager_->end()) {
entity_cycler_ = entity_manager_->begin();
}
}
} else { // direction < 0
// Cycle backward N entities.
for (int i = 0; i < -direction; i++) {
if (entity_cycler_ == entity_manager_->begin()) {
entity_cycler_ = entity_manager_->end();
}
entity_cycler_--;
}
}
// fplbase::LogInfo("Cycled to entity: %x", entity_cycler_);
if (next_entity != nullptr && entity_cycler_.ToReference()) {
*next_entity = GetEntityId(entity_cycler_.ToReference());
}
return true;
}
bool CorgiAdapter::GetAllEntityIDs(std::vector<GenericEntityId>* ids_out) {
if (ids_out != nullptr) ids_out->clear();
for (auto i = entity_manager_->begin(); i != entity_manager_->end(); ++i) {
corgi::EntityRef entity = i.ToReference();
if (ids_out != nullptr) ids_out->push_back(GetEntityId(entity));
}
return true;
}
bool CorgiAdapter::GetAllPrototypeIDs(
std::vector<GenericPrototypeId>* ids_out) {
auto prototype_data = entity_factory_->prototype_data();
if (ids_out != nullptr) ids_out->clear();
for (auto it = prototype_data.begin(); it != prototype_data.end(); ++it) {
if (ids_out != nullptr) ids_out->push_back(it->first);
}
return true;
}
bool CorgiAdapter::GetEntityDescription(const GenericEntityId& id,
std::string* description) {
if (!EntityExists(id)) return false;
corgi::EntityRef entity = GetEntityRef(id);
if (!entity) return false;
auto editor_data = entity_manager_->GetComponentData<MetaData>(entity);
if (editor_data == nullptr) return true;
if (editor_data->prototype.length() > 0 && description != nullptr) {
*description = editor_data->prototype;
}
return editor_data->prototype.length() > 0;
}
bool CorgiAdapter::GetEntitySourceFile(const GenericEntityId& id,
std::string* source_file) {
// If the entity is not found, return false, meaning don't save.
if (source_file != nullptr) *source_file = std::string();
if (!EntityExists(id)) return false;
corgi::EntityRef entity = GetEntityRef(id);
if (!entity) return false;
auto editor_data = entity_manager_->GetComponentData<MetaData>(entity);
if (editor_data == nullptr) return true;
if (source_file != nullptr) {
*source_file = editor_data->source_file;
}
// Entities with a blank filename should not be saved, so return false in that
// case.
return editor_data->source_file.length() > 0;
}
bool CorgiAdapter::GetSchema(const reflection::Schema** schema_out) {
if (schema_data_.length() > 0) {
if (schema_out != nullptr) {
*schema_out = reflection::GetSchema(schema_data_.c_str());
}
return true;
}
return false;
}
bool CorgiAdapter::GetTextSchema(std::string* schema_out) {
if (schema_text_.length() > 0) {
if (schema_out != nullptr) *schema_out = schema_text_;
return true;
}
return false;
}
bool CorgiAdapter::GetTableObject(const GenericComponentId& id,
const reflection::Object** table_out) {
const reflection::Schema* schema;
if (!GetSchema(&schema)) return false;
// GenericComponentId is the table name.
const char* table_name =
entity_factory_->ComponentIdToTableName(GetCorgiComponentId(id));
if (table_name == nullptr) return false;
const reflection::Object* obj = schema->objects()->LookupByKey(table_name);
if (table_out != nullptr) *table_out = obj;
return (obj != nullptr);
}
bool CorgiAdapter::GetEntityComponentList(
const GenericEntityId& id,
std::vector<GenericComponentId>* components_out) {
if (!EntityExists(id)) return false;
corgi::EntityRef entity = GetEntityRef(id);
if (!entity) return false;
if (components_out != nullptr) components_out->clear();
for (corgi::ComponentId i = 0; i < entity_manager_->ComponentCount(); i++) {
if (i != corgi::kInvalidComponent &&
entity_manager_->GetComponent(i)->GetComponentDataAsVoid(entity) !=
nullptr) {
if (components_out != nullptr) {
components_out->push_back(GetGenericComponentId(i));
}
}
}
return true;
}
void CorgiAdapter::GetFullComponentList(
std::vector<GenericComponentId>* components_out) {
if (components_out != nullptr) components_out->clear();
for (corgi::ComponentId i = 0; i < entity_manager_->ComponentCount(); i++) {
if (i != corgi::kInvalidComponent) {
if (components_out != nullptr) {
components_out->push_back(GetGenericComponentId(i));
}
}
}
}
bool CorgiAdapter::IsEntityComponentFromPrototype(
const GenericEntityId& entity_id, const GenericComponentId& component_id) {
if (!EntityExists(entity_id)) return false;
corgi::EntityRef entity = GetEntityRef(entity_id);
corgi::ComponentId cid = GetCorgiComponentId(component_id);
if (!entity || cid == corgi::kInvalidComponent) return false;
auto meta_data = entity_manager_->GetComponentData<MetaData>(entity);
return meta_data ? (meta_data->components_from_prototype.find(cid) !=
meta_data->components_from_prototype.end())
: false;
}
bool CorgiAdapter::SerializeEntities(
const std::vector<GenericEntityId>& id_list,
std::vector<uint8_t>* buffer_out) {
std::vector<std::vector<uint8_t>> entities_serialized;
for (auto id = id_list.begin(); id != id_list.end(); ++id) {
if (!EntityExists(*id)) continue;
corgi::EntityRef entity = GetEntityRef(*id);
if (!entity) continue;
entities_serialized.push_back(std::vector<uint8_t>());
entity_factory_->SerializeEntity(entity, entity_manager_,
&entities_serialized.back());
}
if (buffer_out != nullptr) {
if (!entity_factory_->SerializeEntityList(entities_serialized,
buffer_out)) {
fplbase::LogError("CorgiAdapter: Couldn't serialize entity list.");
return false;
}
}
return true;
}
bool CorgiAdapter::SerializeEntityComponent(
const GenericEntityId& entity_id, const GenericComponentId& component_id,
flatbuffers::unique_ptr_t* data_out) {
if (!EntityExists(entity_id)) return false;
corgi::EntityRef entity = GetEntityRef(entity_id);
corgi::ComponentId cid = GetCorgiComponentId(component_id);
if (!entity || cid == corgi::kInvalidComponent) return false;
corgi::ComponentInterface* component = entity_manager_->GetComponent(cid);
auto services = entity_manager_->GetComponent<CommonServicesComponent>();
bool prev_force_defaults = services->export_force_defaults();
// Force all default fields to have values that the user can edit
services->set_export_force_defaults(true);
flatbuffers::unique_ptr_t raw_data = component->ExportRawData(entity);
services->set_export_force_defaults(prev_force_defaults);
if (raw_data != nullptr) {
if (data_out != nullptr) {
*data_out = std::move(raw_data);
}
return true;
} else {
// No output was serialized.
return false;
}
}
bool CorgiAdapter::DeserializeEntityComponent(
const GenericEntityId& entity_id, const GenericComponentId& component_id,
const uint8_t* data) {
if (data == nullptr) return false;
if (!EntityExists(entity_id)) return false;
corgi::EntityRef entity = GetEntityRef(entity_id);
corgi::ComponentId cid = GetCorgiComponentId(component_id);
if (!entity || cid == corgi::kInvalidComponent) return false;
corgi::ComponentInterface* component = entity_manager_->GetComponent(cid);
component->AddFromRawData(entity, flatbuffers::GetAnyRoot(data));
return true;
}
void CorgiAdapter::OverrideFileCache(const std::string& filename,
const std::vector<uint8_t>& data) {
// TODO: implement
(void)filename;
(void)data;
}
bool CorgiAdapter::HighlightEntity(const corgi::EntityRef& entity, float tint) {
bool did_highlight = false;
if (!entity) return false;
auto render_data = entity_manager_->GetComponentData<RenderMeshData>(entity);
if (render_data != nullptr) {
render_data->tint = mathfu::vec4(tint, tint, tint, 1);
did_highlight = true;
}
// Highlight the node's children as well.
auto transform_data =
entity_manager_->GetComponentData<TransformData>(entity);
if (transform_data != nullptr) {
for (auto iter = transform_data->children.begin();
iter != transform_data->children.end(); ++iter) {
// Highlight the child, but slightly less brightly.
if (HighlightEntity(iter->owner, 1 + ((tint - 1) * .8f)))
did_highlight = true;
}
}
return did_highlight;
}
void CorgiAdapter::CreateDefaultCamera() {
fplbase::LogInfo("Creating a default BasicCamera for Scene Lab CorgiAdapter");
camera_.reset(new scene_lab::BasicCamera());
}
corgi::EntityRef CorgiAdapter::GetEntityRef(const GenericEntityId& id) const {
(void)id;
if (id == kNoEntityId) return corgi::EntityRef();
auto meta_component = entity_manager_->GetComponent<MetaComponent>();
return meta_component->GetEntityFromDictionary(id);
}
GenericEntityId CorgiAdapter::GetEntityId(const corgi::EntityRef& ref) const {
if (!ref) return kNoEntityId;
auto meta_component = entity_manager_->GetComponent<MetaComponent>();
return meta_component->GetEntityID(ref);
}
corgi::ComponentId CorgiAdapter::GetCorgiComponentId(
const GenericComponentId& id) const {
if (id == kNoComponentId) return corgi::kInvalidComponent;
return static_cast<corgi::ComponentId>(atoi(id.c_str()));
}
GenericComponentId CorgiAdapter::GetGenericComponentId(
corgi::ComponentId c) const {
if (c == corgi::kInvalidComponent) return kNoComponentId;
std::stringstream ss;
ss << c;
return ss.str();
}
} // namespace scene_lab_corgi
| 35.377522 | 80 | 0.701043 | [
"object",
"vector",
"transform"
] |
2d8f41ebec71c1c06a0e58010af3b005d2d7738c | 10,916 | cpp | C++ | math/applications/ellipsoid-calc.cpp | mission-systems-pty-ltd/snark | 2bc8a20292ee3684d3a9897ba6fee43fed8d89ae | [
"BSD-3-Clause"
] | 63 | 2015-01-14T14:38:02.000Z | 2022-02-01T09:56:03.000Z | math/applications/ellipsoid-calc.cpp | NEU-LC/snark | db890f73f4c4bbe679405f3a607fd9ea373deb2c | [
"BSD-3-Clause"
] | 39 | 2015-01-21T00:57:38.000Z | 2020-04-22T04:22:35.000Z | math/applications/ellipsoid-calc.cpp | NEU-LC/snark | db890f73f4c4bbe679405f3a607fd9ea373deb2c | [
"BSD-3-Clause"
] | 36 | 2015-01-15T04:17:14.000Z | 2022-02-17T17:13:35.000Z | // This file is part of snark, a generic and flexible library for robotics research
// Copyright (c) 2011 The University of Sydney
// 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 University of Sydney nor the
// names of its contributors may be used to endorse or promote products
// derived from this software without specific prior written permission.
//
// NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE
// GRANTED BY THIS LICENSE. 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 <comma/application/command_line_options.h>
#include <comma/csv/stream.h>
#include "../spherical_geometry/ellipsoid.h"
#include "../spherical_geometry/traits.h"
static void usage( bool more = false )
{
std::cerr << std::endl;
std::cerr << "take coordinates in degrees on ellipsoid from stdin, perform calculations, append result and output to stdout" << std::endl;
std::cerr << std::endl;
std::cerr << "usage examples" << std::endl;
std::cerr << " cat arcs.csv | ellipsoid-calc distance [<options>] > results.csv" << std::endl;
std::cerr << " cat circular-arcs.csv | ellipsoid-calc discretize arc [<options>] > results.csv" << std::endl;
std::cerr << " cat circle.csv | ellipsoid-calc discretize circle [<options>] > results.csv" << std::endl;
std::cerr << std::endl;
std::cerr << "operations" << std::endl;
std::cerr << " distance : output length of ellipsoid arc" << std::endl;
std::cerr << " discretize : output a discretized shape (e.g. circle) with a given resolution" << std::endl;
std::cerr << std::endl;
std::cerr << "operations: details" << std::endl;
std::cerr << std::endl;
std::cerr << " distance: ellipsoid arc distance; if --binary, output as double" << std::endl;
std::cerr << " input fields: " << comma::join( comma::csv::names< snark::spherical::ellipsoid::arc >( true ), ',' ) << std::endl;
std::cerr << std::endl;
std::cerr << " discretize shape: output a discretized shape with a given resolution" << std::endl;
std::cerr << " multiple output lines per input line" << std::endl;
std::cerr << " the result will be appended to the line (see example)" << std::endl;
std::cerr << " shape: circle, arc" << std::endl;
std::cerr << " input fields" << std::endl;
std::cerr << " circle: centre,radius" << std::endl;
std::cerr << " centre: latitude,longitude in degrees" << std::endl;
std::cerr << " radius: metric distance from centre" << std::endl;
std::cerr << " arc: circle/centre,circle/radius,begin,end" << std::endl;
std::cerr << " circle/centre: latitude,longitude in degrees" << std::endl;
std::cerr << " circle/radius: metric distance from centre" << std::endl;
std::cerr << " begin: begin bearing, degrees" << std::endl;
std::cerr << " end: end bearing, degrees" << std::endl;
std::cerr << std::endl;
std::cerr << " options" << std::endl;
std::cerr << " --resolution=<degrees>" << std::endl;
std::cerr << " --circle-size,--size=<number>: number of points in the discretized circle (circle or arc only)" << std::endl;
std::cerr << " if both --resolution and --cricle-size present, whatever gives finer resolution will be choosen" << std::endl;
std::cerr << std::endl;
std::cerr << "options" << std::endl;
std::cerr << " --help,-h: show help; --help --verbose for more help" << std::endl;
std::cerr << " --verbose,-v: more info" << std::endl;
std::cerr << " --major: ellipsoid's major semiaxis; default: 1.0" << std::endl;
std::cerr << " --minor: ellipsoid's minor semiaxis; default: 1.0" << std::endl;
if ( more )
std::cerr << std::endl << "csv options" << std::endl << comma::csv::options::usage() << std::endl;
std::cerr << std::endl;
std::cerr << "examples" << std::endl;
std::cerr << " echo 0,0,45,90 | ellipsoid-calc distance --major=6378137 --minor=6356752.314245" << std::endl;
std::cerr << " echo 0,0,45,90 | ellipsoid-calc distance --major=6378137 --minor=6356752.314245" << std::endl;
std::cerr << " echo 0,0,45,90 | ellipsoid-calc distance --major=1.00336409 --minor=1" << std::endl;
std::cerr << " cat circular-arcs.csv | ellipsoid-calc discretize arc --fields=circle/centre/latitude,circle/centre/longitude,circle/radius,begin,end --circle-size=32 > results.csv" << std::endl;
std::cerr << " cat circle.csv | ellipsoid-calc discretize circle --fields=centre,radius --resolution=0.1 | column -ts," << std::endl;
std::cerr << std::endl;
exit( 1 );
}
template < typename S >
int discretize( const comma::csv::options& csv, snark::spherical::ellipsoid& ellipsoid, const boost::optional< double >& resolution, const boost::optional< unsigned int >& circle_size )
{
comma::csv::input_stream< S > istream( std::cin, csv );
comma::csv::ascii< snark::spherical::coordinates > ascii;
comma::csv::binary< snark::spherical::coordinates > binary;
while( istream.ready() || std::cin.good() )
{
const S* a = istream.read();
if( !a ) { break; }
const std::vector< snark::spherical::coordinates >& v = a->discretize(ellipsoid, resolution, circle_size);
for( unsigned int i = 0; i < v.size(); ++i )
{
if( csv.binary() )
{
std::cout.write( istream.binary().last(), istream.binary().binary().format().size() );
std::vector< char > buf( binary.format().size() );
binary.put( v[i], &buf[0] );
std::cout.write( reinterpret_cast< const char* >( &buf[i] ), buf.size() );
}
else
{
std::cout << comma::join( istream.ascii().last(), csv.delimiter );
std::cout << csv.delimiter << ascii.put( v[i] );
std::cout << std::endl;
}
}
}
return 0;
}
int main( int ac, char **av )
{
try
{
comma::command_line_options options( ac, av );
bool verbose = options.exists( "--verbose,-v" );
if ( options.exists( "--help,-h" ) )
usage( verbose );
comma::csv::options csv( options );
if ( !csv.binary() )
std::cout.precision( options.value( "--precision,-p", 12 ) );
csv.full_xpath = true;
const std::vector<std::string> &operations = options.unnamed( "--verbose,-v,--degrees", "-.*" );
if ( operations.size() != 1 )
{
std::cerr << "ellipsoid-calc: expected one operation, got " << operations.size() << std::endl;
return 1;
}
double major_semiaxis = options.value( "--major", 1.0 );
double minor_semiaxis = options.value( "--minor", 1.0 );
snark::spherical::ellipsoid ellipsoid( major_semiaxis, minor_semiaxis );
if ( operations.size() < 1 )
{
std::cerr << "ellipsoid-calc: expected one operation, got " << operations.size() << std::endl;
return 1;
}
if ( operations[0] == "distance" )
{
comma::csv::input_stream< snark::spherical::ellipsoid::arc > istream( std::cin, csv );
while ( istream.ready() || ( std::cin.good() && !std::cin.eof() ) )
{
const snark::spherical::ellipsoid::arc *a = istream.read();
if ( !a )
break;
double distance = ellipsoid.distance( a->begin, a->end );
if ( csv.binary() )
{
std::cout.write( istream.binary().last(), istream.binary().binary().format().size() );
std::cout.write( reinterpret_cast< const char * >( &distance ), sizeof( double ) );
}
else
std::cout << comma::join( istream.ascii().last(), csv.delimiter ) << csv.delimiter << distance << std::endl;
}
return 0;
}
else if( operations[0] == "discretize" )
{
//whole circle or circular arc
boost::optional< double > resolution = options.optional< double >( "--resolution" );
if( resolution ) { resolution = *resolution * M_PI / 180; }
boost::optional< unsigned int > circle_size = options.optional< unsigned int >( "--circle-size,--size" );
if(operations.size()==2)
{
if ( operations[1] == "circle")
{
return discretize< snark::spherical::ellipsoid::circle >( csv, ellipsoid, resolution, circle_size );
}
else if(operations[1] == "arc")
{
return discretize<snark::spherical::ellipsoid::circle::arc>(csv, ellipsoid, resolution, circle_size );
}
std::cerr << "ellipsoid-calc: unknown shape for discretize: \"" << operations[1] << "\"" << std::endl;
}
else
std::cerr << "ellipsoid-calc: expected shape for operation discretize" << std::endl;
return 1;
}
std::cerr << "ellipsoid-calc: unknown operation: \"" << operations[0] << "\"" << std::endl;
return 1;
}
catch ( std::exception &ex )
{
std::cerr << "ellipsoid-calc: " << ex.what() << std::endl;
}
catch ( ... )
{
std::cerr << "ellipsoid-calc: unknown exception" << std::endl;
}
return 1;
}
| 53.509804 | 201 | 0.579608 | [
"shape",
"vector"
] |
2d90a6dd55d4fa621cbc3173332cc6cb14e9bfda | 1,922 | hpp | C++ | packages/subsets/subsets/Sweep3.hpp | CryptoExperts/AC21-divprop-convexity | ed4fb715c484b12413a5c59e4f189bcc37889449 | [
"MIT"
] | 4 | 2021-11-13T03:31:00.000Z | 2022-02-25T02:02:58.000Z | packages/subsets/subsets/Sweep3.hpp | CryptoExperts/AC21-divprop-convexity | ed4fb715c484b12413a5c59e4f189bcc37889449 | [
"MIT"
] | null | null | null | packages/subsets/subsets/Sweep3.hpp | CryptoExperts/AC21-divprop-convexity | ed4fb715c484b12413a5c59e4f189bcc37889449 | [
"MIT"
] | null | null | null | #pragma once
#include "common.hpp"
#include "ternary.hpp"
template<auto func, typename T>
void GenericSweep3(vector<T> &arr, uint64_t mask) {
auto size = arr.size();
int n = log3(size);
ensure(arr.size() == pow3(n));
uint64_t hi = size / 3;
uint64_t hi_stride = 3;
uint64_t lo = 1;
fori(i, n) {
if ((mask & (1ull << i))) {
uint64_t j = 0;
fori(_, hi) {
fori(_, lo) {
auto j1 = j + lo;
auto j2 = j1 + lo;
func(arr[j], arr[j1], arr[j2]);
j++;
}
j -= lo;
j += hi_stride;
}
}
hi /= 3;
hi_stride *= 3;
lo *= 3;
}
}
template<auto func, typename WORD>
static inline void GenericSweep3WordBit(WORD &word, int shift, const WORD & mask) {
// /!\ here mask corresponds to word mask,
// not index mask as in other places !!!
WORD v0 = word & mask;
word = word >> shift;
WORD v1 = word & mask;
word = word >> shift;
WORD v2 = word & mask;
func(v0, v1, v2);
word = ((v2 << shift) <<shift) | (v1 << shift) | v0;
}
template<auto func, typename WORD>
static inline void GenericSweep3Word(WORD &word, uint64_t mask) {
if (mask & ( 1)) GenericSweep3WordBit<func>(word, 1, MASKS_TERNARY[0]);
if (mask & ( 2)) GenericSweep3WordBit<func>(word, 3, MASKS_TERNARY[1]);
if (mask & ( 4)) GenericSweep3WordBit<func>(word, 9, MASKS_TERNARY[2]);
if (mask & ( 8)) GenericSweep3WordBit<func>(word, 27, MASKS_TERNARY[3]);
if (mask & (16)) GenericSweep3WordBit<func>(word, 81, MASKS_TERNARY[4]);
if (mask & (32)) GenericSweep3WordBit<func>(word, 243, MASKS_TERNARY[5]);
}
TTi void QmC_AND_up_OR(T & a, T & b, T & c) {
c |= a & b;
}
TTi void QmC_NOTAND_down(T & a, T & b, T & c) {
T nc = ~c;
a &= nc;
b &= nc;
} | 27.855072 | 83 | 0.525494 | [
"vector"
] |
2d976f822a6bbe91369ead35fb55da6db2561711 | 11,396 | cpp | C++ | src/sys/xml/sax_reader.cpp | itm/shawn | 49cb715d0044a20a01a19bc4d7b62f9f209df83c | [
"BSD-3-Clause"
] | 15 | 2015-07-07T15:48:30.000Z | 2019-10-27T18:49:49.000Z | src/sys/xml/sax_reader.cpp | itm/shawn | 49cb715d0044a20a01a19bc4d7b62f9f209df83c | [
"BSD-3-Clause"
] | null | null | null | src/sys/xml/sax_reader.cpp | itm/shawn | 49cb715d0044a20a01a19bc4d7b62f9f209df83c | [
"BSD-3-Clause"
] | 4 | 2016-11-23T05:50:01.000Z | 2019-09-18T12:44:36.000Z | /************************************************************************
** This file is part of the network simulator Shawn. **
** Copyright (C) 2004-2007 by the SwarmNet (www.swarmnet.de) project **
** Shawn is free software; you can redistribute it and/or modify it **
** under the terms of the BSD License. Refer to the shawn-licence.txt **
** file in the root of the Shawn source tree for further details. **
************************************************************************/
#include "sax_reader.h"
#include <cassert>
#include <fstream>
#include <string>
#include <cstring>
#include <cerrno>
#include <sstream>
using namespace std;
namespace shawn
{
namespace xml
{
// ----------------------------------------------------------------------
/// Expat C-style callback funcion
void XMLCALL saxreader_start(void *userdata, const char *name, const char **atts)
{
SAXReader* ptr = (SAXReader*) userdata;
AttList a;
for(; *atts; atts += 2)
a.insert( pair<string, string>( atts[0], atts[1] ) );
ptr->handle_start_element(name, a);
}
// ----------------------------------------------------------------------
/// Expat C-style callback funcion
void XMLCALL saxreader_end(void *userdata, const char *name)
{
SAXReader* ptr = (SAXReader*) userdata;
ptr->handle_end_element(name);
}
void XMLCALL saxreader_text(void *userdata, const char* text, int length)
{
SAXReader* ptr = (SAXReader*) userdata;
string content(text, length);
ptr->handle_text_element(content);
}
// ----------------------------------------------------------------------
string
attribute(string name, AttList& atts, string default_val /* = "" */)
{
for(AttList::iterator it = atts.begin(), end = atts.end(); it!=end; ++it)
if( it->first == name )
return it->second;
return default_val;
}
// ----------------------------------------------------------------------
///
/**
*/
SAXReader::
SAXReader()
: stop_flag_(false),
document_uri_(""),
is_(NULL)
{
#ifdef ENABLE_LOGGING
set_logger_name( "SAXReader" );
#endif
}
// ----------------------------------------------------------------------
SAXReader::
~SAXReader()
{
reset();
}
// ----------------------------------------------------------------------
void
SAXReader::
set_document_uri( const std::string& s)
throw()
{
document_uri_ = s;
}
// ----------------------------------------------------------------------
void
SAXReader::
interrupt()
throw()
{
stop_flag_ = true;
}
// ----------------------------------------------------------------------
void
SAXReader::
reset()
throw()
{
//Destroy the parser if existing
if( is_ )
{
delete is_;
is_ = NULL;
}
stop_flag_ = false;
}
// ----------------------------------------------------------------------
void
SAXReader::
open_file()
throw(std::runtime_error)
{
assert( document_uri_.c_str() != NULL );
is_ = new std::ifstream();
is_->open(document_uri_.c_str(), std::ios::in);
if( ! (*is_) )
{
ERROR(logger(), "Unable to open file (" << document_uri_.c_str() <<
") for reading: " << strerror(errno));
throw std::runtime_error("Unable to open XML file");
}
}
// ----------------------------------------------------------------------
void
SAXReader::
parse()
throw(std::runtime_error)
{
char buf[16384];
int len;
//Open the file
open_file();
//Create the SAX parser and register the C-Style handlers which will call back on this object instace
parser = XML_ParserCreate(NULL);
XML_SetUserData(parser, (void*)this);
XML_SetElementHandler(parser, saxreader_start, saxreader_end);
XML_SetCharacterDataHandler(parser, saxreader_text);
//Read the file until the end of file
while( !is_->eof() && !stop_flag_ )
{
is_->read( buf, sizeof(buf) );
len = is_->gcount();
if (XML_Parse(parser, buf, len, is_->eof()) == XML_STATUS_ERROR)
{
ERROR(logger(), XML_ErrorString(XML_GetErrorCode(parser)) <<
"at line " << XML_GetCurrentLineNumber(parser));
reset();
throw std::runtime_error("Error in parsing XML input");
}
}
//Done -> Close the file and free all associated memory
parsing_done();
reset();
XML_ParserFree(parser);
}
void SAXReader::parse_Object(XMLObj * flegsens_xml_obj) throw(std::runtime_error) {
char buf[16384];
int len;
//Create the SAX parser and register the C-Style handlers which will call back on this object instace
parser = XML_ParserCreate(NULL);
XML_SetUserData(parser, (void*)this);
XML_SetElementHandler(parser, saxreader_start, saxreader_end);
while( !flegsens_xml_obj->eof() && !stop_flag_ ) {
flegsens_xml_obj->read( buf, sizeof(buf) );
len = flegsens_xml_obj->gcount();
if (XML_Parse(parser, buf, len, flegsens_xml_obj->eof()) == XML_STATUS_ERROR)
{
ERROR(logger(), XML_ErrorString(XML_GetErrorCode(parser)) <<
"at line " << XML_GetCurrentLineNumber(parser));
reset();
throw std::runtime_error("Error in parsing XML input");
}
}
//Done -> Close the file and free all associated memory
parsing_done();
reset();
XML_ParserFree(parser);
}
// ----------------------------------------------------------------------
void
SAXReader::
parsing_done()
throw()
{}
// ----------------------------------------------------------------------
void
SAXReader::
handle_start_element(std::string name, AttList& atts)
throw(std::runtime_error)
{}
// ----------------------------------------------------------------------
void
SAXReader::
handle_end_element(std::string name)
throw(std::runtime_error)
{}
// ----------------------------------------------------------------------
void
SAXReader::
handle_text_element(std::string content)
throw(std::runtime_error)
{}
// *********************************************************************
// *********************************************************************
// *********************************************************************
// ----------------------------------------------------------------------
void
SAXSkipReader::
reset()
throw()
{
SAXReader::reset();
clear_skip_target();
}
// ----------------------------------------------------------------------
///
void
SAXSkipReader::
handle_start_element(std::string name, AttList& atts)
throw(std::runtime_error)
{
SAXReader::handle_start_element(name, atts);
if( check_skip_target_reached(name, atts, true) )
skip_target_reached(name, atts);
}
// ----------------------------------------------------------------------
void SAXSkipReader::
handle_end_element(std::string name)
throw(std::runtime_error)
{
SAXReader::handle_end_element(name);
AttList atts;
if( check_skip_target_reached(name, atts, false) )
skip_target_reached(name, atts);
}
// *********************************************************************
// *********************************************************************
// *********************************************************************
// ----------------------------------------------------------------------
SAXSimpleSkipReader::
SAXSimpleSkipReader()
: skip_to_tag_( "" )
{
clear_skip_target();
}
// ----------------------------------------------------------------------
void
SAXSimpleSkipReader::
set_skip_target(string name, bool opening_tag /* = true */)
{
assert(name != "");
clear_skip_target();
skip_to_tag_ = name;
skip_to_opening_tag = opening_tag;
}
// ----------------------------------------------------------------------
void
SAXSimpleSkipReader::
clear_skip_target()
{
skip_to_tag_ = "";
skip_to_tag_atts_.clear();
skip_to_opening_tag = true;
return;
}
// ----------------------------------------------------------------------
/// Returns true if we are in skipping mode
/**
*
*/
bool
SAXSimpleSkipReader::
skipping()
{
return skip_to_tag_ != "";
}
// ----------------------------------------------------------------------
void
SAXSimpleSkipReader::
set_skip_target_add_attr(string name, string value)
{
skip_to_tag_atts_[name] = value;
}
// ----------------------------------------------------------------------
bool
SAXSimpleSkipReader::
check_skip_target_reached(string name, AttList& atts, bool opening_tag)
{
string tmp;
//Check if the current tag name equals the needed skip target
if( this->skip_to_tag_ != name )
return false;
//Check if we need to skip at all or the tag is of the same type
if( !skipping() || opening_tag != skip_to_opening_tag)
return false;
//Check all attributes if we have reached an opening tag
if( opening_tag )
{
for( str_str_map::iterator it = skip_to_tag_atts_.begin(); it != skip_to_tag_atts_.end(); it++)
{
tmp = attribute( (*it).first, atts );
//Attribute not found -> No match
if(tmp == "")
return false;
//Attribute has wrong value -> No match
if( (*it).second != tmp )
return false;
}
}
//Skip target reached
clear_skip_target();
return true;
}
}
}
/*-----------------------------------------------------------------------
* Source $Source: /cvs/shawn/shawn/sys/xml/sax_reader.cpp,v $
* Version $Revision: 550 $
* Date $Date: 2011-04-18 10:21:12 +0200 (Mon, 18 Apr 2011) $
*-----------------------------------------------------------------------
* $Log: sax_reader.cpp,v $
*-----------------------------------------------------------------------*/
| 30.308511 | 113 | 0.409354 | [
"object"
] |
2da001dafcd63e73b82709ab4c4a56b1c2ba10c1 | 7,974 | cpp | C++ | Events/src/apKernelSourceBreakpointsUpdatedEvent.cpp | GPUOpen-Tools/common-src-AMDTAPIClasses | 33c696c3b9d17d621675645bfa1437d67dc27d0b | [
"MIT"
] | 1 | 2017-01-28T14:12:29.000Z | 2017-01-28T14:12:29.000Z | Events/src/apKernelSourceBreakpointsUpdatedEvent.cpp | GPUOpen-Tools/common-src-AMDTAPIClasses | 33c696c3b9d17d621675645bfa1437d67dc27d0b | [
"MIT"
] | null | null | null | Events/src/apKernelSourceBreakpointsUpdatedEvent.cpp | GPUOpen-Tools/common-src-AMDTAPIClasses | 33c696c3b9d17d621675645bfa1437d67dc27d0b | [
"MIT"
] | 2 | 2016-09-21T12:28:23.000Z | 2019-11-01T23:07:02.000Z | //==================================================================================
// Copyright (c) 2016 , Advanced Micro Devices, Inc. All rights reserved.
//
/// \author AMD Developer Tools Team
/// \file apKernelSourceBreakpointsUpdatedEvent.cpp
///
//==================================================================================
//------------------------------ apKernelSourceBreakpointsUpdatedEvent.cpp ------------------------------
// Infra:
#include <AMDTBaseTools/Include/gtAssert.h>
#include <AMDTOSWrappers/Include/osChannel.h>
#include <AMDTOSWrappers/Include/osChannelOperators.h>
// Local:
#include <AMDTAPIClasses/Include/Events/apKernelSourceBreakpointsUpdatedEvent.h>
// ---------------------------------------------------------------------------
// Name: apKernelSourceBreakpointsUpdatedEvent::apKernelSourceBreakpointsUpdatedEvent
// Description: Constructor
// Author: AMD Developer Tools Team
// Date: 8/5/2011
// ---------------------------------------------------------------------------
apKernelSourceBreakpointsUpdatedEvent::apKernelSourceBreakpointsUpdatedEvent(osThreadId triggeringThreadID, oaCLProgramHandle debuggedProgramHandle)
: apEvent(triggeringThreadID), _debuggedProgramHandle(debuggedProgramHandle)
{
}
// ---------------------------------------------------------------------------
// Name: apKernelSourceBreakpointsUpdatedEvent::~apKernelSourceBreakpointsUpdatedEvent
// Description: Destructor
// Author: AMD Developer Tools Team
// Date: 8/5/2011
// ---------------------------------------------------------------------------
apKernelSourceBreakpointsUpdatedEvent::~apKernelSourceBreakpointsUpdatedEvent()
{
}
// ---------------------------------------------------------------------------
// Name: apKernelSourceBreakpointsUpdatedEvent::type
// Description: Returns my transferable object type.
// Author: AMD Developer Tools Team
// Date: 8/5/2011
// ---------------------------------------------------------------------------
osTransferableObjectType apKernelSourceBreakpointsUpdatedEvent::type() const
{
return OS_TOBJ_ID_KERNEL_SOURCE_BREAKPOINTS_UPDATED_EVENT;
}
// ---------------------------------------------------------------------------
// Name: apKernelSourceBreakpointsUpdatedEvent::writeSelfIntoChannel
// Description: Writes this class data into a communication channel
// Return Val: bool - Success / failure.
// Author: AMD Developer Tools Team
// Date: 8/5/2011
// ---------------------------------------------------------------------------
bool apKernelSourceBreakpointsUpdatedEvent::writeSelfIntoChannel(osChannel& ipcChannel) const
{
// Call my parent class's version of this function:
bool retVal = apEvent::writeSelfIntoChannel(ipcChannel);
// Write the program handle
ipcChannel << (gtUInt64)_debuggedProgramHandle;
// Write the breakpoint bindings:
gtInt32 numberOfBindings = (gtInt32)_updatedBreakpoints.size();
ipcChannel << numberOfBindings;
for (gtInt32 i = 0; i < numberOfBindings; i++)
{
// Requested line:
ipcChannel << (gtInt32)_updatedBreakpoints[i]._requestedLineNumber;
// Bound line:
ipcChannel << (gtInt32)_updatedBreakpoints[i]._boundLineNumber;
}
return retVal;
}
// ---------------------------------------------------------------------------
// Name: apKernelSourceBreakpointsUpdatedEvent::readSelfFromChannel
// Description: Reads this class data from a communication channel
// Return Val: bool - Success / failure.
// Author: AMD Developer Tools Team
// Date: 8/5/2011
// ---------------------------------------------------------------------------
bool apKernelSourceBreakpointsUpdatedEvent::readSelfFromChannel(osChannel& ipcChannel)
{
// Call my parent class's version of this function:
bool retVal = apEvent::readSelfFromChannel(ipcChannel);
// Read the program handle
gtUInt64 debuggedProgramHandleAsUInt64 = OA_CL_NULL_HANDLE;
ipcChannel >> debuggedProgramHandleAsUInt64;
_debuggedProgramHandle = (oaCLProgramHandle)debuggedProgramHandleAsUInt64;
// Read the breakpoint bindings:
_updatedBreakpoints.clear();
gtInt32 numberOfBindings = -1;
ipcChannel >> numberOfBindings;
for (gtInt32 i = 0; i < numberOfBindings; i++)
{
// Requested line:
gtInt32 requestedLineAsInt32 = -1;
ipcChannel >> requestedLineAsInt32;
// Bound line:
gtInt32 boundLineAsInt32 = -1;
ipcChannel >> boundLineAsInt32;
addBreakpointBinding((int)requestedLineAsInt32, (int)boundLineAsInt32);
}
return retVal;
}
// ---------------------------------------------------------------------------
// Name: apKernelSourceBreakpointsUpdatedEvent::eventType
// Description: Returns my debugged process event type.
// Author: AMD Developer Tools Team
// Date: 8/5/2011
// ---------------------------------------------------------------------------
apEvent::EventType apKernelSourceBreakpointsUpdatedEvent::eventType() const
{
return apEvent::AP_KERNEL_SOURCE_BREAKPOINTS_UPDATED_EVENT;
}
// ---------------------------------------------------------------------------
// Name: apKernelSourceBreakpointsUpdatedEvent::clone
// Description: Creates a new copy of self, and returns it.
// It is the caller's responsibility to delete the created copy.
// Author: AMD Developer Tools Team
// Date: 8/5/2011
// ---------------------------------------------------------------------------
apEvent* apKernelSourceBreakpointsUpdatedEvent::clone() const
{
apKernelSourceBreakpointsUpdatedEvent* pClone = new apKernelSourceBreakpointsUpdatedEvent(triggeringThreadId(), _debuggedProgramHandle);
int numberOfBindings = (int)_updatedBreakpoints.size();
for (int i = 0; i < numberOfBindings; i++)
{
pClone->addBreakpointBinding(_updatedBreakpoints[i]._requestedLineNumber, _updatedBreakpoints[i]._boundLineNumber);
}
return pClone;
}
// ---------------------------------------------------------------------------
// Name: apKernelSourceBreakpointsUpdatedEvent::addBreakpointBinding
// Description: Adds a breakpoint binding to our vector:
// Author: AMD Developer Tools Team
// Date: 8/5/2011
// ---------------------------------------------------------------------------
void apKernelSourceBreakpointsUpdatedEvent::addBreakpointBinding(int requestedLineNumber, int boundLineNumber)
{
apKernelSourceBreakpointBinding newBinding;
newBinding._requestedLineNumber = requestedLineNumber;
newBinding._boundLineNumber = boundLineNumber;
_updatedBreakpoints.push_back(newBinding);
}
// ---------------------------------------------------------------------------
// Name: apKernelSourceBreakpointsUpdatedEvent::getBreakpointBoundLineNumber
// Description: Looks through the breakpoints bound again at the event. If the
// requested line number is matched, returns the new bound number.
// otherwise, returns -1.
// Author: AMD Developer Tools Team
// Date: 8/5/2011
// ---------------------------------------------------------------------------
int apKernelSourceBreakpointsUpdatedEvent::getBreakpointBoundLineNumber(int requestedLineNumber) const
{
int retVal = -1;
// Look for this binding in our list:
int numberOfBindings = (int)_updatedBreakpoints.size();
for (int i = 0; i < numberOfBindings; i++)
{
// If we found it:
if (_updatedBreakpoints[i]._requestedLineNumber == requestedLineNumber)
{
// Make sure it's a valid value:
int foundBoundLineNumber = _updatedBreakpoints[i]._boundLineNumber;
if (foundBoundLineNumber > -1)
{
// Return the value:
retVal = foundBoundLineNumber;
break;
}
}
}
return retVal;
}
| 38.336538 | 148 | 0.576499 | [
"object",
"vector"
] |
2da3b5e2a7ef740082f9d62769eb5e3282b0674b | 4,783 | hpp | C++ | geom/SO3.hpp | kerail/Daisu | d028dd44bf94c3a94897b508beae4efc384bffd0 | [
"MIT"
] | null | null | null | geom/SO3.hpp | kerail/Daisu | d028dd44bf94c3a94897b508beae4efc384bffd0 | [
"MIT"
] | null | null | null | geom/SO3.hpp | kerail/Daisu | d028dd44bf94c3a94897b508beae4efc384bffd0 | [
"MIT"
] | null | null | null | //
// Created by kerail on 10.07.16.
//
#ifndef DAISU_SO3_HPP
#define DAISU_SO3_HPP
#include <Eigen/Core>
#include <Eigen/Geometry>
#include <cmath>
#include <limits>
template<class T>
class SO3 {
public:
typedef Eigen::Matrix<T, 3, 1> Vector3;
typedef Eigen::Matrix<T, 3, 3> Matrix33;
typedef Eigen::Quaternion<T> Quaternion;
SO3(const T &x, const T &y, const T &z) {
m_coeffs = Eigen::Vector3d(x, y, z);
}
SO3(const Vector3 &v) {
m_coeffs = v;
}
SO3(T angle, const Vector3 &v) {
m_coeffs = v * angle;
}
SO3(const Quaternion &q_) {
fromQuaternion(q_);
}
SO3(const Matrix33 &m) {
assert(isRotationMatrix(m));
//TODO: implement
}
Matrix33 getMatrix() const {
Matrix33 m;
const Vector3 &cfs = m_coeffs;
T l2 = cfs.squaredNorm();
T l = sqrt(l2);
T sn_l, cs1_ll, cs;
if (l == T(0)) {
// if l is 0 sin(x)/x = 1
sn_l = T(1);
} else {
sn_l = sin(l) / l;
}
cs = cos(l);
static const T c_pi4096 = cos(M_PI / T(4096));
if (cs > c_pi4096) {//fabs(l) < M_PI/T(4096)
// when l is near nezo, we need to switch to more precise formula
if (l2 == T(0)) {
// when l2 is zero, we can precisely calculate limit
cs1_ll = 1 / T(2);
} else {
// 1 - cos(x) = 2 * sin(x/2)^2
T sn = sin(l / T(2));
cs1_ll = T(2) * sn * sn / l2;
}
} else {
// here l2 > 0 because abs(l) > pi/4096
cs1_ll = (T(1) - cs) / l2;
}
Vector3 sn_ax = sn_l * m_coeffs;
Vector3 cs1_l_ax = cs1_ll * m_coeffs;
T tmp;
tmp = cs1_l_ax.x() * m_coeffs.y();
m.coeffRef(0, 1) = tmp - sn_ax.z();
m.coeffRef(1, 0) = tmp + sn_ax.z();
tmp = cs1_l_ax.x() * m_coeffs.z();
m.coeffRef(0, 2) = tmp + sn_ax.y();
m.coeffRef(2, 0) = tmp - sn_ax.y();
tmp = cs1_l_ax.y() * m_coeffs.z();
m.coeffRef(1, 2) = tmp - sn_ax.x();
m.coeffRef(2, 1) = tmp + sn_ax.x();
m.diagonal() = (cs1_l_ax.cwiseProduct(m_coeffs)).array() + cs;
// Vector3 sq = cs1_l_ax.cwiseProduct(m_coeffs);
// m.coeffRef(0, 0) = 1 + (-sq.y() - sq.z());
// m.coeffRef(1, 1) = 1 + (-sq.x() - sq.z());
// m.coeffRef(2, 2) = 1 + (-sq.x() - sq.y());
// Rotation matrix checks
assert(isRotationMatrix(m));
return m;
}
Quaternion getQuaternion() const {
const Vector3 cf2 = m_coeffs / T(2);
T a = cf2.norm();
if (a > T(0)) {
T sn = sin(a) / a;
return Quaternion(cos(a), cf2.x() * sn, cf2.y() * sn, cf2.z() * sn);
} else {
return Quaternion(T(1), cf2.x(), cf2.y(), cf2.z());
}
}
Vector3 rotateVector(const Vector3 &v) const {
T l2 = m_coeffs.squaredNorm();
T l = sqrt(l2);
T sa_l, ca, ca1_ll;
if (l == T(0)) {
sa_l = 1;
} else {
sa_l = sin(l) / l;
}
ca = cos(l);
static const T c_pi4096 = cos(M_PI / T(4096));
if (ca > c_pi4096) {//fabs(l) < M_PI/T(4096)
// when l is near nezo, we need to switch to more precise formula
if (l2 == T(0)) {
// when l2 is zero, we can precisely calculate limit
ca1_ll = 1 / T(2);
} else {
// 1 - cos(x) = 2 * sin(x/2)^2
T sn = sin(l / T(2));
ca1_ll = T(2) * sn * sn / l2;
}
} else {
// here l2 > 0 because abs(l) > pi/4096
ca1_ll = (T(1) - ca) / l2;
}
return v * ca + (m_coeffs * sa_l).cross(v) + m_coeffs * ((m_coeffs.dot(v)) * ca1_ll);
}
Vector3 coeffs() const {
return m_coeffs;
}
T getAngle() const {
return m_coeffs.norm();
}
Vector3 getAxis() const {
T a = getAngle();
return a > 0 ? (Vector3) (m_coeffs / a) : m_coeffs;
}
SO3<T> inverted() const {
return SO3<T>(-m_coeffs);
}
SO3<T> operator *(const SO3<T> &r) {
SO3<T> l(*this);
return l *= r;
}
SO3<T> &operator *=(const SO3<T> &l) {
fromQuaternion(getQuaternion() * l.getQuaternion());
return *this;
}
SO3<T> operator ~() {
return inverted();
}
private:
Vector3 m_coeffs;
void fromQuaternion(const Quaternion &q_) {
const Quaternion &q = q_.w() >= T(0) ? q_ : Quaternion(-q_.coeffs());
const Vector3 &qv = q.vec();
T sinha = qv.norm();
if (sinha > T(0)) {
T angle = T(2) * atan2(sinha, q.w()); //NOTE: signed
m_coeffs = qv * (angle / sinha);
} else {
// if l is too small, its norm can be equal 0 but norm_inf greater 0
// probably w is much bigger that vec, use it as length
m_coeffs = qv * (T(2) / q.w()); ////NOTE: signed
}
}
bool isRotationMatrix(const Matrix33 &m) const {
return ((m * m.transpose() - Matrix33::Identity()).norm() < 1e-10)
&& (fabs(fabs(m.determinant()) - 1) < 1e-10);
}
};
typedef SO3<double> SO3d;
typedef SO3<float> SO3f;
#endif //DAISU_SO3_HPP
| 23.678218 | 89 | 0.533974 | [
"geometry"
] |
2da788061ca609972237276b0b0da98e263f90d9 | 3,507 | hpp | C++ | rclcpp/include/rclcpp/parameter.hpp | ApexAI/rclcpp | 6b34bcc94c12e2213b6de7af57c3d10109402906 | [
"Apache-2.0"
] | null | null | null | rclcpp/include/rclcpp/parameter.hpp | ApexAI/rclcpp | 6b34bcc94c12e2213b6de7af57c3d10109402906 | [
"Apache-2.0"
] | 3 | 2019-11-14T12:20:06.000Z | 2020-08-07T13:51:10.000Z | rclcpp/include/rclcpp/parameter.hpp | ApexAI/rclcpp | 6b34bcc94c12e2213b6de7af57c3d10109402906 | [
"Apache-2.0"
] | 1 | 2019-04-02T07:50:18.000Z | 2019-04-02T07:50:18.000Z | // Copyright 2015 Open Source Robotics Foundation, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef RCLCPP__PARAMETER_HPP_
#define RCLCPP__PARAMETER_HPP_
#include <iostream>
#include <ostream>
#include <sstream>
#include <string>
#include <vector>
#include "rcl_interfaces/msg/parameter.hpp"
#include "rclcpp/parameter_value.hpp"
#include "rclcpp/visibility_control.hpp"
namespace rclcpp
{
/// Structure to store an arbitrary parameter with templated get/set methods.
class Parameter
{
public:
RCLCPP_PUBLIC
Parameter();
RCLCPP_PUBLIC
Parameter(const std::string & name, const ParameterValue & value);
template<typename ValueTypeT>
explicit Parameter(const std::string & name, ValueTypeT value)
: Parameter(name, ParameterValue(value))
{
}
RCLCPP_PUBLIC
ParameterType
get_type() const;
RCLCPP_PUBLIC
std::string
get_type_name() const;
RCLCPP_PUBLIC
const std::string &
get_name() const;
RCLCPP_PUBLIC
rcl_interfaces::msg::ParameterValue
get_value_message() const;
/// Get value of parameter using rclcpp::ParameterType as template argument.
template<ParameterType ParamT>
decltype(auto)
get_value() const
{
return value_.get<ParamT>();
}
/// Get value of parameter using c++ types as template argument.
template<typename T>
decltype(auto)
get_value() const
{
return value_.get<T>();
}
RCLCPP_PUBLIC
bool
as_bool() const;
RCLCPP_PUBLIC
int64_t
as_int() const;
RCLCPP_PUBLIC
double
as_double() const;
RCLCPP_PUBLIC
const std::string &
as_string() const;
RCLCPP_PUBLIC
const std::vector<uint8_t> &
as_byte_array() const;
RCLCPP_PUBLIC
const std::vector<bool> &
as_bool_array() const;
RCLCPP_PUBLIC
const std::vector<int64_t> &
as_integer_array() const;
RCLCPP_PUBLIC
const std::vector<double> &
as_double_array() const;
RCLCPP_PUBLIC
const std::vector<std::string> &
as_string_array() const;
RCLCPP_PUBLIC
static Parameter
from_parameter_msg(const rcl_interfaces::msg::Parameter & parameter);
RCLCPP_PUBLIC
rcl_interfaces::msg::Parameter
to_parameter_msg() const;
RCLCPP_PUBLIC
std::string
value_to_string() const;
private:
std::string name_;
ParameterValue value_;
};
/// Return a json encoded version of the parameter intended for a dict.
RCLCPP_PUBLIC
std::string
_to_json_dict_entry(const Parameter & param);
RCLCPP_PUBLIC
std::ostream &
operator<<(std::ostream & os, const rclcpp::Parameter & pv);
RCLCPP_PUBLIC
std::ostream &
operator<<(std::ostream & os, const std::vector<Parameter> & parameters);
} // namespace rclcpp
namespace std
{
/// Return a json encoded version of the parameter intended for a list.
RCLCPP_PUBLIC
std::string
to_string(const rclcpp::Parameter & param);
/// Return a json encoded version of a vector of parameters, as a string.
RCLCPP_PUBLIC
std::string
to_string(const std::vector<rclcpp::Parameter> & parameters);
} // namespace std
#endif // RCLCPP__PARAMETER_HPP_
| 21.515337 | 78 | 0.738523 | [
"vector"
] |
2da975d91b69019d28ad94bf7d645866588df2a6 | 13,961 | cc | C++ | tools/framebuffer_viewer/framebuffer_viewer.cc | tsubo164/Fujiyama-Renderer | a451548ba2f0f6379b523e0abf1df57c664f444c | [
"MIT"
] | 36 | 2015-05-28T05:41:10.000Z | 2021-06-07T15:43:54.000Z | tools/framebuffer_viewer/framebuffer_viewer.cc | tsubo164/Fujiyama-Renderer | a451548ba2f0f6379b523e0abf1df57c664f444c | [
"MIT"
] | 1 | 2015-03-06T16:44:10.000Z | 2015-06-25T05:45:49.000Z | tools/framebuffer_viewer/framebuffer_viewer.cc | tsubo164/Fujiyama-Renderer | a451548ba2f0f6379b523e0abf1df57c664f444c | [
"MIT"
] | 6 | 2015-01-16T00:15:31.000Z | 2018-07-08T22:00:08.000Z | // Copyright (c) 2011-2020 Hiroshi Tsubokawa
// See LICENSE and README
#include "framebuffer_viewer.h"
#include "fj_framebuffer_io.h"
#include "fj_rectangle.h"
#include "fj_protocol.h"
#include "fj_numeric.h"
#include "fj_mipmap.h"
#include "fj_color.h"
#include "fj_box.h"
#include "compatible_opengl.h"
#include "load_images.h"
#include <iostream>
#include <cmath>
#include <cassert>
namespace fj {
static bool is_socket_ready = false;
static void draw_tile_guide(int width, int height, int tilesize);
FrameBufferViewer::FrameBufferViewer() :
filename_(""),
status_message_(""),
is_listening_(false),
win_width_(0),
win_height_(0),
diplay_channel_(DISPLAY_RGB),
pressbutton_(MOUSE_BUTTON_NONE),
viewbox_(),
tilesize_(0),
draw_tile_(1),
server_(),
state_(STATE_NONE),
tile_status_(),
frame_id_(-1)
{
set_to_home_position();
}
FrameBufferViewer::~FrameBufferViewer()
{
if (is_socket_ready) {
const int err = SocketCleanup();
if (err) {
std::cerr << "SocketCleanup() failed: " << SocketErrorMessage() << "\n\n";
}
is_socket_ready = false;
}
}
void FrameBufferViewer::Draw() const
{
const int xviewsize = viewbox_.Size()[0];
const int yviewsize = viewbox_.Size()[1];
const float xmove = scale_ * xoffset_;
const float ymove = scale_ * yoffset_;
glClearColor(.2f, .2f, .2f, 1.f);
glClear(GL_COLOR_BUFFER_BIT);
if (fb_.IsEmpty()) {
return;
}
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glTranslatef(xmove, ymove, 0.f);
glScalef(scale_, scale_, 1.f);
glTranslatef(-.5 * xviewsize, -.5 * yviewsize, 0.f);
// render background
glColor3f(0.f, 0.f, 0.f);
glBegin(GL_QUADS);
glVertex3f(viewbox_.min[0], viewbox_.min[1], 0.f);
glVertex3f(viewbox_.max[0], viewbox_.min[1], 0.f);
glVertex3f(viewbox_.max[0], viewbox_.max[1], 0.f);
glVertex3f(viewbox_.min[0], viewbox_.max[1], 0.f);
glEnd();
// render framebuffer
glTranslatef(0.f, 0.f, 0.1f);
if (!fb_.IsEmpty()) {
image_.Draw();
image_.DrawOutline();
}
// render viewbox line
glTranslatef(0.f, 0.f, 0.1f);
draw_viewbox();
// render tile guide
if (tilesize_ > 0 && draw_tile_ == 1) {
glTranslatef(0.f, 0.f, 0.2f);
glPushAttrib(GL_CURRENT_BIT);
glLineStipple(1, 0x3333);
glColor3f(.5f, .5f, .5f);
draw_tile_guide(xviewsize, yviewsize, tilesize_);
glPopAttrib();
}
// render rendering guide
glTranslatef(0.f, 0.f, 0.1f);
glPushAttrib(GL_CURRENT_BIT);
glDisable(GL_LINE_STIPPLE);
glColor3f(1, 1, 1);
for (size_t i = 0; i < tile_status_.size(); i++)
{
if (tile_status_[i].state == STATE_RENDERING) {
GLfloat xmin = tile_status_[i].region.min[0] + 5 * 0;
GLfloat ymin = tile_status_[i].region.min[1] + 5 * 0;
GLfloat xmax = tile_status_[i].region.max[0] - 5 * 0;
GLfloat ymax = tile_status_[i].region.max[1] - 5 * 0;
ymin = yviewsize - ymin;
ymax = yviewsize - ymax;
glBegin(GL_LINE_LOOP);
glVertex3f(xmin, ymin, 0.f);
glVertex3f(xmin, ymax, 0.f);
glVertex3f(xmax, ymax, 0.f);
glVertex3f(xmax, ymin, 0.f);
glEnd();
}
}
glPopAttrib();
// Not swapping the buffers here is intentional.
}
void FrameBufferViewer::Resize(int width, int height)
{
win_width_ = width;
win_height_ = height;
glViewport(0, 0, win_width_, win_height_);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(-.5f * win_width_, .5f * win_width_,
-.5f * win_height_, .5f * win_height_,
-1.f, 1.f);
}
void FrameBufferViewer::PressButton(MouseButton button, int x, int y)
{
xpresspos_ = x;
ypresspos_ = y;
switch (button) {
case MOUSE_BUTTON_LEFT:
break;
case MOUSE_BUTTON_MIDDLE:
pressbutton_ = MOUSE_BUTTON_MIDDLE;
xlockoffset_ = xoffset_;
ylockoffset_ = yoffset_;
dist_per_pixel_ = 1.f/scale_;
break;
case MOUSE_BUTTON_RIGHT:
pressbutton_ = MOUSE_BUTTON_RIGHT;
lockexponent_ = exponent_;
break;
default:
break;
}
}
void FrameBufferViewer::ReleaseButton(MouseButton button, int x, int y)
{
pressbutton_ = MOUSE_BUTTON_NONE;
}
void FrameBufferViewer::MoveMouse(int x, int y)
{
const int posx = x;
const int posy = y;
switch (pressbutton_) {
case MOUSE_BUTTON_MIDDLE:
xoffset_ = xlockoffset_ + dist_per_pixel_ * (posx - xpresspos_);
yoffset_ = ylockoffset_ - dist_per_pixel_ * (posy - ypresspos_);
break;
case MOUSE_BUTTON_RIGHT:
exponent_ = lockexponent_ + .01f * (float)(
(posx - xpresspos_) -
(posy - ypresspos_));
exponent_ = Clamp(exponent_, -5.f, 10.f);
scale_ = pow(2, exponent_);
break;
default:
break;
}
}
void FrameBufferViewer::PressKey(unsigned char key, int mouse_x, int mouse_y)
{
switch (key) {
case 'l':
if (IsListening()) {
StopListening();
} else {
StartListening();
}
break;
case 'h':
set_to_home_position();
Draw();
break;
case 'r':
diplay_channel_ = (diplay_channel_ == DISPLAY_R) ? DISPLAY_RGB : DISPLAY_R;
setup_image_card();
Draw();
break;
case 'g':
diplay_channel_ = (diplay_channel_ == DISPLAY_G) ? DISPLAY_RGB : DISPLAY_G;
setup_image_card();
Draw();
break;
case 'b':
diplay_channel_ = (diplay_channel_ == DISPLAY_B) ? DISPLAY_RGB : DISPLAY_B;
setup_image_card();
Draw();
break;
case 'a':
diplay_channel_ = (diplay_channel_ == DISPLAY_A) ? DISPLAY_RGB : DISPLAY_A;
setup_image_card();
Draw();
break;
case 't':
draw_tile_ = (draw_tile_ == 1) ? 0 : 1;
Draw();
break;
case 'u':
LoadImage(filename_);
Draw();
break;
case 'q':
exit(EXIT_SUCCESS);
break;
case '\033': // ESC ASCII code
if (state_ == STATE_RENDERING) {
state_ = STATE_INTERRUPTED;
}
break;
default:
break;
}
}
void FrameBufferViewer::StartListening()
{
if (IsListening())
return;
if (!is_socket_ready) {
const int err = SocketStartup();
if (err) {
std::cerr << "SocketStartup() failed: " << SocketErrorMessage() << "\n\n";
return;
} else {
is_socket_ready = true;
}
}
server_.Open();
server_.EnableReuseAddr();
server_.Bind();
server_.Listen();
is_listening_ = true;
state_ = STATE_READY;
frame_id_ = -1;
change_status_message("READY: Listening to Renderer");
}
void FrameBufferViewer::StopListening()
{
if (!IsListening())
return;
server_.Shutdown();
server_.Close();
is_listening_ = false;
state_ = STATE_NONE;
frame_id_ = -1;
change_status_message("DISCONNECTED: 'l' to Start Listening");
}
bool FrameBufferViewer::IsListening() const
{
return is_listening_;
}
void FrameBufferViewer::Listen()
{
Socket client;
const int timeout_sec = 0;
const int timeout_micro_sec = 0;
const int result = server_.AcceptOrTimeout(client, timeout_sec, timeout_micro_sec);
if (result == -1) {
// TODO ERROR HANDLING
return;
}
else if (result == 0) {
// time out
return;
}
else {
Message message;
FrameBuffer tilebuf;
int e = ReceiveMessage(client, message, tilebuf);
if (e < 0) {
// TODO ERROR HANDLING
}
client.ShutdownRead();
switch (message.type) {
case MSG_RENDER_FRAME_START:
if (frame_id_ > 0) {
// TODO ERROR HANDLING
std::cerr << "WARNING: fbview recieved another frame ID: " << message.frame_id << "\n";
std::cerr << "WARNING: fbview ignored this message.\n\n";
return;
}
frame_id_ = message.frame_id;
fb_.Resize(message.xres, message.yres, message.channel_count);
viewbox_.min[0] = 0;
viewbox_.min[1] = 0;
viewbox_.max[0] = message.xres;
viewbox_.max[1] = message.yres;
setup_image_card();
tile_status_.clear();
tile_status_.resize(message.tile_count);
state_ = STATE_RENDERING;
change_status_message("RENDERING: ESC to Stop Rendering");
break;
case MSG_RENDER_FRAME_DONE:
if (frame_id_ != message.frame_id) {
std::cerr << "WARNING: fbview recieved another frame ID: " << message.frame_id << "\n";
std::cerr << "WARNING: fbview ignored this message.\n";
return;
}
if (state_ == STATE_RENDERING) {
state_ = STATE_READY;
change_status_message("READY: Listeing to Renderer");
}
else if (state_ == STATE_INTERRUPTED) {
for (size_t i = 0; i < tile_status_.size(); i++) {
tile_status_[i] = TileStatus();
}
state_ = STATE_ABORT;
change_status_message("INCOMPLETE: Rendering Terminated");
}
frame_id_ = -1;
break;
case MSG_RENDER_TILE_START:
if (frame_id_ != message.frame_id) {
return;
}
tile_status_[message.tile_id].region.min[0] = message.xmin;
tile_status_[message.tile_id].region.min[1] = message.ymin;
tile_status_[message.tile_id].region.max[0] = message.xmax;
tile_status_[message.tile_id].region.max[1] = message.ymax;
tile_status_[message.tile_id].state = STATE_RENDERING;
break;
case MSG_RENDER_TILE_DONE:
if (frame_id_ != message.frame_id) {
return;
}
tile_status_[message.tile_id].region.min[0] = message.xmin;
tile_status_[message.tile_id].region.min[1] = message.ymin;
tile_status_[message.tile_id].region.max[0] = message.xmax;
tile_status_[message.tile_id].region.max[1] = message.ymax;
tile_status_[message.tile_id].state = STATE_DONE;
// Gamma
for (int y = 0; y < tilebuf.GetHeight(); y++) {
for (int x = 0; x < tilebuf.GetWidth(); x++) {
const Color4 color = tilebuf.GetColor(x, y);
tilebuf.SetColor(x, y, Gamma(color, 1/2.2));
}
}
PasteInto(fb_, tilebuf,
tile_status_[message.tile_id].region.min[0],
tile_status_[message.tile_id].region.min[1]);
setup_image_card();
break;
default:
// TODO ERROR HANDLING
break;
}
if (state_ == STATE_INTERRUPTED) {
change_status_message("INTERRUPTED: Aborting Render Process");
SendRenderFrameAbort(client, message.frame_id);
// abort;
}
}
}
bool FrameBufferViewer::IsRendering() const
{
return state_ == STATE_RENDERING;
}
int FrameBufferViewer::LoadImage(const std::string &filename)
{
int err = 0;
if (filename_ != filename) {
filename_ = filename;
}
const std::string ext = GetFileExtension(filename_);
if (ext == "") {
return -1;
}
if (ext == "fb") {
BufferInfo info;
err = LoadFb(filename_, &fb_, &info);
viewbox_ = info.viewbox;
tilesize_ = info.tilesize;
}
else if (ext == "mip") {
BufferInfo info;
err = LoadMip(filename_, &fb_, &info);
viewbox_ = info.viewbox;
tilesize_ = info.tilesize;
}
else {
return -1;
}
if (err) {
return -1;
}
// Gamma
for (int y = 0; y < fb_.GetHeight(); y++) {
for (int x = 0; x < fb_.GetWidth(); x++) {
const Color4 color = fb_.GetColor(x, y);
fb_.SetColor(x, y, Gamma(color, 1/2.2));
}
}
setup_image_card();
{
const char *format;
const int nchannels = fb_.GetChannelCount();
switch (nchannels) {
case 1:
format = "GRAYSCALE";
break;
case 3:
format = "RGB";
break;
case 4:
format = "RGBA";
break;
default:
format = "UNKNOWN";
break;
}
const std::string msg = filename_ + " : " +
std::to_string(viewbox_.Size()[0]) + " x " +
std::to_string(viewbox_.Size()[1]) + " : " +
format;
change_status_message(msg);
}
return err;
}
void FrameBufferViewer::GetImageSize(Rectangle &viewbox, int *nchannels) const
{
viewbox = viewbox_;
*nchannels = fb_.GetChannelCount();
}
void FrameBufferViewer::GetWindowSize(int &width, int &height) const
{
width = win_width_;
height = win_height_;
}
const std::string &FrameBufferViewer::GetStatusMessage() const
{
return status_message_;
}
void FrameBufferViewer::set_to_home_position()
{
scale_ = 1.f;
exponent_ = 0.f;
lockexponent_ = 0.f;
dist_per_pixel_ = 0.f;
xoffset_ = 0.f;
yoffset_ = 0.f;
xpresspos_ = 0;
ypresspos_ = 0;
xlockoffset_ = 0.f;
ylockoffset_ = 0.f;
}
void FrameBufferViewer::setup_image_card()
{
if (fb_.IsEmpty()) {
return;
}
image_.Init(fb_.GetReadOnly(0, 0, 0),
fb_.GetChannelCount(), diplay_channel_,
viewbox_.min[0],
-viewbox_.min[1],
viewbox_.Size()[0],
viewbox_.Size()[1]);
}
void FrameBufferViewer::draw_viewbox() const
{
float r, g, b;
switch (state_) {
case STATE_NONE:
r = g = b = .5f;
break;
case STATE_READY:
r = .4f;
g = .6f;
b = 1.f;
break;
case STATE_RENDERING:
r = .4f;
g = 1.f;
b = .6f;
break;
case STATE_INTERRUPTED:
r = 1.f;
g = 1.f;
b = .0f;
break;
case STATE_ABORT:
r = 1.f;
g = .0f;
b = .0f;
break;
default:
r = g = b = .5f;
break;
}
glPushAttrib(GL_CURRENT_BIT);
glLineStipple(1, 0x0F0F);
glColor3f(r, g, b);
glBegin(GL_LINE_LOOP);
glVertex3f(viewbox_.min[0], viewbox_.min[1], 0.f);
glVertex3f(viewbox_.min[0], viewbox_.max[1], 0.f);
glVertex3f(viewbox_.max[0], viewbox_.max[1], 0.f);
glVertex3f(viewbox_.max[0], viewbox_.min[1], 0.f);
glEnd();
glPopAttrib();
}
void FrameBufferViewer::change_status_message(const std::string &message)
{
status_message_ = message;
}
static void draw_tile_guide(int width, int height, int tilesize)
{
const int XNLINES = width / tilesize + 1;
const int YNLINES = height / tilesize + 1;
glBegin(GL_LINES);
for (int i = 0; i < XNLINES; i++) {
glVertex3f(tilesize * i, 0, 0);
glVertex3f(tilesize * i, height, 0);
}
for (int i = 0; i < YNLINES; i++) {
glVertex3f(0, tilesize * i, 0);
glVertex3f(width, tilesize * i, 0);
}
glEnd();
}
} // namespace xxx
| 22.886885 | 95 | 0.622663 | [
"render"
] |
2db8cdee0419c1e64da890d1960e5cfb69fe0e4f | 2,096 | cpp | C++ | src/tracer.cpp | cormackikkert/cadical | a863ff9967bb271f40650e700d7c80f68aa95c3f | [
"MIT"
] | 168 | 2016-11-15T17:41:23.000Z | 2022-03-04T16:58:07.000Z | src/tracer.cpp | cormackikkert/cadical | a863ff9967bb271f40650e700d7c80f68aa95c3f | [
"MIT"
] | 41 | 2018-01-29T17:07:12.000Z | 2022-03-25T07:02:40.000Z | src/tracer.cpp | cormackikkert/cadical | a863ff9967bb271f40650e700d7c80f68aa95c3f | [
"MIT"
] | 68 | 2017-12-04T22:31:21.000Z | 2022-03-13T01:49:23.000Z | #include "internal.hpp"
namespace CaDiCaL {
/*------------------------------------------------------------------------*/
Tracer::Tracer (Internal * i, File * f, bool b) :
internal (i),
file (f), binary (b),
added (0), deleted (0)
{
(void) internal;
LOG ("TRACER new");
}
Tracer::~Tracer () {
LOG ("TRACER delete");
delete file;
}
/*------------------------------------------------------------------------*/
// Support for binary DRAT format.
inline void Tracer::put_binary_zero () {
assert (binary);
assert (file);
file->put ((unsigned char) 0);
}
inline void Tracer::put_binary_lit (int lit) {
assert (binary);
assert (file);
assert (lit != INT_MIN);
unsigned x = 2*abs (lit) + (lit < 0);
unsigned char ch;
while (x & ~0x7f) {
ch = (x & 0x7f) | 0x80;
file->put (ch);
x >>= 7;
}
ch = x;
file->put (ch);
}
/*------------------------------------------------------------------------*/
void Tracer::add_derived_clause (const vector<int> & clause) {
if (file->closed ()) return;
LOG ("TRACER tracing addition of derived clause");
if (binary) file->put ('a');
for (const auto & external_lit : clause)
if (binary) put_binary_lit (external_lit);
else file->put (external_lit), file->put (' ');
if (binary) put_binary_zero ();
else file->put ("0\n");
added++;
}
void Tracer::delete_clause (const vector<int> & clause) {
if (file->closed ()) return;
LOG ("TRACER tracing deletion of clause");
if (binary) file->put ('d');
else file->put ("d ");
for (const auto & external_lit : clause)
if (binary) put_binary_lit (external_lit);
else file->put (external_lit), file->put (' ');
if (binary) put_binary_zero ();
else file->put ("0\n");
deleted++;
}
/*------------------------------------------------------------------------*/
bool Tracer::closed () { return file->closed (); }
void Tracer::close () { assert (!closed ()); file->close (); }
void Tracer::flush () {
assert (!closed ());
file->flush ();
MSG ("traced %" PRId64 " added and %" PRId64 " deleted clauses",
added, deleted);
}
}
| 24.091954 | 76 | 0.517653 | [
"vector"
] |
2dbbddcf9870fc453b0140bcc0cf31fbb61d2d2f | 1,322 | hpp | C++ | src/include/concore/as_scheduler.hpp | lucteo/concore | ffbc3b8cead7498ddad601dcf357fa72529f81ad | [
"MIT"
] | 52 | 2020-05-23T21:34:33.000Z | 2022-02-23T03:06:50.000Z | src/include/concore/as_scheduler.hpp | lucteo/concore | ffbc3b8cead7498ddad601dcf357fa72529f81ad | [
"MIT"
] | null | null | null | src/include/concore/as_scheduler.hpp | lucteo/concore | ffbc3b8cead7498ddad601dcf357fa72529f81ad | [
"MIT"
] | 2 | 2021-05-06T18:41:25.000Z | 2021-07-24T03:50:42.000Z | /**
* @file as_scheduler.hpp
* @brief Definition of @ref concore::v1::as_scheduler "as_scheduler"
*
* @see @ref concore::v1::as_scheduler "as_scheduler"
*/
#pragma once
#include <concore/as_sender.hpp>
namespace concore {
inline namespace v1 {
/**
* @brief Wrapper that transforms an executor into a scheduler
*
* @tparam E The type of the executor
*
* @details
*
* The executor should model `executor<>`.
*
* An instance of this class will be able to create one-shot senders that will execute on the
* executor stored in the instance.
*
* @see scheduler, executor, as_sender
*/
template <typename E>
struct as_scheduler {
//! Constructor
explicit as_scheduler(E e) noexcept
: ex_((E &&) e) {
#if CONCORE_CXX_HAS_CONCEPTS
static_assert(executor<E>, "Type needs to match executor concept");
#endif
}
//! The schedule CPO that returns a sender which will execute on our executor.
concore::as_sender<E> schedule() noexcept { return concore::as_sender<E>{ex_}; }
friend inline bool operator==(as_scheduler lhs, as_scheduler rhs) { return lhs.ex_ == rhs.ex_; }
friend inline bool operator!=(as_scheduler lhs, as_scheduler rhs) { return !(lhs == rhs); }
private:
//! The wrapped executor
E ex_;
};
} // namespace v1
} // namespace concore
| 25.921569 | 100 | 0.6823 | [
"model"
] |
2dbf7d940131cae96f90d5f3a8449bc13df53ccf | 15,594 | cpp | C++ | human_activity_anticipation/src/featuresRGBD_skel.cpp | birlrobotics/birlBaxter_demos | a4871cbf2587a759c958c8451746554e1663e829 | [
"MIT"
] | 24 | 2016-12-29T11:17:41.000Z | 2021-12-06T00:49:10.000Z | human_activity_anticipation/src/featuresRGBD_skel.cpp | birlrobotics/birlBaxter_demos | a4871cbf2587a759c958c8451746554e1663e829 | [
"MIT"
] | 2 | 2019-11-20T05:52:02.000Z | 2019-12-30T09:07:56.000Z | human_activity_anticipation/src/featuresRGBD_skel.cpp | birlrobotics/birlBaxter_demos | a4871cbf2587a759c958c8451746554e1663e829 | [
"MIT"
] | 9 | 2018-02-10T06:12:12.000Z | 2021-10-11T11:56:07.000Z | #include <vector>
#include <assert.h>
//#include "Point2D.h"
//#include "HOG.cpp"
//#include "HOGFeaturesOfBlock.cpp"
using namespace std;
enum BodyPart { HEAD, TORSO, LEFTARM, RIGHTARM, LEFTHAND, RIGHTHAND, FULLBODY };
class FeaturesSkelRGBD{
public:
FILE* pRecFile;
bool mirrored;
static const int BLOCK_SIDE = 8;
static const int width = 320;
static const int WIDTH = 320;
static const int height = 240;
// just keep attaching, don't put newline character (\n)..
void outputFeature(double a) {
fprintf(pRecFile, "%.3f,", a);
}
// Given (x,y,z) coordinates, converts that point into its x pixel number in the 2D image.
int xPixelFromCoords(double x, double y, double z)
{
return (int) (156.8584456124928 + 0.0976862095248 * x - 0.0006444357104 * y + 0.0015715946682 * z);
}
// Given (x,y,z) coordinates, converts that point into its y pixel number in the 2D image.
int yPixelFromCoords(double x, double y, double z)
{
return (int) (125.5357201011431 + 0.0002153447766 * x - 0.1184874093530 * y - 0.0022134485957 * z);
}
/* Given an image IMAGE and skeleton data, as well as sets of indices into the data and pos_data
arrays, and integers telling us how long the ori_inds and pos_inds arrays are, computes the
bounding box around the set of joints specified. The corners array is then populated with
the two points representing the corners of the bounding box. */
void findBoundingBox(int ***IMAGE, double **data, double **pos_data, int *ori_inds, int num_ori_inds,
int *pos_inds, int num_pos_inds, Point2D * corners)
{
const int NJOINTS = 15; // number of joints in the skeleton
const int NORI_JOINTS = 11; // number of joints that have orientation data (data array)
const int NPOS_JOINTS = 4; // number of joints without orientations (pos_data array)
// Will contain pixel values of each joint projected onto the image plane.
int **joint_pos = new int*[num_ori_inds+num_pos_inds];
for (int i = 0; i < num_ori_inds+num_pos_inds; i++){
joint_pos[i] = new int[2];
}
// Compute the pixel values for each joint.
for (int i = 0; i < num_ori_inds; i++)
{
int ind = ori_inds[i];
joint_pos[i][0] = xPixelFromCoords(data[ind][9], data[ind][10], data[ind][11]);
joint_pos[i][1] = yPixelFromCoords(data[ind][9], data[ind][10], data[ind][11]);
}
for (int i = 0; i < num_pos_inds; i++)
{
int ind = pos_inds[i];
joint_pos[num_ori_inds+i][0] = xPixelFromCoords(pos_data[ind][0], pos_data[ind][1], pos_data[ind][2]);
joint_pos[num_ori_inds+i][1] = yPixelFromCoords(pos_data[ind][0], pos_data[ind][1], pos_data[ind][2]);
}
// Find the most extreme x and y values for the bounding box.
int minX = 100000000;
int maxX = 0;
int minY = 100000000;
int maxY = 0;
for (int i = 0; i < num_ori_inds+num_pos_inds; i++)
{
if (joint_pos[i][0] < minX)
minX = joint_pos[i][0];
if (joint_pos[i][0] > maxX)
maxX = joint_pos[i][0];
if (joint_pos[i][1] < minY)
minY = joint_pos[i][1];
if (joint_pos[i][1] > maxY)
maxY = joint_pos[i][1];
}
// Populate the corners array with the bounding box corners.
corners[0] = Point2D(minX, minY);
corners[1] = Point2D(maxX, maxY);
// Tear down
for (int i = 0; i < num_ori_inds+num_pos_inds; i++){
delete [] joint_pos[i];
}
delete [] joint_pos;
}
void findHeadBoundingBox(int ***IMAGE, double **data, double **pos_data, Point2D *corners){
int ori_inds [2] = {0, 1};
int num_ori_inds = 2;
int num_pos_inds = 0;
findBoundingBox(IMAGE, data, pos_data, ori_inds, num_ori_inds, 0, num_pos_inds, corners);
}
void findTorsoBoundingBox(int ***IMAGE, double **data, double **pos_data, Point2D *corners){
int ori_inds [5] = {2, 3, 5, 7, 9};
int num_ori_inds = 5;
int num_pos_inds = 0;
findBoundingBox(IMAGE, data, pos_data, ori_inds, num_ori_inds, 0, num_pos_inds, corners);
}
void findLeftArmBoundingBox(int ***IMAGE, double **data, double **pos_data, Point2D *corners){
int ori_inds [2] = {3, 4};
int num_ori_inds = 2;
int pos_inds [1] = {0};
int num_pos_inds = 1;
findBoundingBox(IMAGE, data, pos_data, ori_inds, num_ori_inds, pos_inds, num_pos_inds, corners);
}
void findRightArmBoundingBox(int ***IMAGE, double **data, double **pos_data, Point2D *corners){
int ori_inds [2] = {5, 6};
int num_ori_inds = 2;
int pos_inds [1] = {1};
int num_pos_inds = 1;
findBoundingBox(IMAGE, data, pos_data, ori_inds, num_ori_inds, pos_inds, num_pos_inds, corners);
}
void findLeftHandBoundingBox(int ***IMAGE, double **data, double **pos_data, Point2D *corners){
int num_ori_inds = 0;
int pos_inds [1] = {0};
int num_pos_inds = 1;
findBoundingBox(IMAGE, data, pos_data, pos_inds, num_ori_inds, pos_inds, num_pos_inds, corners);
corners[1] = Point2D(min(corners[0].x+BLOCK_SIDE, 320), corners[0].y);
}
void findRightHandBoundingBox(int ***IMAGE, double **data, double **pos_data, Point2D *corners){
int num_ori_inds = 0;
int pos_inds [1] = {0};
int num_pos_inds = 1;
findBoundingBox(IMAGE, data, pos_data, pos_inds, num_ori_inds, pos_inds, num_pos_inds, corners);
corners[0] = Point2D(max(corners[1].x-BLOCK_SIDE, 0), corners[1].y);
}
void findFullBodyBoundingBox(int ***IMAGE, double **data, double **pos_data, Point2D *corners){
int ori_inds [11] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int num_ori_inds = 11;
int pos_inds [4] = {0, 1, 2, 3};
int num_pos_inds = 4;
findBoundingBox(IMAGE, data, pos_data, ori_inds, num_ori_inds, pos_inds, num_pos_inds, corners);
}
/* This function takes a HOG object and aggregates the HOG features for each stripe in the chunk.
It populates aggHogVec with one HOGFeaturesOfBlock object for each stripe in the image. */
void computeAggHogBlock(HOG & hog, int numStripes, int minXBlock, int maxXBlock, int minYBlock,
int maxYBlock, std::vector<HOGFeaturesOfBlock> & aggHogVec){
// The number of blocks in a single column of blocks in one stripe in the image.
double stripeSize = ((double)(maxYBlock - minYBlock)) / numStripes;
for (int n = 0; n < numStripes; n++)
{
// For each stripe, create a new HOGFeaturesOfBlock vector hogvec and fill it with the HOGFeaturesOfBlocks
// in this stripe.
std::vector<HOGFeaturesOfBlock> hogvec;
for (int j = (int)(minYBlock + n * stripeSize); j <= (int)(minYBlock + (n+1) * stripeSize); j++){
for (int i = minXBlock; i <= maxXBlock; i++){
HOGFeaturesOfBlock hfob;
hog.getFeatVec(j, i, hfob);
hogvec.push_back(hfob);
}
}
// Now compute the aggregate features for this stripe, and store the aggregate as its own
// HOGFeaturesOfBlock in the aggHogVec vector.
HOGFeaturesOfBlock agg_hfob;
HOGFeaturesOfBlock::aggregateFeatsOfBlocks(hogvec, agg_hfob);
aggHogVec.push_back(agg_hfob);
}
}
/* This function take a bunch of data and an enum specifying the body part, and computes the HOG features
for the bounding box surrounding that body part. The result is pushed into aggHogVec. */
void computeBodyPartHOGFeatures(int ***IMAGE, HOG & hog, double **data, double **pos_data, enum BodyPart bodyPart,
std::vector<HOGFeaturesOfBlock> & aggHogVec){
Point2D corners [2];
const int numStripes = 1;
if (bodyPart == HEAD) findHeadBoundingBox(IMAGE, data, pos_data, corners);
else if (bodyPart == TORSO) findTorsoBoundingBox(IMAGE, data, pos_data, corners);
else if (bodyPart == LEFTARM) findLeftArmBoundingBox(IMAGE, data, pos_data, corners);
else if (bodyPart == RIGHTARM) findRightArmBoundingBox(IMAGE, data, pos_data, corners);
else if (bodyPart == LEFTHAND) findLeftHandBoundingBox(IMAGE, data, pos_data, corners);
else if (bodyPart == RIGHTHAND) findRightHandBoundingBox(IMAGE, data, pos_data, corners);
else if (bodyPart == FULLBODY) findFullBodyBoundingBox(IMAGE, data, pos_data, corners);
else assert(false);
int minXBlock = (int)(corners[0].x / BLOCK_SIDE);
int minYBlock = (int)(corners[0].y / BLOCK_SIDE);
int maxXBlock = (int)(corners[1].x / BLOCK_SIDE);
int maxYBlock = (int)(corners[1].y / BLOCK_SIDE);
computeAggHogBlock(hog, numStripes, minXBlock, maxXBlock, minYBlock, maxYBlock, aggHogVec);
}
/* Take all the features in the vector aggHogVec, and compile them into a single double array. */
double* aggregateFeaturesIntoArray(std::vector<HOGFeaturesOfBlock> & aggHogVec, int *numFeats){
// First, iterate through and just count the number of features we'll need.
std::vector<HOGFeaturesOfBlock>::iterator block_iterator = aggHogVec.begin();
*numFeats = 0;
while (block_iterator != aggHogVec.end()) {
*numFeats += HOGFeaturesOfBlock::numFeats;
block_iterator++;
}
double *feats = new double[*numFeats];
// Now iterator through again and add the features in.
int ind = 0;
block_iterator = aggHogVec.begin();
while (block_iterator != aggHogVec.end()) {
for (int i = 0; i < HOGFeaturesOfBlock::numFeats; i++){
feats[ind] = block_iterator->feats[i];
ind++;
}
block_iterator++;
}
return feats;
}
/* Take all the features in the vector aggHogVec, and compile them into a single double array. */
vector<double> aggregateFeaturesIntoVector(std::vector<HOGFeaturesOfBlock> & aggHogVec, int numFeats){
// First, iterate through and just count the number of features we'll need.
std::vector<HOGFeaturesOfBlock>::iterator block_iterator = aggHogVec.begin();
numFeats = 0;
while (block_iterator != aggHogVec.end()) {
numFeats += HOGFeaturesOfBlock::numFeats;
block_iterator++;
}
vector<double> feats ;
// Now iterator through again and add the features in.
int ind = 0;
block_iterator = aggHogVec.begin();
while (block_iterator != aggHogVec.end()) {
for (int i = 0; i < HOGFeaturesOfBlock::numFeats; i++){
feats.push_back( block_iterator->feats[i]);
ind++;
}
block_iterator++;
}
return feats;
}
void mirrorData(int ***IMAGE, int width, int height){
const int NCHANNELS = 4;
int tmp;
for (int x = 0; x < width/2; x++){
for (int y = 0; y < height; y++){
for (int ch = 0; ch < NCHANNELS; ch++){
tmp = IMAGE[width-1-x][y][ch];
IMAGE[width-1-x][y][ch] = IMAGE[x][y][ch];
IMAGE[x][y][ch] = tmp;
}
}
}
}
void populateDepthImage(int ***IMAGE, int ***depthIMAGE, const int width, const int height){
double scaleFactor = 255.0 / 10000.0;
int maxValue = 255;
for (int i = 0; i < width; i++){
for (int j = 0; j < height; j++){
for (int k = 0; k < 4; k++){
depthIMAGE[i][j][k] = min((int)(IMAGE[i][j][3] * scaleFactor), maxValue);
}
}
}
}
/* Compute the HOG features for the images in the bounding boxes of various body parts.
Computes both image HOG featurs and depth HOG features.
Return a pointer to a double array with those features, and popualte the numFeats
integer with the length of the returned doubled array. Note that the first half
of the returned array is image features, while the second half is depth features. */
vector<double> computeFeatures(int ***IMAGE, double **data, double **pos_data, int numFeats,
bool useHead, bool useTorso, bool useLeftArm,
bool useRightArm, bool useLeftHand, bool useRightHand,
bool useFullBody, bool useImage, bool useDepth) {
int ***depthIMAGE;
if (useDepth){
depthIMAGE = new int**[width];
for (int i = 0; i < width; i++){
depthIMAGE[i] = new int*[height];
for (int j = 0; j < height; j++){
depthIMAGE[i][j] = new int[4];
}
}
populateDepthImage(IMAGE, depthIMAGE, width, height);
}
if (this->mirrored) mirrorData(IMAGE, width, height);
HOG hog, depthHog;
if (useImage)
hog.computeHOG(IMAGE, width, height);
if (useDepth)
depthHog.computeHOG(depthIMAGE, width, height);
std::vector<HOGFeaturesOfBlock> aggHogVec;
if (useImage){
if (useHead)
computeBodyPartHOGFeatures(IMAGE, hog, data, pos_data, HEAD, aggHogVec);
if (useTorso)
computeBodyPartHOGFeatures(IMAGE, hog, data, pos_data, TORSO, aggHogVec);
if (useLeftArm)
computeBodyPartHOGFeatures(IMAGE, hog, data, pos_data, LEFTARM, aggHogVec);
if (useRightArm)
computeBodyPartHOGFeatures(IMAGE, hog, data, pos_data, RIGHTARM, aggHogVec);
if (useLeftHand)
computeBodyPartHOGFeatures(IMAGE, hog, data, pos_data, LEFTHAND, aggHogVec);
if (useRightHand)
computeBodyPartHOGFeatures(IMAGE, hog, data, pos_data, RIGHTHAND, aggHogVec);
if (useFullBody)
computeBodyPartHOGFeatures(IMAGE, hog, data, pos_data, FULLBODY, aggHogVec);
}
if (useDepth){
if (useHead)
computeBodyPartHOGFeatures(depthIMAGE, depthHog, data, pos_data, HEAD, aggHogVec);
if (useTorso)
computeBodyPartHOGFeatures(depthIMAGE, depthHog, data, pos_data, TORSO, aggHogVec);
if (useLeftArm)
computeBodyPartHOGFeatures(depthIMAGE, depthHog, data, pos_data, LEFTARM, aggHogVec);
if (useRightArm)
computeBodyPartHOGFeatures(depthIMAGE, depthHog, data, pos_data, RIGHTARM, aggHogVec);
if (useLeftHand)
computeBodyPartHOGFeatures(depthIMAGE, depthHog, data, pos_data, LEFTHAND, aggHogVec);
if (useRightHand)
computeBodyPartHOGFeatures(depthIMAGE, depthHog, data, pos_data, LEFTHAND, aggHogVec);
if (useFullBody)
computeBodyPartHOGFeatures(depthIMAGE, depthHog, data, pos_data, FULLBODY, aggHogVec);
// Tear down
for (int i = 0; i < width; i++){
for (int j = 0; j < height; j++){
delete [] depthIMAGE[i][j];
}
delete [] depthIMAGE[i];
}
delete [] depthIMAGE;
}
return aggregateFeaturesIntoVector(aggHogVec, numFeats);
}
// MIRRORED means skeleton is mirrored; RGBD comes in non mirrored form
// but mirroring should be easy for RGBD
FeaturesSkelRGBD(FILE* pRecFile, bool mirrored) {
this->pRecFile=pRecFile;
this->mirrored=mirrored;
}
FeaturesSkelRGBD(bool mirrored) {
this->pRecFile=pRecFile;
this->mirrored=mirrored;
}
~FeaturesSkelRGBD() {
}
};
/**
there are 11 joints that have both orientation (3x3) and position (x,y,z) data
XN_SKEL_HEAD,
XN_SKEL_NECK,
XN_SKEL_TORSO,
XN_SKEL_LEFT_SHOULDER,
XN_SKEL_LEFT_ELBOW,
XN_SKEL_RIGHT_SHOULDER,
XN_SKEL_RIGHT_ELBOW,
XN_SKEL_LEFT_HIP,
XN_SKEL_LEFT_KNEE,
XN_SKEL_RIGHT_HIP,
XN_SKEL_RIGHT_KNEE
there are 4 joints that have only position (x,y,z) data
XN_SKEL_LEFT_HAND,
XN_SKEL_RIGHT_HAND,
XN_SKEL_LEFT_FOOT,
XN_SKEL_RIGHT_FOOT
data[][0~8] -> orientation (3x3 matrix)
3x3 matrix is stored as
0 1 2
3 4 5
6 7 8
read PDF for description about 3x3 matrix
data[][9~11] -> x,y,z position for eleven joints
data_CONF[][0] -> confidence value of orientation (data[][0~8])
data_CONF[][1] -> confidence value of xyz position (data[][9~11])
data_pos[][0~2] -> x,y,z position for four joints
data_pos_CONF[] -> confidence value of xyz position (data_pos[][0~2])
X_RES and Y_RES are in constants.h, so just use them.
IMAGE[X_RES][Y_RES][0~2] -> RGB values
IMAGE[X_RES][Y_RES][3] -> depth values
*/
| 36.013857 | 115 | 0.66205 | [
"object",
"vector"
] |
2dcb90d149789df4c80c2acdb32d58a19b92e45f | 26,234 | cpp | C++ | src/modules/linear_systems/sparse_linear_systems.cpp | fmcquillan99/apache-madlib | e2dea62d1eadc7f662f2d926c71f42332f414ca0 | [
"Apache-2.0"
] | 4 | 2018-09-18T07:44:22.000Z | 2021-11-14T19:45:18.000Z | src/modules/linear_systems/sparse_linear_systems.cpp | fmcquillan99/apache-madlib | e2dea62d1eadc7f662f2d926c71f42332f414ca0 | [
"Apache-2.0"
] | 1 | 2018-09-06T05:50:17.000Z | 2018-09-06T05:50:17.000Z | src/modules/linear_systems/sparse_linear_systems.cpp | fmcquillan99/apache-madlib | e2dea62d1eadc7f662f2d926c71f42332f414ca0 | [
"Apache-2.0"
] | 1 | 2019-09-03T20:50:13.000Z | 2019-09-03T20:50:13.000Z | /* ----------------------------------------------------------------------- *//**
*
* @file sparse_linear_systems.cpp
*
* @brief sparse linear systems
*
* We implement sparse linear systems using the direct.
*
*//* ----------------------------------------------------------------------- */
#include <limits>
#include <dbconnector/dbconnector.hpp>
#include <modules/shared/HandleTraits.hpp>
#include <modules/prob/boost.hpp>
#include "sparse_linear_systems.hpp"
#include <Eigen/Sparse>
// Common SQL functions used by all modules
//#include "sparse_linear_systems_states.hpp"
namespace madlib {
// Use Eigen
using namespace dbal::eigen_integration;
using namespace Eigen;
namespace modules {
// Import names from other MADlib modules
using dbal::NoSolutionFoundException;
namespace linear_systems{
// ---------------------------------------------------------------------------
// Direct sparse Linear System States
// ---------------------------------------------------------------------------
// Function protofype of Internal functions
AnyType direct_sparse_stateToResult(
const Allocator &inAllocator,
const ColumnVector &x,
const double residual);
/**
* @brief States for linear systems
*
* TransitionState encapsualtes the transition state during the
* logistic-regression aggregate function. To the database, the state is
* exposed as a single DOUBLE PRECISION array, to the C++ code it is a proper
* object containing scalars and vectors.
*
* Note: We assume that the DOUBLE PRECISION array is initialized by the
* database with length at least 5, and all elemenets are 0.
*
*/
template <class Handle>
class SparseDirectLinearSystemTransitionState {
template <class OtherHandle>
friend class SparseDirectLinearSystemTransitionState;
public:
SparseDirectLinearSystemTransitionState(const AnyType &inArray)
: mStorage(inArray.getAs<Handle>()) {
rebind( static_cast<uint32_t>(mStorage[1]),
static_cast<uint32_t>(mStorage[2]));
}
/**
* @brief Convert to backend representation
*
* We define this function so that we can use State in the
* argument list and as a return type.
*/
inline operator AnyType() const {
return mStorage;
}
/**
* @brief Initialize the conjugate-gradient state.
*
* This function is only called for the first iteration, for the first row.
*/
inline void initialize(const Allocator &inAllocator,
uint32_t innumVars,
uint32_t innumEquations,
uint32_t inNNZA
) {
// Array size does not depend in numVars
mStorage = inAllocator.allocateArray<double, dbal::AggregateContext,
dbal::DoZero, dbal::ThrowBadAlloc>(arraySize(innumEquations, inNNZA));
rebind(innumEquations, inNNZA);
numVars = innumVars;
numEquations = innumEquations;
NNZA = inNNZA;
}
/**
* @brief We need to support assigning the previous state
*/
template <class OtherHandle>
SparseDirectLinearSystemTransitionState &operator=(
const SparseDirectLinearSystemTransitionState<OtherHandle> &inOtherState) {
for (size_t i = 0; i < mStorage.size(); i++)
mStorage[i] = inOtherState.mStorage[i];
return *this;
}
/**
* @brief Merge with another State object by copying the intra-iteration
* fields
*/
template <class OtherHandle>
SparseDirectLinearSystemTransitionState &operator+=(
const SparseDirectLinearSystemTransitionState<OtherHandle> &inOtherState) {
if (mStorage.size() != inOtherState.mStorage.size() ||
numVars != inOtherState.numVars ||
NNZA != inOtherState.NNZA||
numEquations != inOtherState.numEquations)
throw std::logic_error("Internal error: Incompatible transition "
"states");
b += inOtherState.b;
b_stored += inOtherState.b_stored;
// Merge state for sparse loading is not an array add operation
// but it is an array-append operation
for (uint32_t i=0; i < inOtherState.nnz_processed; i++){
r(nnz_processed + i) += inOtherState.r(i);
c(nnz_processed + i) += inOtherState.c(i);
v(nnz_processed + i) += inOtherState.v(i);
}
nnz_processed += inOtherState.nnz_processed;
return *this;
}
/**
* @brief Reset the inter-iteration fields.
*/
inline void reset() {
nnz_processed = 0;
r.fill(0);
c.fill(0);
v.fill(0);
b.fill(0);
b_stored.fill(0);
}
private:
static inline size_t arraySize(const uint32_t innumEquations,
const uint32_t inNNZA) {
return 5 + 3 * inNNZA + 2 * innumEquations;
}
/**
* @brief Rebind to a new storage array
*
* @param innumVars The number of independent variables.
*
* Array layout (iteration refers to one aggregate-function call):
* Inter-iteration components (updated in final function):
* - 0: numVars (Total number of variables)
* - 1: numEquations (Total number of equations)
* - 2: nnZ (Total number of non-zeros)
* - 3: algorithm
* - 4: nnz_processed Number of non-zeros processed by a node
* - 4: b (RHS vector)
* - 4 + 1 * numEquations: r (LHS matrix row)
* - 4 + 1 * numEquations + 1 * nnzA: c (LHS matrix column)
* - 4 + 1 * numEquations + 2 * nnzA: v (LHS matrix value)
*/
void rebind(uint32_t innumEquations, uint32_t inNNZA) {
numVars.rebind(&mStorage[0]);
numEquations.rebind(&mStorage[1]);
NNZA.rebind(&mStorage[2]);
algorithm.rebind(&mStorage[3]);
nnz_processed.rebind(&mStorage[4]);
b.rebind(&mStorage[5], innumEquations);
b_stored.rebind(&mStorage[5 + innumEquations], innumEquations);
r.rebind(&mStorage[5 + 2*innumEquations], inNNZA);
c.rebind(&mStorage[5 + 2*innumEquations + inNNZA], inNNZA);
v.rebind(&mStorage[5 + 2*innumEquations + 2 * inNNZA], inNNZA);
}
Handle mStorage;
public:
typename HandleTraits<Handle>::ReferenceToUInt32 numVars;
typename HandleTraits<Handle>::ReferenceToUInt32 numEquations;
typename HandleTraits<Handle>::ReferenceToUInt32 NNZA;
typename HandleTraits<Handle>::ReferenceToUInt32 nnz_processed;
typename HandleTraits<Handle>::ReferenceToUInt32 algorithm;
typename HandleTraits<Handle>::ColumnVectorTransparentHandleMap b_stored;
typename HandleTraits<Handle>::ColumnVectorTransparentHandleMap b;
typename HandleTraits<Handle>::ColumnVectorTransparentHandleMap r;
typename HandleTraits<Handle>::ColumnVectorTransparentHandleMap c;
typename HandleTraits<Handle>::ColumnVectorTransparentHandleMap v;
};
/**
* @brief Perform the sparse linear system transition step
*/
AnyType
sparse_direct_linear_system_transition::run(AnyType &args) {
SparseDirectLinearSystemTransitionState<MutableArrayHandle<double> >
state = args[0];
int32_t row_id = args[1].getAs<int32_t>();
int32_t col_id = args[2].getAs<int32_t>();
double value = args[3].getAs<double>();
double _b = args[4].getAs<double>();
// When the segment recieves the first non-zero in the sparse matrix
// we initialize the state
if (state.nnz_processed == 0) {
int32_t num_equations = args[5].getAs<int32_t>();
int32_t num_vars = args[6].getAs<int32_t>();
int32_t total_nnz = args[7].getAs<int32_t>();
int algorithm = args[8].getAs<int>();
state.initialize(*this,
num_vars,
num_equations,
total_nnz
);
state.algorithm = algorithm;
state.NNZA = total_nnz;
state.numVars = num_vars;
state.numEquations = num_equations;
state.b_stored.setZero();
state.b.setZero();
}
// Now do the transition step
// First we create a block of zeros in memory
// and then add the vector in the appropriate position
ColumnVector bvec(static_cast<uint32_t>(state.numEquations));
ColumnVector rvec(static_cast<uint32_t>(state.NNZA));
ColumnVector cvec(static_cast<uint32_t>(state.NNZA));
ColumnVector vvec(static_cast<uint32_t>(state.NNZA));
bvec.setZero();
rvec.setZero();
cvec.setZero();
vvec.setZero();
rvec(state.nnz_processed) = row_id;
cvec(state.nnz_processed) = col_id;
vvec(state.nnz_processed) = value;
if (state.b_stored(row_id) == 0) {
bvec(row_id) = _b;
state.b_stored(row_id) = 1;
state.b += bvec;
}
// Build the vector & matrices based on row_id
state.r += rvec;
state.c += cvec;
state.v += vvec;
state.nnz_processed++;
return state;
}
/**
* @brief Perform the perliminary aggregation function: Merge transition states
*/
AnyType
sparse_direct_linear_system_merge_states::run(AnyType &args) {
SparseDirectLinearSystemTransitionState<MutableArrayHandle<double> > stateLeft = args[0];
SparseDirectLinearSystemTransitionState<ArrayHandle<double> > stateRight = args[1];
// We first handle the trivial case where this function is called with one
// of the states being the initial state
if (stateLeft.numEquations == 0)
return stateRight;
else if (stateRight.numEquations == 0)
return stateLeft;
// Merge states together and return
stateLeft += stateRight;
return stateLeft;
}
/**
* @brief Perform the linear system final step
*/
AnyType
sparse_direct_linear_system_final::run(AnyType &args) {
// We request a mutable object. Depending on the backend, this might perform
// a deep copy.
SparseDirectLinearSystemTransitionState<MutableArrayHandle<double> > state = args[0];
// Aggregates that haven't seen any data just return Null.
if (state.numEquations == 0)
return Null();
// Eigen works better when you reserve the number of nnz
// Note: When calling reserve(), it is not required that nnz is the
// exact number of nonzero elements in the final matrix. However, an
// exact estimation will avoid multiple reallocations during the
// insertion phase.
SparseMatrix A(state.numEquations, state.numVars);
A.reserve(state.NNZA);
ColumnVector x;
for (uint32_t i=0; i < state.NNZA; i++){
A.insert(static_cast<uint32_t>(state.r(i)),
static_cast<uint32_t>(state.c(i))) = state.v(i);
}
// Switch case needs scoping in C++ if you want to declare inside it
// Unfortunately, this means that I have to write the code to call the
// solver in each switch case separtely
switch (state.algorithm) {
case 1:{
Eigen::SimplicialLLT<SparseMatrix> solver;
solver.compute(A);
x = solver.solve(state.b);
break;
}
case 2:{
Eigen::SimplicialLDLT<SparseMatrix> solver;
solver.compute(A);
x = solver.solve(state.b);
break;
}
}
// It is unclear whether I should do the residual computation in-memory or
// in-database (as done in the dense linear systems case)
ColumnVector bvec = state.b;
double residual = (A*x-bvec).norm() / bvec.norm();
// Compute the residual
return direct_sparse_stateToResult(*this, x, residual);
}
/**
* @brief Helper function that computes the final statistics
*/
AnyType direct_sparse_stateToResult(
const Allocator &inAllocator,
const ColumnVector &x,
const double residual) {
MutableNativeColumnVector solution(
inAllocator.allocateArray<double>(x.size()));
for (Index i = 0; i < x.size(); ++i) {
solution(i) = x(i);
}
// Return all coefficients, standard errors, etc. in a tuple
AnyType tuple;
tuple << solution
<< residual
<< Null();
return tuple;
}
// ---------------------------------------------------------------------------
// In-memory iterative sparse Linear System States
// ---------------------------------------------------------------------------
// Function protofype of Internal functions
AnyType inmem_iterative_sparse_stateToResult(
const Allocator &inAllocator,
const ColumnVector &x,
const int iters,
const double residual_norm);
/**
* @brief States for linear systems
*
* TransitionState encapsualtes the transition state during the
* logistic-regression aggregate function. To the database, the state is
* exposed as a single DOUBLE PRECISION array, to the C++ code it is a proper
* object containing scalars and vectors.
*
* Note: We assume that the DOUBLE PRECISION array is initialized by the
* database with length at least 5, and all elemenets are 0.
*
*/
template <class Handle>
class SparseInMemIterativeLinearSystemTransitionState {
template <class OtherHandle>
friend class SparseInMemIterativeLinearSystemTransitionState;
public:
SparseInMemIterativeLinearSystemTransitionState(const AnyType &inArray)
: mStorage(inArray.getAs<Handle>()) {
rebind( static_cast<uint32_t>(mStorage[1]),
static_cast<uint32_t>(mStorage[2]));
}
/**
* @brief Convert to backend representation
*
* We define this function so that we can use State in the
* argument list and as a return type.
*/
inline operator AnyType() const {
return mStorage;
}
/**
* @brief Initialize the conjugate-gradient state.
*
* This function is only called for the first iteration, for the first row.
*/
inline void initialize(const Allocator &inAllocator,
uint32_t innumVars,
uint32_t innumEquations,
uint32_t inNNZA
) {
// Array size does not depend in numVars
mStorage = inAllocator.allocateArray<double, dbal::AggregateContext,
dbal::DoZero, dbal::ThrowBadAlloc>(arraySize(innumEquations, inNNZA));
rebind(innumEquations, inNNZA);
numVars = innumVars;
numEquations = innumEquations;
NNZA = inNNZA;
}
/**
* @brief We need to support assigning the previous state
*/
template <class OtherHandle>
SparseInMemIterativeLinearSystemTransitionState &operator=(
const SparseInMemIterativeLinearSystemTransitionState<OtherHandle> &inOtherState) {
for (size_t i = 0; i < mStorage.size(); i++)
mStorage[i] = inOtherState.mStorage[i];
return *this;
}
/**
* @brief Merge with another State object by copying the intra-iteration
* fields
*/
template <class OtherHandle>
SparseInMemIterativeLinearSystemTransitionState &operator+=(
const SparseInMemIterativeLinearSystemTransitionState<OtherHandle> &inOtherState) {
if (mStorage.size() != inOtherState.mStorage.size() ||
numVars != inOtherState.numVars ||
NNZA != inOtherState.NNZA||
numEquations != inOtherState.numEquations)
throw std::logic_error("Internal error: Incompatible transition "
"states");
b += inOtherState.b;
b_stored += inOtherState.b_stored;
// Merge state for sparse loading is not an array add operation
// but it is an array-append operation
for (uint32_t i=0; i < inOtherState.nnz_processed; i++){
r(nnz_processed + i) += inOtherState.r(i);
c(nnz_processed + i) += inOtherState.c(i);
v(nnz_processed + i) += inOtherState.v(i);
}
nnz_processed += inOtherState.nnz_processed;
return *this;
}
/**
* @brief Reset the inter-iteration fields.
*/
inline void reset() {
nnz_processed = 0;
r.fill(0);
c.fill(0);
v.fill(0);
b.fill(0);
b_stored.fill(0);
}
private:
static inline size_t arraySize(const uint32_t innumEquations,
const uint32_t inNNZA) {
return 7 + 3 * inNNZA + 2 * innumEquations;
}
/**
* @brief Rebind to a new storage array
*
* @param innumVars The number of independent variables.
*
* Array layout (iteration refers to one aggregate-function call):
* Inter-iteration components (updated in final function):
* - 0: numVars (Total number of variables)
* - 1: numEquations (Total number of equations)
* - 2: nnZ (Total number of non-zeros)
* - 3: algorithm
* - 4: maxIter
* - 5: termToler
* - 6: nnz_processed Number of non-zeros processed by a node
* - 7: b (RHS vector)
* - 7: b_stored (Boolean: Has the b_vector already been loaded?)
* - 7 + 2 * numEquations: r (LHS matrix row)
* - 7 + 2 * numEquations + 1 * nnzA: c (LHS matrix column)
* - 7 + 2 * numEquations + 2 * nnzA: v (LHS matrix value)
*/
void rebind(uint32_t innumEquations, uint32_t inNNZA) {
numVars.rebind(&mStorage[0]);
numEquations.rebind(&mStorage[1]);
NNZA.rebind(&mStorage[2]);
algorithm.rebind(&mStorage[3]);
nnz_processed.rebind(&mStorage[4]);
maxIter.rebind(&mStorage[5]);
termToler.rebind(&mStorage[6]);
b.rebind(&mStorage[7], innumEquations);
b_stored.rebind(&mStorage[7 + innumEquations], innumEquations);
r.rebind(&mStorage[7 + 2*innumEquations], inNNZA);
c.rebind(&mStorage[7 + 2*innumEquations + inNNZA], inNNZA);
v.rebind(&mStorage[7 + 2*innumEquations + 2 * inNNZA], inNNZA);
}
Handle mStorage;
public:
typename HandleTraits<Handle>::ReferenceToUInt32 numVars;
typename HandleTraits<Handle>::ReferenceToUInt32 numEquations;
typename HandleTraits<Handle>::ReferenceToUInt32 NNZA;
typename HandleTraits<Handle>::ReferenceToUInt32 nnz_processed;
typename HandleTraits<Handle>::ReferenceToUInt32 algorithm;
typename HandleTraits<Handle>::ReferenceToUInt32 maxIter;
typename HandleTraits<Handle>::ReferenceToDouble termToler;
typename HandleTraits<Handle>::ColumnVectorTransparentHandleMap b_stored;
typename HandleTraits<Handle>::ColumnVectorTransparentHandleMap b;
typename HandleTraits<Handle>::ColumnVectorTransparentHandleMap r;
typename HandleTraits<Handle>::ColumnVectorTransparentHandleMap c;
typename HandleTraits<Handle>::ColumnVectorTransparentHandleMap v;
};
/**
* @brief Perform the sparse linear system transition step
*/
AnyType
sparse_inmem_iterative_linear_system_transition::run(AnyType &args) {
SparseInMemIterativeLinearSystemTransitionState<MutableArrayHandle<double> >
state = args[0];
int32_t row_id = args[1].getAs<int32_t>();
int32_t col_id = args[2].getAs<int32_t>();
double value = args[3].getAs<double>();
double _b = args[4].getAs<double>();
// When the segment recieves the first non-zero in the sparse matrix
// we initialize the state
if (state.nnz_processed == 0) {
int32_t num_equations = args[5].getAs<int32_t>();
int32_t num_vars = args[6].getAs<int32_t>();
int32_t total_nnz = args[7].getAs<int32_t>();
int algorithm = args[8].getAs<int>();
int32_t maxIter = args[9].getAs<int>();
double termToler = args[10].getAs<double>();
state.initialize(*this,
num_vars,
num_equations,
total_nnz
);
state.algorithm = algorithm;
state.NNZA = total_nnz;
state.numVars = num_vars;
state.numEquations = num_equations;
state.maxIter = maxIter;
state.termToler = termToler;
state.b_stored.setZero();
state.b.setZero();
}
// Now do the transition step
// First we create a block of zeros in memory
// and then add the vector in the appropriate position
ColumnVector bvec(static_cast<uint32_t>(state.numEquations));
ColumnVector rvec(static_cast<uint32_t>(state.NNZA));
ColumnVector cvec(static_cast<uint32_t>(state.NNZA));
ColumnVector vvec(static_cast<uint32_t>(state.NNZA));
bvec.setZero();
rvec.setZero();
cvec.setZero();
vvec.setZero();
rvec(state.nnz_processed) = row_id;
cvec(state.nnz_processed) = col_id;
vvec(state.nnz_processed) = value;
if (state.b_stored(row_id) == 0) {
bvec(row_id) = _b;
state.b_stored(row_id) = 1;
state.b += bvec;
}
// Build the vector & matrices based on row_id
state.r += rvec;
state.c += cvec;
state.v += vvec;
state.nnz_processed++;
return state;
}
/**
* @brief Perform the perliminary aggregation function: Merge transition states
*/
AnyType
sparse_inmem_iterative_linear_system_merge_states::run(AnyType &args) {
SparseInMemIterativeLinearSystemTransitionState<MutableArrayHandle<double> > stateLeft = args[0];
SparseInMemIterativeLinearSystemTransitionState<ArrayHandle<double> > stateRight = args[1];
// We first handle the trivial case where this function is called with one
// of the states being the initial state
if (stateLeft.numEquations == 0)
return stateRight;
else if (stateRight.numEquations == 0)
return stateLeft;
// Merge states together and return
stateLeft += stateRight;
return stateLeft;
}
/**
* @brief Perform the linear system final step
*/
AnyType
sparse_inmem_iterative_linear_system_final::run(AnyType &args) {
// We request a mutable object. Depending on the backend, this might perform
// a deep copy.
SparseInMemIterativeLinearSystemTransitionState<MutableArrayHandle<double> > state = args[0];
// Aggregates that haven't seen any data just return Null.
if (state.numEquations == 0)
return Null();
// Eigen works better when you reserve the number of nnz
// Note: When calling reserve(), it is not required that nnz is the
// exact number of nonzero elements in the final matrix. However, an
// exact estimation will avoid multiple reallocations during the
// insertion phase.
SparseMatrix A(state.numEquations, state.numVars);
A.reserve(state.NNZA);
ColumnVector x;
for (uint32_t i=0; i < state.NNZA; i++){
A.insert(static_cast<uint32_t>(state.r(i)),
static_cast<uint32_t>(state.c(i))) = state.v(i);
}
int iters = 0;
double error = 0.;
// Switch case needs scoping in C++ if you want to declare inside it
// Unfortunately, this means that I have to write the code to call the
// solver in each switch case separtely
// Note: CG uses a diagonal preconditioner by default
switch (state.algorithm) {
case 1:{
Eigen::ConjugateGradient<SparseMatrix> solver;
solver.setTolerance(state.termToler);
solver.setMaxIterations(static_cast<int>(state.maxIter));
x = solver.compute(A).solve(state.b);
iters = solver.iterations();
error = solver.error();
break;
}
case 2:{
Eigen::BiCGSTAB<SparseMatrix> solver;
solver.setTolerance(state.termToler);
solver.setMaxIterations(static_cast<int>(state.maxIter));
x = solver.compute(A).solve(state.b);
iters = solver.iterations();
error = solver.error();
break;
}
// Preconditioned CG: Uses an incomplete LUT preconditioner
// For the incomplete LUT preconditioner. You might want to see Eigen docs
// for factors like fill-in which will make the algorithm more suitable
// for handling tougher linear systgems
case 3:{
// 3 Arguments in template
// ConjugateGradient< _MatrixType, _UpLo, _Preconditioner >:
Eigen::ConjugateGradient<SparseMatrix, 1,
Eigen::IncompleteLUT<double> > solver;
solver.setTolerance(state.termToler);
solver.setMaxIterations(static_cast<int>(state.maxIter));
x = solver.compute(A).solve(state.b);
iters = solver.iterations();
error = solver.error();
break;
}
case 4:{
// 2 Arguments in template:
// ConjugateGradient< _MatrixType, _UpLo, _Preconditioner >:
// NOTE: BiCGSTAB is a bi-conjugate gradient that does not
// require a lower or upper triangular option
Eigen::BiCGSTAB<SparseMatrix, Eigen::IncompleteLUT<double> > solver;
solver.setTolerance(state.termToler);
solver.setMaxIterations(static_cast<int>(state.maxIter));
x = solver.compute(A).solve(state.b);
iters = solver.iterations();
error = solver.error();
break;
}
}
// Compute the residual
return inmem_iterative_sparse_stateToResult(*this, x, iters, error);
}
/**
* @brief Helper function that computes the final statistics
*/
AnyType inmem_iterative_sparse_stateToResult(
const Allocator &inAllocator,
const ColumnVector &x,
const int iters,
const double residual_norm) {
MutableNativeColumnVector solution(
inAllocator.allocateArray<double>(x.size()));
for (Index i = 0; i < x.size(); ++i) {
solution(i) = x(i);
}
// Return all coefficients, standard errors, etc. in a tuple
AnyType tuple;
tuple << solution
<< residual_norm
<< iters;
return tuple;
}
} // namespace linear_systems
} // namespace modules
} // namespace madlib
| 33.633333 | 101 | 0.624647 | [
"object",
"vector"
] |
2dd045504880c85dae166e783afbcae18675113d | 6,618 | cpp | C++ | mainwindow.cpp | karolyi15/C-idle- | 384c7104092cf6de31022dbedd101fa2ba7ee970 | [
"Apache-2.0"
] | null | null | null | mainwindow.cpp | karolyi15/C-idle- | 384c7104092cf6de31022dbedd101fa2ba7ee970 | [
"Apache-2.0"
] | null | null | null | mainwindow.cpp | karolyi15/C-idle- | 384c7104092cf6de31022dbedd101fa2ba7ee970 | [
"Apache-2.0"
] | null | null | null | #include "mainwindow.h"
#include "ui_mainwindow.h"
//*****************************************MAIN WINDOW*******************************************//
//***********************************************************************************************//
MainWindow::MainWindow(){
//****************************OBJECTS INITIALIZED*****************************//
setup();
//*********************************ADD OBJECTS********************************//
layout->addWidget(textEditor,BorderLayout::Center);
layout->addWidget(Stdout,BorderLayout::South);
layout->addWidget(ram,BorderLayout::East);
layout->addWidget(toolBar,BorderLayout::North);
//*******************************SET LAYOUT/SHOW*****************************//
w->setLayout(layout); //set layout
w->resize(1200,700); //set size
w->show(); //show window
}
void MainWindow::setup(){
textEditor=new CodeEditor();
syntax=new syntaxHightlight(textEditor->document());
Stdout=new QPlainTextEdit();
ram=new QPlainTextEdit();
toolBar=new QToolBar();
runButton = new botoncp(this->Stdout,this->textEditor,"Run");
debugButton=new botoncp(this->Stdout,this->textEditor,"Debug");
toolBar->addWidget(runButton->pButton);
toolBar->addWidget(debugButton->pButton);
Stdout->appendPlainText(">>mainwindow::Stdout \n>>C! Idle initialized...");
ram->appendPlainText(" RAM LIVE VIEW ");
ram->appendPlainText("_________________________________");
}
//***************************************BORDER LAYOUT******************************************//
//**********************************************************************************************//
BorderLayout::BorderLayout(QWidget *parent, int margin, int spacing)
: QLayout(parent)
{
setMargin(margin);
setSpacing(spacing);
}
BorderLayout::BorderLayout(int spacing)
{
setSpacing(spacing);
}
BorderLayout::~BorderLayout()
{
QLayoutItem *l;
while ((l = takeAt(0)))
delete l;
}
void BorderLayout::addItem(QLayoutItem *item)
{
add(item, West);
}
void BorderLayout::addWidget(QWidget *widget, Position position)
{
add(new QWidgetItem(widget), position);
}
Qt::Orientations BorderLayout::expandingDirections() const
{
return Qt::Horizontal | Qt::Vertical;
}
bool BorderLayout::hasHeightForWidth() const
{
return false;
}
int BorderLayout::count() const
{
return list.size();
}
QLayoutItem *BorderLayout::itemAt(int index) const
{
ItemWrapper *wrapper = list.value(index);
if (wrapper)
return wrapper->item;
else
return 0;
}
QSize BorderLayout::minimumSize() const
{
return calculateSize(MinimumSize);
}
void BorderLayout::setGeometry(const QRect &rect)
{
ItemWrapper *center = 0;
int eastWidth = 0;
int westWidth = 0;
int northHeight = 0;
int southHeight = 0;
int centerHeight = 0;
int i;
QLayout::setGeometry(rect);
for (i = 0; i < list.size(); ++i) {
ItemWrapper *wrapper = list.at(i);
QLayoutItem *item = wrapper->item;
Position position = wrapper->position;
if (position == North) {
item->setGeometry(QRect(rect.x(), northHeight, rect.width(),
item->sizeHint().height()));
northHeight += item->geometry().height() + spacing();
} else if (position == South) {
item->setGeometry(QRect(item->geometry().x(),
item->geometry().y(), rect.width(),
item->sizeHint().height()));
southHeight += item->geometry().height() + spacing();
item->setGeometry(QRect(rect.x(),
rect.y() + rect.height() - southHeight + spacing(),
item->geometry().width(),
item->geometry().height()));
} else if (position == Center) {
center = wrapper;
}
}
centerHeight = rect.height() - northHeight - southHeight;
for (i = 0; i < list.size(); ++i) {
ItemWrapper *wrapper = list.at(i);
QLayoutItem *item = wrapper->item;
Position position = wrapper->position;
if (position == West) {
item->setGeometry(QRect(rect.x() + westWidth, northHeight,
item->sizeHint().width(), centerHeight));
westWidth += item->geometry().width() + spacing();
} else if (position == East) {
item->setGeometry(QRect(item->geometry().x(), item->geometry().y(),
item->sizeHint().width(), centerHeight));
eastWidth += item->geometry().width() + spacing();
item->setGeometry(QRect(
rect.x() + rect.width() - eastWidth + spacing(),
northHeight, item->geometry().width(),
item->geometry().height()));
}
}
if (center)
center->item->setGeometry(QRect(westWidth, northHeight,
rect.width() - eastWidth - westWidth,
centerHeight));
}
QSize BorderLayout::sizeHint() const
{
return calculateSize(SizeHint);
}
QLayoutItem *BorderLayout::takeAt(int index)
{
if (index >= 0 && index < list.size()) {
ItemWrapper *layoutStruct = list.takeAt(index);
return layoutStruct->item;
}
return 0;
}
void BorderLayout::add(QLayoutItem *item, Position position)
{
list.append(new ItemWrapper(item, position));
}
QSize BorderLayout::calculateSize(SizeType sizeType) const
{
QSize totalSize;
for (int i = 0; i < list.size(); ++i) {
ItemWrapper *wrapper = list.at(i);
Position position = wrapper->position;
QSize itemSize;
if (sizeType == MinimumSize)
itemSize = wrapper->item->minimumSize();
else // (sizeType == SizeHint)
itemSize = wrapper->item->sizeHint();
if (position == North || position == South || position == Center)
totalSize.rheight() += itemSize.height();
if (position == West || position == East || position == Center)
totalSize.rwidth() += itemSize.width();
}
return totalSize;
}
| 29.945701 | 99 | 0.504382 | [
"geometry"
] |
2dd2656cab9271b3cee6de3e91cece008f3f588c | 6,866 | cpp | C++ | DFS/332. Reconstruct Itinerary.cpp | beckswu/Leetcode | 480e8dc276b1f65961166d66efa5497d7ff0bdfd | [
"MIT"
] | 138 | 2020-02-08T05:25:26.000Z | 2021-11-04T11:59:28.000Z | DFS/332. Reconstruct Itinerary.cpp | beckswu/Leetcode | 480e8dc276b1f65961166d66efa5497d7ff0bdfd | [
"MIT"
] | null | null | null | DFS/332. Reconstruct Itinerary.cpp | beckswu/Leetcode | 480e8dc276b1f65961166d66efa5497d7ff0bdfd | [
"MIT"
] | 24 | 2021-01-02T07:18:43.000Z | 2022-03-20T08:17:54.000Z | /*
332. Reconstruct Itinerary
Given a list of airline tickets represented by pairs of departure and arrival airports [from, to], reconstruct the itinerary in order.
All of the tickets belong to a man who departs from JFK. Thus, the itinerary must begin with JFK.
Note:
If there are multiple valid itineraries, you should return the itinerary that has the smallest lexical order when read as a single string.
For example, the itinerary ["JFK", "LGA"] has a smaller lexical order than ["JFK", "LGB"].
All airports are represented by three capital letters (IATA code).
You may assume all tickets form at least one valid itinerary.
Example 1:
tickets = [["MUC", "LHR"], ["JFK", "MUC"], ["SFO", "SJC"], ["LHR", "SFO"]]
Return ["JFK", "MUC", "LHR", "SFO", "SJC"].
Example 2:
tickets = [["JFK","SFO"],["JFK","ATL"],["SFO","ATL"],["ATL","JFK"],["ATL","SFO"]]
Return ["JFK","ATL","JFK","SFO","ATL","SFO"].
Another possible reconstruction is ["JFK","SFO","ATL","JFK","ATL","SFO"]. But it is larger in lexical order.
Credits:
Special thanks to @dietpepsi for adding this problem and creating all test cases.
*/
/*
First keep going forward until you get stuck. That's a good main path already.
Remaining tickets form cycles which are found on the way back and get merged into that main path.
By writing down the path backwards when retreating from recursion, merging the cycles into the main path is easy -
the end part of the path has already been written, the start part of the path hasn't been written yet,
so just write down the cycle now and then keep backwards-writing the path.
IMAGE: https://leetcode.com/problems/reconstruct-itinerary/discuss/78768/Short-Ruby-Python-Java-C%2B%2B
From JFK we first visit JFK -> A -> C -> D -> A. There we're stuck, so we write down A as the end of the route and retreat back to D.
There we see the unused ticket to B and follow it: D -> B -> C -> JFK -> D.
Then we're stuck again, retreat and write down the airports while doing so: Write down D before the already written A,
then JFK before the D, etc. When we're back from our cycle at D, the written route is D -> B -> C -> JFK -> D -> A.
Then we retreat further along the original path, prepending C, A and finally JFK to the route,
ending up with the route JFK -> A -> C -> D -> B -> C -> JFK -> D -> A.
*/
class Solution {
public:
vector<string> findItinerary(vector<pair<string, string>> tickets) {
unordered_map<string, map<string, int>> m;
vector<string>res={"JFK"};
for(auto t: tickets){
m[t.first][t.second]++;
}
dfs("JFK", res, tickets.size(), m);
return res;
}
bool dfs( string cur,vector<string>& res, int tickets, unordered_map<string, map<string, int>>&m){
if(tickets == 0)
return true;
for(auto &go: m[cur]){
if(go.second>0){
go.second--;
res.push_back(go.first);
if(dfs(go.first,res, tickets-1, m)) return true;
go.second++;
res.pop_back();
}
}
return false;
}
};
class Solution {
public:
vector<string> findItinerary(vector<pair<string, string>> tickets) {
unordered_map<string, multiset<string>>m;
vector<string>route;
for(auto t: tickets){
m[t.first].insert(t.second);
}
dfs("JFK", route, m);
return vector<string>(route.rbegin(), route.rend());
}
void dfs(string cur,vector<string>& route, unordered_map<string,multiset<string>>&m){
while(!m[cur].empty()){
string next = *m[cur].begin();
m[cur].erase(m[cur].begin());
dfs(next, route, m);
}
route.push_back(cur);
}
};
//iterative solution using stk
class Solution {
public:
vector<string> findItinerary(vector<pair<string, string>> tickets) {
unordered_map<string, multiset<string>>m;
vector<string>route;
for(auto t: tickets){
m[t.first].insert(t.second);
}
stack<string>stk;
stk.push("JFK");
while(!stk.empty()){
string cur = stk.top();
while(!m[cur].empty()){
string next = *m[cur].begin();
stk.push(next);
m[cur].erase(m[cur].begin());
cur = next;
}
route.push_back(cur);
stk.pop();
}
return vector<string>(route.rbegin(), route.rend());
}
};
class Solution {
unordered_map<string, priority_queue<string, vector<string>, greater<string>>> graph;
vector<string> result;
void dfs(string vtex)
{
auto & edges = graph[vtex];
while (!edges.empty())
{
string to_vtex = edges.top();
edges.pop();
dfs(to_vtex);
}
result.push_back(vtex);
}
public:
vector<string> findItinerary(vector<pair<string, string>> tickets) {
for (auto e : tickets)
graph[e.first].push(e.second);
dfs("JFK");
reverse(result.begin(), result.end());
return result;
}
};
/**
*
* some observations:
https://leetcode.com/problems/reconstruct-itinerary/discuss/78768/Short-Ruby-Python-Java-C++
The nodes which have odd degrees (int and out) are the entrance or exit. In your example it’s JFK and A.
If there are no nodes have odd degrees, we could follow any path without stuck until hit the last exit node
The reason we got stuck is because that we hit the exit
In your given example, nodes A is the exit node, we hit it and it’s the exit. So we put it to the result as the last node.
*/
class Solution {
public:
vector<string> findItinerary(vector<pair<string, string>> tickets) {
unordered_map<string, priority_queue<string, vector<string>, greater<string>>>m;
vector<string>res;
for(auto t: tickets){
m[t.first].push(t.second);
}
dfs("JFK", res, m);
reverse(res.begin(),res.end());
return res;
}
void dfs(string cur, vector<string>& res, unordered_map<string, priority_queue<string, vector<string>, greater<string>>>& m) {
//cout<<"cur " << cur <<endl;
while(!m[cur].empty()){
string s = m[cur].top();
m[cur].pop();
//cout<<"before dsf cur "<<cur<<" size "<<m[cur].size()<<endl;
dfs(s, res, m);
//cout<<"after dfs "<<cur<<" size "<<m[cur].size()<<endl;
}
//cout<<"push back "<<cur<<endl;
res.push_back(cur);
}
};
| 36.913978 | 140 | 0.578357 | [
"vector"
] |
2dd5de12ace13f1ce04a7521dfa289be9164de19 | 4,274 | cpp | C++ | cpptest.cpp | taboege/libpropcalc | b64dbf66a6d58fb8ec8e646530b482bbd96b0ba6 | [
"Artistic-2.0"
] | 1 | 2021-06-01T01:08:56.000Z | 2021-06-01T01:08:56.000Z | cpptest.cpp | taboege/libpropcalc | b64dbf66a6d58fb8ec8e646530b482bbd96b0ba6 | [
"Artistic-2.0"
] | null | null | null | cpptest.cpp | taboege/libpropcalc | b64dbf66a6d58fb8ec8e646530b482bbd96b0ba6 | [
"Artistic-2.0"
] | null | null | null | #include <iostream>
#include <sstream>
#include <string>
#include <propcalc/propcalc.hpp>
using namespace std;
string dimacs = R"(
c Gaussoids on n=3
p cnf 6 42
1 4 -3 0
1 4 -2 0
2 4 -1 0
2 4 -3 0
1 3 -2 0
1 3 -4 0
1 2 -3 -5 0
3 2 -1 0
3 2 -4 0
4 2 -3 0
4 2 -1 0
3 1 -4 0
3 1 -2 0
3 4 -1 -5 0
1 6 -5 0
1 6 -2 0
2 6 -1 0
2 6 -5 0
1 5 -2 0
1 5 -6 0
1 2 -5 -3 0
5 2 -1 0
5 2 -6 0
6 2 -5 0
6 2 -1 0
5 1 -6 0
5 1 -2 0
5 6 -1 -3 0
3 6 -5 0
3 6 -4 0
4 6 -3 0
4 6 -5 0
3 5 -4 0
3 5 -6 0
3 4 -5 -1 0
5 4 -3 0
5 4 -6 0
6 4 -5 0
6 4 -3 0
5 3 -6 0
5 3 -4 0
5 6 -3 -1 0
)";
template<typename T>
static size_t count_stream(Propcalc::Stream<T>& st) {
size_t size = 0;
for ([[maybe_unused]] auto v : st)
size++;
return size;
}
int main(int argc, char* argv[]) {
if (argc < 2) {
cerr << "no formula given" << endl;
return 1;
}
string fmstr(argv[1]);
Propcalc::Formula fm(fmstr);
Propcalc::Formula fm1("[12|]&[12|3]");
Propcalc::Formula fm2("[13|]^[23|]");
Propcalc::Formula fm3("[12|]");
cout << fm.to_postfix() << endl;
cout << (~fm).to_postfix() << endl;
cout << ((fm & fm1) | fm2).to_postfix() << endl;
cout << fm.eqvf(fm1).to_postfix() << endl;
cout << fm1.thenf(fm2).to_postfix() << endl;
cout << endl;
cout << (fm1 | ~fm3).to_infix() << endl;
cout << ((fm1 | fm2) & ~~fm3).to_infix() << endl;
cout << (fm1 & fm3 & fm2).to_infix() << endl;
cout << endl;
cout << "seen the following variables:" << endl; {
Propcalc::VarNr i = 1;
for (auto& v : Propcalc::Formula::DefaultDomain.list())
cout << v->to_string() << ": " << i++ << endl;
}
cout << endl;
auto vars = fm.vars();
auto assign = Propcalc::Assignment(vars);
while (!assign.overflown()) {
for (auto& v : vars)
cout << v->name << ": " << assign[v] << " ";
cout << "(short: ";
for (auto& v : assign.vars())
cout << assign[v];
cout << ")" << endl;
++assign;
}
cout << endl;
cout << "truth table of " << fm.to_infix() << ":" << endl;
for (const auto& [assigned, value] : fm.truthtable()) {
for (auto& v : assigned.vars())
cout << assigned[v];
cout << ": " << value << endl;
}
cout << endl;
cout << "satisfying assignments of " << fm.to_infix() << ":" << endl;
for (const auto& [assigned, value] : fm.truthtable()) {
if (value) {
cout << "{ ";
for (auto& v : assigned.vars())
cout << v->name << " ";
cout << "}" << endl;
}
}
cout << endl;
cout << "CNF clauses of " << fm.to_infix() << ":" << endl;
for (auto clause : fm.cnf()) {
cout << "{ ";
int i = 0;
for (auto& v : clause.vars()) {
if (i++)
cout << "| ";
cout << (clause[v] ? "" : "~") << v->name << " ";
}
cout << "}" << endl;
}
cout << endl;
cout << "Tseitin transform of " << fm.to_infix() << ":" << endl;
for (auto clause : fm.tseitin()) {
cout << "{ ";
int i = 0;
for (auto& v : clause.vars()) {
if (i++)
cout << "| ";
cout << (clause[v] ? "" : "~") << v->name << " ";
}
cout << "}" << endl;
}
cout << endl;
cout << "Original formula: " << fm.to_infix() << endl;
cout << "Simplified formula: " << fm.simplify().to_infix() << endl;
cout << endl;
cout << "Allocating many variables using unpack:" << endl; {
Propcalc::Formula::DefaultDomain.unpack(15);
Propcalc::VarNr i = 1;
for (auto& v : Propcalc::Formula::DefaultDomain.list())
cout << v->to_string() << ": " << i++ << endl;
}
cout << endl;
{
auto cnf = fm.cnf();
cout << "Number of CNF clauses: " << count_stream(cnf) << endl;
cout << "Counting again: " << count_stream(cnf) << endl;
auto cache = fm.cnf();
cache.is_caching() = true;
cout << "Number of CNF clauses (cached): " << count_stream(cache) << endl;
cout << "Counting again (cached): " << count_stream(cache) << endl;
}
cout << endl;
{
cout << "Reading DIMACS CNF file:" << endl;
auto ss = stringstream(dimacs);
auto fm = Propcalc::DIMACS::read(ss);
cout << fm.to_infix() << endl;
}
cout << endl;
{
cout << "Writing DIMACS CNF file:" << endl;
auto cnf = fm.cnf();
Propcalc::DIMACS::write(cout, cnf, fm.domain);
cout << endl;
cout << "Writing DIMACS CNF of Tseitin transform:" << endl;
auto tsei = fm.tseitin();
Propcalc::DIMACS::write(cout, tsei, tsei.domain, {"Tseitin transform of " + fm.to_infix()});
}
cout << endl;
return 0;
}
| 21.585859 | 94 | 0.543519 | [
"transform"
] |
2de025cd8b536394aeaf4982259eb28f8934648a | 1,054 | cpp | C++ | test/cppworkspace/test/src/testcase_namespaces/test_ptrs.cpp | farre/midas | f31a0e6eea6e74186a1dad11c1a81bd913ef3c4d | [
"MIT"
] | null | null | null | test/cppworkspace/test/src/testcase_namespaces/test_ptrs.cpp | farre/midas | f31a0e6eea6e74186a1dad11c1a81bd913ef3c4d | [
"MIT"
] | 16 | 2022-02-09T09:46:20.000Z | 2022-03-28T13:03:31.000Z | test/cppworkspace/test/src/testcase_namespaces/test_ptrs.cpp | farre/midas | f31a0e6eea6e74186a1dad11c1a81bd913ef3c4d | [
"MIT"
] | null | null | null | #include <string>
#include <vector>
#include <map>
#include <algorithm>
using usize = std::size_t;
static int W_ID = 0;
struct Ref {
int* value = nullptr;
bool has_value() const { return value != nullptr; }
};
struct Foo {
std::string name;
int id;
float f;
};
struct Widget {
static Widget clone_from(std::string name, Widget* w) {
if(w->id.has_value()) {
return Widget{.m_name = name, .id = Ref{.value = w->id.value}};
} else {
return Widget { .m_name = std::move(name), .id = Ref{.value = new int{W_ID++} } };
}
}
void set_foo(Foo* foo) {
this->foo = foo;
}
std::string m_name;
Ref id;
Foo* foo = nullptr;
};
void test_ptrs_main() {
Foo* f = nullptr;
f = new Foo{.name = "Foo type", .id = 10, .f = 3.14f};
auto b = new Foo{.name = "Foo type bar", .id = 30, .f = 444.14f};
Widget foo{.m_name = "foo", .id = Ref{.value = nullptr}};
auto bar = Widget::clone_from("bar", &foo);
foo.set_foo(f);
bar.set_foo(b);
}
| 22.425532 | 94 | 0.547438 | [
"vector"
] |
2de65194e927641cd1fd0a82a160079857675e74 | 3,742 | cpp | C++ | third_party/CppAD/example/utility/lu_invert.cpp | eric-heiden/tds-merge | 1e18447b0096efbb6df5d9ad7d69c8b0cc282747 | [
"Apache-2.0"
] | null | null | null | third_party/CppAD/example/utility/lu_invert.cpp | eric-heiden/tds-merge | 1e18447b0096efbb6df5d9ad7d69c8b0cc282747 | [
"Apache-2.0"
] | null | null | null | third_party/CppAD/example/utility/lu_invert.cpp | eric-heiden/tds-merge | 1e18447b0096efbb6df5d9ad7d69c8b0cc282747 | [
"Apache-2.0"
] | null | null | null | /* --------------------------------------------------------------------------
CppAD: C++ Algorithmic Differentiation: Copyright (C) 2003-20 Bradley M. Bell
CppAD is distributed under the terms of the
Eclipse Public License Version 2.0.
This Source Code may also be made available under the following
Secondary License when the conditions for such availability set forth
in the Eclipse Public License, Version 2.0 are satisfied:
GNU General Public License, Version 2.0 or later.
---------------------------------------------------------------------------- */
/*
$begin lu_invert.cpp$$
$spell
Geq
Cpp
Lu
$$
$section LuInvert: Example and Test$$
$srcthisfile%0%// BEGIN C++%// END C++%1%$$
$end
*/
// BEGIN C++
# include <cstdlib> // for rand function
# include <cppad/utility/lu_invert.hpp> // for CppAD::LuInvert
# include <cppad/utility/near_equal.hpp> // for CppAD::NearEqual
# include <cppad/utility/vector.hpp> // for CppAD::vector
bool LuInvert(void)
{ bool ok = true;
# ifndef _MSC_VER
using std::rand;
using std::srand;
# endif
double eps200 = 200.0 * std::numeric_limits<double>::epsilon();
size_t n = 7; // number rows in A
size_t m = 3; // number columns in B
double rand_max = double(RAND_MAX); // maximum rand value
double sum; // element of L * U
size_t i, j, k; // temporary indices
// dimension matrices
CppAD::vector<double>
A(n*n), X(n*m), B(n*m), LU(n*n), L(n*n), U(n*n);
// seed the random number generator
srand(123);
// pivot vectors
CppAD::vector<size_t> ip(n);
CppAD::vector<size_t> jp(n);
// set pivot vectors
for(i = 0; i < n; i++)
{ ip[i] = (i + 2) % n; // ip = 2 , 3, ... , n-1, 0, 1
jp[i] = (n + 2 - i) % n; // jp = 2 , 1, n-1, n-2, ... , 3
}
// chose L, a random lower triangular matrix
for(i = 0; i < n; i++)
{ for(j = 0; j <= i; j++)
L [i * n + j] = rand() / rand_max;
for(j = i+1; j < n; j++)
L [i * n + j] = 0.;
}
// chose U, a random upper triangular matrix with ones on diagonal
for(i = 0; i < n; i++)
{ for(j = 0; j < i; j++)
U [i * n + j] = 0.;
U[ i * n + i ] = 1.;
for(j = i+1; j < n; j++)
U [i * n + j] = rand() / rand_max;
}
// chose X, a random matrix
for(i = 0; i < n; i++)
{ for(k = 0; k < m; k++)
X[i * m + k] = rand() / rand_max;
}
// set LU to a permuted combination of both L and U
for(i = 0; i < n; i++)
{ for(j = 0; j <= i; j++)
LU [ ip[i] * n + jp[j] ] = L[i * n + j];
for(j = i+1; j < n; j++)
LU [ ip[i] * n + jp[j] ] = U[i * n + j];
}
// set A to a permuted version of L * U
for(i = 0; i < n; i++)
{ for(j = 0; j < n; j++)
{ // compute (i,j) entry in permuted matrix
sum = 0.;
for(k = 0; k < n; k++)
sum += L[i * n + k] * U[k * n + j];
A[ ip[i] * n + jp[j] ] = sum;
}
}
// set B to A * X
for(i = 0; i < n; i++)
{ for(k = 0; k < m; k++)
{ // compute (i,k) entry of B
sum = 0.;
for(j = 0; j < n; j++)
sum += A[i * n + j] * X[j * m + k];
B[i * m + k] = sum;
}
}
// solve for X
CppAD::LuInvert(ip, jp, LU, B);
// check result
for(i = 0; i < n; i++)
{ for(k = 0; k < m; k++)
{ ok &= CppAD::NearEqual(
X[i * m + k], B[i * m + k], eps200, eps200
);
}
}
return ok;
}
// END C++
| 28.784615 | 79 | 0.435329 | [
"vector"
] |
2de7eed83921ec692b075a3702fbfb4c3f258052 | 5,337 | cpp | C++ | src/mytest.cpp | boldwings/GALGO-2.0 | d066dfc4629571245a0e1070d75158fffc41339f | [
"MIT"
] | null | null | null | src/mytest.cpp | boldwings/GALGO-2.0 | d066dfc4629571245a0e1070d75158fffc41339f | [
"MIT"
] | null | null | null | src/mytest.cpp | boldwings/GALGO-2.0 | d066dfc4629571245a0e1070d75158fffc41339f | [
"MIT"
] | null | null | null | //=================================================================================================
// Copyright (C) 2017 Olivier Mallet - All Rights Reserved
//=================================================================================================
#include "Galgo.hpp"
#include <stdlib.h>
#include <chrono>
int count = 0;
// // static __inline__ unsigned long long rdtsc(void) {
// // unsigned hi, lo;
// // __asm__ __volatile__ ("rdtsc" : "=a"(lo), "=d"(hi));
// // return ( (unsigned long long)lo)|( ((unsigned long long)hi)<<32 );
// // }
unsigned long long dur;
unsigned long long ts, te;
int num = 1;
float constant1 = 1.0;
float constant100 = 100.0;
float constant_1 = -1.0;
int count_peak = 0;
unsigned long long dur_peak =0;
unsigned long long dur_orig_obj, t2, t3;
// objective class example
template <typename T>
class MyObjective
{
public:
// theoratical peak 32 Flops/cycle
static void ObjectiveSIMD(T *x, T *y, T *output)
{
// count_peak++;
// t2 = rdtsc();
// use 14 simd registers
__m256 x1 = _mm256_loadu_ps(x);
__m256 y1 = _mm256_loadu_ps(y);
__m256 x2 = _mm256_loadu_ps(x + 8);
__m256 y2 = _mm256_loadu_ps(y + 8);
__m256 x3 = _mm256_loadu_ps(x + 16);
__m256 y3 = _mm256_loadu_ps(y + 16);
__m256 result1 = _mm256_loadu_ps(output);
__m256 result2 = _mm256_loadu_ps(output + 8);
__m256 result3 = _mm256_loadu_ps(output + 16);
/* const 1, 100 */
__m256 c1 = _mm256_broadcast_ss(&constant1);
__m256 c2 = _mm256_broadcast_ss(&constant100);
__m256 c3 = _mm256_broadcast_ss(&constant_1);
/* (y -x^2)^2 */
__m256 z1 = _mm256_mul_ps(x1, x1);
y1 = _mm256_sub_ps(y1, z1);
y1 = _mm256_mul_ps(y1, y1);
__m256 z2 = _mm256_mul_ps(x2, x2);
y2 = _mm256_sub_ps(y2, z2);
y2 = _mm256_mul_ps(y2, y2);
__m256 z3 = _mm256_mul_ps(x3, x3);
y3 = _mm256_sub_ps(y3, z3);
y3 = _mm256_mul_ps(y3, y3);
/* (1 - x) */
x1 = _mm256_sub_ps(c1, x1);
x2 = _mm256_sub_ps(c1, x2);
x3 = _mm256_sub_ps(c1, x3);
result1 = _mm256_fmadd_ps(x1, x1, result1);
result1 = _mm256_fmadd_ps(c2, y1, result1);
result2 = _mm256_fmadd_ps(x2, x2, result2);
result2 = _mm256_fmadd_ps(c2, y2, result2);
result3 = _mm256_fmadd_ps(x3, x3, result3);
result3 = _mm256_fmadd_ps(c2, y3, result3);
result1 = _mm256_mul_ps(result1, c3);
result2 = _mm256_mul_ps(result2, c3);
result3 = _mm256_mul_ps(result3, c3);
_mm256_store_ps(output, result1);
_mm256_store_ps(output + 8, result2);
_mm256_store_ps(output +16, result3);
// t3 = rdtsc();
// dur_peak += t3 - t2;
}
static T Objective(T x, T y) {
return -1*(pow(1 - x, 2) + 100 * pow(y - x*x, 2));
}
static std::vector<T> ObjectiveOrig(const std::vector<T>& x)
{
// t0 = rdtsc();
T obj = -(pow(1-x[0],2)+100*pow(x[1]-x[0]*x[0],2));
// t1 = rdtsc();
// dur_orig_obj = (t1 - t0);
return {obj};
}
// NB: GALGO maximize by default so we will maximize -f(x,y)
};
// constraints example:
// 1) x * y + x - y + 1.5 <= 0
// 2) 10 - x * y <= 0
template <typename T>
std::vector<T> MyConstraint(const std::vector<T>& x)
{
return {x[0]*x[1]+x[0]-x[1]+1.5,10-x[0]*x[1]};
}
// NB: a penalty will be applied if one of the constraints is > 0
// using the default adaptation to constraint(s) method
int main(int argc, char** argv)
{
const uint64_t seed1[4] = {0X922AC4EB35B502D9L, 0X7391BDE169361A0BL, 0XB69327491DAC38A9L, 0X240654AD41BB551AL};
const uint64_t seed2[4] = {0XDA3AA4832B8F1D27L, 0X842ACE731803BAA5L, 0XA8B4384486CD1970L, 0XA8495956C4140021L};
const uint64_t seed3[4] = {0X32814670dccaad26L, 0Xb9be593f2d1b80a9L, 0X5634e877768b3459L, 0X80fce18a26a1c78fL};
const uint64_t seed4[4] = {0Xaec4b82be03abed7L, 0Xd1b9b0a0a632873cL, 0X23035878ee74dfc1L, 0X65dde5fde9d025a7L};
s0 = _mm256_lddqu_si256((const __m256i*)seed1);
s1 = _mm256_lddqu_si256((const __m256i*)seed2);
ss0 = _mm256_lddqu_si256((const __m256i*)seed3);
ss1 = _mm256_lddqu_si256((const __m256i*)seed4);
// initializing parameters lower and upper bounds
// an initial value can be added inside the initializer list after the upper bound
galgo::Parameter<float> par1({0.0,1.0});
galgo::Parameter<float> par2({0.0,13.0});
// here both parameter will be encoded using 16 bits the default value inside the template declaration
// this value can be modified but has to remain between 1 and 64
// initiliazing genetic algorithm
// num = atoi(argv[1]);
// std::cout << "num is " << num << std::endl;
galgo::GeneticAlgorithm<float> ga(MyObjective<float>::ObjectiveSIMD, MyObjective<float>::Objective, MyObjective<float>::ObjectiveOrig,
2000,100,true,par1,par2);
// setting constraints
// ga.Constraint = MyConstraint;
// running genetic algorithm
ga.output = 1;
ts = rdtsc();
ga.run();
te = rdtsc();
std::cout << "total time and count is: " <<te - ts<< std::endl;
std::cout<<"cross_over dur and count: " << dur_crossover << " " << count_crossover << std::endl;
std::cout<<"mutation dur and count: " << dur_mutation << " " << count_mutation << std::endl;
}
| 36.306122 | 137 | 0.609144 | [
"vector"
] |
2de90d5cc1de292aeac4d8e8e5153e735917ce72 | 9,911 | cpp | C++ | TMessagesProj/jni/gifvideo.cpp | Fghgfh/Reyhangram | 4ffba4522ad889f16dfe5b159ae169265d09ff34 | [
"Apache-2.0"
] | null | null | null | TMessagesProj/jni/gifvideo.cpp | Fghgfh/Reyhangram | 4ffba4522ad889f16dfe5b159ae169265d09ff34 | [
"Apache-2.0"
] | null | null | null | TMessagesProj/jni/gifvideo.cpp | Fghgfh/Reyhangram | 4ffba4522ad889f16dfe5b159ae169265d09ff34 | [
"Apache-2.0"
] | null | null | null | #include <jni.h>
#include <utils.h>
#include <libyuv.h>
#include <android/bitmap.h>
#include <cstdint>
#include <limits>
#include <string>
extern "C" {
#include <libavformat/avformat.h>
#include <libavutil/eval.h>
static const std::string av_make_error_str(int errnum) {
char errbuf[AV_ERROR_MAX_STRING_SIZE];
av_strerror(errnum, errbuf, AV_ERROR_MAX_STRING_SIZE);
return (std::string) errbuf;
}
#undef av_err2str
#define av_err2str(errnum) av_make_error_str(errnum).c_str()
typedef struct VideoInfo {
~VideoInfo() {
if (video_dec_ctx) {
avcodec_close(video_dec_ctx);
video_dec_ctx = nullptr;
}
if (fmt_ctx) {
avformat_close_input(&fmt_ctx);
fmt_ctx = nullptr;
}
if (frame) {
av_frame_free(&frame);
frame = nullptr;
}
if (src) {
delete [] src;
src = nullptr;
}
av_free_packet(&orig_pkt);
video_stream_idx = -1;
video_stream = nullptr;
}
AVFormatContext *fmt_ctx = nullptr;
char *src = nullptr;
int video_stream_idx = -1;
AVStream *video_stream = nullptr;
AVCodecContext *video_dec_ctx = nullptr;
AVFrame *frame = nullptr;
bool has_decoded_frames = false;
AVPacket pkt;
AVPacket orig_pkt;
};
jobject makeGlobarRef(JNIEnv *env, jobject object) {
if (object) {
return env->NewGlobalRef(object);
}
return 0;
}
int gifvideoOnJNILoad(JavaVM *vm, JNIEnv *env) {
av_register_all();
return 0;
}
int open_codec_context(int *stream_idx, AVFormatContext *fmt_ctx, enum AVMediaType type) {
int ret;
AVStream *st;
AVCodecContext *dec_ctx = NULL;
AVCodec *dec = NULL;
AVDictionary *opts = NULL;
ret = av_find_best_stream(fmt_ctx, type, -1, -1, NULL, 0);
if (ret < 0) {
LOGE("can't find %s stream in input file\n", av_get_media_type_string(type));
return ret;
} else {
*stream_idx = ret;
st = fmt_ctx->streams[*stream_idx];
dec_ctx = st->codec;
dec = avcodec_find_decoder(dec_ctx->codec_id);
if (!dec) {
LOGE("failed to find %s codec\n", av_get_media_type_string(type));
return ret;
}
av_dict_set(&opts, "refcounted_frames", "1", 0);
if ((ret = avcodec_open2(dec_ctx, dec, &opts)) < 0) {
LOGE("failed to open %s codec\n", av_get_media_type_string(type));
return ret;
}
}
return 0;
}
int decode_packet(VideoInfo *info, int *got_frame) {
int ret = 0;
int decoded = info->pkt.size;
*got_frame = 0;
if (info->pkt.stream_index == info->video_stream_idx) {
ret = avcodec_decode_video2(info->video_dec_ctx, info->frame, got_frame, &info->pkt);
if (ret != 0) {
return ret;
}
}
return decoded;
}
jint Java_org_telegram_ui_Components_AnimatedFileDrawable_createDecoder(JNIEnv *env, jclass clazz, jstring src, jintArray data) {
VideoInfo *info = new VideoInfo();
char const *srcString = env->GetStringUTFChars(src, 0);
int len = strlen(srcString);
info->src = new char[len + 1];
memcpy(info->src, srcString, len);
info->src[len] = '\0';
if (srcString != 0) {
env->ReleaseStringUTFChars(src, srcString);
}
int ret;
if ((ret = avformat_open_input(&info->fmt_ctx, info->src, NULL, NULL)) < 0) {
LOGE("can't open source file %s, %s", info->src, av_err2str(ret));
delete info;
return 0;
}
if ((ret = avformat_find_stream_info(info->fmt_ctx, NULL)) < 0) {
LOGE("can't find stream information %s, %s", info->src, av_err2str(ret));
delete info;
return 0;
}
if (open_codec_context(&info->video_stream_idx, info->fmt_ctx, AVMEDIA_TYPE_VIDEO) >= 0) {
info->video_stream = info->fmt_ctx->streams[info->video_stream_idx];
info->video_dec_ctx = info->video_stream->codec;
}
if (info->video_stream <= 0) {
LOGE("can't find video stream in the input, aborting %s", info->src);
delete info;
return 0;
}
info->frame = av_frame_alloc();
if (info->frame == nullptr) {
LOGE("can't allocate frame %s", info->src);
delete info;
return 0;
}
av_init_packet(&info->pkt);
info->pkt.data = NULL;
info->pkt.size = 0;
jint *dataArr = env->GetIntArrayElements(data, 0);
if (dataArr != nullptr) {
dataArr[0] = info->video_dec_ctx->width;
dataArr[1] = info->video_dec_ctx->height;
AVDictionaryEntry *rotate_tag = av_dict_get(info->video_stream->metadata, "rotate", NULL, 0);
if (rotate_tag && *rotate_tag->value && strcmp(rotate_tag->value, "0")) {
char *tail;
dataArr[2] = (int) av_strtod(rotate_tag->value, &tail);
if (*tail) {
dataArr[2] = 0;
}
} else {
dataArr[2] = 0;
}
env->ReleaseIntArrayElements(data, dataArr, 0);
}
//LOGD("successfully opened file %s", info->src);
return (int) info;
}
void Java_org_telegram_ui_Components_AnimatedFileDrawable_destroyDecoder(JNIEnv *env, jclass clazz, jobject ptr) {
if (ptr == NULL) {
return;
}
VideoInfo *info = (VideoInfo *) ptr;
delete info;
}
jint Java_org_telegram_ui_Components_AnimatedFileDrawable_getVideoFrame(JNIEnv *env, jclass clazz, jobject ptr, jobject bitmap, jintArray data) {
if (ptr == NULL || bitmap == nullptr) {
return 0;
}
VideoInfo *info = (VideoInfo *) ptr;
int ret = 0;
int got_frame = 0;
while (true) {
if (info->pkt.size == 0) {
ret = av_read_frame(info->fmt_ctx, &info->pkt);
//LOGD("got packet with size %d", info->pkt.size);
if (ret >= 0) {
info->orig_pkt = info->pkt;
}
}
if (info->pkt.size > 0) {
ret = decode_packet(info, &got_frame);
if (ret < 0) {
if (info->has_decoded_frames) {
ret = 0;
}
info->pkt.size = 0;
} else {
//LOGD("read size %d from packet", ret);
info->pkt.data += ret;
info->pkt.size -= ret;
}
if (info->pkt.size == 0) {
av_free_packet(&info->orig_pkt);
}
} else {
info->pkt.data = NULL;
info->pkt.size = 0;
ret = decode_packet(info, &got_frame);
if (ret < 0) {
LOGE("can't decode packet flushed %s", info->src);
return 0;
}
if (got_frame == 0) {
if (info->has_decoded_frames) {
//LOGD("file end reached %s", info->src);
if ((ret = avformat_seek_file(info->fmt_ctx, -1, std::numeric_limits<int64_t>::min(), 0, std::numeric_limits<int64_t>::max(), 0)) < 0) {
LOGE("can't seek to begin of file %s, %s", info->src, av_err2str(ret));
return 0;
} else {
avcodec_flush_buffers(info->video_dec_ctx);
}
}
}
}
if (ret < 0) {
return 0;
}
if (got_frame) {
//LOGD("decoded frame with w = %d, h = %d, format = %d", info->frame->width, info->frame->height, info->frame->format);
if (info->frame->format == AV_PIX_FMT_YUV420P || info->frame->format == AV_PIX_FMT_BGRA || info->frame->format == AV_PIX_FMT_YUVJ420P) {
jint *dataArr = env->GetIntArrayElements(data, 0);
int wantedWidth;
int wantedHeight;
if (dataArr != nullptr) {
wantedWidth = dataArr[0];
wantedHeight = dataArr[1];
dataArr[3] = (int) (1000 * info->frame->pkt_pts * av_q2d(info->video_stream->time_base));
env->ReleaseIntArrayElements(data, dataArr, 0);
} else {
AndroidBitmapInfo bitmapInfo;
AndroidBitmap_getInfo(env, bitmap, &bitmapInfo);
wantedWidth = bitmapInfo.width;
wantedHeight = bitmapInfo.height;
}
void *pixels;
if (AndroidBitmap_lockPixels(env, bitmap, &pixels) >= 0) {
if (info->frame->format == AV_PIX_FMT_YUV420P || info->frame->format == AV_PIX_FMT_YUVJ420P) {
//LOGD("y %d, u %d, v %d, width %d, height %d", info->frame->linesize[0], info->frame->linesize[2], info->frame->linesize[1], info->frame->width, info->frame->height);
if (wantedWidth == info->frame->width && wantedHeight == info->frame->height || wantedWidth == info->frame->height && wantedHeight == info->frame->width) {
libyuv::I420ToARGB(info->frame->data[0], info->frame->linesize[0], info->frame->data[2], info->frame->linesize[2], info->frame->data[1], info->frame->linesize[1], (uint8_t *) pixels, info->frame->width * 4, info->frame->width, info->frame->height);
}
} else if (info->frame->format == AV_PIX_FMT_BGRA) {
libyuv::ABGRToARGB(info->frame->data[0], info->frame->linesize[0], (uint8_t *) pixels, info->frame->width * 4, info->frame->width, info->frame->height);
}
AndroidBitmap_unlockPixels(env, bitmap);
}
}
info->has_decoded_frames = true;
av_frame_unref(info->frame);
return 1;
}
}
}
}
| 34.294118 | 276 | 0.539199 | [
"object"
] |
2df8b9fc6db3d822039d42b968612dbaaf72942a | 715 | hpp | C++ | libraries/chain/include/scorum/chain/evaluators/update_game_markets_evaluator.hpp | scorum/scorum | 1da00651f2fa14bcf8292da34e1cbee06250ae78 | [
"MIT"
] | 53 | 2017-10-28T22:10:35.000Z | 2022-02-18T02:20:48.000Z | libraries/chain/include/scorum/chain/evaluators/update_game_markets_evaluator.hpp | Scorum/Scorum | fb4aa0b0960119b97828865d7a5b4d0409af7876 | [
"MIT"
] | 38 | 2017-11-25T09:06:51.000Z | 2018-10-31T09:17:22.000Z | libraries/chain/include/scorum/chain/evaluators/update_game_markets_evaluator.hpp | Scorum/Scorum | fb4aa0b0960119b97828865d7a5b4d0409af7876 | [
"MIT"
] | 27 | 2018-01-08T19:43:35.000Z | 2022-01-14T10:50:42.000Z | #pragma once
#include <vector>
#include <scorum/protocol/scorum_operations.hpp>
#include <scorum/chain/evaluators/evaluator.hpp>
namespace scorum {
namespace chain {
struct account_service_i;
struct game_service_i;
struct betting_service_i;
class update_game_markets_evaluator : public evaluator_impl<data_service_factory_i, update_game_markets_evaluator>
{
public:
using operation_type = scorum::protocol::update_game_markets_operation;
update_game_markets_evaluator(data_service_factory_i& services, betting_service_i&);
void do_apply(const operation_type& op);
private:
account_service_i& _account_service;
betting_service_i& _betting_service;
game_service_i& _game_service;
};
}
}
| 24.655172 | 114 | 0.812587 | [
"vector"
] |
2dfd1b4a924fc034cdc66f454bc5c7cee9aa932c | 2,289 | cpp | C++ | Problems/Hackerrank/variableSizedArray.cpp | pedrotorreao/DSA | 31f9dffbed5275590d5c7b7f6a73fd6dea411564 | [
"MIT"
] | 1 | 2021-07-08T01:02:06.000Z | 2021-07-08T01:02:06.000Z | Problems/Hackerrank/variableSizedArray.cpp | pedrotorreao/DSA | 31f9dffbed5275590d5c7b7f6a73fd6dea411564 | [
"MIT"
] | null | null | null | Problems/Hackerrank/variableSizedArray.cpp | pedrotorreao/DSA | 31f9dffbed5275590d5c7b7f6a73fd6dea411564 | [
"MIT"
] | null | null | null | //-------------------------------------------
//---------- Variable Sized Arrays ----------
//-------------------------------------------
/*
Descr.:
Consider an n-element array, a, where each index i in the array contains a reference to an array of k integers (where the value of k varies from array to array).
Given a, you must answer q queries. Each query is in the format i j, where i denotes an index in array a and j denotes an index in the array located at a[i].
For each query, find and print the value of element j in the array at location a[i] on a new line.
Input:
The first line contains two space-separated integers denoting the respective values of n (the number of variable-length arrays) and q (the number of queries).
Each line of the subsequent lines contains a space-separated sequence in the format k a[i]0 a[i]1 … a[i]k-1 describing the k-element array located at a[i].
Each of the subsequent lines contains two space-separated integers describing the respective values of i (an index in array a) and j (an index in the array
referenced by a[i]) for a query.
Output:
For each pair of i and j values (i.e., for each query), print a single integer that denotes the element located at index j of the array referenced by a[i].
There should be a total of q lines of output.
Example:
Sample input:
2 2
3 1 5 4
5 1 2 8 9 3
0 1
1 3
Sample output:
5
9
*/
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
int numOfArrays {};
cin >> numOfArrays;
int numOfQueries {};
cin >> numOfQueries;
vector<vector<int>> arr {};
for(int i{0}; i < numOfArrays; ++i) {arr.push_back(vector<int>());}
int iter {0};
while(numOfArrays > 0){
int k {};
cin >> k;
for(int i{0}; i < k; ++i){
int ki {};
cin >> ki;
arr[iter].push_back(ki);
}
++iter;
--numOfArrays;
}
while(numOfQueries > 0){
int qi {}, qj{};
cin >> qi;
cin >> qj;
cout << arr.at(qi).at(qj) << endl;
--numOfQueries;
}
return 0;
} | 31.791667 | 163 | 0.598952 | [
"vector"
] |
93009589434ff57b72e97d7903e3b910661545fa | 431 | hpp | C++ | src/problem/instance.hpp | ctjandra/ddopt-bounds | aaf7407da930503a17969cee71718ffcf0c1fe96 | [
"MIT"
] | 6 | 2018-02-15T03:54:35.000Z | 2022-02-24T03:06:05.000Z | src/problem/instance.hpp | ctjandra/ddopt-bounds | aaf7407da930503a17969cee71718ffcf0c1fe96 | [
"MIT"
] | null | null | null | src/problem/instance.hpp | ctjandra/ddopt-bounds | aaf7407da930503a17969cee71718ffcf0c1fe96 | [
"MIT"
] | 2 | 2021-01-07T02:29:55.000Z | 2021-12-05T13:21:13.000Z | /*
* Abstract classes that need to be implemented in order to model a new problem to be solved.
*/
#ifndef INSTANCE_HPP_
#define INSTANCE_HPP_
class Instance
{
public:
double* weights; /**< (linear) objective function (maximize) */
int nvars; /**< number of variables in instance */
virtual ~Instance() {}
};
#endif /* INSTANCE_HPP_ */
| 21.55 | 103 | 0.561485 | [
"model"
] |
9301b2f83dc9ea536405e3d781ab1078fd09b310 | 7,450 | cpp | C++ | src/Plugins/CameraApplication/CameraApplication.cpp | realXtend/tundra-urho3d | 436d41c3e3dd1a9b629703ee76fd0ef2ee212ef8 | [
"Apache-2.0"
] | 13 | 2015-02-25T02:42:38.000Z | 2018-07-31T11:40:56.000Z | src/Plugins/CameraApplication/CameraApplication.cpp | realXtend/tundra-urho3d | 436d41c3e3dd1a9b629703ee76fd0ef2ee212ef8 | [
"Apache-2.0"
] | 8 | 2015-02-12T22:27:05.000Z | 2017-01-21T15:59:17.000Z | src/Plugins/CameraApplication/CameraApplication.cpp | realXtend/tundra-urho3d | 436d41c3e3dd1a9b629703ee76fd0ef2ee212ef8 | [
"Apache-2.0"
] | 12 | 2015-03-25T21:10:50.000Z | 2019-04-10T09:03:10.000Z | // For conditions of distribution and use, see copyright notice in LICENSE
#include "StableHeaders.h"
#include "CameraApplication.h"
#include "GraphicsWorld.h"
#include "Framework.h"
#include "Placeable.h"
#include "../UrhoRenderer/Camera.h" // Possible ambiguity with Urho3D's Camera component
#include "SceneAPI.h"
#include "Entity.h"
#include "TundraLogic.h"
#include "SyncManager.h"
#include "Scene/Scene.h"
#include "LoggingFunctions.h"
#include "Math/float3.h"
#include "Math/MathFunc.h"
#include "InputAPI.h"
#include "InputContext.h"
#include <Urho3D/Input/InputEvents.h>
#include <Urho3D/Resource/ResourceCache.h>
#include <Urho3D/Core/ProcessUtils.h>
#include <Urho3D/Resource/XMLFile.h>
#include <Urho3D/UI/UI.h>
#include <Urho3D/UI/UIEvents.h>
#include <Urho3D/UI/UIElement.h>
namespace Tundra
{
const float cMoveSpeed = 15.0f;
const float cRotateSpeed = 0.20f;
CameraApplication::CameraApplication(Framework* owner) :
IModule("CameraApplication", owner),
joystickId_(-1),
movementHeld_(0.f),
lastMoveVector_(float3::zero)
{
}
CameraApplication::~CameraApplication()
{
}
void CameraApplication::Load()
{
}
void CameraApplication::Initialize()
{
// Connect to scene change signals.
framework->Scene()->SceneCreated.Connect(this, &CameraApplication::OnSceneCreated);
framework->Scene()->SceneAboutToBeRemoved.Connect(this, &CameraApplication::OnSceneAboutToBeRemoved);
inputContext_ = framework->Input()->RegisterInputContext("CameraApplication", 101);
inputContext_->MouseScroll.Connect(this, &CameraApplication::OnMouseScroll);
}
void CameraApplication::Uninitialize()
{
inputContext_.Reset();
}
void CameraApplication::Update(float frameTime)
{
Entity* cameraEntity = framework->Renderer()->MainCamera();
if (cameraEntity)
MoveCamera(cameraEntity, frameTime);
else if (!cameraEntity && lastScene_)
CreateCamera();
}
void CameraApplication::OnSceneCreated(Scene *scene, AttributeChange::Type)
{
if (!scene->ViewEnabled() || framework->IsHeadless())
return;
// Remember this scene for camera creation on the next update
lastScene_ = scene;
if ((Urho3D::GetPlatform() == "Android" || Urho3D::GetPlatform() == "iOS" || GetSubsystem<Urho3D::Input>()->GetTouchEmulation()) && joystickId_ < 0)
{
Urho3D::XMLFile *layout = GetSubsystem<Urho3D::ResourceCache>()->GetResource<Urho3D::XMLFile>("UI/ScreenJoystick.xml");
Urho3D::XMLFile *style = GetSubsystem<Urho3D::ResourceCache>()->GetResource<Urho3D::XMLFile>("UI/DefaultStyle.xml");
joystickId_ = GetSubsystem<Urho3D::Input>()->AddScreenJoystick(layout, style);
}
}
void CameraApplication::OnSceneAboutToBeRemoved(Scene *scene, AttributeChange::Type)
{
if (joystickId_ >= 0 && lastScene_ && scene == lastScene_.Get())
{
GetSubsystem<Urho3D::Input>()->RemoveScreenJoystick(joystickId_);
joystickId_ = -1;
}
}
void CameraApplication::CreateCamera()
{
if (!lastScene_)
return;
StringVector components;
components.Push("Placeable");
components.Push("Camera");
Entity* cameraEntity = lastScene_->CreateEntity(0, components, AttributeChange::LocalOnly, false, false, true);
if (!cameraEntity)
{
LogError("CameraApplication::CreateCamera: failed to create camera entity");
return;
}
cameraEntity->SetName("FreeLookCamera");
IRenderer* renderer = framework->Renderer();
if (!renderer)
{
LogError("CameraApplication::CreateCamera: can not assign camera; no renderer assigned");
return;
}
renderer->SetMainCamera(cameraEntity);
TundraLogic* logic = framework->Module<TundraLogic>();
if (logic)
logic->SyncManager()->SetObserver(EntityPtr(cameraEntity));
lastCamera_ = cameraEntity;
lastScene_->EntityCreated.Connect(this, &CameraApplication::CheckCameraSpawnPos);
CheckCameraSpawnPos(lastScene_->EntityByName("FreeLookCameraSpawnPos"), AttributeChange::Default);
}
void CameraApplication::CheckCameraSpawnPos(Entity* entity, AttributeChange::Type /*change*/)
{
if (!entity || entity->Name() != "FreeLookCameraSpawnPos")
return;
Entity* cameraEntity = framework->Renderer()->MainCamera();
if (!cameraEntity || !cameraEntity->Component<Placeable>())
return;
Placeable* cameraPosPlaceable = entity->Component<Placeable>();
if (cameraPosPlaceable)
cameraEntity->Component<Placeable>()->transform.Set(cameraPosPlaceable->transform.Get());
}
void CameraApplication::MoveCamera(Entity* cameraEntity, float frameTime)
{
if (!cameraEntity)
return;
Placeable* placeable = cameraEntity->Component<Placeable>();
if (!placeable)
return;
InputAPI* input = framework->Input();
bool changed = false;
Transform t = placeable->transform.Get();
float3 rotDelta = float3::zero;
if (inputContext_->IsMouseButtonDown(Urho3D::MOUSEB_RIGHT))
{
rotDelta.x -= input->GetMouseMoveY() * cRotateSpeed;
rotDelta.y -= input->GetMouseMoveX() * cRotateSpeed;
}
else if (inputContext_->GetNumTouches() > 0)
{
// Find a touch point that is not on top of the movement joystick button.
for (int ti=0, len=input->GetNumTouches(); ti<len; ++ti)
{
Urho3D::TouchState *touch = input->GetTouch(ti);
if (!touch->touchedElement_.Get())
{
rotDelta -= (float3(static_cast<float>(touch->delta_.y_), static_cast<float>(touch->delta_.x_), 0.f) * cRotateSpeed);
break;
}
}
}
if (!rotDelta.Equals(float3::zero))
{
RotateChanged.Emit(rotDelta);
t.rot.x += rotDelta.x;
t.rot.y += rotDelta.y;
t.rot.x = Clamp(t.rot.x, -90.0f, 90.0f);
changed = true;
}
float3 moveVector = float3::zero;
// Note right-handed coordinate system
if (inputContext_->IsKeyDown(Urho3D::KEY_W))
moveVector += float3(0.0f, 0.0f, -1.0f);
if (inputContext_->IsKeyDown(Urho3D::KEY_S))
moveVector += float3(0.0f, 0.0f, 1.0f);
if (inputContext_->IsKeyDown(Urho3D::KEY_A))
moveVector += float3(-1.0f, 0.0f, 0.0f);
if (inputContext_->IsKeyDown(Urho3D::KEY_D))
moveVector += float3(1.0f, 0.0f, 0.0f);
if (inputContext_->IsKeyDown(Urho3D::KEY_SPACE))
moveVector += float3(0.0f, 1.0f, 0.0f);
if (inputContext_->IsKeyDown(Urho3D::KEY_C))
moveVector += float3(0.0f, -1.0f, 0.0f);
if (!moveVector.Equals(lastMoveVector_))
{
lastMoveVector_ = moveVector;
MoveChanged.Emit(moveVector);
}
if (inputContext_->IsKeyPressed(Urho3D::KEY_SHIFT))
moveVector *= 2;
if (!moveVector.Equals(float3::zero))
{
movementHeld_ = Clamp(movementHeld_ + (frameTime * 4.f), 0.f, 1.0f);
t.pos += t.Orientation() * (cMoveSpeed * frameTime * moveVector * movementHeld_);
changed = true;
}
else
movementHeld_ = 0.f;
// If some other camera (like avatar) is active, do not actually move, only transmit the move signals
if (changed && cameraEntity == lastCamera_)
placeable->transform.Set(t);
}
void CameraApplication::OnMouseScroll(MouseEvent* e)
{
ZoomChanged.Emit(e->relativeZ);
}
}
extern "C"
{
DLLEXPORT void TundraPluginMain(Tundra::Framework *fw)
{
fw->RegisterModule(new Tundra::CameraApplication(fw));
}
}
| 30.284553 | 152 | 0.673289 | [
"transform"
] |
93020b3298bc1006c69ab23db8baca6768c5ddb6 | 1,592 | cpp | C++ | examples/google-code-jam/cchao/c (1).cpp | rbenic-fer/progauthfp | d0fd96c31ab0aab1a9acdcb7c75f2b430f51c675 | [
"MIT"
] | null | null | null | examples/google-code-jam/cchao/c (1).cpp | rbenic-fer/progauthfp | d0fd96c31ab0aab1a9acdcb7c75f2b430f51c675 | [
"MIT"
] | null | null | null | examples/google-code-jam/cchao/c (1).cpp | rbenic-fer/progauthfp | d0fd96c31ab0aab1a9acdcb7c75f2b430f51c675 | [
"MIT"
] | null | null | null | #include <cstdio>
#include <cstdlib>
#include <cmath>
#include <cstring>
#include <cctype>
#include <iostream>
#include <sstream>
#include <algorithm>
#include <stack>
#include <queue>
#include <deque>
#include <vector>
#include <map>
#include <set>
using namespace std;
struct mountain
{
int h;
int up;
int low;
mountain()
{
h=-1;
low=0;
up=1000000000;
}
};
int main()
{
//freopen("input","r",stdin);
int tt;
cin >> tt;
for(int ii=1;ii<=tt;ii++)
{
int n;
cin >> n;
int r[n];
vector<int> w[n];
for(int k=0;k<n-1;k++)
{
cin >> r[k];
r[k]--;
w[r[k]].push_back(k);
}
mountain m[n];
m[n-1].h = 1000000000;
int ans = 1;
for(int k=n-1;k>=0 && ans;k--)
{
//cout << "50" << endl;
for(int j=0;j<w[k].size();j++)
{
for(int i = w[k][j]; i<k;i++)
{
if(r[i] > k)
{
ans = 0;
break;
}
}
//cout << k << "draw " << w[k][j] << endl;
if(m[w[k][j] ].h >= 0)
{
ans = 0;
break;
}
m[w[k][j] ].h = m[k].h-1;
}
}
printf("Case #%d: ",ii);
if(ans) for(int k=0;k<n;k++) cout << m[k].h << ' ';
else cout << "Impossible";
cout << endl;
}
return 0;
}
| 20.675325 | 59 | 0.356784 | [
"vector"
] |
9304e76a4750fa3d14b64b22cfa67c15549ce73c | 2,498 | hh | C++ | Original Geant4 code/include/ExN03RunAction.hh | ArtistMonkey83/MEGALib_SSGX | b1493cef112c06621322a5d2d21eb504bd9ef8e1 | [
"Apache-2.0"
] | null | null | null | Original Geant4 code/include/ExN03RunAction.hh | ArtistMonkey83/MEGALib_SSGX | b1493cef112c06621322a5d2d21eb504bd9ef8e1 | [
"Apache-2.0"
] | null | null | null | Original Geant4 code/include/ExN03RunAction.hh | ArtistMonkey83/MEGALib_SSGX | b1493cef112c06621322a5d2d21eb504bd9ef8e1 | [
"Apache-2.0"
] | 1 | 2018-04-09T00:10:04.000Z | 2018-04-09T00:10:04.000Z | //
// ExN03RunAction.hh CIPHER 3
//
#ifndef ExN03RunAction_h
#define ExN03RunAction_h 1
#include "G4VPhysicalVolume.hh"
#include "G4VTouchable.hh"
#include "G4TouchableHistory.hh"
#include "G4UserRunAction.hh"
#include "globals.hh"
#include "G4ios.hh"
#include "iomanip"
#include <assert.h>
#include "iostream"
#include "fstream"
#include "functional"
#include "set"
#include "sstream"
#include <vector>
#include <streambuf>
class G4Run;
class ExN03RunAction : public G4UserRunAction
{
public:
ExN03RunAction();
~ExN03RunAction();
public:
void BeginOfRunAction(const G4Run*);
void EndOfRunAction(const G4Run*);
inline void fillPerHit(G4double,G4double,G4double);
private:
const G4int NbOfPixelsInX;
const G4int NbOfPixelsInY;
std::ofstream DoublesFile;
G4int IDinX;
G4int IDinY;
G4int Multiplicity;
G4double PixelEnergy;
G4double TotalPixelEnergy;
G4double InitEnergy;
G4int EventNumber;
G4int Detected;
G4int FullyDetected;
G4int NbOfDoubles;
};
inline
void ExN03RunAction::fillPerHit(G4double IDinX,G4double IDinY,G4double PixelEnergy)
{
static G4int EventNumber = 0;
static G4int Multiplicity = 0;
// static G4int Detected = 0;
// static G4int FullyDetected = 0;
// static G4double PixelEnergy = 0;
static G4double InitEnergy = 0;
static G4double TotalPixelEnergy = 0;
/*** Writing in a file ***/
// Begining of event: Event number, Multiplicity
if(PixelEnergy==-2){
IDinX=0;
IDinY=0;
EventNumber++;
}
// Writing on file at the End of Event
else if(PixelEnergy==-1)
{
if(TotalPixelEnergy==InitEnergy){
FullyDetected++;
}
if(TotalPixelEnergy>20*keV){
Detected++;
}
DoublesFile.open("CdTe200mm200mm10mm.dat");
if((EventNumber)%100==0){ // writes in file each 100
DoublesFile << "Source Photons:: " << EventNumber << G4endl;
DoublesFile << "Detected: " << Detected << " Fully Detected: " << FullyDetected;
DoublesFile << G4endl;
}
DoublesFile.close();
/*** Variables reset ***/
TotalPixelEnergy=0;
Multiplicity=0;
// storyX = -1; storyY = -1;
}
// Writing on file during the event
else
{
Multiplicity++;
if(Multiplicity==1){
InitEnergy=IDinX;
}
if(PixelEnergy>20*keV){
TotalPixelEnergy=TotalPixelEnergy+PixelEnergy;
}
G4cout << "Initial Energy: " << InitEnergy << " Energy: " << PixelEnergy << " Total: " << TotalPixelEnergy << G4endl;
}
}
#endif
| 19.515625 | 123 | 0.672538 | [
"vector"
] |
930553f60ad6d9954b40bfd852109c6ed668950e | 2,295 | cpp | C++ | MegaManX3/StageMiniBoss1.cpp | bboyturtles13/Mega-Man-X3 | b84b35176d72cf43cbce6fd34c5e8e28638a442a | [
"MIT"
] | 7 | 2019-09-19T06:59:47.000Z | 2022-01-26T10:21:49.000Z | MegaManX3/StageMiniBoss1.cpp | bboyturtles13/Mega-Man-X3 | b84b35176d72cf43cbce6fd34c5e8e28638a442a | [
"MIT"
] | 3 | 2020-01-20T04:28:59.000Z | 2020-01-20T05:01:43.000Z | MegaManX3/StageMiniBoss1.cpp | bboyturtles13/Mega-Man-X3 | b84b35176d72cf43cbce6fd34c5e8e28638a442a | [
"MIT"
] | 6 | 2019-11-15T02:13:12.000Z | 2022-01-27T12:30:29.000Z | #include "StageMiniBoss1.h"
StageMiniBoss1::StageMiniBoss1()
{
gateLeft = new Gate(2304, 897, 16, 48, false);
gateRight = new Gate(2546, 897, 16, 48, false);
gateLeft->state = GateOpen;
gateRight->state = GateLock;
genjibo = new Genjibo(-1, 2518, 700);
shurikein = new Shurikein(-1, 2518, 920);
shurikein->state = manifest;
shurikein->visible = false;
genjibo->setShurikein(shurikein);
ready = false;
gateLeftClose = false;
}
StageMiniBoss1::~StageMiniBoss1()
{
}
void StageMiniBoss1::getStaticObjects(unordered_map<int, GameObject*>* saticObjects)
{
if(shurikein->visible)
saticObjects[0][-777] = gateRight;
}
void StageMiniBoss1::getDynamicObjects(unordered_map<int, GameObject*>* dynamicObjects)
{
dynamicObjects[0][-888] = genjibo;
dynamicObjects[0][-889] = shurikein;
}
void StageMiniBoss1::update(DWORD dt, unordered_map<int, GameObject*>* staticObjects)
{
if (ready)
{
genjibo->update(dt);
shurikein->update(dt, staticObjects);
if (!main->enable && shurikein->state != manifest)
main->setEnable(true);
if (!shurikein->visible &&
mainGlobal->getBoundBox().intersectsWith(gateRight->getBoundBox()))
{
gateRight->state = GateOpening;
main->enable = false;
main->speed.vx = 0.005f * dt;
ready = false;
}
}
else
{
if (gateRight->state == GateLock)
{
if(gateLeftClose && gateLeft->state == GateLock)
ready = true;
updateMain(dt);
}
else
if (!main->enable && gateRight->state == GateOpen)
{
updateMain(dt);
}
if (gateLeft->state == GateOpen && !mainGlobal->getBoundBox().intersectsWith(gateLeft->getBoundBox()))
{
gateLeft->state = GateClose;
gateLeftClose = true;
updateMain(dt);
main->speed.vx = 0.0f;
main->dx = 0;
main->state = stand;
}
}
}
void StageMiniBoss1::render(DWORD dt, D3DCOLOR colorBrush)
{
if (ready)
{
genjibo->render(dt);
shurikein->render(dt);
}
gateLeft->render(dt);
gateRight->render(dt);
}
void StageMiniBoss1::reset()
{
gateLeft->state = GateOpen;
gateRight->state = GateLock;
delete genjibo;
delete shurikein;
ready = false;
gateLeftClose = false;
genjibo = new Genjibo(-1, 2518, 700);
shurikein = new Shurikein(-1, 2518, 920);
shurikein->state = manifest;
shurikein->visible = false;
genjibo->setShurikein(shurikein);
}
| 19.784483 | 104 | 0.679303 | [
"render"
] |
930c9ebd54405e6956dae16e319fb5e227e3dea1 | 584 | cpp | C++ | 1046.最后一块石头的重量/lastStoneWeight.cpp | YichengZhong/Top-Interview-Questions | 124828d321f482a0eaa30012b3706267487bfd24 | [
"MIT"
] | 1 | 2019-10-21T14:40:39.000Z | 2019-10-21T14:40:39.000Z | 1046.最后一块石头的重量/lastStoneWeight.cpp | YichengZhong/Top-Interview-Questions | 124828d321f482a0eaa30012b3706267487bfd24 | [
"MIT"
] | null | null | null | 1046.最后一块石头的重量/lastStoneWeight.cpp | YichengZhong/Top-Interview-Questions | 124828d321f482a0eaa30012b3706267487bfd24 | [
"MIT"
] | 1 | 2020-11-04T07:33:34.000Z | 2020-11-04T07:33:34.000Z | class Solution {
public:
int lastStoneWeight(vector<int>& stones) {
if(stones.size()==0)
{
return 0;
}
while(stones.size()>1)
{
sort(stones.begin(),stones.end());
int temp=stones[stones.size()-1]-stones[stones.size()-2];
stones.pop_back();
stones.pop_back();
if(temp!=0)
{
stones.push_back(temp);
}
}
if(stones.size()==0)
{
return 0;
}
return stones[0];
}
}; | 18.83871 | 69 | 0.410959 | [
"vector"
] |
930d9fd68ebe936f407394cc86d6dd48d129f350 | 9,097 | cpp | C++ | src/emulator.cpp | YuviTz1/Gameboy-Emulator | f666d4b75cbbac74695b695358d24d97fc63546b | [
"MIT"
] | null | null | null | src/emulator.cpp | YuviTz1/Gameboy-Emulator | f666d4b75cbbac74695b695358d24d97fc63546b | [
"MIT"
] | null | null | null | src/emulator.cpp | YuviTz1/Gameboy-Emulator | f666d4b75cbbac74695b695358d24d97fc63546b | [
"MIT"
] | null | null | null | #include "emulator.h"
Emulator::Emulator()
{
cpu.init(&memory);
display.init(&memory);
}
// Start emulation of CPU
void Emulator::run()
{
sf::Time time;
while(display.window.isOpen())
{
// CPU cycles to emulate per frame draw
float cycles_per_frame = cpu.CLOCK_SPEED / framerate;
float time_between_frames = 1000 / framerate;
// Current cycle in frame
int current_cycle = 0;
handle_events();
while (current_cycle < cycles_per_frame)
{
Opcode code = memory.read(cpu.reg_PC);
cpu.parse_opcode(code);
current_cycle += cpu.num_cycles;
update_timers(cpu.num_cycles);
update_scanline(cpu.num_cycles);
do_interrupts();
cpu.num_cycles = 0;
}
//display.render();
//cout << "frame " << current_cycle << endl;
current_cycle = 0;
int frame_time = time.asMilliseconds();
float sleep_time = time_between_frames - frame_time;
if (frame_time < time_between_frames)
sf::sleep(sf::milliseconds(sleep_time));
time = time.Zero;
//cout << display.scanlines_rendered << endl;
display.scanlines_rendered = 0;
//debugger
if (debugWindow.window.isOpen())
{
debugWindow.update(cpu);
}
}
}
// Hanlde window events and IO
void Emulator::handle_events()
{
sf::Event event;
while (display.window.pollEvent(event))
{
switch (event.type)
{
case sf::Event::Closed:
display.window.close();
break;
case sf::Event::KeyPressed:
key_pressed(event.key.code);
break;
case sf::Event::KeyReleased:
key_released(event.key.code);
break;
}
}
}
void Emulator::key_pressed(Key key)
{
// Function keys F1 thru F12
if (key >= 85 && key <= 96)
{
int id = key - 84;
if (sf::Keyboard::isKeyPressed(Key::LShift))
save_state(id);
else
load_state(id);
return;
}
if (key == Key::Space)
{
cpu.CLOCK_SPEED *= 100;
return;
}
int key_id = get_key_id(key);
if (key_id < 0)
return;
bool directional = false;
if (key == Key::Up || key == Key::Down || key == Key::Left || key == Key::Right)
{
directional = true;
}
Byte joypad = (directional) ? memory.joypad_arrows : memory.joypad_buttons;
bool unpressed = is_bit_set(joypad, key_id);
if (!unpressed)
return;
if (directional)
memory.joypad_arrows = clear_bit(joypad, key_id);
else
memory.joypad_buttons = clear_bit(joypad, key_id);
request_interrupt(INTERRUPT_JOYPAD);
}
void Emulator::key_released(Key key)
{
if (key == Key::Space)
{
cpu.CLOCK_SPEED /= 100;
}
int key_id = get_key_id(key);
if (key_id < 0)
return;
bool directional = false;
if (key == Key::Up || key == Key::Down || key == Key::Left || key == Key::Right)
{
directional = true;
}
Byte joypad = (directional) ? memory.joypad_arrows : memory.joypad_buttons;
bool unpressed = is_bit_set(joypad, key_id);
if (unpressed)
return;
if (directional)
memory.joypad_arrows = set_bit(joypad, key_id);
else
memory.joypad_buttons = set_bit(joypad, key_id);
}
int Emulator::get_key_id(Key key)
{
switch (key)
{
case Key::A:
case Key::Right:
return BIT_0;
case Key::S: // B
case Key::Left:
return BIT_1;
case Key::X: // select
case Key::Up:
return BIT_2;
case Key::Z:
case Key::Down:
return BIT_3;
default:
return -1;
}
}
void Emulator::update_divider(int cycles)
{
divider_counter += cycles;
if (divider_counter >= 256) // 16384 Hz
{
divider_counter = 0;
memory.DIV.set(memory.DIV.get() + 1);
}
}
// Opcode cycle number may need adjusted, used Nintendo values
void Emulator::update_timers(int cycles)
{
update_divider(cycles);
// This can be optimized if needed
Byte new_freq = get_timer_frequency();
if (timer_frequency != new_freq)
{
set_timer_frequency();
timer_frequency = new_freq;
}
if (timer_enabled())
{
timer_counter -= cycles;
// enough cpu clock cycles have happened to update timer
if (timer_counter <= 0)
{
Byte timer_value = memory.TIMA.get();
set_timer_frequency();
// Timer will overflow, generate interrupt
if (timer_value == 255)
{
memory.TIMA.set(memory.TMA.get());
request_interrupt(INTERRUPT_TIMER);
}
else
{
memory.TIMA.set(timer_value + 1);
}
}
}
}
bool Emulator::timer_enabled()
{
return memory.TAC.is_bit_set(BIT_2);
}
Byte Emulator::get_timer_frequency()
{
return (memory.TAC.get() & 0x3);
}
void Emulator::set_timer_frequency()
{
Byte frequency = get_timer_frequency();
timer_frequency = frequency;
switch (frequency)
{
// timer_counter calculated by (Clock Speed / selected frequency)
case 0: timer_counter = 1024; break; // 4096 Hz
case 1: timer_counter = 16; break; // 262144 Hz
case 2: timer_counter = 64; break; // 65536 Hz
case 3: timer_counter = 256; break; // 16384 Hz
}
}
void Emulator::request_interrupt(Byte id)
{
memory.IF.set_bit(id);
}
void Emulator::do_interrupts()
{
// If there are any interrupts set
if (memory.IF.get() > 0)
{
// Resume CPU state if halted and interrupts are pending
if (memory.IE.get() > 0)
{
if (cpu.halted)
{
cpu.halted = false;
cpu.reg_PC += 1;
}
}
// Loop through each bit and call interrupt for lowest . highest priority bits set
for (int i = 0; i < 5; i++)
{
if (memory.IF.is_bit_set(i))
{
if (memory.IE.is_bit_set(i))
{
// IME only disables the servicing of interrupts,
// not all interrupt functionality
if (cpu.interrupt_master_enable)
{
service_interrupt(i);
}
}
}
}
}
}
void Emulator::service_interrupt(Byte id)
{
cpu.interrupt_master_enable = false;
memory.IF.clear_bit(id);
// Push current execution address to stack
memory.write(--cpu.reg_SP, high_byte(cpu.reg_PC));
memory.write(--cpu.reg_SP, low_byte(cpu.reg_PC));
switch (id)
{
case INTERRUPT_VBLANK: cpu.reg_PC = 0x40; break;
case INTERRUPT_LCDC: cpu.reg_PC = 0x48; break;
case INTERRUPT_TIMER: cpu.reg_PC = 0x50; break;
case INTERRUPT_SERIAL: cpu.reg_PC = 0x58; break;
case INTERRUPT_JOYPAD: cpu.reg_PC = 0x60; break;
}
}
void Emulator::set_lcd_status()
{
Byte status = memory.STAT.get();
Byte current_line = memory.LY.get();
// extract current LCD mode
Byte current_mode = status & 0x03;
Byte mode = 0;
bool do_interrupt = false;
// in VBLANK, set mode to 1
if (current_line >= 144)
{
mode = 1; // In vertical blanking period
// 1 binary
status = set_bit(status, BIT_0);
status = clear_bit(status, BIT_1);
do_interrupt = is_bit_set(status, BIT_4);
}
else
{
int mode2_threshold = 456 - 80;
int mode3_threshold = mode2_threshold - 172;
if (scanline_counter >= mode2_threshold)
{
mode = 2; // Searching OAM RAM
// 2 binary
status = set_bit(status, BIT_1);
status = clear_bit(status, BIT_0);
do_interrupt = is_bit_set(status, BIT_5);
}
else if (scanline_counter >= mode3_threshold)
{
mode = 3; // Transferring data to LCD driver
// 3 binary
status = set_bit(status, BIT_1);
status = set_bit(status, BIT_0);
}
else
{
mode = 0; // CPU has access to all display RAM
// If first time encountering H-blank, update the scanline
if (current_mode != mode)
{
// draw current scanline to screen
if (current_line < 144 && display.scanlines_rendered <= 144)
display.update_scanline(current_line);
}
// 0 binary
status = clear_bit(status, BIT_1);
status = clear_bit(status, BIT_0);
do_interrupt = is_bit_set(status, BIT_3);
}
}
// Entered new mode, request interrupt
if (do_interrupt && (mode != current_mode))
request_interrupt(INTERRUPT_LCDC);
// check coincidence flag, set bit 2 if it matches
if (memory.LY.get() == memory.LYC.get())
{
status = set_bit(status, BIT_2);
if (is_bit_set(status, BIT_6))
request_interrupt(INTERRUPT_LCDC);
}
// clear bit 2 if not
else
status = clear_bit(status, BIT_2);
memory.STAT.set(status);
memory.video_mode = mode;
}
void Emulator::update_scanline(int cycles)
{
scanline_counter -= cycles;
set_lcd_status();
if (memory.LY.get() > 153)
memory.LY.clear();
// Enough time has passed to draw the next scanline
if (scanline_counter <= 0)
{
Byte current_scanline = memory.LY.get();
// increment scanline and reset counter
memory.LY.set(++current_scanline);
scanline_counter = 456;
// Entered VBLANK period
if (current_scanline == 144)
{
request_interrupt(INTERRUPT_VBLANK);
if (display.scanlines_rendered <= 144)
display.render();
}
// Reset counter if past maximum
else if (current_scanline > 153)
memory.LY.clear();
}
}
void Emulator::save_state(int id)
{
ofstream file;
string filename = "./saves/" + memory.rom_name + "_" + to_string(id) + ".sav";
file.open(filename, ios::binary | ios::trunc);
if (!file.bad())
{
cpu.save_state(file);
memory.save_state(file);
file.close();
cout << "wrote save state " << id << endl;
}
}
void Emulator::load_state(int id)
{
string filename = "./saves/" + memory.rom_name + "_" + to_string(id) + ".sav";
ifstream file(filename, ios::binary);
if (file.is_open())
{
cpu.load_state(file);
memory.load_state(file);
file.close();
cout << "loaded state " << id << endl;
}
}
| 20.215556 | 84 | 0.666154 | [
"render"
] |
9314336af542be5816dfa29781485b38dc8705dc | 2,216 | cpp | C++ | boost/libs/functional/hash/test/hash_std_tuple_test.cpp | randolphwong/mcsema | eb5b376736e7f57ff0a61f7e4e5a436bbb874720 | [
"BSD-3-Clause"
] | 2 | 2018-12-15T19:56:07.000Z | 2021-01-10T09:49:33.000Z | boost/libs/functional/hash/test/hash_std_tuple_test.cpp | randolphwong/mcsema | eb5b376736e7f57ff0a61f7e4e5a436bbb874720 | [
"BSD-3-Clause"
] | null | null | null | boost/libs/functional/hash/test/hash_std_tuple_test.cpp | randolphwong/mcsema | eb5b376736e7f57ff0a61f7e4e5a436bbb874720 | [
"BSD-3-Clause"
] | 1 | 2020-11-23T01:52:12.000Z | 2020-11-23T01:52:12.000Z |
// Copyright 2012 Daniel James.
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#include "./config.hpp"
#ifdef TEST_EXTENSIONS
# ifdef TEST_STD_INCLUDES
# include <functional>
# else
# include <boost/functional/hash.hpp>
# endif
#endif
#include <boost/config.hpp>
#include <boost/detail/lightweight_test.hpp>
#if defined(TEST_EXTENSIONS) && !defined(BOOST_NO_CXX11_HDR_TUPLE)
#define TEST_TUPLE
#include <tuple>
#include <vector>
#endif
#ifdef TEST_TUPLE
template <typename T>
void tuple_tests(T const& v) {
boost::hash<typename T::value_type> hf;
for(typename T::const_iterator i = v.begin(); i != v.end(); ++i) {
for(typename T::const_iterator j = v.begin(); j != v.end(); ++j) {
if (i != j)
BOOST_TEST(hf(*i) != hf(*j));
else
BOOST_TEST(hf(*i) == hf(*j));
}
}
}
void empty_tuple_test() {
boost::hash<std::tuple<> > empty_tuple_hash;
std::tuple<> empty_tuple;
BOOST_TEST(empty_tuple_hash(empty_tuple) == boost::hash_value(empty_tuple));
}
void int_tuple_test() {
std::vector<std::tuple<int> > int_tuples;
int_tuples.push_back(std::make_tuple(0));
int_tuples.push_back(std::make_tuple(1));
int_tuples.push_back(std::make_tuple(2));
tuple_tests(int_tuples);
}
void int_string_tuple_test() {
std::vector<std::tuple<int, std::string> > int_string_tuples;
int_string_tuples.push_back(std::make_tuple(0, std::string("zero")));
int_string_tuples.push_back(std::make_tuple(1, std::string("one")));
int_string_tuples.push_back(std::make_tuple(2, std::string("two")));
int_string_tuples.push_back(std::make_tuple(0, std::string("one")));
int_string_tuples.push_back(std::make_tuple(1, std::string("zero")));
int_string_tuples.push_back(std::make_tuple(0, std::string("")));
int_string_tuples.push_back(std::make_tuple(1, std::string("")));
tuple_tests(int_string_tuples);
}
#endif // TEST_TUPLE
int main()
{
#ifdef TEST_TUPLE
empty_tuple_test();
int_tuple_test();
int_string_tuple_test();
#endif
return boost::report_errors();
}
| 28.410256 | 80 | 0.676895 | [
"vector"
] |
7939eab53de948fce81925d1435d744f5c30df2b | 5,084 | cpp | C++ | src/Util/JoystickWindows.cpp | jun0/choreonoid | 37167e52bfa054088272e1924d2062604104ac08 | [
"MIT"
] | 2 | 2019-01-24T17:57:49.000Z | 2021-09-21T21:42:22.000Z | src/Util/JoystickWindows.cpp | jun0/choreonoid | 37167e52bfa054088272e1924d2062604104ac08 | [
"MIT"
] | null | null | null | src/Util/JoystickWindows.cpp | jun0/choreonoid | 37167e52bfa054088272e1924d2062604104ac08 | [
"MIT"
] | 1 | 2020-12-11T06:42:16.000Z | 2020-12-11T06:42:16.000Z | /**
@author Shizuko Hattori
@author Shin'ichiro Nakaoka
*/
#include "Joystick.h"
#include "ExtJoystick.h"
#include <boost/dynamic_bitset.hpp>
#include <windows.h>
#include <mmsystem.h>
#include <vector>
#include <string>
using namespace std;
using namespace cnoid;
namespace cnoid {
class JoystickImpl
{
public:
Joystick* self;
ExtJoystick* extJoystick;
int id;
int numAvailableAxes;
vector<double> axes;
boost::dynamic_bitset<> axisEnabled;
vector<bool> buttons;
string errorMessage;
Signal<void(int id, bool isPressed)> sigButton;
Signal<void(int id, double position)> sigAxis;
JoystickImpl();
bool openDevice();
bool readCurrentState();
};
}
Joystick::Joystick()
{
impl = new JoystickImpl();
}
Joystick::Joystick(const char* device)
{
impl = new JoystickImpl();
}
JoystickImpl::JoystickImpl()
{
id = -1;
extJoystick = 0;
if (!openDevice()){
extJoystick = ExtJoystick::findJoystick("*");
}
}
bool JoystickImpl::openDevice()
{
numAvailableAxes = 0;
std::vector<UINT> devIds;
JOYINFOEX info;
info.dwSize = sizeof(JOYINFOEX);
info.dwFlags = JOY_RETURNALL;
int i = 0;
while(true){
MMRESULT result = joyGetPosEx(i, &info);
if(result == JOYERR_PARMS){
break;
}
if(result == JOYERR_NOERROR){
devIds.push_back(i);
}
++i;
}
if(!devIds.empty()){
// Pick up the first device
id = devIds.front();
JOYCAPS caps;
joyGetDevCaps(id, &caps, sizeof(caps));
numAvailableAxes = caps.wNumAxes;
axes.resize(numAvailableAxes, 0.0);
axisEnabled.resize(numAvailableAxes, true);
buttons.resize(caps.wNumButtons, false);
return readCurrentState();
}
return false;
}
Joystick::~Joystick()
{
delete impl;
}
bool Joystick::isReady() const
{
return impl->extJoystick ? true : (impl->id >= 0);
}
const char* Joystick::errorMessage() const
{
return impl->errorMessage.c_str();
}
int Joystick::fileDescriptor() const
{
return impl->id;
}
int Joystick::numAxes() const
{
return impl->extJoystick ? impl->extJoystick->numAxes() : impl->numAvailableAxes;
}
void Joystick::setAxisEnabled(int axis, bool on)
{
if (!impl->extJoystick){
if (axis < impl->axes.size()){
impl->axes[axis] = 0.0;
impl->axisEnabled[axis] = on;
}
}
}
int Joystick::numButtons() const
{
return impl->extJoystick ? impl->extJoystick->numButtons() : impl->buttons.size();
}
bool Joystick::readCurrentState()
{
return impl->extJoystick ? impl->extJoystick->readCurrentState() : impl->readCurrentState();
}
bool JoystickImpl::readCurrentState()
{
if(id < 0){
return false;
}
JOYINFOEX info;
info.dwSize = sizeof(info);
info.dwFlags = JOY_RETURNBUTTONS | JOY_RETURNX | JOY_RETURNY | JOY_RETURNZ;
if(joyGetPosEx(id, &info) != JOYERR_NOERROR) {
return false;
} else {
// buttons
for(size_t i=0; i < buttons.size(); ++i){
if(info.dwButtons & JOY_BUTTON1){
buttons[i] = true;
} else {
buttons[i] = false;
}
info.dwButtons >>= 1;
}
// axes. normalize value (-1.0 to 1.0)
if (axisEnabled[0])
axes[0] = ((double)info.dwXpos - 32767.0) / 32768.0;
if (axisEnabled[1])
axes[1] = ((double)info.dwYpos - 32767.0) / 32768.0;
if (axisEnabled[2])
axes[2] = ((double)info.dwZpos - 32767.0) / 32768.0;
// axis 3 and 4 are exchanged to be the same as Linux
if (axisEnabled[4])
axes[4] = ((double)info.dwRpos - 32767.0) / 32768.0;
if (axisEnabled[3])
axes[3] = ((double)info.dwUpos - 32767.0) / 32768.0;
if (axisEnabled[5])
axes[5] = ((double)info.dwVpos - 32767.0) / 32768.0;
return true;
}
return false;
}
double Joystick::getPosition(int axis) const
{
if (impl->extJoystick){
return impl->extJoystick->getPosition(axis);
}
if(axis < impl->axes.size()){
return impl->axes[axis];
}
return 0.0;
}
bool Joystick::getButtonState(int button) const
{
if (impl->extJoystick){
return impl->extJoystick->getButtonState(button);
}
if(button < impl->buttons.size()){
return impl->buttons[button];
}
return false;
}
bool Joystick::isActive() const
{
if (impl->extJoystick){
return impl->extJoystick->isActive();
}
for(size_t i=0; i < impl->axes.size(); ++i){
if(impl->axes[i] != 0.0){
return true;
}
}
for(size_t i=0; i < impl->buttons.size(); ++i){
if(impl->buttons[i]){
return true;
}
}
return false;
}
SignalProxy<void(int id, bool isPressed)> Joystick::sigButton()
{
return impl->sigButton;
}
SignalProxy<void(int id, double position)> Joystick::sigAxis()
{
return impl->sigAxis;
}
| 19.629344 | 96 | 0.584382 | [
"vector"
] |
793b710791a78272b44f90111aada0d652a76940 | 742 | cc | C++ | src/388.cc | o-olll/shuati | 64a031a5218670afd4bdbba5d3af3c428757b3fd | [
"Apache-2.0"
] | null | null | null | src/388.cc | o-olll/shuati | 64a031a5218670afd4bdbba5d3af3c428757b3fd | [
"Apache-2.0"
] | null | null | null | src/388.cc | o-olll/shuati | 64a031a5218670afd4bdbba5d3af3c428757b3fd | [
"Apache-2.0"
] | null | null | null | #include <iostream>
#include <sstream>
#include <vector>
#include <unordered_map>
#include <string>
#include "utils.h"
using namespace std;
int lengthLongestPath(string input)
{
istringstream iss(input);
string line;
unordered_map<int,int> counts;
int res = 0;
while (getline(iss, line)) {
int t = line.find_last_of('\t') + 1;
int remain = line.size() - t;
if (line.find('.') != string::npos) {
res = max(res, remain+counts[t-1]);
} else {
counts[t] = remain + counts[t-1] + 1;
}
}
return res;
}
int main(int argc, char** argv)
{
string test(argv[1]);
cout << test << endl;
cout << lengthLongestPath(test) << endl;
return 0;
}
| 19.025641 | 49 | 0.567385 | [
"vector"
] |
793ebfaba00ceed0f8fd165d2509f5a24f1739ff | 7,557 | cpp | C++ | source/test_core/test_analytical_solver_implementation.cpp | UshakovSergeySergey/kinverse | bae781e885cfa0771ec8e53506ec5cc57ac17154 | [
"BSD-3-Clause"
] | 1 | 2020-12-19T13:40:31.000Z | 2020-12-19T13:40:31.000Z | source/test_core/test_analytical_solver_implementation.cpp | UshakovSergeySergey/kinverse | bae781e885cfa0771ec8e53506ec5cc57ac17154 | [
"BSD-3-Clause"
] | 13 | 2020-12-09T10:57:31.000Z | 2020-12-19T13:01:52.000Z | source/test_core/test_analytical_solver_implementation.cpp | UshakovSergeySergey/kinverse | bae781e885cfa0771ec8e53506ec5cc57ac17154 | [
"BSD-3-Clause"
] | null | null | null | /**
* BSD 3-Clause License
*
* Copyright (c) 2020, Sergey Ushakov
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "stdafx.h"
#include "test_analytical_solver_implementation.h"
#include <implementation/analytical_solver_implementation.h>
#include <kinverse/math/math.h>
namespace kinverse {
namespace core {
TEST_F(TestAnalyticalSolverImplementation, Constructor_WhenRobotIsNullptr_ThrowsException) {
// arrange act assert
EXPECT_THROW(AnalyticalSolverImplementation(nullptr), std::domain_error);
}
TEST_F(TestAnalyticalSolverImplementation, Constructor_WhenNumberOfJointsNotEqualSix_ThrowsException) {
// arrange
const std::vector<DenavitHartenbergParameters> dhTable{ DenavitHartenbergParameters{}, DenavitHartenbergParameters{} };
const auto robot = std::make_shared<Robot>();
robot->setDHTable(dhTable);
// act assert
EXPECT_THROW(std::make_shared<AnalyticalSolverImplementation>(robot), std::domain_error);
}
TEST_P(TestAnalyticalSolverImplementationGetGamma, GetGamma_WhenCalled_ReturnsCorrectDistance) {
// arrange
const DenavitHartenbergParameters dhParamsA3 = std::get<0>(GetParam());
const DenavitHartenbergParameters dhParamsA4 = std::get<1>(GetParam());
const double expectedGamma = std::get<2>(GetParam());
std::vector<DenavitHartenbergParameters> dhTable(6, DenavitHartenbergParameters{});
dhTable[2] = dhParamsA3;
dhTable[3] = dhParamsA4;
const auto robot = std::make_shared<Robot>();
robot->setDHTable(dhTable);
AnalyticalSolverImplementation solver(robot);
// act
const auto gamma = solver.getGamma();
// assert
EXPECT_DOUBLE_EQ(gamma, expectedGamma);
}
TEST_P(TestAnalyticalSolverImplementationGetDistanceFromA3ToA2, GetDistanceFromA3ToA2_WhenCalled_ReturnsCorrectDistance) {
// arrange
const DenavitHartenbergParameters dhParamsA2 = std::get<0>(GetParam());
const double expectedDistance = std::get<1>(GetParam());
std::vector<DenavitHartenbergParameters> dhTable(6, DenavitHartenbergParameters{});
dhTable[1] = dhParamsA2;
const auto robot = std::make_shared<Robot>();
robot->setDHTable(dhTable);
AnalyticalSolverImplementation solver(robot);
// act
const auto distance = solver.getDistanceFromA3ToA2();
// assert
EXPECT_DOUBLE_EQ(distance, expectedDistance);
}
TEST_P(TestAnalyticalSolverImplementationGetDistanceFromA3ToWrist, GetDistanceFromA3ToWrist_WhenCalled_ReturnsCorrectDistance) {
// arrange
const DenavitHartenbergParameters dhParamsA3 = std::get<0>(GetParam());
const DenavitHartenbergParameters dhParamsA4 = std::get<1>(GetParam());
const double expectedDistance = std::get<2>(GetParam());
std::vector<DenavitHartenbergParameters> dhTable(6, DenavitHartenbergParameters{});
dhTable[2] = dhParamsA3;
dhTable[3] = dhParamsA4;
const auto robot = std::make_shared<Robot>();
robot->setDHTable(dhTable);
AnalyticalSolverImplementation solver(robot);
// act
const auto distance = solver.getDistanceFromA3ToWrist();
// assert
EXPECT_DOUBLE_EQ(distance, expectedDistance);
}
TEST_F(TestAnalyticalSolverImplementation, GetA1ZAxis_WhenCalled_ReturnsUnitZ) {
// arrange
const std::vector<DenavitHartenbergParameters> dhTable(6, DenavitHartenbergParameters{});
const auto robot = std::make_shared<Robot>();
robot->setDHTable(dhTable);
AnalyticalSolverImplementation solver(robot);
// act
const Eigen::Vector3d axis = solver.getA1ZAxis();
// assert
EXPECT_TRUE(axis.isApprox(Eigen::Vector3d::UnitZ()));
}
TEST_F(TestAnalyticalSolverImplementation, ConvertWorldToA1Local_WhenCalled_ReturnsCorrectResult) {
// arrange
const Eigen::Affine3d robotTransform = math::fromXYZABC(Eigen::Vector3d{ 100.0, 200.0, 300.0 }, Eigen::Vector3d{ M_PI_2, -M_PI_2, M_PI_2 });
const Eigen::Affine3d robotBaseTransform = math::fromXYZABC(Eigen::Vector3d::Zero(), Eigen::Vector3d{ 0.0, 0.0, M_PI });
const Eigen::Affine3d worldTransform = math::fromXYZABC(Eigen::Vector3d{ -300.0, -200.0, -100.0 }, Eigen::Vector3d{ M_PI, -M_PI_2, 0.0 });
const Eigen::Affine3d expectedLocalTransform = math::fromXYZABC(Eigen::Vector3d{ -400.0, -400.0, 400.0 }, Eigen::Vector3d{ 0.0, 0.0, M_PI });
const std::vector<DenavitHartenbergParameters> dhTable(6, DenavitHartenbergParameters{});
const auto robot = std::make_shared<Robot>();
robot->setDHTable(dhTable);
robot->setTransform(robotTransform);
robot->setBaseTransform(robotBaseTransform);
AnalyticalSolverImplementation solver(robot);
// act
const Eigen::Affine3d localTransform = solver.convertWorldToA1Local(worldTransform);
// assert
EXPECT_TRUE(localTransform.isApprox(expectedLocalTransform));
}
TEST_F(TestAnalyticalSolverImplementation, ConvertTCPToFlange_WhenCalled_ReturnsCorrectResult) {
// arrange
const Eigen::Affine3d robotTCPTransform = math::fromXYZABC(Eigen::Vector3d{ 100.0, 200.0, 300.0 }, Eigen::Vector3d{ M_PI_2, -M_PI_2, 0.0 });
const Eigen::Affine3d tcpTransform = math::fromXYZABC(Eigen::Vector3d{ 100.0, -100.0, 100.0 }, Eigen::Vector3d{ -M_PI_2, 0.0, M_PI_2 });
const Eigen::Affine3d expectedFlangeTransform = math::fromXYZABC(Eigen::Vector3d{ -100.0, 200.0, 200.0 }, Eigen::Vector3d{ -M_PI_2, M_PI_2, 0.0 });
const std::vector<DenavitHartenbergParameters> dhTable(6, DenavitHartenbergParameters{});
const auto robot = std::make_shared<Robot>();
robot->setDHTable(dhTable);
robot->setTCPTransform(robotTCPTransform);
AnalyticalSolverImplementation solver(robot);
// act
const Eigen::Affine3d flangeTransform = solver.convertTCPToFlange(tcpTransform);
// assert
EXPECT_TRUE(flangeTransform.isApprox(expectedFlangeTransform));
}
} // namespace core
} // namespace kinverse
| 41.751381 | 153 | 0.72767 | [
"vector"
] |
794166e253991be6145b51c1d31becbb53e75b5d | 1,233 | cpp | C++ | p1108.cpp | ThinkiNOriginal/PTA-Advanced | 55cae28f76102964d0f6fd728dd62d6eba980c49 | [
"MIT"
] | null | null | null | p1108.cpp | ThinkiNOriginal/PTA-Advanced | 55cae28f76102964d0f6fd728dd62d6eba980c49 | [
"MIT"
] | null | null | null | p1108.cpp | ThinkiNOriginal/PTA-Advanced | 55cae28f76102964d0f6fd728dd62d6eba980c49 | [
"MIT"
] | null | null | null | #include <iostream>
#include <vector>
#include <cmath>
#include <string>
using namespace std;
bool is_legal(string& str) {
int dotcnt = 0;
int afterdot = 0;
int negcnt = 0;
int len = str.size();
bool dot = false;
for (int i = 0; i < len; i++) {
auto x = str[i];
if (x == '-') {
negcnt++;
if (negcnt > 1)
return false;
continue;
}
if (x == '.') {
dotcnt++;
dot = true;
if (dotcnt > 1)
return false;
continue;
}else
if (x < '0' or x > '9')
return false;
if (dot) {
afterdot++;
if (afterdot > 2)
return false;
}
}
return true;
}
int main() {
int N;
scanf("%d", &N);
int cnt = 0;
double total = 0;
for (int i = 0; i < N; i++) {
string tmp;
cin >> tmp;
if (is_legal(tmp)) {
double td = stod(tmp);
if (-1000 <= td and td <= 1000) {
total += td;
cnt++;
} else
printf("ERROR: %s is not a legal number\n", tmp.c_str());
} else {
printf("ERROR: %s is not a legal number\n", tmp.c_str());
}
}
if (cnt == 0)
printf("The average of 0 numbers is Undefined\n");
else if (cnt == 1) {
printf("The average of 1 number is %.2lf", total);
}
else {
printf("The average of %d numbers is %.2lf", cnt, total / cnt);
}
return 0;
}
| 16.890411 | 65 | 0.537713 | [
"vector"
] |
79467e033970c501505008f5079d6c6786328f49 | 13,288 | cpp | C++ | src/ransac_plain.cpp | michaelczhou/travel_mod | 198ac84f012ba7acca1c58b895a5edffaf8360e3 | [
"MIT"
] | null | null | null | src/ransac_plain.cpp | michaelczhou/travel_mod | 198ac84f012ba7acca1c58b895a5edffaf8360e3 | [
"MIT"
] | null | null | null | src/ransac_plain.cpp | michaelczhou/travel_mod | 198ac84f012ba7acca1c58b895a5edffaf8360e3 | [
"MIT"
] | null | null | null | #include <iostream>
#include <stdio.h>
#include <time.h>
#include "Eigen/Dense"
#include <opencv2/opencv.hpp>
namespace RANSAC
{
using namespace std;
using namespace cv;
// Parallel Loop Body to determine whether the point is on the plane
class Parallel_Cos: public ParallelLoopBody
{
public:
Parallel_Cos(const Mat &_img, Mat &_mask1, Mat &_mask2, Eigen::Vector4d &_model, double _threshold) : img(_img), mask1(_mask1), mask2(_mask2), model(_model)
{
threshold = _threshold;
}
void operator() (const Range &r) const
{
for(int j=r.start; j<r.end; ++j)
{
Point3f *current = (Point3f *)img.ptr(j);
Point3f *last = current + img.cols;
unsigned char *dst_in = (unsigned char *)mask1.ptr(j);
unsigned char *dst_out = (unsigned char *)mask2.ptr(j);
for (; current != last; ++current,++dst_in,++dst_out)
{
const Point3f p = *current;
if(p.x!=0.0f && p.y!=0.0f && p.z!=0.0f)
{
if( abs(model[0]*p.x+model[1]*p.y+model[2]*p.z+model[3]) < threshold )
*dst_in = 0xFF; // on the plane
else
*dst_out = 0x7F; // not on the plane
}
}
}
}
private:
const Mat img;
Mat mask1;
Mat mask2;
Eigen::Vector4d model;
double threshold;
};
// ransacForPlane
template <typename T>
static bool ransacForPlane(
const std::vector<T> &x,
const std::vector<T> &y,
const std::vector<T> &z,
const double distanceThreshold,
const unsigned int minimumSizeSamplesToFit,
std::vector<int> &out_best_inliers,
std::vector<double> &out_best_model,
const size_t min_inliers_for_valid_plane,
const double p,
const size_t maxIter = 1000,
bool verbose = false )
{
const size_t Npts = x.size();
if (verbose)
printf("[RANSAC] number of points:%d\n", (int)Npts);
out_best_model.clear();
out_best_inliers.clear();
size_t trialcount = 0;
size_t bestscore = std::string::npos; // npos will mean "none"
size_t N = 1; // Dummy initialisation for number of trials.
int ind[3]={0};
double coefs[4]={0.0};
srand((unsigned)time(0));
// get model
while (N > trialcount)
{
bool degenerate=true;
while (degenerate)
{
// Generate s random indicies in the range 1..npts
ind[0] = rand()%Npts;
ind[1] = rand()%Npts;
ind[2] = rand()%Npts;
Point3d p1 = Point3d(x[ind[0]], y[ind[0]], z[ind[0]]);
Point3d p2 = Point3d(x[ind[1]], y[ind[1]], z[ind[1]]);
Point3d p3 = Point3d(x[ind[2]], y[ind[2]], z[ind[2]]);
double dx1=p2.x-p1.x;
double dy1=p2.y-p1.y;
double dz1=p2.z-p1.z;
double dx2=p3.x-p1.x;
double dy2=p3.y-p1.y;
double dz2=p3.z-p1.z;
coefs[0]=dy1*dz2-dy2*dz1;
coefs[1]=dz1*dx2-dz2*dx1;
coefs[2]=dx1*dy2-dx2*dy1;
if (abs(coefs[0])<0.00001&&abs(coefs[1])<0.00001&&abs(coefs[2])<0.00001)
{
degenerate = true; // regenerate a model
}
else
{
degenerate = false;
coefs[3]=-coefs[0]*p1.x-coefs[1]*p1.y-coefs[2]*p1.z;
}
}
// get inliers
vector<int> inliers;
inliers.reserve(100);
const double num = 1/sqrt(coefs[0]*coefs[0]+coefs[1]*coefs[1]+coefs[2]*coefs[2]);
for (size_t i=0;i<Npts;i++)
{
const double d = abs(coefs[0]*x[i]+coefs[1]*y[i]+coefs[2]*z[i]+coefs[3]) * num;
if (d<distanceThreshold)
inliers.push_back(i);
}
// Find the number of inliers to this model.
const size_t ninliers = inliers.size();
bool update_estim_num_iters = (trialcount==0); // Always update on the first iteration, regardless of the result (even for ninliers=0)
if (ninliers > bestscore || (bestscore==std::string::npos && ninliers!=0))
{
bestscore = ninliers; // Record data for this model
out_best_model = std::vector<double>(coefs, coefs + sizeof(coefs)/sizeof(double));
out_best_inliers = inliers;
update_estim_num_iters = true;
}
if (update_estim_num_iters)
{
// Update estimate of N, the number of trials to ensure we pick,
// with probability p, a data set with no outliers.
double fracinliers = ninliers/static_cast<double>(Npts);
double pNoOutliers = 1 - pow(fracinliers,static_cast<double>(minimumSizeSamplesToFit));
pNoOutliers = std::max( std::numeric_limits<double>::epsilon(), pNoOutliers); // Avoid division by -Inf
pNoOutliers = std::min(1.0 - std::numeric_limits<double>::epsilon() , pNoOutliers); // Avoid division by 0.
N = (size_t)(log(1-p)/log(pNoOutliers));
if (verbose)
printf("[RANSAC] Iter #%u Estimated number of iters: %u pNoOutliers = %f #inliers: %u\n", (unsigned)trialcount ,(unsigned)N,pNoOutliers, (unsigned)ninliers);
}
++trialcount;
if (verbose)
printf("[RANSAC] trial %u out of %u \r",(unsigned int)trialcount, (unsigned int)ceil(static_cast<double>(N)));
// Safeguard against being stuck in this loop forever
if (trialcount > maxIter)
{
if (verbose)
printf("[RANSAC] Warning: maximum number of trials (%u) reached\n", (unsigned)maxIter);
break;
}
}
if (out_best_inliers.size() > min_inliers_for_valid_plane)
{ // We got a solution
if (verbose)
printf("[RANSAC] Finished in %u iterations.\n",(unsigned)trialcount );
return true;
}
else
{
if (verbose)
printf("[RANSAC] Warning: Finished without any proper solution.\n");
return false;
}
}
Vec4d getMonoMask(
const Mat &pcd,
Mat &mask,
Size sz,
const double threshold,
const int stride,
const float validRate,
const int numResample
)
{
Vec4d m;
mask.create(sz, CV_8U);
// Load valid data into vector
// ------------------------------------
std::vector<float> x,y,z;
x.reserve(0xFF);
y.reserve(0xFF);
z.reserve(0xFF);
for(int i=0; i<pcd.rows; i=i+stride)
{
Point3f *ptr = (Point3f* )pcd.ptr(i);
for(int j=0; j <pcd.cols; j=j+stride)
{
const Point3f p = ptr[j];
// set valid range for X,Y,Z
// in OpenCV reprojectImageTo3D, if point is invalid, Z=10000
if(p.z>0.0f && p.z<5000.0f)
{
x.push_back(p.x);
y.push_back(p.y);
z.push_back(p.z);
}
}
}
if (x.empty())
{
mask.setTo(Scalar(0));
return m;
}
// Run RANSAC
// ------------------------------------
std::vector<int> best_inliers;
std::vector<double> this_best_model(4);
const size_t min_inliers_for_valid_plane = (size_t)(x.size()*validRate);
bool result = ransacForPlane(
x,y,z,
threshold,
3, // Minimum set of points
best_inliers,
this_best_model,
min_inliers_for_valid_plane,
0.999, // Prob. of good result
500, // max trial
//true // Verbose
false
);
if (result != true)
{
mask.setTo(Scalar(0));
return m;
}
// Recalculate the model using LSQ
// ------------------------------------
const int ninliers = best_inliers.size();
int nResample = numResample < ninliers ? numResample:ninliers;
Eigen::Matrix<double, Eigen::Dynamic, 3> rsMat;
rsMat.resize(nResample, Eigen::NoChange);
srand((unsigned int) time(0));
for( int i=0; i<nResample;i++)
{
int idx = rand()%ninliers;
rsMat.row(i) = Eigen::Vector3d(x[best_inliers[idx]], y[best_inliers[idx]], z[best_inliers[idx]]);
}
Eigen::RowVector3d rsMean = rsMat.colwise().mean();
//cout << "rsMean: "<< rsMean <<endl;
rsMat.rowwise() -= rsMean;
Eigen:: JacobiSVD<Eigen::MatrixXd> svd(rsMat, Eigen::ComputeThinV);
//cout << "Its singular values are:" << endl << svd.singularValues() << endl;
//cout << "Its right singular vectors are the columns of the thin V matrix:" << endl << svd.matrixV() << endl;
Eigen::Vector3d normVec = svd.matrixV().col(2); // get the last row
Eigen::Vector4d model; // ax+by+cz+d=0
//model<< normVec, -model[0]*rsMean[0]-model[1]*rsMean[1]-model[2]*rsMean[2];
model<< normVec, -normVec.dot(rsMean);
//cout << model <<endl;
// after SVD, the vector V is already a norm vector
// double s = normVec.norm();
// cout<<"scale" << s<<endl;
// model /= s;
// cout << "after "<< model <<endl;
// get mask
// ------------------------------------
Mat mask_inliers(pcd.size(),CV_8UC1,Scalar(0));
Mat mask_outliers(pcd.size(),CV_8UC1,Scalar(0));
// parallel_for_( Range(0,mask.rows) , Parallel_Cos(pcd,mask_inliers,mask_outliers,model,threshold)) ;
for(int i=0; i<pcd.rows; ++i)
{
Point3f *ptr = (Point3f* )pcd.ptr(i);
unsigned char *dst_in = (unsigned char *)mask_inliers.ptr(i);
unsigned char *dst_out = (unsigned char *)mask_outliers.ptr(i);
for(int j=0; j <pcd.cols; ++j)
{
const Point3f p = ptr[j];
if(p.z>0.0f && p.z<5000.0f)
{
if( abs(model[0]*p.x+model[1]*p.y+model[2]*p.z+model[3]) < threshold )
dst_in[j] = 0xFF; // on the plane
else
dst_out[j] = 0x7F; // not on the plane
}
}
}
resize(mask_inliers,mask_inliers,sz);
resize(mask_outliers,mask_outliers,sz);
// do a blur first to reduce noise
const int blurSize = (int)(sz.width/45.0f);
blur(mask_inliers,mask_inliers,Size(blurSize,blurSize));
blur(mask_outliers,mask_outliers,Size(blurSize,blurSize));
// kick out noise
cv::threshold(mask_inliers,mask_inliers,(0xFF-85),0xFF,THRESH_BINARY);
cv::threshold(mask_outliers,mask_outliers,(0x7F-85),0x7F,THRESH_BINARY);
mask = mask_inliers + mask_outliers;
const int kernalSize = (int)(sz.width/20.0f + 0.5f);
Mat kernal = getStructuringElement(MORPH_ELLIPSE,Size(kernalSize,kernalSize));
morphologyEx(mask,mask,MORPH_CLOSE,kernal);
morphologyEx(mask,mask,MORPH_OPEN,kernal);
m[0] = model[0];
m[1] = model[1];
m[2] = model[2];
m[3] = model[3];
return m;
}
void cvtMaskn3(const Mat &mono, Mat &mask)
{
mask.create(mono.size(), CV_8UC3);
for(int i=0; i<mask.rows; ++i)
{
const unsigned char *ptr = (unsigned char*)mono.ptr(i);
unsigned char *dst = (unsigned char*)mask.ptr(i);
for(int j=0; j <mask.cols; ++j)
{
const unsigned char xx = ptr[j];
if(xx > 205)
{
dst[3*j+0] = 0;
dst[3*j+1] = 255;
dst[3*j+2] = 0;
}
else if(xx>75 && xx<175)
{
dst[3*j+0] = 0;
dst[3*j+1] = 0;
dst[3*j+2] = 255;
}
else
{
dst[3*j+0] = 0;
dst[3*j+1] = 0;
dst[3*j+2] = 0;
}
}
}
}
} | 36.01084 | 180 | 0.47193 | [
"vector",
"model"
] |
7947e95620dd417fbb0512d015a61f9f635cf107 | 4,346 | cpp | C++ | c++/print.cpp | forgotter/Snippets | bb4e39cafe7ef2c1ef3ac24b450a72df350a248b | [
"MIT"
] | 38 | 2018-09-17T18:16:24.000Z | 2022-02-10T10:26:23.000Z | c++/print.cpp | forgotter/Snippets | bb4e39cafe7ef2c1ef3ac24b450a72df350a248b | [
"MIT"
] | 1 | 2020-10-01T10:48:45.000Z | 2020-10-04T11:27:44.000Z | c++/print.cpp | forgotter/Snippets | bb4e39cafe7ef2c1ef3ac24b450a72df350a248b | [
"MIT"
] | 12 | 2018-11-13T13:36:41.000Z | 2021-05-02T10:07:44.000Z | /// Name: PrintFunctions
/// Description: Print function for various containers
/// Detail:
/// Guarantee: } // PrintFunctions
// Print function prototype
template <typename T>
void print(const T data);
void print(const __int128_t data);
void print(const __uint128_t data);
template <typename T, typename U>
void print(const pair<T, U> data);
template <typename T>
void print(const deque<T> data);
template <typename T>
void print(const stack<T> data);
template <typename T>
void print(const queue<T> data);
template <typename T>
void print(const priority_queue<T> data);
template <typename T>
void print(const vector<T> data);
template <typename T>
void print(const set<T> data);
template <typename T>
void print(const unordered_set<T> data);
template <typename T>
void print(const multiset<T> data);
template <typename T, typename U>
void print(const map<T, U> data);
template <typename T, typename U>
void print(const unordered_map<T, U> data);
// Print functions
template <typename T>
void print(const T data)
{
cout << data;
}
void print(const __int128_t data)
{
cout << "int128:: ";
bool negative = false;
stack<int> temp;
if (data == 0)
temp.push(0);
else
{
__int128_t _data = data;
if (_data < 0)
{
negative = true;
_data = -data;
}
while (_data)
{
temp.push(_data % 10);
_data /= 10;
}
}
if (negative)
cout << "-";
while (temp.size())
{
cout << temp.top();
temp.pop();
}
}
void print(const __uint128_t data)
{
stack<int> temp;
if (data == 0)
temp.push(0);
else
{
__uint128_t _data = data;
while (_data)
{
temp.push(_data % 10);
_data /= 10;
}
}
while (temp.size())
{
cout << temp.top();
temp.pop();
}
}
template <typename T, typename U>
void print(const pair<T, U> data)
{
print(data.first);
cout << " : ";
print(data.second);
}
template <typename T>
void print(const deque<T> data)
{
cout << "<deque>{";
for (T val : data)
{
print(val);
cout << ", ";
}
cout << "}";
}
template <typename T>
void print(const stack<T> data)
{
cout << "<stack>{";
while (!data.empty())
{
T val = data.top();
data.pop();
print(val);
cout << ", ";
}
cout << "}";
}
template <typename T>
void print(const queue<T> data)
{
cout << "<queue>{";
while (!data.empty())
{
T val = data.front();
data.pop();
print(val);
cout << ", ";
}
cout << "}";
}
template <typename T>
void print(const priority_queue<T> data)
{
cout << "<priority_queue>{";
while (!data.empty())
{
T val = data.top();
data.pop();
print(val);
cout << ", ";
}
cout << "}";
}
template <typename T>
void print(const vector<T> data)
{
cout << "<vector>{";
for (T val : data)
{
print(val);
cout << ", ";
}
cout << "}";
}
template <typename T>
void print(const set<T> data)
{
cout << "<set>{";
for (T val : data)
{
print(val);
cout << ", ";
}
cout << "}";
}
template <typename T>
void print(const unordered_set<T> data)
{
cout << "<unordered_set>{";
for (T val : data)
{
print(val);
cout << ", ";
}
cout << "}";
}
template <typename T>
void print(const multiset<T> data)
{
cout << "<multiset>{";
for (T val : data)
{
print(val);
cout << ", ";
}
cout << "}";
}
template <typename T, typename U>
void print(const map<T, U> data)
{
cout << "<map>{\n";
for (pair<T, U> val : data)
{
print(val);
cout << "\n";
}
cout << "}";
}
template <typename T, typename U>
void print(const unordered_map<T, U> data)
{
cout << "<unordered_map>{\n";
for (pair<T, U> val : data)
{
print(val);
cout << "\n";
}
cout << "}";
} // PrintFunctions | 18.260504 | 55 | 0.492637 | [
"vector"
] |
79499c8bda40f749dc0b8701af08e8d14d026cb9 | 8,502 | cpp | C++ | EU4toV2/Source/Configuration.cpp | nickbabcock/EU4toVic2 | e81ccd21e1218c92193aae6c7d98d96697fc46ab | [
"MIT"
] | 1 | 2020-07-10T15:37:02.000Z | 2020-07-10T15:37:02.000Z | EU4toV2/Source/Configuration.cpp | nickbabcock/EU4toVic2 | e81ccd21e1218c92193aae6c7d98d96697fc46ab | [
"MIT"
] | null | null | null | EU4toV2/Source/Configuration.cpp | nickbabcock/EU4toVic2 | e81ccd21e1218c92193aae6c7d98d96697fc46ab | [
"MIT"
] | null | null | null | #include "Configuration.h"
#include "Log.h"
#include "OSCompatibilityLayer.h"
#include "ParserHelpers.h"
#include <fstream>
#include <vector>
#include "CommonFunctions.h"
Configuration theConfiguration;
void Configuration::instantiate(std::istream& theStream, bool (*DoesFolderExist)(const std::string& path2), bool (*doesFileExist)(const std::string& path3))
{
registerKeyword("SaveGame", [this](const std::string& unused, std::istream& theStream) {
const commonItems::singleString path(theStream);
EU4SaveGamePath = path.getString();
});
registerKeyword("EU4directory", [this, DoesFolderExist, doesFileExist](const std::string& unused, std::istream& theStream) {
const commonItems::singleString path(theStream);
EU4Path = path.getString();
verifyEU4Path(EU4Path, DoesFolderExist, doesFileExist);
});
registerKeyword("EU4DocumentsDirectory", [this](const std::string& unused, std::istream& theStream) {
const commonItems::singleString path(theStream);
EU4DocumentsPath = path.getString();
});
registerKeyword("SteamWorkshopDirectory", [this](const std::string& unused, std::istream& theStream) {
const commonItems::singleString path(theStream);
SteamWorkshopPath = path.getString();
});
registerKeyword("CK2ExportDirectory", [this](const std::string& unused, std::istream& theStream) {
const commonItems::singleString path(theStream);
CK2ExportPath = path.getString();
});
registerKeyword("Vic2directory", [this, DoesFolderExist, doesFileExist](const std::string& unused, std::istream& theStream) {
const commonItems::singleString path(theStream);
Vic2Path = path.getString();
verifyVic2Path(Vic2Path, DoesFolderExist, doesFileExist);
});
registerKeyword("Vic2Documentsdirectory", [this, DoesFolderExist](const std::string& unused, std::istream& theStream) {
const commonItems::singleString path(theStream);
Vic2DocumentsPath = path.getString();
verifyVic2DocumentsPath(Vic2DocumentsPath, DoesFolderExist);
});
registerKeyword("max_literacy", [this](const std::string& unused, std::istream& theStream) {
const commonItems::singleString maxLiteracyString(theStream);
MaxLiteracy = static_cast<double>(std::stoi(maxLiteracyString.getString())) / 100;
LOG(LogLevel::Info) << "Max Literacy: " << MaxLiteracy;
});
registerKeyword("remove_type", [this](const std::string& unused, std::istream& theStream) {
const commonItems::singleString removeTypeString(theStream);
removeType = DEADCORES(std::stoi(removeTypeString.getString()));
});
registerKeyword("absorb_colonies", [this](const std::string& unused, std::istream& theStream) {
const commonItems::singleString absorbString(theStream);
absorbColonies = ABSORBCOLONIES(std::stoi(absorbString.getString()));
LOG(LogLevel::Info) << "Absorb Colonies: " << absorbString.getString();
});
registerKeyword("liberty_threshold", [this](const std::string& unused, std::istream& theStream) {
const commonItems::singleString libertyThresholdString(theStream);
libertyThreshold = LIBERTYDESIRE(std::stoi(libertyThresholdString.getString()));
LOG(LogLevel::Info) << "Liberty Treshold: " << libertyThresholdString.getString();
});
registerKeyword("pop_shaping", [this](const std::string& unused, std::istream& theStream) {
const commonItems::singleString popShapingString(theStream);
popShaping = POPSHAPES(std::stoi(popShapingString.getString()));
LOG(LogLevel::Info) << "Pop Shaping: " << popShapingString.getString();
});
registerKeyword("core_handling", [this](const std::string& unused, std::istream& theStream) {
const commonItems::singleString coreHandlingString(theStream);
coreHandling = COREHANDLES(std::stoi(coreHandlingString.getString()));
LOG(LogLevel::Info) << "Core Handling: " << coreHandlingString.getString();
});
registerKeyword("pop_shaping_factor", [this](const std::string& unused, std::istream& theStream) {
const commonItems::singleString popShapingFactorString(theStream);
popShapingFactor = static_cast<double>(std::stoi(popShapingFactorString.getString()));
LOG(LogLevel::Info) << "Pop Shaping Factor: " << popShapingFactor;
});
registerKeyword("euro_centrism", [this](const std::string& unused, std::istream& theStream) {
const commonItems::singleString euroCentrismString(theStream);
euroCentric = EUROCENTRISM(std::stoi(euroCentrismString.getString()));
LOG(LogLevel::Info) << "Eurocentrism: " << euroCentrismString.getString();
});
registerKeyword("africa_reset", [this](const std::string& unused, std::istream& theStream) {
const commonItems::singleString africaResetString(theStream);
africaReset = AFRICARESET(std::stoi(africaResetString.getString()));
LOG(LogLevel::Info) << "Africa Reset: " << africaResetString.getString();
});
registerKeyword("debug", [this](const std::string& unused, std::istream& theStream) {
const commonItems::singleString debugString(theStream);
debug = (debugString.getString() == "yes");
});
registerKeyword("randomise_rgos", [this](const std::string& unused, std::istream& theStream) {
const commonItems::singleString randomiseRgosString(theStream);
randomiseRgos = randomiseRgosString.getString() == "yes";
LOG(LogLevel::Info) << "Randomise RGOs: " << randomiseRgosString.getString();
});
registerKeyword("convert_all", [this](const std::string& unused, std::istream& theStream) {
const commonItems::singleString convertAllString(theStream);
convertAll = convertAllString.getString() == "yes";
LOG(LogLevel::Info) << "Convert All: " << convertAllString.getString();
});
registerKeyword("output_name", [this](const std::string& unused, std::istream& theStream) {
const commonItems::singleString outputNameStr(theStream);
incomingOutputName = outputNameStr.getString();
LOG(LogLevel::Info) << "Output Name: " << incomingOutputName;
});
registerRegex("[a-zA-Z0-9\\_.:]+", commonItems::ignoreItem);
LOG(LogLevel::Info) << "Reading configuration file";
parseStream(theStream);
clearRegisteredKeywords();
setOutputName();
Log(LogLevel::Progress) << "3 %";
}
void Configuration::verifyEU4Path(const std::string& path, bool (*DoesFolderExist)(const std::string& path2), bool (*doesFileExist)(const std::string& path3))
{
if (!DoesFolderExist(path))
throw std::runtime_error(path + " does not exist!");
if (!doesFileExist(path + "/eu4.exe") && !doesFileExist(path + "/eu4") && !DoesFolderExist(path + "/eu4.app"))
throw std::runtime_error(path + " does not contain Europa Universalis 4!");
if (!doesFileExist(path + "/map/positions.txt"))
throw std::runtime_error(path + " does not appear to be a valid EU4 install!");
LOG(LogLevel::Info) << "\tEU4 install path is " << path;
}
void Configuration::verifyVic2Path(const std::string& path, bool (*DoesFolderExist)(const std::string& path2), bool (*doesFileExist)(const std::string& path3))
{
if (!DoesFolderExist(path))
throw std::runtime_error(path + " does not exist!");
if (!doesFileExist(path + "/v2game.exe") && !DoesFolderExist(path + "/Victoria 2 - Heart Of Darkness.app") && !DoesFolderExist(path + "../../MacOS"))
throw std::runtime_error(path + " does not contain Victoria 2!");
LOG(LogLevel::Info) << "\tVictoria 2 install path is " << path;
}
void Configuration::verifyVic2DocumentsPath(const std::string& path, bool (*DoesFolderExist)(const std::string& path2))
{
if (!DoesFolderExist(path))
throw std::runtime_error(path + " does not exist!");
LOG(LogLevel::Info) << "\tVictoria 2 documents directory is " << path;
}
bool Configuration::wasDLCActive(const std::string& DLC) const
{
for (const auto& activeDLC: activeDLCs)
if (DLC == activeDLC)
return true;
return false;
}
void Configuration::setOutputName()
{
if (incomingOutputName.empty())
{
outputName = trimPath(EU4SaveGamePath);
}
else
{
outputName = incomingOutputName;
}
outputName = trimExtension(outputName);
outputName = replaceCharacter(outputName, '-');
outputName = replaceCharacter(outputName, ' ');
theConfiguration.setActualName(outputName);
outputName = Utils::normalizeUTF8Path(outputName);
theConfiguration.setOutputName(outputName);
LOG(LogLevel::Info) << "Using output name " << outputName;
}
ConfigurationFile::ConfigurationFile(const std::string& filename)
{
std::ifstream confFile(filename);
if (!confFile.is_open())
{
Log(LogLevel::Error) << "Cound not open configuration file!";
throw std::runtime_error("Cound not open configuration file!");
}
theConfiguration.instantiate(confFile, Utils::DoesFolderExist, Utils::DoesFileExist);
confFile.close();
}
| 45.956757 | 159 | 0.740061 | [
"vector"
] |
79503b8ed683b877e752c8ce49d55e0c020e2023 | 15,184 | cpp | C++ | workspace/src/EKF/EKF.cpp | arunj088/barc | 859b385480e16de16cc4c4adb57f49e98bfd3ade | [
"MIT"
] | null | null | null | workspace/src/EKF/EKF.cpp | arunj088/barc | 859b385480e16de16cc4c4adb57f49e98bfd3ade | [
"MIT"
] | 4 | 2020-02-12T02:28:33.000Z | 2021-06-10T21:49:51.000Z | workspace/src/EKF/EKF.cpp | arunj088/barc | 859b385480e16de16cc4c4adb57f49e98bfd3ade | [
"MIT"
] | null | null | null | //
// Academic License - for use in teaching, academic research, and meeting
// course requirements at degree granting institutions only. Not for
// government, commercial, or other organizational use.
//
// File: EKF.cpp
//
// Code generated for Simulink model 'EKF'.
//
// Model version : 1.7
// Simulink Coder version : 9.0 (R2018b) 24-May-2018
// C/C++ source code generated on : Thu Jun 13 15:11:48 2019
//
// Target selection: ert.tlc
// Embedded hardware selection: Generic->Unspecified (assume 32-bit Generic)
// Code generation objectives: Unspecified
// Validation result: Not run
//
#include "EKF.h"
#include "EKF_private.h"
// Block signals (default storage)
B_EKF_T EKF_B;
// Block states (default storage)
DW_EKF_T EKF_DW;
// Real-time model
RT_MODEL_EKF_T EKF_M_;
RT_MODEL_EKF_T *const EKF_M = &EKF_M_;
// Forward declaration for local functions
static void EKF_Bicycle(real_T x[6], const real_T ip[2]);
static void matlabCodegenHandle_matlabCo_bd(robotics_slros_internal_blo_b_T *obj);
static void matlabCodegenHandle_matlabCodeg(robotics_slros_internal_block_T *obj);
// Function for MATLAB Function: '<S10>/Predict'
static void EKF_Bicycle(real_T x[6], const real_T ip[2])
{
real_T Ff;
real_T Cd;
real_T delta;
real_T Fyf;
real_T Fyr;
boolean_T ip_0;
int32_T i;
Ff = 0.12902;
Cd = 0.33267;
delta = ip[1];
Fyf = (atan((0.125 * x[2] + x[1]) / x[0]) - ip[1]) * -6.0826;
Fyr = atan((x[1] - 0.125 * x[2]) / x[0]) * -6.0826;
if (ip[0] == 0.0) {
Cd = 0.0;
Ff = 0.0;
Fyf = 0.0;
Fyr = 0.0;
delta = 0.0;
}
Ff = ((((ip[0] * 1.7675 - Fyf * sin(delta)) * 0.26315789473684209 + x[2] * x[1])
- x[0] * x[0] * Cd) - Ff) * 0.01 + x[0];
delta = cos(delta);
Cd = ((Fyf * delta + Fyr) * 0.26315789473684209 + -x[2] * Ff) * 0.01 + x[1];
delta = (0.125 * Fyf * delta - 0.125 * Fyr) * 0.04821368304324767 + x[2];
ip_0 = (ip[0] == 0.0);
EKF_B.Ff[0] = Ff;
EKF_B.Ff[1] = Cd;
EKF_B.Ff[2] = delta;
Fyf = sin(x[5]);
Fyr = cos(x[5]);
EKF_B.Ff[3] = (Ff * Fyr - Cd * Fyf) * 0.01 + x[3];
EKF_B.Ff[4] = (Ff * Fyf + Cd * Fyr) * 0.01 + x[4];
EKF_B.Ff[5] = 0.01 * delta + x[5];
for (i = 0; i < 6; i++) {
if (ip_0) {
x[i] = 0.0;
} else {
x[i] = EKF_B.Ff[i];
}
}
}
static void matlabCodegenHandle_matlabCo_bd(robotics_slros_internal_blo_b_T *obj)
{
if (!obj->matlabCodegenIsDeleted) {
obj->matlabCodegenIsDeleted = true;
}
}
static void matlabCodegenHandle_matlabCodeg(robotics_slros_internal_block_T *obj)
{
if (!obj->matlabCodegenIsDeleted) {
obj->matlabCodegenIsDeleted = true;
}
}
// Model step function
void EKF_step(void)
{
int32_T j;
static const int8_T a[6] = { 0, 0, 1, 0, 0, 0 };
boolean_T b_varargout_1;
int32_T i;
int32_T i_0;
int32_T Jacobian_tmp;
// Outputs for Atomic SubSystem: '<Root>/Subscribe1'
// MATLABSystem: '<S7>/SourceBlock' incorporates:
// Inport: '<S14>/In1'
b_varargout_1 = Sub_EKF_8.getLatestMessage(&EKF_B.b_varargout_2);
// Outputs for Enabled SubSystem: '<S7>/Enabled Subsystem' incorporates:
// EnablePort: '<S14>/Enable'
if (b_varargout_1) {
EKF_B.In1 = EKF_B.b_varargout_2;
}
// End of MATLABSystem: '<S7>/SourceBlock'
// End of Outputs for SubSystem: '<S7>/Enabled Subsystem'
// End of Outputs for SubSystem: '<Root>/Subscribe1'
// Outputs for Enabled SubSystem: '<S3>/Correct1' incorporates:
// EnablePort: '<S8>/Enable'
// Constant: '<S3>/Enable1'
if (EKF_P.Enable1_Value) {
// MATLAB Function: '<S8>/Correct' incorporates:
// Constant: '<S3>/R1'
// DataStoreRead: '<S8>/Data Store ReadP'
// DataStoreRead: '<S8>/Data Store ReadX'
EKF_B.z_c = 0.0;
for (i = 0; i < 6; i++) {
EKF_B.z_c += (real_T)a[i] * EKF_DW.x[i];
EKF_B.z[i] = a[i];
}
for (j = 0; j < 6; j++) {
for (i = 0; i < 6; i++) {
EKF_B.imvec[i] = EKF_DW.x[i];
}
EKF_B.epsilon = 1.4901161193847656E-8 * fabs(EKF_DW.x[j]);
if ((1.4901161193847656E-8 > EKF_B.epsilon) || rtIsNaN(EKF_B.epsilon)) {
EKF_B.epsilon = 1.4901161193847656E-8;
}
EKF_B.imvec[j] = EKF_DW.x[j] + EKF_B.epsilon;
EKF_B.z_k = 0.0;
for (i = 0; i < 6; i++) {
EKF_B.z_k += EKF_B.z[i] * EKF_B.imvec[i];
}
EKF_B.dHdx[j] = (EKF_B.z_k - EKF_B.z_c) / EKF_B.epsilon;
}
EKF_B.z_c = 0.0;
for (i = 0; i < 6; i++) {
EKF_B.z[i] = 0.0;
for (j = 0; j < 6; j++) {
EKF_B.z[i] += EKF_DW.P[6 * i + j] * EKF_B.dHdx[j];
}
EKF_B.z_c += EKF_B.z[i] * EKF_B.dHdx[i];
}
EKF_B.z_c += EKF_P.R1_Value;
EKF_B.epsilon = 0.0;
for (i = 0; i < 6; i++) {
EKF_B.z_k = 0.0;
for (j = 0; j < 6; j++) {
EKF_B.z_k += EKF_DW.P[6 * j + i] * EKF_B.dHdx[j];
}
EKF_B.imvec[i] = EKF_B.z_k / EKF_B.z_c;
EKF_B.epsilon += (real_T)a[i] * EKF_DW.x[i];
}
EKF_B.z_c = EKF_B.In1.AngularVelocity.Z - EKF_B.epsilon;
for (i = 0; i < 6; i++) {
for (j = 0; j < 6; j++) {
EKF_B.Jacobian[i + 6 * j] = EKF_B.imvec[i] * EKF_B.dHdx[j];
}
for (j = 0; j < 6; j++) {
EKF_B.z_k = 0.0;
for (i_0 = 0; i_0 < 6; i_0++) {
EKF_B.z_k += EKF_B.Jacobian[6 * i_0 + i] * EKF_DW.P[6 * j + i_0];
}
EKF_B.Jacobian_m[i + 6 * j] = EKF_DW.P[6 * j + i] - EKF_B.z_k;
}
}
// DataStoreWrite: '<S8>/Data Store WriteP'
memcpy(&EKF_DW.P[0], &EKF_B.Jacobian_m[0], 36U * sizeof(real_T));
// DataStoreWrite: '<S8>/Data Store WriteX' incorporates:
// DataStoreRead: '<S8>/Data Store ReadX'
// MATLAB Function: '<S8>/Correct'
for (i = 0; i < 6; i++) {
EKF_DW.x[i] += EKF_B.imvec[i] * EKF_B.z_c;
}
// End of DataStoreWrite: '<S8>/Data Store WriteX'
}
// End of Constant: '<S3>/Enable1'
// End of Outputs for SubSystem: '<S3>/Correct1'
// BusAssignment: '<Root>/Bus Assignment' incorporates:
// DataStoreRead: '<S9>/Data Store Read'
EKF_B.BusAssignment.X = EKF_DW.x[3];
EKF_B.BusAssignment.Y = EKF_DW.x[4];
EKF_B.BusAssignment.Z = EKF_DW.x[5];
// Outputs for Atomic SubSystem: '<Root>/Publish'
// MATLABSystem: '<S4>/SinkBlock'
Pub_EKF_16.publish(&EKF_B.BusAssignment);
// End of Outputs for SubSystem: '<Root>/Publish'
// BusAssignment: '<Root>/Bus Assignment1' incorporates:
// DataStoreRead: '<S9>/Data Store Read'
EKF_B.BusAssignment1.X = EKF_DW.x[0];
EKF_B.BusAssignment1.Y = EKF_DW.x[1];
EKF_B.BusAssignment1.Z = EKF_DW.x[2];
// Outputs for Atomic SubSystem: '<Root>/Publish1'
// MATLABSystem: '<S5>/SinkBlock'
Pub_EKF_21.publish(&EKF_B.BusAssignment1);
// End of Outputs for SubSystem: '<Root>/Publish1'
// Outputs for Atomic SubSystem: '<Root>/Subscribe'
// MATLABSystem: '<S6>/SourceBlock' incorporates:
// Inport: '<S13>/In1'
b_varargout_1 = Sub_EKF_30.getLatestMessage(&EKF_B.b_varargout_2_c);
// Outputs for Enabled SubSystem: '<S6>/Enabled Subsystem' incorporates:
// EnablePort: '<S13>/Enable'
if (b_varargout_1) {
EKF_B.In1_e = EKF_B.b_varargout_2_c;
}
// End of MATLABSystem: '<S6>/SourceBlock'
// End of Outputs for SubSystem: '<S6>/Enabled Subsystem'
// End of Outputs for SubSystem: '<Root>/Subscribe'
// Outputs for Atomic SubSystem: '<S3>/Predict'
// SignalConversion: '<S12>/TmpSignal ConversionAt SFunction Inport4' incorporates:
// DataTypeConversion: '<Root>/Data Type Conversion'
// DataTypeConversion: '<Root>/Data Type Conversion1'
// MATLAB Function: '<S10>/Predict'
EKF_B.TmpSignalConversionAtSFunct[0] = EKF_B.In1_e.Motor;
EKF_B.TmpSignalConversionAtSFunct[1] = EKF_B.In1_e.Servo;
// MATLAB Function: '<S10>/Predict' incorporates:
// DataStoreRead: '<S10>/Data Store ReadX'
for (i = 0; i < 6; i++) {
EKF_B.z[i] = EKF_DW.x[i];
}
EKF_Bicycle(EKF_B.z, EKF_B.TmpSignalConversionAtSFunct);
for (j = 0; j < 6; j++) {
for (i = 0; i < 6; i++) {
EKF_B.imvec[i] = EKF_DW.x[i];
}
EKF_B.epsilon = 1.4901161193847656E-8 * fabs(EKF_DW.x[j]);
if ((1.4901161193847656E-8 > EKF_B.epsilon) || rtIsNaN(EKF_B.epsilon)) {
EKF_B.epsilon = 1.4901161193847656E-8;
}
EKF_B.imvec[j] = EKF_DW.x[j] + EKF_B.epsilon;
EKF_Bicycle(EKF_B.imvec, EKF_B.TmpSignalConversionAtSFunct);
for (i = 0; i < 6; i++) {
EKF_B.Jacobian[i + 6 * j] = (EKF_B.imvec[i] - EKF_B.z[i]) / EKF_B.epsilon;
}
}
// DataStoreWrite: '<S10>/Data Store WriteX' incorporates:
// MATLAB Function: '<S10>/Predict'
EKF_Bicycle(EKF_DW.x, EKF_B.TmpSignalConversionAtSFunct);
// MATLAB Function: '<S10>/Predict' incorporates:
// DataStoreRead: '<S10>/Data Store ReadP'
for (i = 0; i < 6; i++) {
for (j = 0; j < 6; j++) {
Jacobian_tmp = j + 6 * i;
EKF_B.Jacobian_m[Jacobian_tmp] = 0.0;
for (i_0 = 0; i_0 < 6; i_0++) {
EKF_B.Jacobian_m[Jacobian_tmp] = EKF_B.Jacobian[6 * i_0 + j] * EKF_DW.P
[6 * i + i_0] + EKF_B.Jacobian_m[6 * i + j];
}
}
}
// DataStoreWrite: '<S10>/Data Store WriteP' incorporates:
// Constant: '<S3>/Q'
// MATLAB Function: '<S10>/Predict'
for (i = 0; i < 6; i++) {
for (j = 0; j < 6; j++) {
EKF_B.z_k = 0.0;
for (i_0 = 0; i_0 < 6; i_0++) {
EKF_B.z_k += EKF_B.Jacobian_m[6 * i_0 + i] * EKF_B.Jacobian[6 * i_0 + j];
}
EKF_DW.P[i + 6 * j] = EKF_P.Q_Value[6 * j + i] + EKF_B.z_k;
}
}
// End of DataStoreWrite: '<S10>/Data Store WriteP'
// End of Outputs for SubSystem: '<S3>/Predict'
}
// Model initialize function
void EKF_initialize(void)
{
// Registration code
// initialize non-finites
rt_InitInfAndNaN(sizeof(real_T));
// initialize error status
rtmSetErrorStatus(EKF_M, (NULL));
// block I/O
(void) memset(((void *) &EKF_B), 0,
sizeof(B_EKF_T));
// states (dwork)
(void) memset((void *)&EKF_DW, 0,
sizeof(DW_EKF_T));
{
int32_T i;
static const char_T tmp[10] = { '/', 's', 't', 'a', 't', 'e', '_', 'e', 's',
't' };
static const char_T tmp_0[9] = { '/', 'p', 'o', 's', 'e', '_', 'e', 's', 't'
};
static const char_T tmp_1[9] = { '/', 'i', 'm', 'u', '/', 'd', 'a', 't', 'a'
};
char_T tmp_2[5];
char_T tmp_3[11];
char_T tmp_4[10];
// Start for Atomic SubSystem: '<Root>/Subscribe1'
// Start for MATLABSystem: '<S7>/SourceBlock'
EKF_DW.obj_e.matlabCodegenIsDeleted = true;
EKF_DW.obj_e.isInitialized = 0;
EKF_DW.obj_e.matlabCodegenIsDeleted = false;
EKF_DW.obj_e.isSetupComplete = false;
EKF_DW.obj_e.isInitialized = 1;
for (i = 0; i < 9; i++) {
tmp_4[i] = tmp_1[i];
}
tmp_4[9] = '\x00';
Sub_EKF_8.createSubscriber(tmp_4, 1);
EKF_DW.obj_e.isSetupComplete = true;
// End of Start for MATLABSystem: '<S7>/SourceBlock'
// End of Start for SubSystem: '<Root>/Subscribe1'
// Start for Atomic SubSystem: '<Root>/Publish'
// Start for MATLABSystem: '<S4>/SinkBlock'
EKF_DW.obj_l.matlabCodegenIsDeleted = true;
EKF_DW.obj_l.isInitialized = 0;
EKF_DW.obj_l.matlabCodegenIsDeleted = false;
EKF_DW.obj_l.isSetupComplete = false;
EKF_DW.obj_l.isInitialized = 1;
for (i = 0; i < 9; i++) {
tmp_4[i] = tmp_0[i];
}
tmp_4[9] = '\x00';
Pub_EKF_16.createPublisher(tmp_4, 1);
EKF_DW.obj_l.isSetupComplete = true;
// End of Start for MATLABSystem: '<S4>/SinkBlock'
// End of Start for SubSystem: '<Root>/Publish'
// Start for Atomic SubSystem: '<Root>/Publish1'
// Start for MATLABSystem: '<S5>/SinkBlock'
EKF_DW.obj.matlabCodegenIsDeleted = true;
EKF_DW.obj.isInitialized = 0;
EKF_DW.obj.matlabCodegenIsDeleted = false;
EKF_DW.obj.isSetupComplete = false;
EKF_DW.obj.isInitialized = 1;
for (i = 0; i < 10; i++) {
tmp_3[i] = tmp[i];
}
tmp_3[10] = '\x00';
Pub_EKF_21.createPublisher(tmp_3, 1);
EKF_DW.obj.isSetupComplete = true;
// End of Start for MATLABSystem: '<S5>/SinkBlock'
// End of Start for SubSystem: '<Root>/Publish1'
// Start for Atomic SubSystem: '<Root>/Subscribe'
// Start for MATLABSystem: '<S6>/SourceBlock'
EKF_DW.obj_d.matlabCodegenIsDeleted = true;
EKF_DW.obj_d.isInitialized = 0;
EKF_DW.obj_d.matlabCodegenIsDeleted = false;
EKF_DW.obj_d.isSetupComplete = false;
EKF_DW.obj_d.isInitialized = 1;
tmp_2[0] = '/';
tmp_2[1] = 'e';
tmp_2[2] = 'c';
tmp_2[3] = 'u';
tmp_2[4] = '\x00';
Sub_EKF_30.createSubscriber(tmp_2, 1);
EKF_DW.obj_d.isSetupComplete = true;
// End of Start for SubSystem: '<Root>/Subscribe'
// Start for DataStoreMemory: '<S3>/DataStoreMemory - P'
memcpy(&EKF_DW.P[0], &EKF_P.DataStoreMemoryP_InitialValue[0], 36U * sizeof
(real_T));
// Start for DataStoreMemory: '<S3>/DataStoreMemory - x'
for (i = 0; i < 6; i++) {
EKF_DW.x[i] = EKF_P.DataStoreMemoryx_InitialValue[i];
}
// End of Start for DataStoreMemory: '<S3>/DataStoreMemory - x'
// SystemInitialize for Atomic SubSystem: '<Root>/Subscribe1'
// SystemInitialize for Enabled SubSystem: '<S7>/Enabled Subsystem'
// SystemInitialize for Outport: '<S14>/Out1'
EKF_B.In1 = EKF_P.Out1_Y0;
// End of SystemInitialize for SubSystem: '<S7>/Enabled Subsystem'
// End of SystemInitialize for SubSystem: '<Root>/Subscribe1'
// SystemInitialize for Atomic SubSystem: '<Root>/Subscribe'
// SystemInitialize for Enabled SubSystem: '<S6>/Enabled Subsystem'
// SystemInitialize for Outport: '<S13>/Out1'
EKF_B.In1_e = EKF_P.Out1_Y0_l;
// End of SystemInitialize for SubSystem: '<S6>/Enabled Subsystem'
// End of SystemInitialize for SubSystem: '<Root>/Subscribe'
}
}
// Model terminate function
void EKF_terminate(void)
{
// Terminate for Atomic SubSystem: '<Root>/Subscribe1'
// Terminate for MATLABSystem: '<S7>/SourceBlock'
matlabCodegenHandle_matlabCo_bd(&EKF_DW.obj_e);
// End of Terminate for SubSystem: '<Root>/Subscribe1'
// Terminate for Atomic SubSystem: '<Root>/Publish'
// Terminate for MATLABSystem: '<S4>/SinkBlock'
matlabCodegenHandle_matlabCodeg(&EKF_DW.obj_l);
// End of Terminate for SubSystem: '<Root>/Publish'
// Terminate for Atomic SubSystem: '<Root>/Publish1'
// Terminate for MATLABSystem: '<S5>/SinkBlock'
matlabCodegenHandle_matlabCodeg(&EKF_DW.obj);
// End of Terminate for SubSystem: '<Root>/Publish1'
// Terminate for Atomic SubSystem: '<Root>/Subscribe'
// Terminate for MATLABSystem: '<S6>/SourceBlock'
matlabCodegenHandle_matlabCo_bd(&EKF_DW.obj_d);
// End of Terminate for SubSystem: '<Root>/Subscribe'
}
//
// File trailer for generated code.
//
// [EOF]
//
| 30.551308 | 86 | 0.593322 | [
"model"
] |
7957f1cb159565909dedd79ba4be3c5f1abe2fdc | 1,615 | cpp | C++ | PTA/1015.cpp | wenbo1188/Data-Structure-Review | 727f65af03c8c76eafefd5dff6208392ce7a1298 | [
"MIT"
] | null | null | null | PTA/1015.cpp | wenbo1188/Data-Structure-Review | 727f65af03c8c76eafefd5dff6208392ce7a1298 | [
"MIT"
] | null | null | null | PTA/1015.cpp | wenbo1188/Data-Structure-Review | 727f65af03c8c76eafefd5dff6208392ce7a1298 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
#define MAX 10010
typedef struct pair
{
int num;
int radix;
}PAIR;
int judge_prime(int num)
{
if (num == 1)
{
return 0;
}
if (num == 2)
{
return 1;
}
for (int i = 2;i <= (int)sqrt(num);++i)
{
if (num % i == 0)
{
return 0;
}
}
return 1;
}
int get_reverse(PAIR p)
{
int num = p.num;
int radix = p.radix;
int shang = 1;
int yu = 0;
int sum = 0;
while (shang != 0)
{
sum *= radix;
shang = num / radix;
yu = num % radix;
num = shang;
sum += yu;
}
return sum;
}
int main()
{
int N = 0, D = 0;
PAIR p = {0};
int count = 0;
vector<PAIR> pairs(MAX);
while (1)
{
scanf("%d", &N);
if (N >= 0)
{
// printf("%d\n", N);
scanf("%d", &D);
p.num = N;
p.radix = D;
pairs[count] = p;
++count;
}
else
{
break;
}
}
// printf("i am here\n");
for (int i = 0;i < count;++i)
{
// printf("%d\n", pairs[i].num);
if (!judge_prime(pairs[i].num))
{
printf("No\n");
}
else
{
int reverse = get_reverse(pairs[i]);
// printf("%d\n", reverse);
if (judge_prime(reverse))
{
printf("Yes\n");
}
else
{
printf("No\n");
}
}
}
return 0;
} | 16.15 | 48 | 0.364087 | [
"vector"
] |
795886dace5e70a2bdbd59bdf7171fb43d88f304 | 2,866 | cpp | C++ | kernel/platform/pc/src/irq/pic.cpp | tristanseifert/kush-os | 1ffd595aae8f3dc880e798eff72365b8b6c631f0 | [
"0BSD"
] | 4 | 2021-06-22T20:52:30.000Z | 2022-02-04T00:19:44.000Z | kernel/platform/pc/src/irq/pic.cpp | tristanseifert/kush-os | 1ffd595aae8f3dc880e798eff72365b8b6c631f0 | [
"0BSD"
] | null | null | null | kernel/platform/pc/src/irq/pic.cpp | tristanseifert/kush-os | 1ffd595aae8f3dc880e798eff72365b8b6c631f0 | [
"0BSD"
] | null | null | null | #include "pic.h"
#include <arch/x86_io.h>
/// Master PIC IO address
#define PIC1 0x20
/// Slave PIC IO address
#define PIC2 0xA0
#define PIC1_COMMAND PIC1
#define PIC1_DATA (PIC1+1)
#define PIC2_COMMAND PIC2
#define PIC2_DATA (PIC2+1)
/// Signals an end-of-interrupt to the PIC
#define PIC_EOI 0x20
#define ICW1_ICW4 0x01 /* ICW4 (not) needed */
#define ICW1_SINGLE 0x02 /* Single (cascade) mode */
#define ICW1_INTERVAL4 0x04 /* Call address interval 4 (8) */
#define ICW1_LEVEL 0x08 /* Level triggered (edge) mode */
#define ICW1_INIT 0x10 /* Initialization - required! */
/// Use 8086/88 (MCS-80/85) mode
#define ICW4_8086 0x01
/// Auto (normal) EOI mode
#define ICW4_AUTO 0x02
/// Buffered mode (slave)
#define ICW4_BUF_SLAVE 0x08
/// Buffered mode (master)
#define ICW4_BUF_MASTER 0x0C
/// Special (fully nested, not)
#define ICW4_SFNM 0x10
/// OCW3 irq ready next CMD read
#define PIC_READ_IRR 0x0A
/// OCW3 irq service next CMD read
#define PIC_READ_ISR 0x0B
static void pic_irq_remap(const uint8_t offset1, const uint8_t offset2);
/**
* Initialize the PIC.
*/
void pic_init() {
// all we've to do is remap the vectors
pic_irq_remap(0x20, 0x28);
}
/**
* Remap the PIC interrupt offsets.
*
* @param offset1 Vector offset for the first (master) PIC's interrupts
* @param offset2 Vector offset for the second (slave) PIC's interrupts
*/
static void pic_irq_remap(const uint8_t offset1, const uint8_t offset2) {
uint8_t a1, a2;
a1 = io_inb(PIC1_DATA); // save masks
a2 = io_inb(PIC2_DATA);
io_outb(PIC1_COMMAND, ICW1_INIT+ICW1_ICW4); // starts the initialization sequence (in cascade mode)
io_wait();
io_outb(PIC2_COMMAND, ICW1_INIT+ICW1_ICW4);
io_wait();
io_outb(PIC1_DATA, offset1); // ICW2: Master PIC vector offset
io_wait();
io_outb(PIC2_DATA, offset2); // ICW2: Slave PIC vector offset
io_wait();
io_outb(PIC1_DATA, 4); // ICW3: tell Master PIC that there is a slave PIC at IRQ2 (0000 0100)
io_wait();
io_outb(PIC2_DATA, 2); // ICW3: tell Slave PIC its cascade identity (0000 0010)
io_wait();
io_outb(PIC1_DATA, ICW4_8086);
io_wait();
io_outb(PIC2_DATA, ICW4_8086);
io_wait();
io_outb(PIC1_DATA, a1); // restore saved masks.
io_outb(PIC2_DATA, a2);
}
/*
* Sends the End of Interrupt command to the PIC
*/
void pic_irq_eoi(const uint8_t irq) {
if(irq >= 8) {
io_outb(PIC2_COMMAND,PIC_EOI);
}
io_outb(PIC1_COMMAND,PIC_EOI);
}
/*
* Disables the PICs.
*/
void pic_irq_disable() {
io_outb(PIC1_DATA, 0xFF);
io_wait();
io_outb(PIC2_DATA, 0xFF);
io_wait();
}
| 27.037736 | 103 | 0.633287 | [
"vector"
] |
795ddd4cad289a718348f0ae2d3f21f6936f41f4 | 1,726 | cpp | C++ | common/util/os.cpp | LuminarLight/jak-project | f341be65e9848977158c9a9a2898f0f047a157df | [
"ISC"
] | 54 | 2022-02-08T13:07:50.000Z | 2022-03-31T14:18:42.000Z | common/util/os.cpp | LuminarLight/jak-project | f341be65e9848977158c9a9a2898f0f047a157df | [
"ISC"
] | 120 | 2022-02-08T05:19:11.000Z | 2022-03-30T22:26:52.000Z | common/util/os.cpp | LuminarLight/jak-project | f341be65e9848977158c9a9a2898f0f047a157df | [
"ISC"
] | 8 | 2022-02-13T22:39:55.000Z | 2022-03-30T02:17:57.000Z | #include "os.h"
#include "common/common_types.h"
#ifdef __linux__
#include <sys/resource.h>
size_t get_peak_rss() {
rusage x;
getrusage(RUSAGE_SELF, &x);
return x.ru_maxrss * 1024;
}
#else
size_t get_peak_rss() {
return 0;
}
#endif
#ifdef _WIN32
// windows has a __cpuid
#include <intrin.h>
#else
// using int to be compatible with msvc's intrinsic
void __cpuidex(int result[4], int eax, int ecx) {
asm("cpuid\n\t"
: "=a"(result[0]), "=b"(result[1]), "=c"(result[2]), "=d"(result[3])
: "0"(eax), "2"(ecx));
}
#endif
CpuInfo gCpuInfo;
void setup_cpu_info() {
if (gCpuInfo.initialized) {
return;
}
// as a test, get the brand and model
for (u32 i = 0x80000002; i <= 0x80000004; i++) {
int result[4];
__cpuidex(result, i, 0);
for (auto reg : result) {
for (int c = 0; c < 4; c++) {
gCpuInfo.model.push_back(reg);
reg >>= 8;
}
}
}
{
int result[4];
__cpuidex(result, 0, 0);
for (auto r : {1, 3, 2}) {
for (int c = 0; c < 4; c++) {
gCpuInfo.brand.push_back(result[r]);
result[r] >>= 8;
}
}
}
// check for AVX2
{
int result[4];
__cpuidex(result, 7, 0);
gCpuInfo.has_avx2 = result[1] & (1 << 5);
}
{
int result[4];
__cpuidex(result, 1, 0);
gCpuInfo.has_avx = result[2] & (1 << 28);
}
printf("-------- CPU Information --------\n");
printf(" Brand: %s\n", gCpuInfo.brand.c_str());
printf(" Model: %s\n", gCpuInfo.model.c_str());
printf(" AVX : %s\n", gCpuInfo.has_avx ? "true" : "false");
printf(" AVX2 : %s\n", gCpuInfo.has_avx2 ? "true" : "false");
fflush(stdout);
gCpuInfo.initialized = true;
}
CpuInfo& get_cpu_info() {
return gCpuInfo;
} | 19.613636 | 74 | 0.561414 | [
"model"
] |
795debbf19421525dbc7cc7e59887876cc2effbf | 8,431 | cpp | C++ | create_image_task.cpp | The-never-lemon/Fractal_Designer | 88df89caafd7cb623fdbc26bcdf6a1efe88cdb84 | [
"MIT"
] | null | null | null | create_image_task.cpp | The-never-lemon/Fractal_Designer | 88df89caafd7cb623fdbc26bcdf6a1efe88cdb84 | [
"MIT"
] | null | null | null | create_image_task.cpp | The-never-lemon/Fractal_Designer | 88df89caafd7cb623fdbc26bcdf6a1efe88cdb84 | [
"MIT"
] | null | null | null | #include "create_image_task.h"
#include "mainwindow.h"
Create_Image_Task::Create_Image_Task(QWidget* parent)
{
MainWindow* p = (MainWindow*) parent;
connect(this, &Create_Image_Task::updateImage_preview, p, &MainWindow::getImage);
connect(this, &Create_Image_Task::progressInform_preview, p, &MainWindow::updateProgressBar);
connect(this, &Create_Image_Task::finished, p, &MainWindow::build_image_finished_deal);
connect(this, &Create_Image_Task::one_ok, p, &MainWindow::build_image_one_ok);
connect(this, &Create_Image_Task::updateImage_route, p->route_tool_window, &Route_Tool::getImage);
connect(this, &Create_Image_Task::progressInform_route, p->route_tool_window, &Route_Tool::updateProgressBar);
connect(p, &MainWindow::createImageStop, this, &Create_Image_Task::stop);
}
void Create_Image_Task::run()
{
qDebug() << "Got it here";
qDebug() << "The working thread: " << QThread::currentThreadId();
double progress = 0;
int progress_now = 0;
// qDebug() << QThread::currentThreadId();
QImage image_build(X, Y, QImage::Format_ARGB32);
for(int i = X - 1; i >= 0; i--)
{
if(isCancelled) return;
progress = 100 * static_cast<double>(X - i) / X;
if(static_cast<int>(progress) > progress_now)
{
if(work_name == "Preview") emit progressInform_preview(progress);
if(work_name == "Route") emit progressInform_route(progress);
progress_now = static_cast<int>(progress);
}
for(int j = Y - 1; j >= 0; j--)
{
double dx = x_width * (static_cast<double>(i) / X - 0.5);
double dy = - y_height * (static_cast<double>(j) / Y - 0.5);
if (y_inverse) dy = - dy;
double mod = sqrt(dx * dx + dy * dy);
double theta = atan2(dy, dx) + rotate_angle / 180 * Pi;
std::complex<double> this_point(x + mod * cos(theta), y + mod * sin(theta));
std::complex<double> z0(this_point), last_point(-this_point);
bool convergent = true;
int k = 0;
for (k = 0; k < max_loop_t; k++)
{
if (abs(this_point) > max_class_v)
{
convergent = false;
break;
}
else if (template_ != 4 && abs(this_point) < min_class_v)
{
// convergent = true;
break;
}
else if (template_ == 4 && abs(this_point - last_point) / (abs(this_point)) < min_class_v)
{
// convergent = true;
break;
}
else
{
if (template_ == 4) last_point = this_point;
switch(template_)
{
case 1: this_point = this_point * this_point + z0; break;
case 2: this_point = this_point * this_point + c0; break;
case 3:
{
std::complex<double> c { fabs(this_point.real()), fabs(this_point.imag())};
this_point = c * c + z0; break;
}
case 4:
{
std::complex<double> p = 0, p_ = 0;
for(int i = 0; i != 10; i++)
{
p += Newton_xn[i] * pow(this_point, i);
p_ += Newton_xn[i] * pow(this_point, i - 1) * std::complex<double>(i);
}
p += Newton_ex * exp(this_point);
p += Newton_sin * sin(this_point);
p += Newton_cos * cos(this_point);
p_ += Newton_ex * exp(this_point);
p_ += Newton_sin * cos(this_point);
p_ -= Newton_cos * sin(this_point);
this_point = this_point - Newton_a * p / p_;
}
case 5:
{
std::vector<std::complex<double>> num_list
{
this_point, this_point.real(), this_point.imag(), z0, z0.real(), z0.imag(), t, double(k)
};
std::string msg;
this_point = eval_postorder(Formula, num_list, &msg);
if (!msg.empty())
{
// 0 indicates formula error
emit error_calc(0);
}
break;
}
default: break;
}
}
}
double RGBA[4];
if (!setRGBA(RGBA, convergent, this_point, z0, t, k))
{
// 1 indicates colour error in convergent point
// 2 indicates colour error in divergent point
emit error_calc(convergent ? 1 : 2);
}
else
{
image_build.setPixel(i, j, qRgba(RGBA[0], RGBA[1], RGBA[2], RGBA[3]));
}
}
}
qDebug() << img_path + "/" + img_title + "." + img_format;
image_build.save(img_path + "/" + img_title + "." + img_format);
image_build.load(img_path + "/" + img_title + "." + img_format);
if(work_name == "Preview") emit updateImage_preview(image_build);
if(work_name == "Route") emit updateImage_route(image_build);
if(work_name == "Create_Image") emit one_ok();
if(work_name == "Create_Image_Last") emit finished();
}
void Create_Image_Task::setImage(double x_, double y_, double x_width_, double y_height_, int X_, int Y_, double rotate_angle_, double t_,
QString img_format_, QString img_path_, QString img_title_, QString work_name_, bool y_inverse_)
{
x = x_;
y = y_;
x_width = x_width_;
y_height = y_height_;
X = X_;
Y = Y_;
rotate_angle = rotate_angle_;
t = t_;
img_format = img_format_;
img_path = img_path_;
img_title = img_title_;
work_name = work_name_;
y_inverse = y_inverse_;
}
void Create_Image_Task::setData(std::vector<_var> C1[4], std::vector<_var> C2[4], int temp, double min, double max, int lpt)
{
for (int i = 0; i != 4; i++)
{
Colour1_f[i] = C1[i];
Colour2_f[i] = C2[i];
}
template_ = temp;
min_class_v = min < 1E-10 ? 1E-10 : min;
max_class_v = max < 1E-10 ? 1E-10 : max;
max_loop_t = lpt;
}
void Create_Image_Task::setFormula(const std::vector<_var>& post)
{
Formula = post;
}
void Create_Image_Task::setTemplate2(std::complex<double> c)
{
c0 = c;
}
void Create_Image_Task::setTemplate4(const std::complex<double>& c1, std::complex<double> c2[10], const std::complex<double>& c3, const std::complex<double>& c4, const std::complex<double>& c5)
{
Newton_a = c1;
for(int i = 0; i != 10; i++) Newton_xn[i] = c2[i];
Newton_sin = c3;
Newton_cos = c4;
Newton_ex = c5;
}
void Create_Image_Task::stop()
{
isCancelled = true;
}
int Create_Image_Task::range_complex_to_255(const std::complex<double>& c)
{
if (c.real() > 255) return 255;
if (c.real() < 0) return 0;
return c.real() + 0.5;
}
bool Create_Image_Task::setRGBA(double rgba[4], bool convergent, const std::complex<double>& z, const std::complex<double>& z0, double t, int k)
{
std::string msg;
std::vector<std::complex<double>> num_list { z, z.real(), z.imag(), z0, z0.real(), z0.imag(), t, double(k) };
if (convergent)
{
for (int i = 0; i != 4; i++)
{
rgba[i] = range_complex_to_255(eval_postorder(Colour1_f[i], num_list, &msg));
if (!msg.empty())
{
return false;
}
}
}
else
{
for (int i = 0; i != 4; i++)
{
rgba[i] = range_complex_to_255(eval_postorder(Colour2_f[i], num_list, &msg));
if (!msg.empty())
{
return false;
}
}
}
return true;
}
| 37.30531 | 193 | 0.49401 | [
"vector"
] |
795e31053e8440aef12ea941b844f8a7f6c4b6ef | 5,134 | cpp | C++ | src/Utils/tests/TestDoubleBufferContainer.cpp | Megaxela/HGEngineReloaded | 62d319308c2d8a62f6854721c31afc4981aa13df | [
"MIT"
] | 2 | 2021-02-26T05:25:48.000Z | 2021-09-16T22:30:41.000Z | src/Utils/tests/TestDoubleBufferContainer.cpp | Megaxela/HGEngineReloaded | 62d319308c2d8a62f6854721c31afc4981aa13df | [
"MIT"
] | 1 | 2019-10-19T10:36:43.000Z | 2019-10-19T10:36:43.000Z | src/Utils/tests/TestDoubleBufferContainer.cpp | Megaxela/HGEngineReloaded | 62d319308c2d8a62f6854721c31afc4981aa13df | [
"MIT"
] | 2 | 2019-10-22T18:56:59.000Z | 2020-03-12T04:38:31.000Z | // HG::Utils
#include <HG/Utils/DoubleBufferContainer.hpp>
// GTest
#include <gtest/gtest.h>
TEST(Utils, DoubleBufferContainerConstructorsDefault)
{
HG::Utils::DoubleBufferContainer<std::size_t> data;
ASSERT_EQ(data.size(), 0);
ASSERT_EQ(data.added().size(), 0);
ASSERT_EQ(data.current().size(), 0);
ASSERT_EQ(data.removable().size(), 0);
}
TEST(Utils, DoubleBufferContainerConstructorsCopy)
{
HG::Utils::DoubleBufferContainer<std::size_t> data;
data.add(1);
data.add(2);
data.add(3);
data.merge();
data.add(4);
data.add(5);
data.remove(3);
HG::Utils::DoubleBufferContainer<std::size_t> copied(data);
ASSERT_EQ(copied.size(), 3);
ASSERT_EQ(copied.current().size(), copied.size());
ASSERT_EQ(copied.removable().size(), 1);
ASSERT_EQ(copied.added().size(), 2);
}
static std::size_t copied = 0;
static std::size_t moved = 0;
static std::size_t constructed = 0;
static std::size_t counter = 0;
class SampleData
{
public:
SampleData() : data(++counter)
{
++constructed;
}
SampleData(const SampleData& copy) : data(copy.data)
{
++copied;
}
SampleData(SampleData&& move) noexcept : data(move.data)
{
++moved;
}
SampleData& operator=(const SampleData& rhs)
{
++copied;
data = rhs.data;
return (*this);
}
SampleData& operator=(SampleData&& rhs) noexcept
{
++moved;
data = rhs.data;
return (*this);
}
bool operator==(const SampleData& rhs) const
{
return data == rhs.data;
}
std::size_t data;
};
namespace std
{
template <>
struct hash<SampleData>
{
std::size_t operator()(const SampleData& d) const
{
return d.data;
}
};
} // namespace std
TEST(Utils, DoubleBufferContainerConstructorsMove)
{
HG::Utils::DoubleBufferContainer<SampleData> data;
data.add(SampleData());
data.add(SampleData());
data.add(SampleData());
data.merge();
data.add(SampleData());
data.add(SampleData());
data.remove(SampleData());
ASSERT_EQ(data.size(), 3);
ASSERT_EQ(data.current().size(), data.size());
ASSERT_EQ(data.removable().size(), 1);
ASSERT_EQ(data.added().size(), 2);
ASSERT_EQ(copied, 0);
ASSERT_EQ(moved, 15); // todo: Too many I guess, but it's ok for now
ASSERT_EQ(constructed, 6);
copied = 0;
moved = 0;
constructed = 0;
auto movedData = std::move(data);
ASSERT_EQ(movedData.size(), 3);
ASSERT_EQ(movedData.current().size(), movedData.size());
ASSERT_EQ(movedData.removable().size(), 1);
ASSERT_EQ(movedData.added().size(), 2);
ASSERT_EQ(copied, 0);
ASSERT_EQ(moved, 0);
ASSERT_EQ(constructed, 0);
}
TEST(Utils, DoubleBufferContainerConstructorsModifiersAndGetters)
{
HG::Utils::DoubleBufferContainer<std::size_t> data;
ASSERT_EQ(data.size(), data.current().size());
ASSERT_EQ(data.current().size(), 0);
ASSERT_EQ(data.removable().size(), 0);
ASSERT_EQ(data.added().size(), 0);
data.add(1);
data.add(1);
data.add(1);
data.add(2);
data.add(2);
data.add(3);
ASSERT_EQ(data.current().size(), 0);
ASSERT_EQ(data.removable().size(), 0);
ASSERT_EQ(data.added().size(), 3);
data.remove(4);
ASSERT_EQ(data.current().size(), 0);
ASSERT_EQ(data.removable().size(), 1);
ASSERT_EQ(data.added().size(), 3);
data.remove(1);
ASSERT_EQ(data.isRemoving(1), true);
ASSERT_EQ(data.current().size(), 0);
ASSERT_EQ(data.removable().size(), 2);
ASSERT_EQ(data.added().size(), 3);
data.merge();
data.add(2);
ASSERT_EQ(data.current().size(), 2);
ASSERT_EQ(data.removable().size(), 0);
ASSERT_EQ(data.added().size(), 0);
data.remove(2);
data.add(4);
ASSERT_EQ(data.current().size(), 2);
ASSERT_EQ(data.removable().size(), 1);
ASSERT_EQ(data.added().size(), 1);
data.clearState();
ASSERT_EQ(data.current().size(), 2);
ASSERT_EQ(data.removable().size(), 0);
ASSERT_EQ(data.added().size(), 0);
ASSERT_EQ(data[0], 2);
ASSERT_EQ(data[1], 3);
std::vector<std::size_t> expected = {2, 3};
std::vector<std::size_t> actual(data.begin(), data.end());
ASSERT_EQ(expected, actual);
data.clear();
ASSERT_EQ(data.current().size(), 0);
ASSERT_EQ(data.removable().size(), 0);
ASSERT_EQ(data.added().size(), 0);
}
TEST(Utils, DoubleBufferContainerOutOfRangeIndex)
{
#ifndef NDEBUG
HG::Utils::DoubleBufferContainer<std::size_t> data;
ASSERT_THROW(data[12] == 12, std::out_of_range);
#endif
}
TEST(Utils, DoubleBufferContainerMultipleRemoving)
{
HG::Utils::DoubleBufferContainer<std::size_t> data;
data.add(1);
data.add(2);
data.add(3);
data.add(4);
ASSERT_EQ(data.added().size(), 4);
data.merge();
data.remove(1);
ASSERT_NO_THROW(data.remove(1));
ASSERT_EQ(data.removable().size(), 1);
data.merge();
ASSERT_EQ(data.current().size(), 3);
ASSERT_EQ(data.removable().size(), 0);
ASSERT_EQ(data.added().size(), 0);
}
| 21.302905 | 72 | 0.613946 | [
"vector"
] |
79644a6aaa7d91a15a670d8c54ca74b162d71e14 | 16,278 | cpp | C++ | applications/3DimViewer/src/CDataInfoDialog.cpp | SindenDev/3dimviewer | e23a3147edc35034ef4b75eae9ccdcbc7192b1a1 | [
"Apache-2.0"
] | 6 | 2020-04-14T16:10:55.000Z | 2021-05-21T07:13:55.000Z | applications/3DimViewer/src/CDataInfoDialog.cpp | SindenDev/3dimviewer | e23a3147edc35034ef4b75eae9ccdcbc7192b1a1 | [
"Apache-2.0"
] | null | null | null | applications/3DimViewer/src/CDataInfoDialog.cpp | SindenDev/3dimviewer | e23a3147edc35034ef4b75eae9ccdcbc7192b1a1 | [
"Apache-2.0"
] | 2 | 2020-07-24T16:25:38.000Z | 2021-01-19T09:23:18.000Z | ///////////////////////////////////////////////////////////////////////////////
// $Id$
//
// 3DimViewer
// Lightweight 3D DICOM viewer.
//
// Copyright 2008-2016 3Dim Laboratory s.r.o.
//
// 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 "CDataInfoDialog.h"
#include "ui_CDataInfoDialog.h"
#include <C3DimApplication.h>
#include <QTableWidgetItem>
#include <QSettings>
#include <QDateTime>
#include <QDebug>
#include <QClipboard>
#include <data/CDensityData.h>
#include <data/CModelManager.h>
#include <data/CImageLoaderInfo.h>
#include <data/CVolumeTransformation.h>
#include <data/CRegionData.h>
#include <data/CRegionColoring.h>
#include <coremedi/app/Signals.h>
///////////////////////////////////////////////////////////////////////////////
// DICOM tags dump
#if defined (TRIDIM_USE_GDCM)
//GDCM
#include <gdcmReader.h>
#include <gdcmStringFilter.h>
bool dumpFileGDCM(CDataInfoDialog *pDialog, const char *ifname)
{
// Read file
gdcm::Reader reader;
reader.SetFileName(ifname);
if (!reader.Read())
{
QString message = "Failed to read file ";
message += ifname;
QMessageBox::critical(pDialog, QApplication::applicationName(), message);
return false;
}
//String filter used to get tag values as strings
gdcm::StringFilter stringFilter;
stringFilter.SetFile(reader.GetFile());
//Get all data elements from dataset
const std::set<gdcm::DataElement> &dataElementSet = reader.GetFile().GetDataSet().GetDES();
foreach(gdcm::DataElement el, dataElementSet)
{
//Convert to string pair: first = parameter, second = value
std::pair<std::string, std::string> pair = stringFilter.ToStringPair(el);
//if empty or undifined do not add
if (!pair.first.empty() && !pair.second.empty() && pair.first != "?" && pair.second != "?")
{
pDialog->AddRow(QString::fromStdString(pair.first), QString::fromStdString(pair.second));
}
}
//Return true if we managed to get any data elements
return dataElementSet.size() > 0;
}
#else
#include "dcmtk/config/osconfig.h" /* make sure OS specific configuration is included first */
#define HAVE_STD_STRING
#include "dcmtk/ofstd/ofstring.h"
#include <dcmtk/dcmdata/dcfilefo.h>
//ORIGIINAL
bool dumpFileDCTk(
CDataInfoDialog *pDialog,
const char *ifname,
const E_FileReadMode readMode,
const E_TransferSyntax xfer,
const size_t printFlags,
const OFBool loadIntoMemory,
const OFBool stopOnErrors,
const OFBool convertToUTF8)
{
#define COUT qDebug()
if (NULL == ifname || 0 == ifname[0])
return false;
DcmFileFormat dfile;
DcmObject *dset = &dfile;
if (readMode == ERM_dataset)
dset = dfile.getDataset();
const OFCmdUnsignedInt maxReadLength = 4096; // default is 4 KB
OFCondition cond = dfile.loadFile(ifname, xfer, EGL_noChange, maxReadLength, readMode);
if (cond.bad())
{
qDebug() << "error invalid filename";
return false;
}
if (loadIntoMemory)
dfile.loadAllDataIntoMemory();
#ifdef WITH_LIBICONV
if (convertToUTF8)
{
qDebug() << "converting all element values that are affected by Specific Character Set (0008,0005) to UTF-8";
cond = dfile.convertToUTF8();
if (cond.bad())
{
qDebug() << "error converting file to UTF-8";
if (stopOnErrors)
return false;
}
}
#endif
size_t pixelCounter = 0;
const char *pixelFileName = NULL;
OFString pixelFilenameStr;
// dump file content
std::stringstream out;
dset->print(out, printFlags, 0 /*level*/, pixelFileName, &pixelCounter);
QStringList sl = (QString::fromStdString(out.str())).split('\n');
foreach(QString str, sl)
{
if (!str.isEmpty())
{
QStringList entrySplit = str.split('#');
if (entrySplit.size()>1)
{
if (2 == entrySplit.size())
pDialog->AddRow(entrySplit[1], entrySplit[0], QColor(QColor::Invalid), Qt::AlignLeft);
else
pDialog->AddRow(entrySplit[entrySplit.size() - 1], str.left(str.length() - entrySplit[entrySplit.size() - 1].length() - 1), QColor(QColor::Invalid), Qt::AlignLeft);
}
else
pDialog->AddRow("", str, QColor(QColor::Invalid), Qt::AlignLeft);
}
}
return sl.size()>0;
}
#endif
///////////////////////////////////////////////////////////////////////////////
// static method
QString CDataInfoDialog::formatDicomDateAndTime(const QString& wsDate, const QString& wsTime)
{
// convert date and time from dicom format
QDate date = QDate::fromString(wsDate,"yyyy.MM.dd");
if (!date.isValid())
date = QDate::fromString(wsDate,"yyyyMMdd");
if (!date.isValid() && !wsDate.isEmpty())
return wsDate + " " + wsTime;
QTime time = QTime::fromString(wsTime,"hhmmss.zzz");
if (!time.isValid())
time = QTime::fromString(wsTime,"hhmmss");
if (!time.isValid())
time = QTime::fromString(wsTime,"hh:mm:ss.zzz");
if (!time.isValid())
time = QTime::fromString(wsTime,"hh:mm:ss");
if (!wsTime.isEmpty() && time.isValid())
{
if (date.isValid())
{
QDateTime dt;
dt.setDate(date);
dt.setTime(time);
return dt.toString(Qt::DefaultLocaleLongDate);
}
else
return time.toString(Qt::DefaultLocaleLongDate);
}
else
{
if (date.isValid())
return date.toString(Qt::DefaultLocaleLongDate);
}
return "";
}
CDataInfoDialog::CDataInfoDialog(QWidget *parent) :
QDialog(parent, Qt::WindowTitleHint | Qt::WindowSystemMenuHint | Qt::WindowMaximizeButtonHint | Qt::WindowCloseButtonHint),
ui(new Ui::CDataInfoDialog)
{
ui->setupUi(this);
int activeDataset = VPL_SIGNAL(SigGetActiveDataSet).invoke2();
ui->tableWidget->setContextMenuPolicy(Qt::CustomContextMenu);
connect(ui->tableWidget, SIGNAL(customContextMenuRequested(const QPoint &)), this, SLOT(tableContextMenu(const QPoint &)));
{
data::CObjectPtr<data::CDensityData> spVolume( APP_STORAGE.getEntry(activeDataset) );
QString PatientName(spVolume->m_sPatientName.c_str());
QString PatientID(spVolume->m_sPatientId.c_str());
QString PatientBirthday(spVolume->m_sPatientBirthday.c_str());
QString PatientSex(spVolume->m_sPatientSex.c_str());
QString PatientDescription(spVolume->m_sPatientDescription.c_str());
QString Date(spVolume-> m_sSeriesDate.c_str());
QString Time(spVolume-> m_sSeriesTime.c_str());
QString SeriesID(spVolume-> m_sSeriesUid.c_str());
QString SeriesDescription(spVolume-> m_sSeriesDescription.c_str());
QString StudyID(spVolume-> m_sStudyUid.c_str());
QString StudyDate(spVolume-> m_sStudyDate.c_str());
QString StudyDescription(spVolume-> m_sStudyDescription.c_str());
QString PatientPosition(spVolume-> m_sPatientPosition.c_str());
QString Manufacturer(spVolume-> m_sManufacturer.c_str());
QString ModelName(spVolume-> m_sModelName.c_str());
QString ScanOptions(spVolume-> m_sScanOptions.c_str());
AddRow(tr("Patient Data"),"",QColor(0,128,255));
AddRow(tr("Dimensions"),QString(tr("%1 x %2 x %3 voxels")).arg(spVolume->getXSize()).arg(spVolume->getYSize()).arg(spVolume->getZSize()));
AddRow(tr("Resolution"),QString(tr("%1 x %2 x %3 mm")).arg(spVolume->getDX(),0,'f',4).arg(spVolume->getDY(),0,'f',4).arg(spVolume->getDZ(),0,'f',4));
AddRow(tr("Size"),QString(tr("%1 x %2 x %3 mm")).arg(spVolume->getXSize()*spVolume->getDX(),0,'f',2).arg(spVolume->getYSize()*spVolume->getDY(),0,'f',2).arg(spVolume->getZSize()*spVolume->getDZ(),0,'f',2));
AddRow(tr("Patient Name"),PatientName);
AddRow(tr("Patient ID"),PatientID);
AddRow(tr("Patient Position"),PatientPosition);
AddRowIfNotEmpty(tr("Patient Birthday"),PatientBirthday);
AddRowIfNotEmpty(tr("Patient Sex"),PatientSex);
AddRowIfNotEmpty(tr("Patient Description"),PatientDescription);
AddRowIfNotEmpty(tr("Study ID"),StudyID);
AddRowIfNotEmpty(tr("Study Date"),formatDicomDateAndTime(StudyDate,""));
AddRowIfNotEmpty(tr("Study Description"),StudyDescription);
AddRow(tr("Series ID"),SeriesID);
AddRow(tr("Series Date"),formatDicomDateAndTime(Date,""));
AddRow(tr("Series Time"),formatDicomDateAndTime("",Time));
AddRowIfNotEmpty(tr("Series Description"),SeriesDescription);
AddRowIfNotEmpty(tr("Scan Options"),ScanOptions);
AddRow(tr("Manufacturer"),Manufacturer);
AddRow(tr("Model Name"),ModelName);
spVolume.release();
}
{
data::CObjectPtr<data::CDensityData> spVolume( APP_STORAGE.getEntry(activeDataset) );
vpl::img::CVector3D pos = spVolume->m_ImagePosition;
data::CObjectPtr<data::CVolumeTransformation> spVolumeTransformation(APP_STORAGE.getEntry(data::Storage::VolumeTransformation::Id));
osg::Matrix volMx = spVolumeTransformation->getTransformation();
if (!volMx.isIdentity() || pos.getLength()>0.001)
{
AddRow(tr("Volume Transformation"),"",QColor(0,128,255));
if (!volMx.isIdentity())
{
for(int i=0;i<4;i++)
AddRow(i==0?(tr("Matrix")):"",QString("%1 %2 %3 %4").arg(volMx(i,0),0,'f',3).arg(volMx(i,1),0,'f',3).arg(volMx(i,2),0,'f',3).arg(volMx(i,3),0,'f',3));
}
AddRow(tr("Position"),QString("%1 %2 %3").arg(pos.getX(),0,'f',3).arg(pos.getY(),0,'f',3).arg(pos.getZ(),0,'f',3));
}
APP_STORAGE.invalidate(spVolumeTransformation.getEntryPtr());
}
for(int id=0;id<MAX_IMPORTED_MODELS;id++)
{
data::CObjectPtr<data::CModel> spModel( APP_STORAGE.getEntry(data::Storage::ImportedModel::Id+id, data::Storage::NO_UPDATE) );
if(spModel->hasData())
{
geometry::CMesh *pMesh = spModel->getMesh(false);
//const std::string &std_name(spModel->getLabel());
//QString qs_name(QString::fromStdString(std_name));
AddRow(tr("Model %1").arg(id+1),"",QColor(0,128,255));
if (!spModel->getLabel().empty())
AddRow(tr("Name"),QString::fromStdString(spModel->getLabel()));
AddRow(tr("Triangles"),QString::number(pMesh->n_faces()));
AddRow(tr("Nodes"),QString::number(pMesh->n_vertices()));
AddRow(tr("Components"),QString::number(pMesh->componentCount()));
if (!pMesh->isClosed())
AddRow(tr("Closed"),tr("No"));
if (!spModel->getTransformationMatrix().isIdentity())
{
osg::Matrix mx = spModel->getTransformationMatrix();
for (int i = 0; i<4; i++)
AddRow(i == 0 ? (tr("Matrix")) : "", QString("%1 %2 %3 %4").arg(mx(i, 0), 0, 'f', 3).arg(mx(i, 1), 0, 'f', 3).arg(mx(i, 2), 0, 'f', 3).arg(mx(i, 3), 0, 'f', 3));
}
}
}
// info on region data
{
data::CObjectPtr<data::CRegionColoring> spColoring( APP_STORAGE.getEntry(data::Storage::RegionColoring::Id) );
data::CObjectPtr< data::CRegionData > rVolume( APP_STORAGE.getEntry( data::Storage::RegionData::Id ) );
data::CObjectPtr<data::CDensityData> spVolume( APP_STORAGE.getEntry(data::Storage::PatientData::Id) );
const int xSize = rVolume->getXSize();
const int ySize = rVolume->getYSize();
const int zSize = rVolume->getZSize();
const double voxelSize = spVolume->getDX() * spVolume->getDY() * spVolume->getDZ();
const int nRegions = spColoring->getNumOfRegions();
std::map<int,int> rInfo;
for(int i = 0; i < nRegions; i++)
rInfo[i]=0;
for(int z=0; z<zSize; z++)
{
for(int y=0; y<ySize; y++)
{
for(int x=0; x<xSize; x++)
{
auto val = rVolume->at(x,y,z);
if (val!=0)
rInfo[val]++;
}
}
}
for(auto it = rInfo.begin(); it!=rInfo.end(); it++)
{
if (it->second>0)
{
auto color = spColoring->getColor( it->first );
AddRow(tr("Region %1").arg(it->first),"",QColor(color.getR(),color.getG(),color.getB()));
AddRow(tr("Voxels"),QString::number(it->second));
AddRow(tr("Volume"), QString::number(it->second * voxelSize, 'f', 2) + QString(" mm%1").arg(QChar(179)));
}
}
}
{ // dicom file info
data::CObjectPtr<data::CImageLoaderInfo> spInfo( APP_STORAGE.getEntry(data::Storage::ImageLoaderInfo::Id) );
if (spInfo->getNumOfFiles()>0)
{
const data::CImageLoaderInfo::tFiles & list = spInfo->getList();
QString str;
#ifdef _MSC_VER
str = QString::fromUtf16((const ushort *)list[0].c_str());
#else
str = QString::fromStdString(list[0]);
#endif
if (QFile::exists(str))
{
AddRow(tr("DICOM Info"),str,QColor(0,128,255));
#ifdef _WIN32
std::string file = C3DimApplication::wcs2ACP(list[0]);
#else
std::string file = list[0];
#endif
#if defined(TRIDIM_USE_GDCM)
dumpFileGDCM(this, file.c_str());
#else
E_FileReadMode readMode = ERM_autoDetect;
E_TransferSyntax xfer = EXS_Unknown;
size_t printFlags = DCMTypes::PF_shortenLongTagValues;
OFBool loadIntoMemory = OFTrue;
OFBool stopOnErrors = OFTrue;
OFBool convertToUTF8 = OFFalse;
dumpFileDCTk(this, file.c_str(), readMode, xfer, printFlags, loadIntoMemory, stopOnErrors, convertToUTF8);
#endif
}
}
}
QSettings settings;
settings.beginGroup("DataInfoWindow");
resize(settings.value("size",minimumSize()).toSize());
settings.endGroup();
}
void CDataInfoDialog::AddRowIfNotEmpty(const QString& param, const QString& value, const QColor& color)
{
if (value.isEmpty()) return;
AddRow(param,value,color);
}
void CDataInfoDialog::AddRow(const QString& param, const QString& value, const QColor& color, int alignment)
{
int Id=ui->tableWidget->rowCount();
ui->tableWidget->insertRow(Id);
QTableWidgetItem *i0 = new QTableWidgetItem(param);
i0->setFlags(i0->flags() & ~Qt::ItemIsEditable);
if (color.isValid())
i0->setBackgroundColor(color);
ui->tableWidget->setItem(Id,0,i0);
QTableWidgetItem *i1 = new QTableWidgetItem(value);
i1->setFlags(i1->flags() & ~Qt::ItemIsEditable);
i1->setTextAlignment(alignment);
if (color.isValid())
i1->setBackgroundColor(color);
ui->tableWidget->setItem(Id,1,i1);
}
CDataInfoDialog::~CDataInfoDialog()
{
QSettings settings;
settings.beginGroup("DataInfoWindow");
settings.setValue("size",size());
settings.endGroup();
delete ui;
}
void CDataInfoDialog::tableContextMenu(const QPoint &pos)
{
QTableWidget* pTable = qobject_cast<QTableWidget*>(sender());
if (NULL != pTable)
{
QTableWidgetItem *item = pTable->itemAt(pos);
if (NULL != item)
{
QMenu *menu = new QMenu;
QAction* copyToClipboard = menu->addAction(tr("Copy"));
QAction* res = menu->exec(pTable->viewport()->mapToGlobal(pos));
if (NULL != res)
{
if (res == copyToClipboard)
{
QClipboard *clipboard = QApplication::clipboard();
clipboard->setText(item->text());
}
}
}
}
} | 36.911565 | 215 | 0.609657 | [
"geometry",
"model",
"3d"
] |
7975f1ba9dc2948c2cbaf38abc401284497b7328 | 5,739 | cpp | C++ | src/highlevel_feature_extractor.cpp | sanmit/HFO-benchmark | 0104ff7527485c8a7c159e6bf16c410eded72c0a | [
"MIT"
] | null | null | null | src/highlevel_feature_extractor.cpp | sanmit/HFO-benchmark | 0104ff7527485c8a7c159e6bf16c410eded72c0a | [
"MIT"
] | null | null | null | src/highlevel_feature_extractor.cpp | sanmit/HFO-benchmark | 0104ff7527485c8a7c159e6bf16c410eded72c0a | [
"MIT"
] | null | null | null | #ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include "highlevel_feature_extractor.h"
#include <rcsc/common/server_param.h>
using namespace rcsc;
HighLevelFeatureExtractor::HighLevelFeatureExtractor(int num_teammates,
int num_opponents,
bool playing_offense) :
FeatureExtractor(num_teammates, num_opponents, playing_offense)
{
assert(numTeammates >= 0);
assert(numOpponents >= 0);
numFeatures = num_basic_features + features_per_teammate * numTeammates;
if (numOpponents > 0) {
// One extra basic feature and one feature per teammate
numFeatures += 1 + numTeammates;
}
feature_vec.resize(numFeatures);
}
HighLevelFeatureExtractor::~HighLevelFeatureExtractor() {}
const std::vector<float>& HighLevelFeatureExtractor::ExtractFeatures(
const WorldModel& wm) {
featIndx = 0;
const ServerParam& SP = ServerParam::i();
const SelfObject& self = wm.self();
const Vector2D& self_pos = self.pos();
const float self_ang = self.body().radian();
const PlayerCont& teammates = wm.teammates();
float maxR = sqrtf(SP.pitchHalfLength() * SP.pitchHalfLength()
+ SP.pitchHalfWidth() * SP.pitchHalfWidth());
// features about self pos
// Allow the agent to go 10% over the playfield in any direction
float tolerance_x = .1 * SP.pitchHalfLength();
float tolerance_y = .1 * SP.pitchHalfWidth();
// Feature[0]: X-postion
if (playingOffense) {
addNormFeature(self_pos.x, -tolerance_x, SP.pitchHalfLength() + tolerance_x);
} else {
addNormFeature(self_pos.x, -SP.pitchHalfLength()-tolerance_x, tolerance_x);
}
// addFeature(self_pos.x);
// Feature[1]: Y-Position
addNormFeature(self_pos.y, -SP.pitchHalfWidth() - tolerance_y,
SP.pitchHalfWidth() + tolerance_y);
// addFeature(self_pos.y);
// Feature[2]: Self Angle
addNormFeature(self_ang, -2*M_PI, 2*M_PI); // addFeature(self_ang);
float r;
float th;
// features about the ball
Vector2D ball_pos = wm.ball().pos();
angleDistToPoint(self_pos, ball_pos, th, r);
// Feature[3]: Dist to ball
addNormFeature(r, 0, maxR); // addFeature(r);
// Feature[4]: Ang to ball
addNormFeature(th, -2*M_PI, 2*M_PI); // addFeature(th);
// Feature[5]: Able to kick
addNormFeature(self.isKickable(), false, true); // addFeature(self.isKickable());
// features about distance to goal center
Vector2D goalCenter(SP.pitchHalfLength(), 0);
if (!playingOffense) {
goalCenter.assign(-SP.pitchHalfLength(), 0);
}
angleDistToPoint(self_pos, goalCenter, th, r);
// Feature[6]: Goal Center Distance
addNormFeature(r, 0, maxR); // addFeature(r);
// Feature[7]: Angle to goal center
addNormFeature(th, -2*M_PI, 2*M_PI); // addFeature(th);
// Feature[8]: largest open goal angle
addNormFeature(calcLargestGoalAngle(wm, self_pos), 0, M_PI);
// addFeature(calcLargestGoalAngle(wm, self_pos));
// Features [9+T - 9 + 2T]: teammate's open angle to goal
int detected_teammates = 0;
for (PlayerCont::const_iterator it=teammates.begin(); it != teammates.end(); ++it) {
const PlayerObject& teammate = *it;
if (valid(teammate) && detected_teammates < numTeammates) {
addNormFeature(calcLargestGoalAngle(wm, teammate.pos()), 0, M_PI);
// addFeature(calcLargestGoalAngle(wm, teammate.pos()));
detected_teammates++;
}
}
// Add zero features for any missing teammates
for (int i=detected_teammates; i<numTeammates; ++i) {
addFeature(FEAT_INVALID);
}
// dist to our closest opp
if (numOpponents > 0) {
calcClosestOpp(wm, self_pos, th, r);
addNormFeature(r, 0, maxR); // addFeature(r);
// teammates dists to closest opps
detected_teammates = 0;
for (PlayerCont::const_iterator it=teammates.begin(); it != teammates.end(); ++it) {
const PlayerObject& teammate = *it;
if (valid(teammate) && detected_teammates < numTeammates) {
calcClosestOpp(wm, teammate.pos(), th, r);
addNormFeature(r, 0, maxR); // addFeature(r);
detected_teammates++;
}
}
// Add zero features for any missing teammates
for (int i=detected_teammates; i<numTeammates; ++i) {
addFeature(FEAT_INVALID);
}
}
// Features [9+2T - 9+3T]: open angle to teammates
detected_teammates = 0;
for (PlayerCont::const_iterator it=teammates.begin(); it != teammates.end(); ++it) {
const PlayerObject& teammate = *it;
if (valid(teammate) && detected_teammates < numTeammates) {
addNormFeature(calcLargestTeammateAngle(wm, self_pos, teammate.pos()),0,M_PI);
// addFeature(calcLargestTeammateAngle(wm, self_pos, teammate.pos()));
detected_teammates++;
}
}
// Add zero features for any missing teammates
for (int i=detected_teammates; i<numTeammates; ++i) {
addFeature(FEAT_INVALID);
}
// Features [9+3T - end]: dist, angle, unum of teammates
detected_teammates = 0;
for (PlayerCont::const_iterator it=teammates.begin(); it != teammates.end(); ++it) {
const PlayerObject& teammate = *it;
if (valid(teammate) && detected_teammates < numTeammates) {
angleDistToPoint(self_pos, teammate.pos(), th, r);
addNormFeature(r,0,maxR); // addFeature(r);
addNormFeature(th,-M_PI,M_PI); // addFeature(th);
addFeature(teammate.unum());
detected_teammates++;
}
}
// Add zero features for any missing teammates
for (int i=detected_teammates; i<numTeammates; ++i) {
addFeature(FEAT_INVALID);
addFeature(FEAT_INVALID);
addFeature(FEAT_INVALID);
}
assert(featIndx == numFeatures);
// checkFeatures();
//std::cout << "features: " << features.rows(0,ind-1).t();
return feature_vec;
}
| 36.322785 | 88 | 0.670326 | [
"vector"
] |
7977266d7e4e97b114dedb47b4d556608cf67335 | 7,962 | cpp | C++ | src/mlpack/methods/decision_tree/decision_tree_main.cpp | NaxAlpha/mlpack-build | 1f0c1454d4b35eb97ff115669919c205cee5bd1c | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | src/mlpack/methods/decision_tree/decision_tree_main.cpp | NaxAlpha/mlpack-build | 1f0c1454d4b35eb97ff115669919c205cee5bd1c | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | src/mlpack/methods/decision_tree/decision_tree_main.cpp | NaxAlpha/mlpack-build | 1f0c1454d4b35eb97ff115669919c205cee5bd1c | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | /**
* @file decision_tree_main.cpp
* @author Ryan Curtin
*
* A command-line program to build a decision tree.
*
* 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.
*/
#include <mlpack/core.hpp>
#include "decision_tree.hpp"
#include <mlpack/core/data/load.hpp>
#include <mlpack/core/data/save.hpp>
using namespace std;
using namespace mlpack;
using namespace mlpack::tree;
PROGRAM_INFO("Decision tree",
"Train and evaluate using a decision tree. Given a dataset containing "
"numeric features and associated labels for each point in the dataset, this"
" program can train a decision tree on that data."
"\n\n"
"The training file and associated labels are specified with the "
"--training_file and --labels_file options, respectively. The labels "
"should be in the range [0, num_classes - 1]."
"\n\n"
"When a model is trained, it may be saved to file with the "
"--output_model_file (-M) option. A model may be loaded from file for "
"predictions with the --input_model_file (-m) option. The "
"--input_model_file option may not be specified when the --training_file "
"option is specified. The --minimum_leaf_size (-n) parameter specifies "
"the minimum number of training points that must fall into each leaf for "
"it to be split. If --print_training_error (-e) is specified, the training"
" error will be printed."
"\n\n"
"A file containing test data may be specified with the --test_file (-T) "
"option, and if performance numbers are desired for that test set, labels "
"may be specified with the --test_labels_file (-L) option. Predictions f"
"for each test point may be stored into the file specified by the "
"--predictions_file (-p) option. Class probabilities for each prediction "
"will be stored in the file specified by the --probabilities_file (-P) "
"option.");
// Datasets.
PARAM_STRING_IN("training_file", "File containing training points.", "t", "");
PARAM_STRING_IN("labels_file", "File containing training labels.", "l", "");
PARAM_STRING_IN("test_file", "File containing test points.", "T", "");
PARAM_STRING_IN("test_labels_file", "File containing test labels, if accuracy "
"calculation is desired.", "L", "");
// Training parameters.
PARAM_INT_IN("minimum_leaf_size", "Minimum number of points in a leaf.", "n",
20);
PARAM_FLAG("print_training_error", "Print the training error.", "e");
// Output parameters.
PARAM_STRING_IN("probabilities_file", "File to save class probabilities to for"
" each test point.", "P", "");
PARAM_STRING_IN("predictions_file", "File to save class predictions to for "
"each test point.", "p", "");
/**
* This is the class that we will serialize. It is a pretty simple wrapper
* around DecisionTree<>. In order to support categoricals, it will need to
* also hold and serialize a DatasetInfo.
*/
class DecisionTreeModel
{
public:
// The tree itself, left public for direct access by this program.
DecisionTree<> tree;
// Create the model.
DecisionTreeModel() { /* Nothing to do. */ }
// Serialize the model.
template<typename Archive>
void Serialize(Archive& ar, const unsigned int /* version */)
{
ar & data::CreateNVP(tree, "tree");
}
};
// Models.
PARAM_STRING_IN("input_model_file", "File to load pre-trained decision tree "
"from, to be used with test points.", "m", "");
PARAM_STRING_IN("output_model_file", "File to save trained decision tree to.",
"M", "");
int main(int argc, char** argv)
{
CLI::ParseCommandLine(argc, argv);
// Check parameters.
if (CLI::HasParam("training_file") && CLI::HasParam("input_model_file"))
Log::Fatal << "Cannot specify both --training_file and --input_model_file!"
<< endl;
if (CLI::HasParam("training_file") && !CLI::HasParam("labels_file"))
Log::Fatal << "Must specify --labels_file when --training_file is "
<< "specified!" << endl;
if (CLI::HasParam("test_labels_file") && !CLI::HasParam("test_file"))
Log::Warn << "--test_labels_file ignored because --test_file is not passed."
<< endl;
if (!CLI::HasParam("output_model_file") &&
!CLI::HasParam("probabilities_file") &&
!CLI::HasParam("predictions_file") &&
!CLI::HasParam("test_labels_file"))
Log::Warn << "None of --output_model_file, --probabilities_file, or "
<< "--predictions_file are given, and accuracy is not being calculated;"
<< " no output will be saved!" << endl;
if (CLI::HasParam("print_training_error") && !CLI::HasParam("training_file"))
Log::Warn << "--print_training_error ignored because --training_file is not"
<< " specified." << endl;
if (!CLI::HasParam("test_file"))
{
if (CLI::HasParam("probabilities_file"))
Log::Warn << "--probabilities_file ignored because --test_file is not "
<< "specified." << endl;
if (CLI::HasParam("predictions_file"))
Log::Warn << "--predictions_file ignored because --test_file is not "
<< "specified." << endl;
}
// Load the model or build the tree.
DecisionTreeModel model;
if (CLI::HasParam("training_file"))
{
arma::mat dataset;
data::Load(CLI::GetParam<std::string>("training_file"), dataset, true);
arma::Mat<size_t> labels;
data::Load(CLI::GetParam<std::string>("labels_file"), labels, true);
// Calculate number of classes.
const size_t numClasses = arma::max(arma::max(labels)) + 1;
// Now build the tree.
const size_t minLeafSize = (size_t) CLI::GetParam<int>("minimum_leaf_size");
model.tree = DecisionTree<>(dataset, labels.row(0), numClasses,
minLeafSize);
// Do we need to print training error?
if (CLI::HasParam("print_training_error"))
{
arma::Row<size_t> predictions;
arma::mat probabilities;
model.tree.Classify(dataset, predictions, probabilities);
size_t correct = 0;
for (size_t i = 0; i < dataset.n_cols; ++i)
if (predictions[i] == labels[i])
++correct;
// Print number of correct points.
Log::Info << double(correct) / double(dataset.n_cols) * 100 << "\% "
<< "correct on training set (" << correct << " / " << dataset.n_cols
<< ")." << endl;
}
}
else
{
data::Load(CLI::GetParam<std::string>("input_model_file"), "model", model,
true);
}
// Do we need to get predictions?
if (CLI::HasParam("test_file"))
{
arma::mat testPoints;
data::Load(CLI::GetParam<std::string>("test_file"), testPoints, true);
arma::Row<size_t> predictions;
arma::mat probabilities;
model.tree.Classify(testPoints, predictions, probabilities);
// Do we need to calculate accuracy?
if (CLI::HasParam("test_labels_file"))
{
arma::Mat<size_t> testLabels;
data::Load(CLI::GetParam<std::string>("test_labels_file"), testLabels,
true);
size_t correct = 0;
for (size_t i = 0; i < testPoints.n_cols; ++i)
if (predictions[i] == testLabels[i])
++correct;
// Print number of correct points.
Log::Info << double(correct) / double(testPoints.n_cols) * 100 << "\% "
<< "correct on test set (" << correct << " / " << testPoints.n_cols
<< ")." << endl;
}
// Do we need to save outputs?
if (CLI::HasParam("predictions_file"))
data::Save(CLI::GetParam<std::string>("prediction_file"), predictions);
if (CLI::HasParam("probabilities_file"))
data::Save(CLI::GetParam<std::string>("probabilities_file"),
probabilities);
}
// Do we need to save the model?
if (CLI::HasParam("output_model_file"))
data::Save(CLI::GetParam<std::string>("output_model_file"), "model", model);
}
| 36.691244 | 80 | 0.657498 | [
"model"
] |
79777685ef5bc99fb2c20df1c581956d3b895f8a | 6,029 | cpp | C++ | poincare/src/code_point_layout.cpp | VersiraSec/epsilon-cfw | d12b44c6c6668ecc14b60d8dd098ba5c230b1291 | [
"FSFAP"
] | 1,442 | 2017-08-28T19:39:45.000Z | 2022-03-30T00:56:14.000Z | poincare/src/code_point_layout.cpp | VersiraSec/epsilon-cfw | d12b44c6c6668ecc14b60d8dd098ba5c230b1291 | [
"FSFAP"
] | 1,321 | 2017-08-28T23:03:10.000Z | 2022-03-31T19:32:17.000Z | poincare/src/code_point_layout.cpp | VersiraSec/epsilon-cfw | d12b44c6c6668ecc14b60d8dd098ba5c230b1291 | [
"FSFAP"
] | 421 | 2017-08-28T22:02:39.000Z | 2022-03-28T20:52:21.000Z | #include <poincare/code_point_layout.h>
#include <poincare/layout_helper.h>
#include <poincare/serialization_helper.h>
#include <escher/metric.h>
namespace Poincare {
// LayoutNode
void CodePointLayoutNode::moveCursorLeft(LayoutCursor * cursor, bool * shouldRecomputeLayout, bool forSelection) {
if (cursor->position() == LayoutCursor::Position::Right) {
cursor->setPosition(LayoutCursor::Position::Left);
return;
}
LayoutNode * parentNode = parent();
if (parentNode != nullptr) {
parentNode->moveCursorLeft(cursor, shouldRecomputeLayout);
}
}
void CodePointLayoutNode::moveCursorRight(LayoutCursor * cursor, bool * shouldRecomputeLayout, bool forSelection) {
if (cursor->position() == LayoutCursor::Position::Left) {
cursor->setPosition(LayoutCursor::Position::Right);
return;
}
LayoutNode * parentNode = parent();
if (parentNode != nullptr) {
parentNode->moveCursorRight(cursor, shouldRecomputeLayout);
}
}
int CodePointLayoutNode::serialize(char * buffer, int bufferSize, Preferences::PrintFloatMode floatDisplayMode, int numberOfSignificantDigits) const {
return SerializationHelper::CodePoint(buffer, bufferSize, m_codePoint);
}
bool CodePointLayoutNode::isCollapsable(int * numberOfOpenParenthesis, bool goingLeft) const {
if (*numberOfOpenParenthesis <= 0) {
if (m_codePoint == '+'
|| m_codePoint == UCodePointRightwardsArrow
|| m_codePoint == '='
|| m_codePoint == ',')
{
return false;
}
if (m_codePoint == '-') {
/* If the expression is like 3ᴇ-200, we want '-' to be collapsable.
* Otherwise, '-' is not collapsable. */
Layout thisRef = CodePointLayout(this);
Layout parent = thisRef.parent();
if (!parent.isUninitialized()) {
int indexOfThis = parent.indexOfChild(thisRef);
if (indexOfThis > 0) {
Layout leftBrother = parent.childAtIndex(indexOfThis-1);
if (leftBrother.type() == Type::CodePointLayout
&& static_cast<CodePointLayout&>(leftBrother).codePoint() == UCodePointLatinLetterSmallCapitalE)
{
return true;
}
}
}
return false;
}
if (isMultiplicationCodePoint()) {
/* We want '*' to be collapsable only if the following brother is not a
* fraction, so that the user can write intuitively "1/2 * 3/4". */
Layout thisRef = CodePointLayout(this);
Layout parent = thisRef.parent();
if (!parent.isUninitialized()) {
int indexOfThis = parent.indexOfChild(thisRef);
Layout brother;
if (indexOfThis > 0 && goingLeft) {
brother = parent.childAtIndex(indexOfThis-1);
} else if (indexOfThis < parent.numberOfChildren() - 1 && !goingLeft) {
brother = parent.childAtIndex(indexOfThis+1);
}
if (!brother.isUninitialized() && brother.type() == LayoutNode::Type::FractionLayout) {
return false;
}
}
}
}
return true;
}
bool CodePointLayoutNode::canBeOmittedMultiplicationLeftFactor() const {
if (isMultiplicationCodePoint()) {
return false;
}
return LayoutNode::canBeOmittedMultiplicationLeftFactor();
}
bool CodePointLayoutNode::canBeOmittedMultiplicationRightFactor() const {
if (m_codePoint == '!' || isMultiplicationCodePoint()) {
return false;
}
return LayoutNode::canBeOmittedMultiplicationRightFactor();
}
// Sizing and positioning
KDSize CodePointLayoutNode::computeSize() {
KDCoordinate totalHorizontalMargin = 0;
if (m_displayType == DisplayType::Implicit) {
totalHorizontalMargin += Escher::Metric::OperatorHorizontalMargin;
} else if (m_displayType == DisplayType::Operator) {
totalHorizontalMargin += 2 * Escher::Metric::OperatorHorizontalMargin;
} else if (m_displayType == DisplayType::Thousand) {
totalHorizontalMargin += Escher::Metric::ThousandsSeparatorWidth;
}
KDSize glyph = m_font->glyphSize();
return KDSize(glyph.width() + totalHorizontalMargin, glyph.height());
}
KDCoordinate CodePointLayoutNode::computeBaseline() {
return m_font->glyphSize().height()/2;
}
void CodePointLayoutNode::render(KDContext * ctx, KDPoint p, KDColor expressionColor, KDColor backgroundColor, Layout * selectionStart, Layout * selectionEnd, KDColor selectionColor) {
constexpr int bufferSize = sizeof(CodePoint)/sizeof(char) + 1; // Null-terminating char
char buffer[bufferSize];
SerializationHelper::CodePoint(buffer, bufferSize, m_codePoint);
if (m_displayType == DisplayType::Operator || m_displayType == DisplayType::Implicit) {
p = p.translatedBy(KDPoint(Escher::Metric::OperatorHorizontalMargin, 0));
}
ctx->drawString(buffer, p, m_font, expressionColor, backgroundColor);
}
bool CodePointLayoutNode::isMultiplicationCodePoint() const {
return m_codePoint == '*'
|| m_codePoint == UCodePointMultiplicationSign
|| m_codePoint == UCodePointMiddleDot;
}
bool CodePointLayoutNode::protectedIsIdenticalTo(Layout l) {
assert(l.type() == Type::CodePointLayout);
CodePointLayout & cpl = static_cast<CodePointLayout &>(l);
return codePoint() == cpl.codePoint() && font() == cpl.font();
}
void CodePointLayout::DistributeThousandDisplayType(Layout l, int start, int stop) {
if (l.type() != LayoutNode::Type::HorizontalLayout
|| stop - start < 5) {
/* Do not add a separator to a number with less than five digits.
* i.e. : 12 345 but 1234 */
return;
}
for (int i = stop - 4; i >= start; i -= 3) {
assert(l.childAtIndex(i).type() == LayoutNode::Type::CodePointLayout);
static_cast<CodePointLayoutNode *>(l.childAtIndex(i).node())->setDisplayType(CodePointLayoutNode::DisplayType::Thousand);
}
}
CodePointLayout CodePointLayout::Builder(CodePoint c, const KDFont * font) {
void * bufferNode = TreePool::sharedPool()->alloc(sizeof(CodePointLayoutNode));
CodePointLayoutNode * node = new (bufferNode) CodePointLayoutNode(c, font);
TreeHandle h = TreeHandle::BuildWithGhostChildren(node);
return static_cast<CodePointLayout &>(h);
}
}
| 37.918239 | 184 | 0.699619 | [
"render"
] |
797b20ca247f32d43e8d308f90e336386be62e6e | 4,964 | hpp | C++ | src/task_thread.hpp | ptrmu/camsim | 2d79bf2eff32a33aca81cc205cb9256937abcbed | [
"BSD-3-Clause"
] | 1 | 2020-12-12T16:51:58.000Z | 2020-12-12T16:51:58.000Z | src/task_thread.hpp | ptrmu/camsim | 2d79bf2eff32a33aca81cc205cb9256937abcbed | [
"BSD-3-Clause"
] | null | null | null | src/task_thread.hpp | ptrmu/camsim | 2d79bf2eff32a33aca81cc205cb9256937abcbed | [
"BSD-3-Clause"
] | null | null | null |
#ifndef _TASK_THREAD_HPP
#define _TASK_THREAD_HPP
#include <atomic>
#include <condition_variable>
#include <chrono>
#include <functional>
#include <future>
#include <mutex>
#include <queue>
#include <thread>
namespace task_thread
{
// Items are moved into the queue. In other words, The queue takes
// ownership of the items placed in it. TItem must be movable but
// it does not need a default constructor.
//
// Sample code:
// task_thread::ConcurrentQueue<std::unique_ptr<int>> cqi{};
// cqi.push(std::make_unique<int>(5));
// auto i6 = std::make_unique<int>(6);
// cqi.push(std::move(i6));
// std::unique_ptr<int> pi5;
// cqi.try_pop(pi5);
// std::cout << *pi5 << " " << *cqi.pop() << std::endl;
//
template<typename TItem>
class ConcurrentQueue
{
std::queue<TItem> q_{};
std::mutex m_{};
std::condition_variable cv_{};
// This class is needed in order to return
// an object with no default constructor from
// the pop() method.
class Popper
{
std::queue<TItem> &q_;
public:
Popper(std::queue<TItem> &q) : q_{q}
{}
~Popper()
{ q_.pop(); } // Do the pop after the item has been moved from the queue.
TItem pop()
{ return std::move(q_.front()); }
};
public:
void push(TItem item)
{
std::unique_lock<std::mutex> lock{m_};
q_.push(std::move(item));
lock.unlock(); // Unlock so the notify-ee can access the resource immediately
cv_.notify_one();
}
TItem pop()
{
std::unique_lock<std::mutex> lock{m_};
while (q_.empty()) {
cv_.wait_for(lock, std::chrono::milliseconds(250));
}
return Popper(q_).pop();
}
bool try_pop(TItem &popped_item)
{
std::unique_lock<std::mutex> lock{m_};
if (q_.empty()) {
return false;
}
popped_item = std::move(Popper(q_).pop());
return true;
}
bool pop_or_abort(TItem &popped_item, volatile int &abort)
{
std::unique_lock<std::mutex> lock{m_};
while (!abort && q_.empty()) {
cv_.wait_for(lock, std::chrono::milliseconds(250));
}
if (abort) {
return false;
}
popped_item = std::move(Popper(q_).pop());
return true;
}
void notify_one()
{
cv_.notify_one();
}
bool empty()
{
std::unique_lock<std::mutex> lock{m_};
return q_.empty();
}
std::size_t size()
{
std::unique_lock<std::mutex> lock{m_};
return q_.size();
}
};
// TaskThread is instantiated with a work object. The functors in the queue
// contain code that operates on the work object. The functors are executed
// on a thread. A convenient way to return results from a functor calculation
// is with another ConcurrentQueue. Or promise/future can be used to return
// results. NOTE: std::packaged_task objects are used to hold the callable
// object instead of std::function objects. This is because std::function
// is not movable. The future functionality of std::packaged_task is not used.
//
// Sample code:
// task_thread::ConcurrentQueue<int> out_q{}; // The output queue must have a longer life than the TaskThread
// auto work = std::make_unique<int>(5);
// task_thread::TaskThread<int> tti{std::move(work)};
// tti.push([&out_q](int &i)
// {
// i += 2;
// out_q.push(i);
// });
// tti.push([&out_q](int &i)
// {
// i += 3;
// out_q.push(i);
// });
// std::cout << out_q.pop() << " " << out_q.pop() << std::endl;
//
template<class TWork>
class TaskThread
{
ConcurrentQueue<std::packaged_task<void(TWork &)>> q_{};
std::unique_ptr<TWork> work_;
std::thread thread_;
volatile int abort_{0};
static void run(TaskThread *tt)
{
// Occasionally when running under the debugger, this thread will hang
// and not get started. The following line seems to fix the problem.
std::this_thread::sleep_for(std::chrono::milliseconds(1));
std::packaged_task<void(TWork &)> task{};
while (tt->q_.pop_or_abort(task, tt->abort_)) {
task(*tt->work_);
}
}
public:
TaskThread(std::unique_ptr<TWork> work) :
work_{std::move(work)}, thread_{run, this}
{}
~TaskThread()
{
abort_ = 1;
q_.notify_one();
thread_.join();
}
void abort()
{
abort_ = 1;
q_.notify_one();
}
template <class TTask>
void push(TTask task)
{
q_.push(std::packaged_task<void(TWork &)>{std::move(task)});
}
bool empty()
{
return q_.empty();
}
std::size_t tasks_in_queue()
{
return q_.size();
}
void wait_until_empty()
{
while (!empty()) {
std::this_thread::sleep_for(std::chrono::milliseconds(250));
}
}
};
}
#endif //_TASK_THREAD_HPP
| 24.574257 | 112 | 0.581789 | [
"object"
] |
7981afa3b09e52d428d65ac2471919cf6f6d1459 | 17,872 | cc | C++ | src/update_engine/ext2_metadata.cc | coreos/update_engine | b0a992aca295028f9854a9036f1e089c09539fb1 | [
"BSD-3-Clause"
] | 34 | 2015-01-29T16:35:35.000Z | 2021-11-18T20:17:00.000Z | src/update_engine/ext2_metadata.cc | coreos/update_engine | b0a992aca295028f9854a9036f1e089c09539fb1 | [
"BSD-3-Clause"
] | 81 | 2015-01-30T17:41:45.000Z | 2018-07-12T09:16:15.000Z | src/update_engine/ext2_metadata.cc | flatcar-linux/update_engine | 748eb99b18b67747f2e047327e9f2a18aa09d3b5 | [
"BSD-3-Clause"
] | 39 | 2015-04-08T23:49:19.000Z | 2022-03-15T12:10:45.000Z | // Copyright (c) 2012 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 <algorithm>
#include <string>
#include <vector>
#include <et/com_err.h>
#include <ext2fs/ext2_io.h>
#include <ext2fs/ext2fs.h>
#include "files/scoped_file.h"
#include "strings/string_printf.h"
#include "update_engine/bzip.h"
#include "update_engine/delta_diff_generator.h"
#include "update_engine/ext2_metadata.h"
#include "update_engine/extent_ranges.h"
#include "update_engine/graph_utils.h"
#include "update_engine/utils.h"
using std::min;
using std::string;
using std::vector;
using strings::StringPrintf;
namespace chromeos_update_engine {
namespace {
const size_t kBlockSize = 4096;
typedef DeltaDiffGenerator::Block Block;
// Utility class to close a file system
class ScopedExt2fsCloser {
public:
explicit ScopedExt2fsCloser(ext2_filsys filsys) : filsys_(filsys) {}
~ScopedExt2fsCloser() { ext2fs_close(filsys_); }
private:
ext2_filsys filsys_;
DISALLOW_COPY_AND_ASSIGN(ScopedExt2fsCloser);
};
// Read data from the specified extents.
bool ReadExtentsData(const ext2_filsys fs,
const vector<Extent>& extents,
vector<char>* data) {
// Resize the data buffer to hold all data in the extents
size_t num_data_blocks = 0;
for (const Extent& extent : extents) {
num_data_blocks += extent.num_blocks();
}
data->resize(num_data_blocks * kBlockSize);
// Read in the data blocks
const size_t kMaxReadBlocks = 256;
vector<Block>::size_type blocks_copied_count = 0;
for (const Extent& extent : extents) {
vector<Block>::size_type blocks_read = 0;
while (blocks_read < extent.num_blocks()) {
const int copy_block_cnt =
min(kMaxReadBlocks,
static_cast<size_t>(
extent.num_blocks() - blocks_read));
TEST_AND_RETURN_FALSE_ERRCODE(
io_channel_read_blk(fs->io,
extent.start_block() + blocks_read,
copy_block_cnt,
&(*data)[blocks_copied_count * kBlockSize]));
blocks_read += copy_block_cnt;
blocks_copied_count += copy_block_cnt;
}
}
return true;
}
// Compute the bsdiff between two metadata blobs.
bool ComputeMetadataBsdiff(const vector<char>& old_metadata,
const vector<char>& new_metadata,
vector<char>* bsdiff_delta) {
const string kTempFileTemplate("/tmp/CrAU_temp_data.XXXXXX");
// Write the metadata buffers to temporary files
int old_fd;
string temp_old_file_path;
TEST_AND_RETURN_FALSE(
utils::MakeTempFile(kTempFileTemplate, &temp_old_file_path, &old_fd));
TEST_AND_RETURN_FALSE(old_fd >= 0);
ScopedPathUnlinker temp_old_file_path_unlinker(temp_old_file_path);
files::ScopedFD old_fd_closer(old_fd);
TEST_AND_RETURN_FALSE(utils::WriteAll(old_fd,
&old_metadata[0],
old_metadata.size()));
int new_fd;
string temp_new_file_path;
TEST_AND_RETURN_FALSE(
utils::MakeTempFile(kTempFileTemplate, &temp_new_file_path, &new_fd));
TEST_AND_RETURN_FALSE(new_fd >= 0);
ScopedPathUnlinker temp_new_file_path_unlinker(temp_new_file_path);
files::ScopedFD new_fd_closer(new_fd);
TEST_AND_RETURN_FALSE(utils::WriteAll(new_fd,
&new_metadata[0],
new_metadata.size()));
// Perform bsdiff on these files
TEST_AND_RETURN_FALSE(
DeltaDiffGenerator::BsdiffFiles(temp_old_file_path,
temp_new_file_path,
bsdiff_delta));
return true;
}
// Add the specified metadata extents to the graph and blocks vector.
bool AddMetadataExtents(Graph* graph,
vector<Block>* blocks,
const ext2_filsys fs_old,
const ext2_filsys fs_new,
const string& metadata_name,
const vector<Extent>& extents,
int data_fd,
off_t* data_file_size) {
vector<char> data; // Data blob that will be written to delta file.
InstallOperation op;
{
// Read in the metadata blocks from the old and new image.
vector<char> old_data;
TEST_AND_RETURN_FALSE(ReadExtentsData(fs_old, extents, &old_data));
vector<char> new_data;
TEST_AND_RETURN_FALSE(ReadExtentsData(fs_new, extents, &new_data));
// Determine the best way to compress this.
vector<char> new_data_bz;
TEST_AND_RETURN_FALSE(BzipCompress(new_data, &new_data_bz));
CHECK(!new_data_bz.empty());
size_t current_best_size = 0;
if (new_data.size() <= new_data_bz.size()) {
op.set_type(InstallOperation_Type_REPLACE);
current_best_size = new_data.size();
data = new_data;
} else {
op.set_type(InstallOperation_Type_REPLACE_BZ);
current_best_size = new_data_bz.size();
data = new_data_bz;
}
if (old_data == new_data) {
// No change in data.
op.set_type(InstallOperation_Type_MOVE);
current_best_size = 0;
data.clear();
} else {
// Try bsdiff of old to new data
vector<char> bsdiff_delta;
TEST_AND_RETURN_FALSE(ComputeMetadataBsdiff(old_data,
new_data,
&bsdiff_delta));
CHECK_GT(bsdiff_delta.size(), static_cast<vector<char>::size_type>(0));
if (bsdiff_delta.size() < current_best_size) {
op.set_type(InstallOperation_Type_BSDIFF);
current_best_size = bsdiff_delta.size();
data = bsdiff_delta;
}
}
CHECK_EQ(data.size(), current_best_size);
// Set the source and dest extents to be the same since the filesystem
// structures are identical
if (op.type() == InstallOperation_Type_MOVE ||
op.type() == InstallOperation_Type_BSDIFF) {
DeltaDiffGenerator::StoreExtents(extents, op.mutable_src_extents());
op.set_src_length(old_data.size());
}
DeltaDiffGenerator::StoreExtents(extents, op.mutable_dst_extents());
op.set_dst_length(new_data.size());
}
// Write data to output file
if (op.type() != InstallOperation_Type_MOVE) {
op.set_data_offset(*data_file_size);
op.set_data_length(data.size());
}
TEST_AND_RETURN_FALSE(utils::WriteAll(data_fd, &data[0], data.size()));
*data_file_size += data.size();
// Now, insert into graph and blocks vector
graph->resize(graph->size() + 1);
Vertex::Index vertex = graph->size() - 1;
(*graph)[vertex].op = op;
CHECK((*graph)[vertex].op.has_type());
(*graph)[vertex].file_name = metadata_name;
TEST_AND_RETURN_FALSE(DeltaDiffGenerator::AddInstallOpToBlocksVector(
(*graph)[vertex].op,
*graph,
vertex,
blocks));
return true;
}
// Reads the file system metadata extents.
bool ReadFilesystemMetadata(Graph* graph,
vector<Block>* blocks,
const ext2_filsys fs_old,
const ext2_filsys fs_new,
int data_fd,
off_t* data_file_size) {
LOG(INFO) << "Processing <fs-metadata>";
// Read all the extents that belong to the main file system metadata.
// The metadata blocks are at the start of each block group and goes
// until the end of the inode table.
for (dgrp_t bg = 0; bg < fs_old->group_desc_count; bg++) {
struct ext2_group_desc* group_desc = ext2fs_group_desc(fs_old,
fs_old->group_desc,
bg);
__u32 num_metadata_blocks = (group_desc->bg_inode_table +
fs_old->inode_blocks_per_group) -
(bg * fs_old->super->s_blocks_per_group);
__u32 bg_start_block = bg * fs_old->super->s_blocks_per_group;
// Due to bsdiff slowness, we're going to break each block group down
// into metadata chunks and feed them to bsdiff.
__u32 num_chunks = 10;
__u32 blocks_per_chunk = num_metadata_blocks / num_chunks;
__u32 curr_block = bg_start_block;
for (__u32 chunk = 0; chunk < num_chunks; chunk++) {
Extent extent;
if (chunk < num_chunks - 1) {
extent = ExtentForRange(curr_block, blocks_per_chunk);
} else {
extent = ExtentForRange(curr_block,
bg_start_block + num_metadata_blocks -
curr_block);
}
vector<Extent> extents;
extents.push_back(extent);
string metadata_name = StringPrintf("<fs-bg-%d-%d-metadata>",
bg, chunk);
LOG(INFO) << "Processing " << metadata_name;
TEST_AND_RETURN_FALSE(AddMetadataExtents(graph,
blocks,
fs_old,
fs_new,
metadata_name,
extents,
data_fd,
data_file_size));
curr_block += blocks_per_chunk;
}
}
return true;
}
// Processes all blocks belonging to an inode
int ProcessInodeAllBlocks(ext2_filsys fs,
blk_t* blocknr,
e2_blkcnt_t blockcnt,
blk_t ref_blk,
int ref_offset,
void* priv) {
vector<Extent>* extents = static_cast<vector<Extent>*>(priv);
graph_utils::AppendBlockToExtents(extents, *blocknr);
return 0;
}
// Processes only indirect, double indirect or triple indirect metadata
// blocks belonging to an inode
int ProcessInodeMetadataBlocks(ext2_filsys fs,
blk_t* blocknr,
e2_blkcnt_t blockcnt,
blk_t ref_blk,
int ref_offset,
void* priv) {
vector<Extent>* extents = static_cast<vector<Extent>*>(priv);
if (blockcnt < 0) {
graph_utils::AppendBlockToExtents(extents, *blocknr);
}
return 0;
}
// Read inode metadata blocks.
bool ReadInodeMetadata(Graph* graph,
vector<Block>* blocks,
const ext2_filsys fs_old,
const ext2_filsys fs_new,
int data_fd,
off_t* data_file_size) {
TEST_AND_RETURN_FALSE_ERRCODE(ext2fs_read_inode_bitmap(fs_old));
TEST_AND_RETURN_FALSE_ERRCODE(ext2fs_read_inode_bitmap(fs_new));
ext2_inode_scan iscan;
TEST_AND_RETURN_FALSE_ERRCODE(ext2fs_open_inode_scan(fs_old, 0, &iscan));
ext2_ino_t ino;
ext2_inode old_inode;
while (true) {
// Get the next inode on both file systems
errcode_t error = ext2fs_get_next_inode(iscan, &ino, &old_inode);
// If we get an error enumerating the inodes, we'll just log the error
// and exit from our loop which will eventually return a success code
// back to the caller. The inode blocks that we cannot account for will
// be handled by DeltaDiffGenerator::ReadUnwrittenBlocks().
if (error) {
LOG(ERROR) << "Failed to retrieve next inode (" << error << ")";
break;
}
if (ino == 0) {
break;
}
if (ino == EXT2_RESIZE_INO) {
continue;
}
ext2_inode new_inode;
error = ext2fs_read_inode(fs_new, ino, &new_inode);
if (error) {
LOG(ERROR) << "Failed to retrieve new inode (" << error << ")";
continue;
}
// Skip inodes that are not in use
if (!ext2fs_test_inode_bitmap(fs_old->inode_map, ino) ||
!ext2fs_test_inode_bitmap(fs_new->inode_map, ino)) {
continue;
}
// Skip inodes that have no data blocks
if (old_inode.i_blocks == 0 || new_inode.i_blocks == 0) {
continue;
}
// Skip inodes that are not the same type
bool is_old_dir = (ext2fs_check_directory(fs_old, ino) == 0);
bool is_new_dir = (ext2fs_check_directory(fs_new, ino) == 0);
if (is_old_dir != is_new_dir) {
continue;
}
// Process the inodes metadata blocks
// For normal files, metadata blocks are indirect, double indirect
// and triple indirect blocks (no data blocks). For directories and
// the journal, all blocks are considered metadata blocks.
LOG(INFO) << "Processing inode " << ino << " metadata";
bool all_blocks = ((ino == EXT2_JOURNAL_INO) || is_old_dir || is_new_dir);
vector<Extent> old_extents;
error = ext2fs_block_iterate2(fs_old, ino, 0, NULL,
all_blocks ? ProcessInodeAllBlocks :
ProcessInodeMetadataBlocks,
&old_extents);
if (error) {
LOG(ERROR) << "Failed to enumerate old inode " << ino
<< " blocks (" << error << ")";
continue;
}
vector<Extent> new_extents;
error = ext2fs_block_iterate2(fs_new, ino, 0, NULL,
all_blocks ? ProcessInodeAllBlocks :
ProcessInodeMetadataBlocks,
&new_extents);
if (error) {
LOG(ERROR) << "Failed to enumerate new inode " << ino
<< " blocks (" << error << ")";
continue;
}
// Skip inode if there are no metadata blocks
if (old_extents.size() == 0 || new_extents.size() == 0) {
continue;
}
// Make sure the two inodes have the same metadata blocks
if (old_extents.size() != new_extents.size()) {
continue;
}
bool same_metadata_extents = true;
vector<Extent>::iterator it_old;
vector<Extent>::iterator it_new;
for (it_old = old_extents.begin(),
it_new = new_extents.begin();
it_old != old_extents.end() && it_new != new_extents.end();
it_old++, it_new++) {
if (it_old->start_block() != it_new->start_block() ||
it_old->num_blocks() != it_new->num_blocks()) {
same_metadata_extents = false;
break;
}
}
if (!same_metadata_extents) {
continue;
}
// We have identical inode metadata blocks, we can now add them to
// our graph and blocks vector
string metadata_name = StringPrintf("<fs-inode-%d-metadata>", ino);
TEST_AND_RETURN_FALSE(AddMetadataExtents(graph,
blocks,
fs_old,
fs_new,
metadata_name,
old_extents,
data_fd,
data_file_size));
}
ext2fs_close_inode_scan(iscan);
return true;
}
} // namespace {}
// Reads metadata from old image and new image and determines
// the smallest way to encode the metadata for the diff.
// If there's no change in the metadata, it creates a MOVE
// operation. If there is a change, the smallest of REPLACE, REPLACE_BZ,
// or BSDIFF wins. It writes the diff to data_fd and updates data_file_size
// accordingly. It also adds the required operation to the graph and adds the
// metadata extents to blocks.
// Returns true on success.
bool Ext2Metadata::DeltaReadMetadata(Graph* graph,
vector<Block>* blocks,
const string& old_image,
const string& new_image,
int data_fd,
off_t* data_file_size) {
// Open the two file systems.
ext2_filsys fs_old;
TEST_AND_RETURN_FALSE_ERRCODE(ext2fs_open(old_image.c_str(), 0, 0, 0,
unix_io_manager, &fs_old));
ScopedExt2fsCloser fs_old_closer(fs_old);
ext2_filsys fs_new;
TEST_AND_RETURN_FALSE_ERRCODE(ext2fs_open(new_image.c_str(), 0, 0, 0,
unix_io_manager, &fs_new));
ScopedExt2fsCloser fs_new_closer(fs_new);
// Make sure these two file systems are the same.
// If they are not the same, the metadata blocks will be packaged up in its
// entirety by ReadUnwrittenBlocks().
if (fs_old->blocksize != fs_new->blocksize ||
fs_old->fragsize != fs_new->fragsize ||
fs_old->group_desc_count != fs_new->group_desc_count ||
fs_old->inode_blocks_per_group != fs_new->inode_blocks_per_group ||
fs_old->super->s_inodes_count != fs_new->super->s_inodes_count ||
fs_old->super->s_blocks_count != fs_new->super->s_blocks_count) {
return true;
}
// Process the main file system metadata (superblock, inode tables, etc)
TEST_AND_RETURN_FALSE(ReadFilesystemMetadata(graph,
blocks,
fs_old,
fs_new,
data_fd,
data_file_size));
// Process each inode metadata blocks.
TEST_AND_RETURN_FALSE(ReadInodeMetadata(graph,
blocks,
fs_old,
fs_new,
data_fd,
data_file_size));
return true;
}
}; // namespace chromeos_update_engine
| 36.032258 | 78 | 0.582867 | [
"vector"
] |
798231e1595310a316b83dd0010e1b96cd594655 | 540 | cpp | C++ | algorithms/RotateImage/solution.cpp | senlinzhan/algorithms | 8a8ba89844d645f3e0461e81e25c0bb44b837521 | [
"MIT"
] | 2 | 2017-12-02T05:47:10.000Z | 2018-01-08T08:43:15.000Z | algorithms/RotateImage/solution.cpp | senlinzhan/algorithms | 8a8ba89844d645f3e0461e81e25c0bb44b837521 | [
"MIT"
] | null | null | null | algorithms/RotateImage/solution.cpp | senlinzhan/algorithms | 8a8ba89844d645f3e0461e81e25c0bb44b837521 | [
"MIT"
] | 1 | 2018-07-06T02:14:18.000Z | 2018-07-06T02:14:18.000Z | class Solution {
public:
void rotate(vector<vector<int>>& matrix)
{
int size = matrix.size();
for (int i = 0; i < size - 1; i++)
{
for (int j = 0; j < size - i - 1; j++)
{
std::swap(matrix[i][j], matrix[size - j - 1][size - i - 1]);
}
}
for (int i = 0; i < size / 2; i++)
{
for (int j = 0; j < size; j++)
{
std::swap(matrix[i][j], matrix[size - i - 1][j]);
}
}
}
};
| 22.5 | 76 | 0.348148 | [
"vector"
] |
7983e86fe8f46686dba2060fed54bd542489c233 | 509 | cpp | C++ | OJ/codeforces.com/500A.cpp | webturing/CPlusPlus | 6b9c671b0c9a7c0d24d937610bf54e9aec9a5a1f | [
"AFL-2.0"
] | 14 | 2018-06-21T14:41:26.000Z | 2021-12-19T14:43:51.000Z | OJ/codeforces.com/500A.cpp | webturing/CPlusPlus | 6b9c671b0c9a7c0d24d937610bf54e9aec9a5a1f | [
"AFL-2.0"
] | null | null | null | OJ/codeforces.com/500A.cpp | webturing/CPlusPlus | 6b9c671b0c9a7c0d24d937610bf54e9aec9a5a1f | [
"AFL-2.0"
] | 2 | 2020-04-20T11:16:53.000Z | 2021-01-02T15:58:35.000Z | //
// Created by jal on 2019-05-25.
//
#include <bits/stdc++.h>
using namespace std;
int main(){
int n, t;
cin >> n >> t;
t--;
vector<int>v(n);
for(int i = 0; i < n-1; i++){
cin >> v[i];
}
int i = 0;
int flag = 0;
while(i < n-1){
if(i == t){
flag = 1;
break;
}
i += v[i];
}
if(i == t){
flag = 1;
}
if(flag == 1){
cout << "YES" << endl;
}else{
cout << "NO" << endl;
}
} | 15.90625 | 33 | 0.353635 | [
"vector"
] |
798aec5c0616922dc193b2171d187580b4876aef | 366 | cpp | C++ | CMinus/CMinus/type/type_with_storage.cpp | benbraide/CMinus | 3b845e0bc22840b549f108bf6600f1f34d865e7b | [
"MIT"
] | null | null | null | CMinus/CMinus/type/type_with_storage.cpp | benbraide/CMinus | 3b845e0bc22840b549f108bf6600f1f34d865e7b | [
"MIT"
] | null | null | null | CMinus/CMinus/type/type_with_storage.cpp | benbraide/CMinus | 3b845e0bc22840b549f108bf6600f1f34d865e7b | [
"MIT"
] | null | null | null | #include "type_with_storage.h"
cminus::type::with_storage::with_storage(const std::string &name, logic::storage::object *parent)
: storage_base_type(name, parent){}
cminus::type::with_storage::~with_storage() = default;
void cminus::type::with_storage::print(logic::runtime &runtime, bool is_qualified) const{
storage_base_type::print(runtime, is_qualified);
}
| 33.272727 | 97 | 0.76776 | [
"object"
] |
799131fd6796ac866b46396581ede99c8f87e93b | 7,601 | cpp | C++ | src/amalg/Amalg.cpp | raptoravis/two | 4366fcf8b3072d0233eb8e1e91ac1105194f60f5 | [
"Zlib"
] | 578 | 2019-05-04T09:09:42.000Z | 2022-03-27T23:02:21.000Z | src/amalg/Amalg.cpp | raptoravis/two | 4366fcf8b3072d0233eb8e1e91ac1105194f60f5 | [
"Zlib"
] | 14 | 2019-05-11T14:34:56.000Z | 2021-02-02T07:06:46.000Z | src/amalg/Amalg.cpp | raptoravis/two | 4366fcf8b3072d0233eb8e1e91ac1105194f60f5 | [
"Zlib"
] | 42 | 2019-05-11T16:04:19.000Z | 2022-01-24T02:21:43.000Z | #include <stl/string.h>
#include <stl/set.h>
#include <stl/map.h>
#include <stl/algorithm.h>
#include <infra/Vector.h>
#include <infra/File.h>
#include <infra/StringOps.h>
#include <amalg/Amalg.h>
#include <stl/string.hpp>
#include <stl/vector.hpp>
#include <stl/unordered_set.hpp>
#include <stl/unordered_map.hpp>
#include <cstdio>
namespace stl
{
template class unordered_set<string>;
}
namespace two
{
class Amalgamator
{
public:
class Module
{
public:
Module(const string& root, const string& dist, const string& nemespace, const string& name)
: m_root(root), m_dist(dist), m_nemespace(nemespace), m_name(name), m_dotname(replace(name, "-", "."))
{
m_preproc_name = to_upper(nemespace + "_" + replace(m_dotname, ".", "_"));
}
string m_root;
string m_dist;
string m_nemespace;
string m_name;
string m_dotname;
vector<string> m_files;
string m_preproc_name;
set<string> m_included_h;
set<string> m_included_cpp;
string m_h;
string m_cpp;
//set<string> m_includes_h;
//set<string> m_includes_cpp;
set<string> m_deps_h;
set<string> m_deps_cpp;
string dest_h() { return m_nemespace + "/" + m_dotname + ".h"; }
string dest_cpp() { return m_nemespace + "/" + m_dotname + ".cpp"; }
string dest_hpp() { return m_nemespace + "/" + m_dotname + ".hpp"; }
string include(bool header_only) { return header_only ? this->dest_hpp() : this->dest_h(); }
};
vector<string> m_filter;
vector<Module> m_modules;
bool filter(const string& line)
{
if(line == "#pragma once") return true;
return has(m_filter, line);
}
struct Include { Module* module = nullptr; string file; };
Include module_include(const string& line)
{
string clean = replace(replace(line, " ", ""), "\t", "");
if(clean.substr(0, 8) != "#include")
return {};
string file = line.substr(line.find("<") + 1, line.rfind(">") - line.find("<") - 1);
for(Module& module : m_modules)
if(has(module.m_files, file))
{
return { &module, file };
}
return { nullptr, file };
}
void process_cpp(Module& module, const string& file, bool header_only)
{
if(module.m_included_cpp.find(file) != module.m_included_cpp.end())
return;
printf("processing file %s\n", file.c_str());
module.m_included_cpp.insert(file);
auto read_line = [&](const string& line)
{
Include include = module_include(line);
if(include.module)
{
if(file_extension(include.file) == "h"
|| file_extension(include.file) == "hpp")
module.m_deps_cpp.insert(include.module->include(header_only));
else
process_cpp(module, include.file, header_only);
}
//else if(include.file != "")
// module.m_includes_cpp.insert(include.file);
else if(filter(line))
;
else
module.m_cpp += line + "\n";
return true;
};
read_text_file(module.m_root + "/" + file, read_line);
}
void process_h(Module& module, const string& file, bool header_only)
{
if(module.m_included_h.find(file) != module.m_included_h.end())
return;
printf("processing file %s\n", file.c_str());
module.m_included_h.insert(file);
auto read_line = [&](const string& line)
{
Include include = module_include(line);
if(include.module == &module)
process_h(module, include.file, header_only);
else if(include.module)
module.m_deps_h.insert(include.module->include(header_only));
//else if(include.file != "")
// module.m_includes_h.insert(include.file);
else if(filter(line))
;
else
module.m_h += line + "\n";
return true;
};
read_text_file(module.m_root + "/" + file, read_line);
}
void add(const string& root, const string& dist, const string& nemespace, const string& name, const string& subdir, bool refl = true)
{
Module& m = push(m_modules, root, dist, nemespace, name);
auto add_file = [&](const string& file) { m.m_files.push_back(subdir + "/" + file); };
visit_files_recursive(root + "/" + subdir, add_file);
if(refl)
{
Module& refl = push(m_modules, root, dist, nemespace, name + ".refl");
string meta_h = "meta/" + replace(name, "-", ".") + ".meta.h";
string conv_h = "meta/" + replace(name, "-", ".") + ".conv.h";
string meta_cpp = "meta/" + replace(name, "-", ".") + ".meta.cpp";
refl.m_files = { meta_h, conv_h, meta_cpp };
}
}
void run(bool header_only)
{
for(Module& module : m_modules)
this->process(module, header_only);
}
void process(Module& module, bool header_only)
{
module.m_h = {};
module.m_cpp = {};
module.m_included_h = {};
module.m_included_cpp = {};
module.m_deps_h = {};
module.m_deps_cpp = {};
for(const string& file : module.m_files)
{
string ext = file_extension(file);
if(has({ "cpp", "cxx", "cc", "c" }, ext))
process_cpp(module, file, header_only);
if(has({ "hpp", "hh", "h" }, ext))
process_h(module, file, header_only);
}
auto write_includes = [&](const set<string>& includes, bool pragma, string& file)
{
string header;
if(pragma)
header += "#pragma once\n\n";
for(string include : includes)
header += "#include <" + include + ">" + "\n";
header += "\n";
file.insert(size_t(0), header);
};
//write_includes(module.m_includes_h, module.m_h);
//write_includes(module.m_includes_cpp, module.m_cpp);
write_includes(module.m_deps_h, true, module.m_h);
write_includes(module.m_deps_cpp, false, module.m_cpp);
if(header_only)
{
string hpp = module.m_h;
hpp += "\n";
hpp += "#ifdef " + module.m_preproc_name + "_IMPL\n";
hpp += module.m_cpp;
hpp += "#endif\n";
update_file(module.m_dist + "/" + module.dest_hpp(), hpp);
}
else
{
update_file(module.m_dist + "/" + module.dest_h(), module.m_h);
update_file(module.m_dist + "/" + module.dest_cpp(), module.m_cpp);
}
}
};
}
using namespace two;
int main(int argc, char *argv[])
{
vector<string> filter = {
"// Copyright (c) 2019 Hugo Amiard hugo.amiard@laposte.net",
"// This software is provided 'as-is' under the zlib License, see the LICENSE.txt file.",
"// This notice and the license may not be removed or altered from any source distribution.",
"// This software is licensed under the terms of the GNU General Public License v3.0.",
"// See the attached LICENSE.txt file or https://www.gnu.org/licenses/gpl-3.0.en.html.",
};
string twosrc = "d:/Documents/Programmation/toy/two/src";
string twodist = "d:/Documents/Programmation/toy/two/dist";
string toysrc = "d:/Documents/Programmation/toy/src";
string toydist = "d:/Documents/Programmation/toy/dist";
Amalgamator amalgamator;
amalgamator.m_filter = filter;
for(string module : { "infra", "jobs", "type", "tree", "pool", "refl", "ecs", "srlz", "math", "geom", "noise", "wfc", "fract", "lang", "ctx", "ui", "uio", "snd" })
amalgamator.add(twosrc, twodist, "two", module, module);
for(string module : { "ctx-glfw", "ctx-wasm", "ctx-win" })
amalgamator.add(twosrc, twodist, "two", module, module);
for(string module : { "ui-vg", "ui-nvg" })
amalgamator.add(twosrc, twodist, "two", module, module);
for(string module : { "bgfx", "gfx", "gltf", "gfx-pbr", "gfx-obj", "gfx-gltf", "gfx-ui", "gfx-edit", "tool", "wfc-gfx", "frame" })
amalgamator.add(twosrc, twodist, "two", module, module);
for(string module : { "util", "core", "visu", "block", "edit", "shell" })
amalgamator.add(toysrc, toydist, "toy", module, module);
//amalgamator.run(true);
amalgamator.run(false);
return 0;
}
| 28.04797 | 164 | 0.634653 | [
"vector"
] |
7992938eafb3ff348358cf1ec9b353801ffc10a7 | 13,523 | cpp | C++ | src/indexing/test/indexing.cpp | lynshi/CCF | a651fb542eab3f53431bf791d6d31c81d0d6ee51 | [
"Apache-2.0"
] | null | null | null | src/indexing/test/indexing.cpp | lynshi/CCF | a651fb542eab3f53431bf791d6d31c81d0d6ee51 | [
"Apache-2.0"
] | null | null | null | src/indexing/test/indexing.cpp | lynshi/CCF | a651fb542eab3f53431bf791d6d31c81d0d6ee51 | [
"Apache-2.0"
] | null | null | null | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the Apache 2.0 License.
#include "ccf/indexing/strategies/seqnos_by_key_in_memory.h"
#include "consensus/aft/raft.h"
#include "consensus/aft/test/logging_stub.h"
#include "ds/test/stub_writer.h"
#include "indexing/historical_transaction_fetcher.h"
#include "indexing/test/common.h"
#include "node/share_manager.h"
#define DOCTEST_CONFIG_IMPLEMENT_WITH_MAIN
#include <doctest/doctest.h>
// Transitively see a header that tries to use ThreadMessaging, so need to
// initialise here
threading::ThreadMessaging threading::ThreadMessaging::thread_messaging;
std::atomic<uint16_t> threading::ThreadMessaging::thread_count = 1;
using IndexA = ccf::indexing::strategies::SeqnosByKey_InMemory<decltype(map_a)>;
using LazyIndexA = ccf::indexing::LazyStrategy<IndexA>;
using IndexB = ccf::indexing::strategies::SeqnosByKey_InMemory<decltype(map_b)>;
constexpr size_t certificate_validity_period_days = 365;
using namespace std::literals;
auto valid_from = crypto::OpenSSL::to_x509_time_string(
std::chrono::system_clock::to_time_t(std::chrono::system_clock::now() - 24h));
auto valid_to = crypto::compute_cert_valid_to_string(
valid_from, certificate_validity_period_days);
template <typename AA>
void run_tests(
const std::function<void()>& tick_until_caught_up,
kv::Store& kv_store,
ccf::indexing::Indexer& indexer,
ExpectedSeqNos& seqnos_hello,
ExpectedSeqNos& seqnos_saluton,
ExpectedSeqNos& seqnos_1,
ExpectedSeqNos& seqnos_2,
const std::shared_ptr<AA> index_a,
const std::shared_ptr<IndexB> index_b)
{
REQUIRE(index_a != nullptr);
REQUIRE(index_b != nullptr);
if constexpr (std::is_same_v<AA, LazyIndexA>)
{
index_a->extend_index_to(kv_store.current_txid());
}
tick_until_caught_up();
{
REQUIRE(check_seqnos(seqnos_1, index_b->get_all_write_txs(1)));
REQUIRE(check_seqnos(seqnos_2, index_b->get_all_write_txs(2)));
}
{
INFO("Sub-ranges can be requested");
const auto current_seqno = kv_store.current_version();
const auto sub_range_start = current_seqno / 5;
const auto sub_range_end = current_seqno / 3;
const auto invalid_seqno_a = current_seqno + 1;
const auto invalid_seqno_b = current_seqno * 2;
const auto full_range_hello =
index_a->get_write_txs_in_range("hello", 0, current_seqno);
REQUIRE(full_range_hello.has_value());
REQUIRE(check_seqnos(seqnos_hello, full_range_hello));
const auto sub_range_saluton = index_a->get_write_txs_in_range(
"saluton", sub_range_start, sub_range_end);
REQUIRE(sub_range_saluton.has_value());
REQUIRE(check_seqnos(seqnos_saluton, sub_range_saluton, false));
const auto max_seqnos = 3;
const auto truncated_sub_range_saluton = index_a->get_write_txs_in_range(
"saluton", sub_range_start, sub_range_end, max_seqnos);
REQUIRE(truncated_sub_range_saluton.has_value());
REQUIRE(truncated_sub_range_saluton->size() == max_seqnos);
REQUIRE(check_seqnos(seqnos_saluton, truncated_sub_range_saluton, false));
REQUIRE(check_seqnos(
seqnos_1, index_b->get_write_txs_in_range(1, 0, current_seqno)));
REQUIRE(check_seqnos(
seqnos_2,
index_b->get_write_txs_in_range(2, sub_range_start, sub_range_end),
false));
REQUIRE_FALSE(
index_a->get_write_txs_in_range("hello", 0, invalid_seqno_a).has_value());
REQUIRE_FALSE(
index_a
->get_write_txs_in_range("unused_key", sub_range_start, invalid_seqno_b)
.has_value());
REQUIRE_FALSE(
index_b->get_write_txs_in_range(1, current_seqno, invalid_seqno_a)
.has_value());
REQUIRE_FALSE(
index_b->get_write_txs_in_range(42, invalid_seqno_a, invalid_seqno_b)
.has_value());
}
{
INFO("Both indexes continue to be updated with new entries");
REQUIRE(create_transactions(
kv_store, seqnos_hello, seqnos_saluton, seqnos_1, seqnos_2, 100));
if constexpr (std::is_same_v<AA, LazyIndexA>)
{
index_a->extend_index_to(kv_store.current_txid());
}
tick_until_caught_up();
REQUIRE(check_seqnos(seqnos_hello, index_a->get_all_write_txs("hello")));
REQUIRE(
check_seqnos(seqnos_saluton, index_a->get_all_write_txs("saluton")));
REQUIRE(check_seqnos(seqnos_1, index_b->get_all_write_txs(1)));
REQUIRE(check_seqnos(seqnos_2, index_b->get_all_write_txs(2)));
}
}
// Uses stub classes to test just indexing logic in isolation
TEST_CASE("basic indexing" * doctest::test_suite("indexing"))
{
kv::Store kv_store;
auto consensus = std::make_shared<AllCommittableConsensus>();
kv_store.set_consensus(consensus);
auto fetcher = std::make_shared<TestTransactionFetcher>();
ccf::indexing::Indexer indexer(fetcher);
auto encryptor = std::make_shared<kv::NullTxEncryptor>();
kv_store.set_encryptor(encryptor);
REQUIRE_THROWS(indexer.install_strategy(nullptr));
auto index_a = std::make_shared<IndexA>(map_a);
REQUIRE(indexer.install_strategy(index_a));
REQUIRE_FALSE(indexer.install_strategy(index_a));
static constexpr auto num_transactions =
ccf::indexing::Indexer::MAX_REQUESTABLE * 3;
ExpectedSeqNos seqnos_hello, seqnos_saluton, seqnos_1, seqnos_2;
REQUIRE(create_transactions(
kv_store, seqnos_hello, seqnos_saluton, seqnos_1, seqnos_2));
auto tick_until_caught_up = [&]() {
while (indexer.update_strategies(step_time, kv_store.current_txid()) ||
!fetcher->requested.empty())
{
// Do the fetch, simulating an asynchronous fetch by the historical query
// system
for (auto seqno : fetcher->requested)
{
REQUIRE(consensus->replica.size() >= seqno);
const auto& entry = std::get<1>(consensus->replica[seqno - 1]);
fetcher->fetched_stores[seqno] =
fetcher->deserialise_transaction(seqno, entry->data(), entry->size());
}
fetcher->requested.clear();
}
};
tick_until_caught_up();
{
INFO("Confirm that pre-existing strategy was populated already");
REQUIRE(check_seqnos(seqnos_hello, index_a->get_all_write_txs("hello")));
REQUIRE(
check_seqnos(seqnos_saluton, index_a->get_all_write_txs("saluton")));
}
INFO(
"Indexes can be installed later, and will be populated after enough "
"ticks");
auto index_b = std::make_shared<IndexB>(map_b);
REQUIRE(indexer.install_strategy(index_b));
REQUIRE_FALSE(indexer.install_strategy(index_b));
auto current_ = kv_store.current_txid();
ccf::TxID current{current_.term, current_.version};
REQUIRE(index_a->get_indexed_watermark() == current);
REQUIRE(index_b->get_indexed_watermark() == ccf::TxID());
tick_until_caught_up();
REQUIRE(index_a->get_indexed_watermark() == current);
REQUIRE(index_b->get_indexed_watermark() == current);
run_tests(
tick_until_caught_up,
kv_store,
indexer,
seqnos_hello,
seqnos_saluton,
seqnos_1,
seqnos_2,
index_a,
index_b);
}
kv::Version rekey(
kv::Store& kv_store,
const std::shared_ptr<ccf::LedgerSecrets>& ledger_secrets)
{
// This isn't really used, but is needed for ShareManager, so can be recreated
// each time here
ccf::NetworkState network;
network.ledger_secrets = ledger_secrets;
ccf::ShareManager share_manager(network);
auto tx = kv_store.create_tx();
auto new_ledger_secret = ccf::make_ledger_secret();
share_manager.issue_recovery_shares(tx, new_ledger_secret);
REQUIRE(tx.commit() == kv::CommitResult::SUCCESS);
auto tx_version = tx.commit_version();
ledger_secrets->set_secret(
tx_version + 1,
std::make_shared<ccf::LedgerSecret>(
std::move(new_ledger_secret->raw_key), tx_version));
return tx_version;
}
aft::LedgerStubProxy* add_raft_consensus(
std::shared_ptr<kv::Store> kv_store,
std::shared_ptr<ccf::indexing::Indexer> indexer)
{
using TRaft = aft::Aft<aft::LedgerStubProxy, aft::StubSnapshotter>;
using AllCommittableRaftConsensus = AllCommittableWrapper<TRaft>;
using ms = std::chrono::milliseconds;
const std::string node_id = "Node 0";
const consensus::Configuration settings{
ConsensusType::CFT, {"20ms"}, {"100ms"}};
auto consensus = std::make_shared<AllCommittableRaftConsensus>(
settings,
std::make_unique<aft::Adaptor<kv::Store>>(kv_store),
std::make_unique<aft::LedgerStubProxy>(node_id),
std::make_shared<aft::ChannelStubProxy>(),
std::make_shared<aft::StubSnapshotter>(),
std::make_shared<aft::State>(node_id),
nullptr,
nullptr);
aft::Configuration::Nodes initial_config;
initial_config[node_id] = {};
consensus->add_configuration(0, initial_config);
consensus->force_become_primary();
kv_store->set_consensus(consensus);
return consensus->ledger.get();
}
// Uses the real classes, to test their interaction with indexing
TEST_CASE_TEMPLATE(
"integrated indexing" * doctest::test_suite("indexing"),
AA,
IndexA,
LazyIndexA)
{
auto kv_store_p = std::make_shared<kv::Store>();
auto& kv_store = *kv_store_p;
auto ledger_secrets = std::make_shared<ccf::LedgerSecrets>();
kv_store.set_encryptor(std::make_shared<ccf::NodeEncryptor>(ledger_secrets));
auto stub_writer = std::make_shared<StubWriter>();
auto cache = std::make_shared<ccf::historical::StateCacheImpl>(
kv_store, ledger_secrets, stub_writer);
auto fetcher =
std::make_shared<ccf::indexing::HistoricalTransactionFetcher>(cache);
auto indexer_p = std::make_shared<ccf::indexing::Indexer>(fetcher);
auto& indexer = *indexer_p;
auto index_a = std::make_shared<AA>(map_a);
REQUIRE(indexer.install_strategy(index_a));
auto ledger = add_raft_consensus(kv_store_p, indexer_p);
ledger_secrets->init();
{
INFO("Store one recovery member");
// This is necessary to rekey the ledger and issue recovery shares for the
// new ledger secret
auto tx = kv_store.create_tx();
auto config = tx.rw<ccf::Configuration>(ccf::Tables::CONFIGURATION);
constexpr size_t recovery_threshold = 1;
config->put({recovery_threshold});
auto member_info = tx.rw<ccf::MemberInfo>(ccf::Tables::MEMBER_INFO);
auto member_public_encryption_keys = tx.rw<ccf::MemberPublicEncryptionKeys>(
ccf::Tables::MEMBER_ENCRYPTION_PUBLIC_KEYS);
auto kp = crypto::make_key_pair();
auto cert = kp->self_sign("CN=member", valid_from, valid_to);
auto member_id =
crypto::Sha256Hash(crypto::cert_pem_to_der(cert)).hex_str();
member_info->put(member_id, {ccf::MemberStatus::ACTIVE});
member_public_encryption_keys->put(
member_id, crypto::make_rsa_key_pair()->public_key_pem());
REQUIRE(tx.commit() == kv::CommitResult::SUCCESS);
}
ExpectedSeqNos seqnos_hello, seqnos_saluton, seqnos_1, seqnos_2;
for (size_t i = 0; i < 3; ++i)
{
REQUIRE(create_transactions(
kv_store, seqnos_hello, seqnos_saluton, seqnos_1, seqnos_2, 10));
rekey(kv_store, ledger_secrets);
}
REQUIRE(create_transactions(
kv_store, seqnos_hello, seqnos_saluton, seqnos_1, seqnos_2));
size_t handled_writes = 0;
const auto& writes = stub_writer->writes;
auto tick_until_caught_up = [&]() {
size_t loops = 0;
while (indexer.update_strategies(step_time, kv_store.current_txid()) ||
handled_writes < writes.size())
{
// Do the fetch, simulating an asynchronous fetch by the historical
// query system
for (auto it = writes.begin() + handled_writes; it != writes.end(); ++it)
{
const auto& write = *it;
const uint8_t* data = write.contents.data();
size_t size = write.contents.size();
REQUIRE(write.m == consensus::ledger_get_range);
auto [from_seqno, to_seqno, purpose_] =
ringbuffer::read_message<consensus::ledger_get_range>(data, size);
auto& purpose = purpose_;
REQUIRE(purpose == consensus::LedgerRequestPurpose::HistoricalQuery);
std::vector<uint8_t> combined;
for (auto seqno = from_seqno; seqno <= to_seqno; ++seqno)
{
const auto entry = ledger->get_raw_entry_by_idx(seqno);
REQUIRE(entry.has_value());
combined.insert(combined.end(), entry->begin(), entry->end());
}
cache->handle_ledger_entries(from_seqno, to_seqno, combined);
}
handled_writes = writes.end() - writes.begin();
if (loops++ > 100)
{
throw std::logic_error("Looks like a permanent loop");
}
}
};
tick_until_caught_up();
if constexpr (std::is_same_v<AA, LazyIndexA>)
{
INFO("Lazy indexes require an additional prod to be populated");
REQUIRE(index_a->get_all_write_txs("hello")->empty());
REQUIRE(index_a->get_all_write_txs("saluton")->empty());
index_a->extend_index_to(kv_store.current_txid());
tick_until_caught_up();
REQUIRE_FALSE(index_a->get_all_write_txs("hello")->empty());
REQUIRE_FALSE(index_a->get_all_write_txs("saluton")->empty());
}
{
INFO("Confirm that pre-existing strategy was populated already");
REQUIRE(check_seqnos(seqnos_hello, index_a->get_all_write_txs("hello")));
REQUIRE(
check_seqnos(seqnos_saluton, index_a->get_all_write_txs("saluton")));
}
INFO(
"Indexes can be installed later, and will be populated after enough "
"ticks");
auto index_b = std::make_shared<IndexB>(map_b);
REQUIRE(indexer.install_strategy(index_b));
run_tests(
tick_until_caught_up,
kv_store,
indexer,
seqnos_hello,
seqnos_saluton,
seqnos_1,
seqnos_2,
index_a,
index_b);
}
| 32.822816 | 80 | 0.71493 | [
"vector"
] |
799564d4563fd7a43bdebb2923fa1bfc6da0948c | 35,665 | cxx | C++ | inetcore/winhttp/v5.1/auth/passport.cxx | npocmaka/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 17 | 2020-11-13T13:42:52.000Z | 2021-09-16T09:13:13.000Z | inetcore/winhttp/v5.1/auth/passport.cxx | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 2 | 2020-10-19T08:02:06.000Z | 2020-10-19T08:23:18.000Z | inetcore/winhttp/v5.1/auth/passport.cxx | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 14 | 2020-11-14T09:43:20.000Z | 2021-08-28T08:59:57.000Z | #include <wininetp.h>
#include <urlmon.h>
#include <splugin.hxx>
#include "htuu.h"
#include "auth.h"
/*---------------------------------------------------------------------------
PASSPORT_CTX
---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------
Constructor
---------------------------------------------------------------------------*/
PASSPORT_CTX::PASSPORT_CTX(HTTP_REQUEST_HANDLE_OBJECT *pRequest, BOOL fIsProxy,
SPMData* pSPM, AUTH_CREDS* pCreds)
: AUTHCTX(pSPM, pCreds)
{
_fIsProxy = fIsProxy;
_pRequest = pRequest;
m_hLogon = NULL;
m_pNewThreadInfo = NULL;
m_pwszPartnerInfo = NULL;
m_lpszRetUrl = NULL;
m_wRealm[0] = '\0';
m_pszFromPP = NULL;
m_fPreauthFailed = FALSE;
m_fAnonymous = TRUE;
// m_AuthComplete = FALSE;
_fChallengeSeen = FALSE;
m_pszCbUrl = NULL;
m_pszCbTxt = NULL;
m_wTarget[0] = 0;
::MultiByteToWideChar(CP_ACP, 0, _pRequest->GetServerName(), -1, m_wTarget, MAX_AUTH_TARGET_LEN);
}
BOOL PASSPORT_CTX::Init(void)
{
m_pNewThreadInfo = ::InternetCreateThreadInfo(FALSE);
if (m_pNewThreadInfo == NULL)
{
return FALSE;
}
LPINTERNET_THREAD_INFO pCurrentThreadInfo = ::InternetGetThreadInfo();
m_pNewThreadInfo->ThreadId = ::GetCurrentThreadId();
::InternetSetThreadInfo(m_pNewThreadInfo);
m_pInternet = GetRootHandle (_pRequest);
if (!m_pInternet->GetPPContext())
{
PWSTR pProxyUser = NULL;
PWSTR pProxyPass = NULL;
if (!_pRequest->_pTweenerProxyCreds)
{
// prepare for the possibility that contacting Passport servers need to go thru auth'ing proxy
LPSTR lpszUser, lpszPass = NULL;
_pRequest->GetUserAndPass(TRUE/*proxy*/, &lpszUser, &lpszPass);
if (lpszUser && lpszPass)
{
_pRequest->_pTweenerProxyCreds = CreateCreds(_pRequest, TRUE/*proxy*/, _pSPMData, NULL);
if (_pRequest->_pTweenerProxyCreds)
{
_pRequest->_pTweenerProxyCreds->SetUser(lpszUser);
_pRequest->_pTweenerProxyCreds->SetPass(lpszPass);
}
}
if (lpszPass)
{
SecureZeroMemory(lpszPass, strlen(lpszPass));
FREE_MEMORY(lpszPass);
}
}
if (_pRequest->_pTweenerProxyCreds)
{
if (_pRequest->_pTweenerProxyCreds->lpszUser)
{
DWORD dwProxyUserLength = strlen(_pRequest->_pTweenerProxyCreds->lpszUser);
pProxyUser = new WCHAR[dwProxyUserLength+1];
if (pProxyUser)
{
::MultiByteToWideChar(CP_ACP, 0, _pRequest->_pTweenerProxyCreds->lpszUser, -1, pProxyUser, dwProxyUserLength+1);
}
}
LPSTR lpszPass = _pRequest->_pTweenerProxyCreds->GetPass();
if (lpszPass)
{
DWORD dwProxyPassLength = strlen(lpszPass);
pProxyPass = new WCHAR[dwProxyPassLength+1];
if (pProxyPass)
{
::MultiByteToWideChar(CP_ACP, 0, lpszPass, -1, pProxyPass, dwProxyPassLength+1);
}
SecureZeroMemory(lpszPass, dwProxyPassLength);
FREE_MEMORY(lpszPass);
lpszPass = NULL;
}
}
PP_CONTEXT hPP = ::PP_InitContext(L"WinHttp.Dll", m_pInternet->GetPseudoHandle(), pProxyUser, pProxyPass);
m_pInternet->SetPPContext(hPP);
hPP = NULL;
pProxyUser = NULL;
pProxyPass = NULL;
}
::InternetSetThreadInfo(pCurrentThreadInfo);
if (!m_pInternet->GetPPContext())
{
return FALSE;
}
return TRUE;
}
/*---------------------------------------------------------------------------
Destructor
---------------------------------------------------------------------------*/
PASSPORT_CTX::~PASSPORT_CTX()
{
LPINTERNET_THREAD_INFO pCurrentThreadInfo = ::InternetGetThreadInfo();
m_pNewThreadInfo->ThreadId = ::GetCurrentThreadId();
::InternetSetThreadInfo(m_pNewThreadInfo);
if (m_hLogon)
{
::PP_FreeLogonContext(m_hLogon);
m_hLogon = NULL;
}
::InternetSetThreadInfo(pCurrentThreadInfo);
if (m_pNewThreadInfo)
{
::InternetFreeThreadInfo(m_pNewThreadInfo);
}
if (m_pwszPartnerInfo)
{
delete [] m_pwszPartnerInfo;
}
if (m_lpszRetUrl)
{
delete [] m_lpszRetUrl;
}
if (m_pszFromPP)
{
delete [] m_pszFromPP;
}
if (m_pszCbUrl != NULL)
{
delete [] m_pszCbUrl;
}
if (m_pszCbTxt != NULL)
{
delete [] m_pszCbTxt;
}
}
BOOL PASSPORT_CTX::CallbackRegistered(void)
{
LPINTERNET_THREAD_INFO lpThreadInfo = InternetGetThreadInfo();
if (lpThreadInfo)
{
WINHTTP_STATUS_CALLBACK appCallback =
((INTERNET_HANDLE_BASE *)lpThreadInfo->hObjectMapped)->GetStatusCallback();
if (appCallback != NULL)
{
return TRUE;
}
}
return FALSE;
}
DWORD PASSPORT_CTX::HandleSuccessfulLogon(
LPWSTR* ppwszFromPP,
PDWORD pdwFromPP,
BOOL fPreAuth
)
{
// biaow-todo: I am betting the RU DWORD UrlLength = 1024;
LPWSTR pwszUrl = (LPWSTR) ALLOCATE_FIXED_MEMORY(1024 * sizeof(WCHAR));
DWORD dwwUrlLength = 1024;// won't be too long, but I could be wrong
LPSTR pszUrl = (LPSTR) ALLOCATE_FIXED_MEMORY(dwwUrlLength * sizeof(CHAR));
BOOL fRetrySameUrl;
DWORD dwRet = ERROR_SUCCESS;
if (pwszUrl == NULL || pszUrl == NULL)
{
dwRet = ERROR_NOT_ENOUGH_MEMORY;
goto exit;
}
*pdwFromPP = 0;
if (::PP_GetAuthorizationInfo(m_hLogon,
NULL,
pdwFromPP,
&fRetrySameUrl,
pwszUrl,
&dwwUrlLength
) == FALSE)
{
*ppwszFromPP = new WCHAR[*pdwFromPP];
if (*ppwszFromPP == NULL)
{
dwRet = ERROR_WINHTTP_LOGIN_FAILURE;
goto exit;
}
}
else
{
INET_ASSERT(FALSE); // this shouldn't happen
}
if (::PP_GetAuthorizationInfo(m_hLogon,
*ppwszFromPP,
pdwFromPP,
&fRetrySameUrl,
pwszUrl,
&dwwUrlLength
) == FALSE)
{
INET_ASSERT(FALSE); // this shouldn't happen
dwRet = ERROR_WINHTTP_LOGIN_FAILURE;
goto exit;
}
// save the DA Host name for Logout security check
/*
WCHAR wszDAHost[256];
DWORD dwHostLen = ARRAY_ELEMENTS(wszDAHost);
if (::PP_GetLogonHost(m_hLogon, wszDAHost, &dwHostLen) == TRUE)
{
::WideCharToMultiByte(CP_ACP, 0, wszDAHost, -1, g_szPassportDAHost, 256, NULL, NULL);
}
*/
if (!fRetrySameUrl)
{
if (_pRequest->GetMethodType() == HTTP_METHOD_TYPE_GET)
{
// DA wanted us to GET to a new Url
::WideCharToMultiByte(CP_ACP, 0, pwszUrl, -1, pszUrl, 1024, NULL, NULL);
}
else
{
fRetrySameUrl = TRUE; // *** WinHttp currently supports retry custom verb to same URL only ***
}
}
if (fPreAuth)
{
// We are sending, in the context of AuthOnRequest.
if (fRetrySameUrl)
{
// DA told us to keep Verb & Url, so there is nothing more needs to be done
goto exit;
}
// Regardless whether we are asked to handle redirect, we'll need to fake
// that a 302 just came in.
// biaow-todo: this is causing problem for QueryHeaders(StatusCode). I don't know why yet...
/*
_pRequest->AddInternalResponseHeader(HTTP_QUERY_STATUS_TEXT, // use non-standard index, since we never query this normally
"HTTP/1.0 302 Object Moved",
strlen("HTTP/1.0 302 Object Moved")
);
_pRequest->AddInternalResponseHeader(HTTP_QUERY_LOCATION,
pszUrl,
strlen(pszUrl));
*/
//
// todo: if REDIRECT_POLICY is POLICY_DISALLOW_HTTPS_TO_HTTP, do not allow
//the passport server to redirect to an HTTP site if the original request
//was to an HTTPS site
//
if (_pRequest->GetDwordOption(WINHTTP_OPTION_REDIRECT_POLICY) == WINHTTP_OPTION_REDIRECT_POLICY_NEVER)
{
if (!CallbackRegistered())
{
_pRequest->SetPPAbort(TRUE);
dwRet = ERROR_WINHTTP_LOGIN_FAILURE;
goto exit;
}
}
::InternetIndicateStatusString(WINHTTP_CALLBACK_STATUS_REDIRECT, pszUrl);
}
else
{
// We are receiving a 302, in the context of AuthOnResponse.
// Here we need to re-play the request to lpszRetUrl. One way to
// achieve this is returning ERROR_INTERNET_FORCE_RETRY. But before
// that, we'll need to remember the lpszRetUrl.
// *NOTE* This is in effective an 401. To prevent the send path from
// following the 302 Location: header, caller must set the status code
// to 401.
if (!fRetrySameUrl)
{
//
// todo: if REDIRECT_POLICY is POLICY_DISALLOW_HTTPS_TO_HTTP, do not allow
//the passport server to redirect to an HTTP site if the original request
//was to an HTTPS site
//
if (_pRequest->GetDwordOption(WINHTTP_OPTION_REDIRECT_POLICY) == WINHTTP_OPTION_REDIRECT_POLICY_NEVER)
{
if (!CallbackRegistered())
{
dwRet = ERROR_WINHTTP_LOGIN_FAILURE;
goto exit;
}
::InternetIndicateStatusString(WINHTTP_CALLBACK_STATUS_REDIRECT, pszUrl);
}
}
dwRet = ERROR_WINHTTP_RESEND_REQUEST;
}
PCSTR lpszRetUrl = NULL;
if (fRetrySameUrl)
{
lpszRetUrl = _pRequest->GetURL();
}
else
{
lpszRetUrl = pszUrl;
}
if (m_lpszRetUrl)
{
delete [] m_lpszRetUrl;
}
m_lpszRetUrl = new CHAR[strlen(lpszRetUrl) + 1];
if (m_lpszRetUrl)
{
strcpy(m_lpszRetUrl, lpszRetUrl);
}
exit:
if (pwszUrl)
{
FREE_MEMORY(pwszUrl);
}
if (pszUrl)
{
FREE_MEMORY(pszUrl);
}
return dwRet;
}
DWORD PASSPORT_CTX::SetCreds(BOOL* pfCredSet)
{
DWORD dwError = ERROR_SUCCESS;
BOOL fUseDefaultCreds;
LPWSTR pwszUser = NULL;
LPWSTR pwszPass = NULL;
LPSTR lpszPass = _pCreds->GetPass();
if (_pCreds->lpszUser && lpszPass) // both User and Pass are specified
{
fUseDefaultCreds = FALSE;
}
else if (!_pCreds->lpszUser && !lpszPass) // both User and Pass are NULL
{
fUseDefaultCreds = TRUE;
}
else
{
INET_ASSERT(FALSE); // this case should not happen
fUseDefaultCreds = FALSE;
}
PSYSTEMTIME pCredTimestamp = NULL;
SYSTEMTIME TimeCredsEntered;
if (!fUseDefaultCreds)
{
pwszUser = (LPWSTR) ALLOCATE_FIXED_MEMORY((strlen(_pCreds->lpszUser) + 1) * sizeof(WCHAR));
pwszPass = (LPWSTR) ALLOCATE_FIXED_MEMORY((strlen(lpszPass) + 1) * sizeof(WCHAR));
if (pwszUser && pwszPass)
{
if( (0 == ::MultiByteToWideChar(CP_ACP, 0, _pCreds->lpszUser, -1, pwszUser, strlen(_pCreds->lpszUser) + 1))
|| (0 ==::MultiByteToWideChar(CP_ACP, 0, lpszPass, -1, pwszPass, strlen(lpszPass) + 1)))
{
pwszUser[0] = L'\0';
pwszPass[0] = L'\0';
dwError=GetLastError();
}
}
else
{
dwError = ERROR_NOT_ENOUGH_MEMORY;
}
pCredTimestamp = &TimeCredsEntered;
::GetSystemTime(pCredTimestamp); // time-stamp the creds
}
if (dwError == ERROR_SUCCESS)
{
if (pwszUser == NULL && pwszPass == NULL && m_pInternet->KeyringDisabled())
{
*pfCredSet = FALSE;
}
else
{
*pfCredSet = ::PP_SetCredentials(m_hLogon, m_wRealm, m_wTarget, pwszUser, pwszPass, pCredTimestamp);
}
}
if (pwszUser)
{
SecureZeroMemory( pwszUser, sizeof(pwszUser[0])*wcslen(pwszUser));
FREE_MEMORY(pwszUser);
}
if (pwszPass)
{
SecureZeroMemory( pwszPass, sizeof(pwszPass[0])*wcslen(pwszPass));
FREE_MEMORY(pwszPass);
}
if (lpszPass)
{
SecureZeroMemory(lpszPass, strlen(lpszPass));
FREE_MEMORY(lpszPass);
}
return dwError;
}
DWORD PASSPORT_CTX::ModifyRequestBasedOnRU(void)
{
DWORD dwError = ERROR_SUCCESS;
INTERNET_SCHEME schemeType;
INTERNET_SCHEME currentSchemeType;
INTERNET_PORT currentHostPort;
LPSTR currentHostName;
DWORD currentHostNameLength;
INTERNET_PORT port = 0;
LPSTR pszHostName;
DWORD dwHostNameLength = 0;
LPSTR pszUrlPath;
DWORD dwUrlPathLength = 0;
LPSTR extra;
DWORD extraLength;
dwError = CrackUrl(m_lpszRetUrl,
0,
FALSE, // don't escape URL-path
&schemeType,
NULL, // scheme name, don't care
NULL,
&pszHostName,
&dwHostNameLength,
FALSE, // -biaow- do NOT unscape hostnamesd
&port,
NULL, // UserName, don't care
NULL,
NULL, // Password, don't care
NULL,
&pszUrlPath,
&dwUrlPathLength,
&extra,
&extraLength,
NULL);
if (dwError != ERROR_SUCCESS)
{
goto cleanup;
}
CHAR chBkChar = pszHostName[dwHostNameLength]; // save off char
pszHostName[dwHostNameLength] = '\0';
if (!IsValidHostNameA(pszHostName, IVHN_DISALLOW_IPV6_SCOPE_ID))
{
pszHostName[dwHostNameLength] = chBkChar; // put back char
dwError = ERROR_WINHTTP_LOGIN_FAILURE;
goto cleanup;
}
pszHostName[dwHostNameLength] = chBkChar; // put back char
//
// if there is an intra-page link on the redirected URL then get rid of it:
// we don't send it to the server, and we have already indicated it to the
// app
//
if (extraLength != 0) {
INET_ASSERT(extra != NULL);
INET_ASSERT(!IsBadWritePtr(extra, 1));
if (*extra == '#') {
*extra = '\0';
// newUrlLength -= extraLength;
} else {
dwUrlPathLength += extraLength;
}
}
if (port == INTERNET_INVALID_PORT_NUMBER) {
port = (INTERNET_PORT)((schemeType == INTERNET_SCHEME_HTTPS)
? INTERNET_DEFAULT_HTTPS_PORT
: INTERNET_DEFAULT_HTTP_PORT);
}
currentHostPort = _pRequest->GetHostPort();
currentHostName = _pRequest->GetHostName(¤tHostNameLength);
if (port != currentHostPort) {
_pRequest->SetHostPort(port);
}
if ((dwHostNameLength != currentHostNameLength)
|| (strnicmp(pszHostName, currentHostName, dwHostNameLength) != 0)) {
char hostValue[INTERNET_MAX_HOST_NAME_LENGTH + sizeof(":4294967295")];
LPSTR hostValueStr;
DWORD hostValueSize;
chBkChar = pszHostName[dwHostNameLength]; // save off char
pszHostName[dwHostNameLength] = '\0';
_pRequest->SetHostName(pszHostName);
hostValueSize = dwHostNameLength;
hostValueStr = pszHostName;
if ((port != INTERNET_DEFAULT_HTTP_PORT)
&& (port != INTERNET_DEFAULT_HTTPS_PORT)) {
if (hostValueSize > INTERNET_MAX_HOST_NAME_LENGTH)
{
pszHostName[dwHostNameLength] = chBkChar; // put back char
dwError = ERROR_INVALID_PARAMETER;
goto cleanup;
}
hostValueSize = wsprintf(hostValue, "%s:%d", pszHostName, (port & 0xffff));
hostValueStr = hostValue;
}
pszHostName[dwHostNameLength] = chBkChar; // put back char
//
// replace the "Host:" header
//
_pRequest->ReplaceRequestHeader(HTTP_QUERY_HOST,
hostValueStr,
hostValueSize,
0, // dwIndex
ADD_HEADER
);
//
// and get the corresponding server info, resolving the name if
// required
//
// _pRequest->SetServerInfo(FALSE);
//
// Since we are redirecting to a different host, force an update of the origin
// server. Otherwise, we will still pick up the proxy info of the first server.
//
// todo:
// _pRequest->SetOriginServer(TRUE);
}
currentSchemeType = ((WINHTTP_FLAG_SECURE & _pRequest->GetOpenFlags()) ?
INTERNET_SCHEME_HTTPS :
INTERNET_SCHEME_HTTP);
if ( currentSchemeType != schemeType )
{
DWORD OpenFlags = _pRequest->GetOpenFlags();
// Switched From HTTPS to HTTP
if ( currentSchemeType == INTERNET_SCHEME_HTTPS )
{
INET_ASSERT(schemeType != INTERNET_SCHEME_HTTPS );
OpenFlags &= ~(WINHTTP_FLAG_SECURE);
}
// Switched From HTTP to HTTPS
else if ( schemeType == INTERNET_SCHEME_HTTPS )
{
INET_ASSERT(currentSchemeType == INTERNET_SCHEME_HTTP );
OpenFlags |= (WINHTTP_FLAG_SECURE);
}
_pRequest->SetOpenFlags(OpenFlags);
_pRequest->SetSchemeType(schemeType);
}
_pRequest->SetURL(m_lpszRetUrl);
if (_pRequest->IsRequestUsingProxy())
{
_pRequest->ModifyRequest(_pRequest->GetMethodType(),
m_lpszRetUrl,
strlen(m_lpszRetUrl),
NULL,
0);
}
else
{
_pRequest->ModifyRequest(_pRequest->GetMethodType(),
pszUrlPath, // m_lpszRetUrl,
strlen(pszUrlPath),//strlen(m_lpszRetUrl),
NULL,
0);
}
cleanup:
return dwError;
}
/*---------------------------------------------------------------------------
PreAuthUser
---------------------------------------------------------------------------*/
DWORD PASSPORT_CTX::PreAuthUser(IN LPSTR pBuf, IN OUT LPDWORD pcbBuf)
{
DEBUG_ENTER ((
DBG_HTTP,
Dword,
"PASSPORT_CTX::PreAuthUser",
"this=%#x pBuf=%#x pcbBuf=%#x {%d}",
this,
pBuf,
pcbBuf,
*pcbBuf
));
if (!AuthLock())
{
return ERROR_NOT_ENOUGH_MEMORY;
}
DWORD dwError = ERROR_SUCCESS;
LPWSTR pwszFromPP = NULL;
// Prefix the header value with the auth type.
const static BYTE szPassport[] = "Passport1.4 ";
#define PASSPORT_LEN sizeof(szPassport)-1
if (m_pszFromPP == NULL)
{
if (m_hLogon == NULL)
{
dwError = ERROR_WINHTTP_INTERNAL_ERROR;
goto cleanup;
}
DWORD dwFromPPLen = 0;
BOOL fCredSet;
dwError = SetCreds(&fCredSet);
if (dwError != ERROR_SUCCESS)
{
goto cleanup;
}
LPINTERNET_THREAD_INFO pCurrentThreadInfo = ::InternetGetThreadInfo();
m_pNewThreadInfo->ThreadId = ::GetCurrentThreadId();
::InternetSetThreadInfo(m_pNewThreadInfo);
DWORD dwLogonStatus = ::PP_Logon(m_hLogon,
FALSE,
0,
NULL,
0);
::InternetSetThreadInfo(pCurrentThreadInfo);
if (dwLogonStatus != PP_LOGON_SUCCESS)
{
if (dwLogonStatus == PP_LOGON_FAILED)
{
m_fPreauthFailed = TRUE;
}
dwError = ERROR_WINHTTP_INTERNAL_ERROR; // need to double check this return error
goto cleanup;
}
dwError = HandleSuccessfulLogon(&pwszFromPP, &dwFromPPLen, TRUE);
if (dwError == ERROR_WINHTTP_LOGIN_FAILURE)
{
goto cleanup;
}
m_pszFromPP = new CHAR [dwFromPPLen];
if (m_pszFromPP == NULL)
{
dwError = ERROR_NOT_ENOUGH_MEMORY;
goto cleanup;
}
::WideCharToMultiByte(CP_ACP, 0, pwszFromPP, -1, m_pszFromPP, dwFromPPLen, NULL, NULL);
}
// check to see if we need to update url
if (m_lpszRetUrl)
{
dwError = ModifyRequestBasedOnRU();
if (dwError != ERROR_SUCCESS)
{
// delete [] m_lpszRetUrl;
// m_lpszRetUrl = NULL;
goto cleanup;
}
// delete [] m_lpszRetUrl;
// m_lpszRetUrl = NULL;
}
// Ticket and profile is already present
if ((PASSPORT_LEN + ::strlen(m_pszFromPP) + 1) > (*pcbBuf))
{
DWORD dwRequiredSize = (DWORD)(PASSPORT_LEN + strlen(m_pszFromPP));
*pcbBuf = HTTP_AUTHORIZATION_LEN + 1 + dwRequiredSize + 2 + 1;
dwError = ERROR_INSUFFICIENT_BUFFER;
goto cleanup;
}
// put in the header
memcpy (pBuf, szPassport, PASSPORT_LEN);
pBuf += PASSPORT_LEN;
// append the ticket
strcpy(pBuf, m_pszFromPP);
*pcbBuf = (DWORD)(PASSPORT_LEN + strlen(m_pszFromPP));
// m_AuthComplete = TRUE;
cleanup:
if (pwszFromPP)
delete [] pwszFromPP;
AuthUnlock();
DEBUG_LEAVE(dwError);
return dwError;
}
/*---------------------------------------------------------------------------
UpdateFromHeaders
---------------------------------------------------------------------------*/
DWORD PASSPORT_CTX::UpdateFromHeaders(HTTP_REQUEST_HANDLE_OBJECT *pRequest, BOOL fIsProxy)
{
DEBUG_ENTER ((
DBG_HTTP,
Dword,
"PASSPORT_CTX::UpdateFromHeaders",
"this=%#x request=%#x isproxy=%B",
this,
pRequest,
fIsProxy
));
if (!AuthLock())
{
return ERROR_NOT_ENOUGH_MEMORY;
}
DWORD dwAuthIdx, cbChallenge, dwError;
LPSTR szChallenge = NULL;
// Get the associated header.
if ((dwError = FindHdrIdxFromScheme(&dwAuthIdx)) != ERROR_SUCCESS)
goto exit;
//if (m_AuthComplete)
//{
// _pRequest->SetStatusCode(401); // this is needed to prevent send code from tracing Location: header
// dwError = ERROR_WINHTTP_LOGIN_FAILURE;
// goto exit;
//}
// Get the complete auth header.
dwError = GetAuthHeaderData(pRequest, fIsProxy, NULL,
&szChallenge, &cbChallenge, ALLOCATE_BUFFER, dwAuthIdx);
if (dwError != ERROR_SUCCESS)
{
szChallenge = NULL;
goto exit;
}
if (_fChallengeSeen)
{
dwError = ERROR_HTTP_HEADER_NOT_FOUND;
goto exit;
}
if (!_pCreds)
{
_pCreds = CreateCreds(pRequest, fIsProxy, _pSPMData, NULL);
if (!_pCreds)
{
dwError = ERROR_NOT_ENOUGH_MEMORY;
goto exit;
}
}
if (m_pwszPartnerInfo)
{
delete [] m_pwszPartnerInfo;
m_pwszPartnerInfo = NULL;
}
{
LPSTR lpszVerb;
DWORD dwVerbLength;
lpszVerb = _pRequest->_RequestHeaders.GetVerb(&dwVerbLength);
#define MAX_VERB_LENGTH 16
CHAR szOrgVerb[MAX_VERB_LENGTH] = {0};
if (dwVerbLength > MAX_VERB_LENGTH - 1)
{
goto exit;
}
strncpy(szOrgVerb, lpszVerb, dwVerbLength+1);
PCSTR pszOrgUrl = _pRequest->GetURL();
const LPWSTR pwszOrgVerbAttr = L",OrgVerb=";
const LPWSTR pwszOrgUrlAttr = L",OrgUrl=";
DWORD dwPartnerInfoLength = cbChallenge
+::wcslen(pwszOrgVerbAttr)
+::strlen(szOrgVerb)
+::wcslen(pwszOrgUrlAttr)
+::strlen(pszOrgUrl)
+ 1; // NULL terminator
DWORD dwSize = 0;
PWSTR pwszPartnerInfo = NULL;
m_pwszPartnerInfo = new WCHAR[dwPartnerInfoLength];
if (m_pwszPartnerInfo == NULL)
{
dwError = ERROR_NOT_ENOUGH_MEMORY;
goto exit;
}
pwszPartnerInfo = m_pwszPartnerInfo;
dwSize = ::MultiByteToWideChar(CP_ACP, 0, szChallenge, -1, pwszPartnerInfo, dwPartnerInfoLength) - 1;
::wcscat(pwszPartnerInfo, pwszOrgVerbAttr);
pwszPartnerInfo += (dwSize + wcslen(pwszOrgVerbAttr));
dwPartnerInfoLength -= (dwSize + wcslen(pwszOrgVerbAttr));
dwSize = ::MultiByteToWideChar(CP_ACP, 0, szOrgVerb, -1, pwszPartnerInfo, dwPartnerInfoLength) - 1;
::wcscat(pwszPartnerInfo, pwszOrgUrlAttr);
pwszPartnerInfo += (dwSize + wcslen(pwszOrgUrlAttr));
dwPartnerInfoLength -= (dwSize + wcslen(pwszOrgUrlAttr));
dwSize = ::MultiByteToWideChar(CP_ACP, 0, pszOrgUrl, -1, pwszPartnerInfo, dwPartnerInfoLength) - 1;
dwError = ERROR_SUCCESS;
}
_fChallengeSeen = TRUE;
exit:
if (szChallenge)
delete []szChallenge;
AuthUnlock();
DEBUG_LEAVE(dwError);
return dwError;
}
BOOL PASSPORT_CTX::InitLogonContext(void)
{
// set up the thread context before calling the Passport auth library
LPINTERNET_THREAD_INFO pCurrentThreadInfo = ::InternetGetThreadInfo();
m_pNewThreadInfo->ThreadId = ::GetCurrentThreadId();
::InternetSetThreadInfo(m_pNewThreadInfo);
if (!m_hLogon)
{
INET_ASSERT(m_pInternet->GetPPContext()); // must have been initialized in the Init() call
m_hLogon = ::PP_InitLogonContext(
m_pInternet->GetPPContext(),
m_pwszPartnerInfo,
(_pRequest->GetOpenFlags() & INTERNET_FLAG_NO_COOKIES),
NULL,
NULL
);
}
// restore the WinHttp thread context
::InternetSetThreadInfo(pCurrentThreadInfo);
PCWSTR pwszRealm = ::wcsstr(m_pwszPartnerInfo, L"srealm");
if (pwszRealm)
{
pwszRealm += ::wcslen(L"srealm");
if (*pwszRealm == L'=')
{
pwszRealm++;
DWORD i = 0;
while (*pwszRealm != 0 && *pwszRealm != L',' && i < MAX_AUTH_REALM_LEN-1)
{
m_wRealm[i++] = *pwszRealm++;
}
m_wRealm[i] = 0; // null-terminate it
}
}
if (!m_wRealm[0])
{
DWORD dwRealmLen = MAX_AUTH_REALM_LEN;
PP_GetRealm(m_pInternet->GetPPContext(), m_wRealm, &dwRealmLen);
}
return m_hLogon != NULL;
}
/*---------------------------------------------------------------------------
PostAuthUser
---------------------------------------------------------------------------*/
DWORD PASSPORT_CTX::PostAuthUser()
{
DEBUG_ENTER ((
DBG_HTTP,
Dword,
"PASSPORT_CTX::PostAuthUser",
"this=%#x",
this
));
if (!AuthLock())
{
return ERROR_NOT_ENOUGH_MEMORY;
}
DWORD dwRet = ERROR_SUCCESS;
if (InitLogonContext() == FALSE)
{
dwRet = ERROR_WINHTTP_LOGIN_FAILURE;
goto exit;
}
BOOL fCredSet;
dwRet = SetCreds(&fCredSet);
if (dwRet != ERROR_SUCCESS)
{
goto exit;
}
// Ok, Let's give it a try
LPINTERNET_THREAD_INFO pCurrentThreadInfo = ::InternetGetThreadInfo();
m_pNewThreadInfo->ThreadId = ::GetCurrentThreadId();
::InternetSetThreadInfo(m_pNewThreadInfo);
DWORD dwLogonStatus = ::PP_Logon(m_hLogon,
m_fAnonymous,
0,
NULL,
0);
// restore the WinHttp thread context
::InternetSetThreadInfo(pCurrentThreadInfo);
if (dwLogonStatus == PP_LOGON_REQUIRED)
{
// no creds specified, we are required to sign on.
// change from 302 to 401
_pRequest->ReplaceResponseHeader(HTTP_QUERY_STATUS_CODE,
"401", strlen("401"),
0, HTTP_ADDREQ_FLAG_REPLACE);
// biaow-todo: 1) nice to replace the status text as well; weird to have "HTTP/1.1 401 object moved"
// for example 2) remove the Location: header
BOOL fPrompt;
DWORD dwCbUrlSize = 0;
DWORD dwCbTxtSize = 0;
::PP_GetChallengeInfo(m_hLogon,
&fPrompt, NULL, &dwCbUrlSize, NULL, &dwCbTxtSize, m_wRealm, MAX_AUTH_REALM_LEN);
PWSTR pwszCbUrl = NULL;
PWSTR pwszCbTxt = NULL;
if (dwCbUrlSize)
{
pwszCbUrl = new WCHAR[dwCbUrlSize];
}
if (dwCbTxtSize)
{
pwszCbTxt = new WCHAR[dwCbTxtSize];
}
::PP_GetChallengeInfo(m_hLogon,
NULL, pwszCbUrl, &dwCbUrlSize, pwszCbTxt, &dwCbTxtSize, NULL, 0);
if (pwszCbUrl)
{
m_pszCbUrl = new CHAR[wcslen(pwszCbUrl)+1];
if (m_pszCbUrl)
{
::WideCharToMultiByte(CP_ACP, 0, pwszCbUrl, -1, m_pszCbUrl, wcslen(pwszCbUrl)+1, NULL, NULL);
UrlUnescapeA(m_pszCbUrl, NULL, NULL, URL_UNESCAPE_INPLACE);
}
}
if (pwszCbTxt)
{
m_pszCbTxt = new CHAR[wcslen(pwszCbTxt)+1];
if (m_pszCbTxt)
{
::WideCharToMultiByte(CP_ACP, 0, pwszCbTxt, -1, m_pszCbTxt, wcslen(pwszCbTxt)+1, NULL, NULL);
UrlUnescapeA(m_pszCbTxt, NULL, NULL, URL_UNESCAPE_INPLACE);
}
}
delete [] pwszCbUrl;
delete [] pwszCbTxt;
if (fPrompt)
{
dwRet = ERROR_WINHTTP_INCORRECT_PASSWORD;
}
else
{
if (m_fAnonymous)
{
if (fCredSet)
{
dwRet = ERROR_WINHTTP_RESEND_REQUEST;
}
else
{
dwRet = ERROR_WINHTTP_INCORRECT_PASSWORD;
}
m_fAnonymous = FALSE;
}
else
{
dwRet = ERROR_WINHTTP_INCORRECT_PASSWORD;
}
}
if (dwRet == ERROR_WINHTTP_INCORRECT_PASSWORD)
{
Transfer401ContentFromPP();
}
/*
if (RetryLogon() == TRUE)
{
dwRet = ERROR_WINHTTP_RESEND_REQUEST;
}
else
{
dwRet = ERROR_WINHTTP_INCORRECT_PASSWORD;
}
*/
}
else if (dwLogonStatus == PP_LOGON_SUCCESS)
{
// wow! we got in!!!
DWORD dwFromPPLen = 0;
LPWSTR pwszFromPP = NULL;
dwRet = HandleSuccessfulLogon(&pwszFromPP, &dwFromPPLen, FALSE);
if (dwRet != ERROR_WINHTTP_LOGIN_FAILURE)
{
if (m_pszFromPP)
{
delete [] m_pszFromPP;
}
m_pszFromPP = new CHAR [dwFromPPLen];
if (m_pszFromPP)
{
::WideCharToMultiByte(CP_ACP, 0, pwszFromPP, -1, m_pszFromPP, dwFromPPLen, NULL, NULL);
}
}
if (pwszFromPP)
{
delete [] pwszFromPP;
}
m_fAnonymous = FALSE;
}
else
{
Transfer401ContentFromPP();
dwRet = ERROR_WINHTTP_LOGIN_FAILURE;
}
exit:
_pRequest->SetStatusCode(401); // this is needed to prevent send code from tracing Location: header
AuthUnlock();
DEBUG_LEAVE(dwRet);
return dwRet;
}
BOOL PASSPORT_CTX::Transfer401ContentFromPP(void)
{
DWORD ContentLength = 0;
::PP_GetChallengeContent(m_hLogon,
NULL,
&ContentLength);
if (ContentLength > 0)
{
LPBYTE pContent = (LPBYTE)ALLOCATE_FIXED_MEMORY(ContentLength);
if (pContent == NULL)
{
return FALSE;
}
if (::PP_GetChallengeContent(m_hLogon,
pContent,
&ContentLength) == TRUE)
{
BOOL fDrained;
// play with socket mode to force DrainResponse to return synchronously
ICSocket* pSocket = _pRequest->_Socket;
if (pSocket)
{
BOOL fSocketModeSet = FALSE;
if (pSocket->IsNonBlocking())
{
pSocket->SetNonBlockingMode(FALSE);
fSocketModeSet = TRUE;
}
INET_ASSERT(pSocket->IsNonBlocking() == FALSE);
_pRequest->DrainResponse(&fDrained);
if (fSocketModeSet)
{
pSocket->SetNonBlockingMode(TRUE);
}
}
_pRequest->_ResponseHeaders.FreeHeaders();
_pRequest->FreeResponseBuffer();
_pRequest->ResetResponseVariables();
_pRequest->_ResponseHeaders.Initialize();
// _pRequest->_dwCurrentStreamPosition = 0;
_pRequest->CloneResponseBuffer(pContent, ContentLength);
}
FREE_MEMORY(pContent);
}
return TRUE;
}
| 29.019528 | 134 | 0.508622 | [
"object"
] |
79a0f26a86b4121cf76a498e46b1007d88cd7c9a | 76 | hpp | C++ | src/boost_geometry_strategies_default_comparable_distance_result.hpp | miathedev/BoostForArduino | 919621dcd0c157094bed4df752b583ba6ea6409e | [
"BSL-1.0"
] | 10 | 2018-03-17T00:58:42.000Z | 2021-07-06T02:48:49.000Z | src/boost_geometry_strategies_default_comparable_distance_result.hpp | miathedev/BoostForArduino | 919621dcd0c157094bed4df752b583ba6ea6409e | [
"BSL-1.0"
] | 2 | 2021-03-26T15:17:35.000Z | 2021-05-20T23:55:08.000Z | src/boost_geometry_strategies_default_comparable_distance_result.hpp | miathedev/BoostForArduino | 919621dcd0c157094bed4df752b583ba6ea6409e | [
"BSL-1.0"
] | 4 | 2019-05-28T21:06:37.000Z | 2021-07-06T03:06:52.000Z | #include <boost/geometry/strategies/default_comparable_distance_result.hpp>
| 38 | 75 | 0.881579 | [
"geometry"
] |
79a263291e21a95f696d1d07d4c1e246845552ae | 6,447 | hpp | C++ | core/sceneManager/network/3rdParty/raknet/DependentExtensions/cat/net/DNSClient.hpp | wterkaj/ApertusVR | 424ec5515ae08780542f33cc4841a8f9a96337b3 | [
"MIT"
] | 158 | 2016-11-17T19:37:51.000Z | 2022-03-21T19:57:55.000Z | core/sceneManager/network/3rdParty/raknet/DependentExtensions/cat/net/DNSClient.hpp | wterkaj/ApertusVR | 424ec5515ae08780542f33cc4841a8f9a96337b3 | [
"MIT"
] | 94 | 2016-11-18T09:55:57.000Z | 2021-01-14T08:50:40.000Z | core/sceneManager/network/3rdParty/raknet/DependentExtensions/cat/net/DNSClient.hpp | wterkaj/ApertusVR | 424ec5515ae08780542f33cc4841a8f9a96337b3 | [
"MIT"
] | 60 | 2015-02-17T00:12:11.000Z | 2021-08-21T22:16:58.000Z | /*
Copyright (c) 2009-2010 Christopher A. Taylor. 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 LibCat 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.
*/
// TODO: React to timeouts from DNS server by switching to a backup
// TODO: Use TTL from DNS record instead of fixed constant
// TODO: If the DNS resolution load is high, it would make sense to put
// multiple requests in the same DNS packet
// TODO: Retransmissions could also be grouped into the same DNS packets
// TODO: The locks held in DNSClient are fairly coarse and could be broken up
#ifndef CAT_DNS_CLIENT_HPP
#define CAT_DNS_CLIENT_HPP
#include <cat/net/ThreadPoolSockets.hpp>
#include <cat/threads/Thread.hpp>
#include <cat/threads/WaitableFlag.hpp>
#include <cat/crypt/rand/Fortuna.hpp>
#include <cat/port/FastDelegate.h>
namespace cat {
static const int HOSTNAME_MAXLEN = 63; // Max characters in a hostname request
static const int DNSREQ_TIMEOUT = 3000; // DNS request timeout interval
static const int DNSREQ_REPOST_TIME = 300; // Number of milliseconds between retries
static const int DNSREQ_MAX_SIMUL = 2048; // Maximum number of simultaneous DNS requests
static const int DNSCACHE_MAX_REQS = 8; // Maximum number of requests to cache
static const int DNSCACHE_MAX_RESP = 8; // Maximum number of responses to cache
static const int DNSCACHE_TIMEOUT = 60000; // Time until a cached response is dropped
// Prototype: bool MyResultCallback(const char *, const NetAddr*, int);
typedef fastdelegate::FastDelegate3<const char *, const NetAddr*, int, bool> DNSResultCallback;
//// DNSRequest
struct DNSCallback
{
DNSCallback *next;
DNSResultCallback cb;
ThreadRefObject *ref;
};
struct DNSRequest
{
DNSRequest *last, *next;
u32 first_post_time; // Timestamp for first post, for timeout
u32 last_post_time; // Timestamp for last post, for retries and cache
// Our copy of the hostname string
char hostname[HOSTNAME_MAXLEN+1];
u16 id; // Random request ID
DNSCallback callback_head;
// For caching purposes
NetAddr responses[DNSCACHE_MAX_RESP];
int num_responses;
};
//// DNSClient
class DNSClient : Thread, public UDPEndpoint, public Singleton<DNSClient>
{
static const int TICK_RATE = 200; // milliseconds
static const int DNS_THREAD_KILL_TIMEOUT = 10000; // 10 seconds
CAT_SINGLETON(DNSClient)
: UDPEndpoint(REFOBJ_PRIO_0+5)
{
_server_addr.Invalidate();
_dns_unavailable = true;
_cache_head = _cache_tail = 0;
_cache_size = 0;
_request_head = _request_tail = 0;
_request_queue_size = 0;
}
public:
virtual ~DNSClient();
/*
In your startup code, call Initialize() and check the return value.
In your shutdown code, call Shutdown(). This will delete the DNSClient object.
*/
bool Initialize();
void Shutdown();
/*
If hostname is numeric or in the cache, the callback function will be invoked
immediately from the requesting thread, rather than from another thread.
First attempts numerical resolve of hostname, then queries the DNS server.
Hostname string length limited to HOSTNAME_MAXLEN characters.
Caches the most recent DNSCACHE_MAX_REQS requests.
Returns up to DNSCACHE_MAX_RESP addresses per resolve request.
Performs DNS lookup on a cached request after DNSCACHE_TIMEOUT.
Gives up on DNS lookup after DNSREQ_TIMEOUT.
If holdRef is valid, the reference will be held until the callback completes.
If no results were found, array_length == 0.
If the callback returns false, the result will not be entered into the cache.
The resolved addresses may need to be promoted to IPv6.
If Resolve() returns false, no callback will be generated.
*/
bool Resolve(const char *hostname, DNSResultCallback, ThreadRefObject *holdRef = 0);
private:
NetAddr _server_addr;
volatile bool _dns_unavailable;
FortunaOutput *_csprng;
private:
Mutex _request_lock;
DNSRequest *_request_head;
DNSRequest *_request_tail;
int _request_queue_size;
bool GetUnusedID(u16 &id); // not thread-safe, caller must lock
bool IsValidHostname(const char *hostname);
DNSRequest *PullRequest(u16 id); // not thread-safe, caller must lock
private:
Mutex _cache_lock;
DNSRequest *_cache_head;
DNSRequest *_cache_tail;
int _cache_size;
// These functions do not lock, caller must lock:
void CacheAdd(DNSRequest *req); // Assumes not already in cache
DNSRequest *CacheGet(const char *hostname); // Case-insensitive
void CacheKill(DNSRequest *req); // Assumes already in cache
private:
bool GetServerAddr();
bool BindToRandomPort(bool ignoreUnreachable);
bool PostDNSPacket(DNSRequest *req, u32 now);
bool PerformLookup(DNSRequest *req); // not thread-safe, caller must lock
protected:
virtual void OnRead(ThreadPoolLocalStorage *tls, const NetAddr &src, u8 *data, u32 bytes);
virtual void OnClose();
virtual void OnUnreachable(const NetAddr &src);
protected:
void ProcessDNSResponse(DNSRequest *req, int qdcount, int ancount, u8 *data, u32 bytes);
void NotifyRequesters(DNSRequest *req);
private:
WaitableFlag _kill_flag;
bool ThreadFunction(void *param);
};
} // namespace cat
#endif // CAT_DNS_CLIENT_HPP
| 33.578125 | 95 | 0.772918 | [
"object"
] |
79a2f021f97c0ad6dfb8d1ed6a0129fc032b29fa | 7,780 | cpp | C++ | server/objectSurvey.cpp | goreacraft/OneLife | 53897c580b97ed72013a59e52925953256b96175 | [
"Linux-OpenIB"
] | 69 | 2018-10-05T23:29:10.000Z | 2022-03-29T22:34:24.000Z | server/objectSurvey.cpp | goreacraft/OneLife | 53897c580b97ed72013a59e52925953256b96175 | [
"Linux-OpenIB"
] | 62 | 2018-11-08T14:14:40.000Z | 2022-03-01T20:38:01.000Z | server/objectSurvey.cpp | goreacraft/OneLife | 53897c580b97ed72013a59e52925953256b96175 | [
"Linux-OpenIB"
] | 24 | 2018-10-11T09:20:27.000Z | 2021-11-06T19:23:17.000Z | #include "minorGems/system/Time.h"
#include "minorGems/util/SimpleVector.h"
#include "minorGems/util/SettingsManager.h"
#include "minorGems/io/file/File.h"
#include "minorGems/util/log/AppLog.h"
#include "../gameSource/objectBank.h"
#include "map.h"
#include <stdlib.h>
static double lastCheckTime = 0;
void initObjectSurvey() {
lastCheckTime = Time::getCurrentTime();
}
void freeObjectSurvey() {
}
static char surveyRunning = false;
static SimpleVector<GridPos> playerPosToCheck;
static int nextPlayerPosToCheck = 0;
static SimpleVector<GridPos> finalPlayerPos;
static int nextFinalPosToAdd = 0;
static SimpleVector<GridPos> mapPosToCheck;
static int mapPosBatch = 100;
static int playerBoxRadius = 10;
typedef struct SurveyRecord {
int id;
int count;
} SurveyRecord;
static SimpleVector<SurveyRecord> objectSurveyRecords;
static SurveyRecord *findRecord( int inID ) {
for( int i=0; i<objectSurveyRecords.size(); i++ ) {
SurveyRecord *r = objectSurveyRecords.getElement( i );
if( r->id == inID ) {
return r;
}
}
return NULL;
}
void stepObjectSurvey() {
if( surveyRunning ) {
if( nextPlayerPosToCheck < playerPosToCheck.size() ) {
// run one step of checking player pos against final list
// on 200 player server, this will take 200 server steps
// (spread work out)
GridPos pos =
playerPosToCheck.getElementDirect( nextPlayerPosToCheck );
nextPlayerPosToCheck ++;
char tooClose = false;
for( int p=0; p<finalPlayerPos.size(); p++ ) {
GridPos thisPos = finalPlayerPos.getElementDirect( p );
if( abs( pos.x - thisPos.x ) <= playerBoxRadius &&
abs( pos.y - thisPos.y ) <= playerBoxRadius ) {
tooClose = true;
break;
}
}
if( ! tooClose ) {
finalPlayerPos.push_back( pos );
}
if( nextPlayerPosToCheck == playerPosToCheck.size() ) {
AppLog::infoF(
"Final object survey list of %d player positions ready",
finalPlayerPos.size() );
}
return;
}
// else final list ready
if( nextFinalPosToAdd < finalPlayerPos.size() ) {
// add all map pos in box radius around player
GridPos pos =
finalPlayerPos.getElementDirect( nextFinalPosToAdd );
nextFinalPosToAdd ++;
for( int y=-playerBoxRadius; y<=playerBoxRadius; y++ ) {
for( int x=-playerBoxRadius; x<=playerBoxRadius; x++ ) {
GridPos boxPos = pos;
boxPos.x += x;
boxPos.y += y;
mapPosToCheck.push_back( boxPos );
}
}
if( nextFinalPosToAdd == finalPlayerPos.size() ) {
AppLog::infoF(
"Final object survey list of %d map positions ready",
mapPosToCheck.size() );
}
return;
}
int numMapPosLeft = mapPosToCheck.size();
if( numMapPosLeft > 0 ) {
int thisBatchSize = mapPosBatch;
if( thisBatchSize > numMapPosLeft ) {
thisBatchSize = numMapPosLeft;
}
for( int i=0; i<thisBatchSize; i++ ) {
GridPos pos =
mapPosToCheck.getElementDirect( numMapPosLeft - 1 );
mapPosToCheck.deleteElement( numMapPosLeft - 1 );
numMapPosLeft--;
int id = getMapObject( pos.x, pos.y );
if( id > 0 ) {
SurveyRecord *r = findRecord( id );
if( r != NULL ) {
r->count ++;
}
else {
SurveyRecord newRec = { id, 1 };
objectSurveyRecords.push_back( newRec );
}
}
}
return;
}
// else totally done, print report
surveyRunning = false;
AppLog::infoF(
"Saving object survey report for %d unique objects",
objectSurveyRecords.size() );
File logDir( NULL, "objectSurveys" );
if( ! logDir.exists() ) {
Directory::makeDirectory( &logDir );
}
if( ! logDir.isDirectory() ) {
AppLog::error( "Non-directory objectSurveys is in the way" );
return;
}
int nextSurveyID = 1;
int numFiles = 0;
File **childFiles = logDir.getChildFiles( &numFiles );
if( numFiles > 0 ) {
for( int i=0; i<numFiles; i++ ) {
char *name = childFiles[i]->getFileName();
int thisNum = 0;
sscanf( name, "survey%d.txt", &thisNum );
if( thisNum >= nextSurveyID ) {
nextSurveyID = thisNum + 1;
}
delete [] name;
delete childFiles[i];
}
}
delete [] childFiles;
char *thisFileName = autoSprintf( "survey%d.txt", nextSurveyID );
File *thisFile = logDir.getChildFile( thisFileName );
char *thisFilePath = thisFile->getFullFileName();
delete [] thisFileName;
delete thisFile;
// easy enough to sort with other tools externally
// just print the counts and IDs and names
FILE *f = fopen( thisFilePath, "w" );
AppLog::infoF(
"Saving object survey report into file %s", thisFilePath );
if( f != NULL ) {
for( int i=0; i<objectSurveyRecords.size(); i++ ) {
SurveyRecord *r = objectSurveyRecords.getElement( i );
fprintf( f, "%d [%d] %s\n",
r->count, r->id, getObject( r->id )->description );
}
fclose( f );
}
else {
AppLog::errorF( "Failed to open %s for writing", thisFilePath );
}
delete [] thisFilePath;
}
}
char shouldRunObjectSurvey() {
double curTime = Time::getCurrentTime();
if( curTime > lastCheckTime + 10 ) {
lastCheckTime = curTime;
char run = false;
if( SettingsManager::getIntSetting( "runObjectSurveyNow", 0 ) ) {
run = true;
SettingsManager::setSetting( "runObjectSurveyNow", 0 );
}
return run;
}
return false;
}
void startObjectSurvey( SimpleVector<GridPos> *inLivingPlayerPositions ) {
AppLog::infoF( "Starting object survey around %d players",
inLivingPlayerPositions->size() );
surveyRunning = true;
playerPosToCheck.deleteAll();
finalPlayerPos.deleteAll();
mapPosToCheck.deleteAll();
objectSurveyRecords.deleteAll();
playerPosToCheck.push_back_other( inLivingPlayerPositions );
nextPlayerPosToCheck = 0;
nextFinalPosToAdd = 0;
}
| 26.107383 | 76 | 0.486247 | [
"object"
] |
79a3df9a04ca9864d13f294f85c32457b5b7061c | 9,459 | cpp | C++ | modules/gate_ops/diffusion/test_diffusion.cpp | ICHEC/QNLP | 2966c7f71e6979c7ddef62520c3749cf6473fabe | [
"Apache-2.0"
] | 29 | 2020-04-13T04:40:35.000Z | 2021-12-17T11:21:35.000Z | modules/gate_ops/diffusion/test_diffusion.cpp | ICHEC/QNLP | 2966c7f71e6979c7ddef62520c3749cf6473fabe | [
"Apache-2.0"
] | 6 | 2020-03-12T17:40:00.000Z | 2021-01-20T12:15:08.000Z | modules/gate_ops/diffusion/test_diffusion.cpp | ICHEC/QNLP | 2966c7f71e6979c7ddef62520c3749cf6473fabe | [
"Apache-2.0"
] | 9 | 2020-09-28T05:00:30.000Z | 2022-03-04T02:11:49.000Z | #include "diffusion.hpp"
#include "oracle.hpp"
#include "Simulator.hpp"
#include "IntelSimulator.cpp"
#include "catch2/catch.hpp"
#include <bitset>
using namespace QNLP;
typedef ComplexDP Type;
/**
* @brief Test diffusion for 4 qubits
*
*/
TEST_CASE("4 qubit diffusion using module","[diffusion]"){
std::size_t num_qubits = 4;
IntelSimulator sim(num_qubits);
auto& reg = sim.getQubitRegister();
double previous_prob = 0.;
SECTION("2^4 bit patterns (16)"){
// Testing patterns 000 001 010 011, etc.
std::vector<std::size_t> bit_patterns;
for(std::size_t s = 0; s < (std::size_t)(0b1 << num_qubits); s++){
bit_patterns.push_back(s);
}
//Declare which indices are control lines
std::vector<std::size_t> ctrl_indices;
for(std::size_t i = 0; i < num_qubits-1; ++i){
ctrl_indices.push_back(i);
}
//Create oracle object with num_ctrl_gates and indices
Oracle<decltype(sim)> oracle;
Diffusion<decltype(sim)> diffusion;
// Loop over given bit-patterns and show effect on resulting state
for(auto &i : bit_patterns){
DYNAMIC_SECTION("bitStringNCU with pattern " << i){
sim.initRegister();
//Create initial superposition
for(std::size_t j = 0; j < num_qubits; ++j){
sim.applyGateH(j);
}
// sqrt(N) iterations optimal
for(int iteration = 1 ; iteration < (M_PI/4)*sqrt( (0b1<<num_qubits) / 1); iteration++){
// Mark state: convert matching state pattern to |11...1>
// apply nCZ, and undo conversion; negates the matched pattern phase
oracle.bitStringNCU(sim, i, ctrl_indices, num_qubits-1, sim.getGateZ(), "Z");
CAPTURE( reg[i], i );
//REQUIRE( reg[i].real() < 0.);
//reg.Print("PRE-DIFF iteration=" + std::to_string(iteration));
diffusion.applyOpDiffusion( sim, ctrl_indices, num_qubits-1);
CAPTURE( reg[i], i );
if(i>0){
REQUIRE( abs(reg[i])*abs(reg[i]) > abs(reg[0])*abs(reg[0]) );
}
else {
REQUIRE( abs(reg[i])*abs(reg[i]) > abs(reg[1])*abs(reg[1]) );
}
REQUIRE( abs(reg[i])*abs(reg[i]) > previous_prob );
previous_prob = abs(reg[i])*abs(reg[i]);
}
}
}
}
}
/**
* @brief Test diffusion for 8 qubits
*
*/
TEST_CASE("8 qubit diffusion using module","[diffusion]"){
std::size_t num_qubits = 8;
IntelSimulator sim(num_qubits);
auto& reg = sim.getQubitRegister();
double previous_prob = 0.;
SECTION("2^8 bit patterns (256)"){
// Testing patterns 000 001 010 011, etc.
std::vector<std::size_t> bit_patterns;
for(std::size_t s = 0; s < (std::size_t)(0b1 << num_qubits); s++){
bit_patterns.push_back(s);
}
//Declare which indices are control lines
std::vector<std::size_t> ctrl_indices;
for(std::size_t i = 0; i < num_qubits-1; ++i){
ctrl_indices.push_back(i);
}
//Create oracle object with num_ctrl_gates and indices
Oracle<decltype(sim)> oracle;
Diffusion<decltype(sim)> diffusion;
// Loop over given bit-patterns and show effect on resulting state
for(auto &i : bit_patterns){
DYNAMIC_SECTION("bitStringNCU with pattern " << i){
sim.initRegister();
//Create initial superposition
for(std::size_t j = 0; j < num_qubits; ++j){
sim.applyGateH(j);
}
// O sqrt(N) iterations optimal
// R = (M_PI/4)*sqrt( (0b1<<num_qubits) / 1);
for(int iteration = 1 ; iteration < (M_PI/4)*sqrt( (0b1<<num_qubits) / 1); iteration++){
// Mark state: convert matching state pattern to |11...1>
// apply nCZ, and undo conversion; negates the matched pattern phase
oracle.bitStringNCU(sim, i, ctrl_indices, num_qubits-1, sim.getGateZ(), "Z");
CAPTURE( reg[i], i );
//REQUIRE( reg[i].real() < 0.);
//reg.Print("PRE-DIFF iteration=" + std::to_string(iteration));
diffusion.applyOpDiffusion( sim, ctrl_indices, num_qubits-1);
CAPTURE( reg[i], i );
if(i>0){
REQUIRE( abs(reg[i])*abs(reg[i]) > abs(reg[0])*abs(reg[0]) );
}
else {
REQUIRE( abs(reg[i])*abs(reg[i]) > abs(reg[1])*abs(reg[1]) );
}
REQUIRE( abs(reg[i])*abs(reg[i]) > previous_prob );
previous_prob = abs(reg[i])*abs(reg[i]);
}
}
}
}
}
/**
* @brief Test diffusion for 4 qubits using Simulator method
*
*/
TEST_CASE("4 qubit diffusion using Simulator method","[diffusion]"){
std::size_t num_qubits = 4;
IntelSimulator sim(num_qubits);
auto& reg = sim.getQubitRegister();
double previous_prob = 0.;
SECTION("2^4 bit patterns (16)"){
// Testing patterns 000 001 010 011, etc.
std::vector<std::size_t> bit_patterns;
for(std::size_t s = 0; s < (std::size_t)(0b1 << num_qubits); s++){
bit_patterns.push_back(s);
}
//Declare which indices are control lines
std::vector<std::size_t> ctrl_indices;
for(std::size_t i = 0; i < num_qubits-1; ++i){
ctrl_indices.push_back(i);
}
// Loop over given bit-patterns and show effect on resulting state
for(auto &i : bit_patterns){
DYNAMIC_SECTION("bitStringNCU with pattern " << i){
sim.initRegister();
//Create initial superposition
for(std::size_t j = 0; j < num_qubits; ++j){
sim.applyGateH(j);
}
// sqrt(N) iterations optimal
for(int iteration = 1 ; iteration < (M_PI/4)*sqrt( (0b1<<num_qubits) / 1); iteration++){
// Mark state: convert matching state pattern to |11...1>
// apply nCZ, and undo conversion; negates the matched pattern phase
sim.applyOracleU(i, ctrl_indices, num_qubits-1, sim.getGateZ(), "Z");
CAPTURE( reg[i], i );
sim.applyDiffusion(ctrl_indices, num_qubits-1);
CAPTURE( reg[i], i );
if(i>0){
REQUIRE( abs(reg[i])*abs(reg[i]) > abs(reg[0])*abs(reg[0]) );
}
else {
REQUIRE( abs(reg[i])*abs(reg[i]) > abs(reg[1])*abs(reg[1]) );
}
REQUIRE( abs(reg[i])*abs(reg[i]) > previous_prob );
previous_prob = abs(reg[i])*abs(reg[i]);
}
}
}
}
}
/**
* @brief Test diffusion for 8 qubits using Simulator method
*
*/
TEST_CASE("8 qubit diffusion using Simulator method","[diffusion]"){
std::size_t num_qubits = 8;
IntelSimulator sim(num_qubits);
auto& reg = sim.getQubitRegister();
double previous_prob = 0.;
SECTION("2^8 bit patterns (256)"){
// Testing patterns 000 001 010 011, etc.
std::vector<std::size_t> bit_patterns;
for(std::size_t s = 0; s < (std::size_t)(0b1 << num_qubits); s++){
bit_patterns.push_back(s);
}
//Declare which indices are control lines
std::vector<std::size_t> ctrl_indices;
for(std::size_t i = 0; i < num_qubits-1; ++i){
ctrl_indices.push_back(i);
}
// Loop over given bit-patterns and show effect on resulting state
for(auto &i : bit_patterns){
DYNAMIC_SECTION("bitStringNCU with pattern " << i){
sim.initRegister();
//Create initial superposition
for(std::size_t j = 0; j < num_qubits; ++j){
sim.applyGateH(j);
}
// O sqrt(N) iterations optimal
// R = (M_PI/4)*sqrt( (0b1<<num_qubits) / 1);
for(int iteration = 1 ; iteration < (M_PI/4)*sqrt( (0b1<<num_qubits) / 1); iteration++){
// Mark state: convert matching state pattern to |11...1>
// apply nCZ, and undo conversion; negates the matched pattern phase
sim.applyOracleU(i, ctrl_indices, num_qubits-1, sim.getGateZ(), "Z");
CAPTURE( reg[i], i );
sim.applyDiffusion(ctrl_indices, num_qubits-1);
CAPTURE( reg[i], i );
if(i>0){
REQUIRE( abs(reg[i])*abs(reg[i]) > abs(reg[0])*abs(reg[0]) );
}
else {
REQUIRE( abs(reg[i])*abs(reg[i]) > abs(reg[1])*abs(reg[1]) );
}
REQUIRE( abs(reg[i])*abs(reg[i]) > previous_prob );
previous_prob = abs(reg[i])*abs(reg[i]);
}
}
}
}
} | 37.535714 | 104 | 0.504916 | [
"object",
"vector"
] |
79a862d04bc2437fbf04b224353879ffb21b715d | 4,662 | cpp | C++ | src/examples/exampleSink.cpp | KanaHayama/opensmile | d800be39d6d5f01321abf3f07300429f7d402eb9 | [
"BSD-3-Clause"
] | 202 | 2016-06-16T12:09:36.000Z | 2022-03-17T08:27:46.000Z | src/examples/exampleSink.cpp | KanaHayama/opensmile | d800be39d6d5f01321abf3f07300429f7d402eb9 | [
"BSD-3-Clause"
] | 206 | 2018-02-19T15:35:57.000Z | 2022-03-25T11:27:38.000Z | src/examples/exampleSink.cpp | KanaHayama/opensmile | d800be39d6d5f01321abf3f07300429f7d402eb9 | [
"BSD-3-Clause"
] | 88 | 2016-01-27T00:23:31.000Z | 2022-03-23T11:35:12.000Z | /*F***************************************************************************
*
* openSMILE - the Munich open source Multimedia Interpretation by
* Large-scale Extraction toolkit
*
* This file is part of openSMILE.
*
* openSMILE is copyright (c) by audEERING GmbH. All rights reserved.
*
* See file "COPYING" for details on usage rights and licensing terms.
* By using, copying, editing, compiling, modifying, reading, etc. this
* file, you agree to the licensing terms in the file COPYING.
* If you do not agree to the licensing terms,
* you must immediately destroy all copies of this file.
*
* THIS SOFTWARE COMES "AS IS", WITH NO WARRANTIES. THIS MEANS NO EXPRESS,
* IMPLIED OR STATUTORY WARRANTY, INCLUDING WITHOUT LIMITATION, WARRANTIES OF
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ANY WARRANTY AGAINST
* INTERFERENCE WITH YOUR ENJOYMENT OF THE SOFTWARE OR ANY WARRANTY OF TITLE
* OR NON-INFRINGEMENT. THERE IS NO WARRANTY THAT THIS SOFTWARE WILL FULFILL
* ANY OF YOUR PARTICULAR PURPOSES OR NEEDS. ALSO, YOU MUST PASS THIS
* DISCLAIMER ON WHENEVER YOU DISTRIBUTE THE SOFTWARE OR DERIVATIVE WORKS.
* NEITHER TUM NOR ANY CONTRIBUTOR TO THE SOFTWARE WILL BE LIABLE FOR ANY
* DAMAGES RELATED TO THE SOFTWARE OR THIS LICENSE AGREEMENT, INCLUDING
* DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL OR INCIDENTAL DAMAGES, TO THE
* MAXIMUM EXTENT THE LAW PERMITS, NO MATTER WHAT LEGAL THEORY IT IS BASED ON.
* ALSO, YOU MUST PASS THIS LIMITATION OF LIABILITY ON WHENEVER YOU DISTRIBUTE
* THE SOFTWARE OR DERIVATIVE WORKS.
*
* Main authors: Florian Eyben, Felix Weninger,
* Martin Woellmer, Bjoern Schuller
*
* Copyright (c) 2008-2013,
* Institute for Human-Machine Communication,
* Technische Universitaet Muenchen, Germany
*
* Copyright (c) 2013-2015,
* audEERING UG (haftungsbeschraenkt),
* Gilching, Germany
*
* Copyright (c) 2016,
* audEERING GmbH,
* Gilching Germany
***************************************************************************E*/
/* openSMILE component:
example dataSink:
reads data from data memory and outputs it to console/logfile (via smileLogger)
this component is also useful for debugging
*/
#include <examples/exampleSink.hpp>
#define MODULE "cExampleSink"
SMILECOMPONENT_STATICS(cExampleSink)
SMILECOMPONENT_REGCOMP(cExampleSink)
{
SMILECOMPONENT_REGCOMP_INIT
scname = COMPONENT_NAME_CEXAMPLESINK;
sdescription = COMPONENT_DESCRIPTION_CEXAMPLESINK;
// we inherit cDataSink configType and extend it:
SMILECOMPONENT_INHERIT_CONFIGTYPE("cDataSink")
SMILECOMPONENT_IFNOTREGAGAIN(
ct->setField("filename","The name of a text file to dump values to (this file will be overwritten, if it exists)",(const char *)NULL);
ct->setField("lag","Output data <lag> frames behind",0,0,0);
)
SMILECOMPONENT_MAKEINFO(cExampleSink);
}
SMILECOMPONENT_CREATE(cExampleSink)
//-----
cExampleSink::cExampleSink(const char *_name) :
cDataSink(_name),
fHandle(NULL)
{
// ...
}
void cExampleSink::fetchConfig()
{
cDataSink::fetchConfig();
filename = getStr("filename");
SMILE_DBG(2,"filename = '%s'",filename);
lag = getInt("lag");
SMILE_DBG(2,"lag = %i",lag);
}
/*
int cExampleSink::myConfigureInstance()
{
return cDataSink::myConfigureInstance();
}
*/
int cExampleSink::myFinaliseInstance()
{
// FIRST call cDataSink myFinaliseInstance, this will finalise our dataWriter...
int ret = cDataSink::myFinaliseInstance();
/* if that was SUCCESSFUL (i.e. ret == 1), then do some stuff like
loading models or opening output files: */
if ((ret)&&(filename != NULL)) {
fHandle = fopen(filename,"w");
if (fHandle == NULL) {
SMILE_IERR(1,"failed to open file '%s' for writing!",filename);
COMP_ERR("aborting");
//return 0;
}
}
return ret;
}
int cExampleSink::myTick(long long t)
{
SMILE_DBG(4,"tick # %i, reading value vector:",t);
cVector *vec= reader_->getFrameRel(lag); //new cVector(nValues+1);
if (vec == NULL) return 0;
//else reader->nextFrame();
long vi = vec->tmeta->vIdx;
double tm = vec->tmeta->time;
// now print the vector:
int i;
for (i=0; i<vec->N; i++) {
//SMILE_PRINT(" (a=%i vi=%i, tm=%fs) %s.%s = %f",reader->getCurR(),vi,tm,reader->getLevelName(),vec->name(i),vec->dataF[i]);
printf(" %s.%s = %f\n",reader_->getLevelName(),vec->name(i),vec->dataF[i]);
}
if (fHandle != NULL) {
for (i=0; i<vec->N; i++) {
fprintf(fHandle, "%s = %f\n",vec->name(i),vec->dataF[i]);
}
}
// tick success
return 1;
}
cExampleSink::~cExampleSink()
{
if (fHandle != NULL) {
fclose(fHandle);
}
}
| 27.75 | 138 | 0.672244 | [
"vector"
] |
79aa39aa765929aa98936b77d5b0080d61d3909b | 1,920 | hpp | C++ | include/cru/ui/mapper/Mapper.hpp | crupest/cru | 3c3a08a02a0f8fc56dc2da3374f025d4fdaf62c5 | [
"Apache-2.0"
] | 1 | 2021-09-30T11:43:03.000Z | 2021-09-30T11:43:03.000Z | include/cru/ui/mapper/Mapper.hpp | crupest/cru | 3c3a08a02a0f8fc56dc2da3374f025d4fdaf62c5 | [
"Apache-2.0"
] | 11 | 2021-08-22T12:55:56.000Z | 2022-03-13T15:01:29.000Z | include/cru/ui/mapper/Mapper.hpp | crupest/cru | 3c3a08a02a0f8fc56dc2da3374f025d4fdaf62c5 | [
"Apache-2.0"
] | null | null | null | #pragma once
#include "../Base.hpp"
#include "cru/common/Exception.hpp"
#include "cru/xml/XmlNode.hpp"
#include <typeindex>
#include <typeinfo>
namespace cru::ui::mapper {
template <typename T>
class Mapper;
class CRU_UI_API MapperBase : public Object {
public:
explicit MapperBase(std::type_index type_index);
CRU_DELETE_COPY(MapperBase)
CRU_DELETE_MOVE(MapperBase)
~MapperBase() override = default;
public:
std::type_index GetTypeIndex() const { return type_index_; }
template <typename T>
Mapper<T>* StaticCast() {
return static_cast<Mapper<T>*>(this);
}
template <typename T>
Mapper<T>* DynamicCast() {
return dynamic_cast<Mapper<T>*>(this);
}
private:
std::type_index type_index_;
};
template <typename T>
class CRU_UI_API BasicMapper : public MapperBase {
public:
BasicMapper() : MapperBase(typeid(T)) {}
CRU_DELETE_COPY(BasicMapper)
CRU_DELETE_MOVE(BasicMapper)
~BasicMapper() override = default;
virtual bool SupportMapFromString() { return false; }
virtual std::unique_ptr<T> MapFromString(String str) {
if (!SupportMapFromString()) {
throw Exception(u"This mapper does not support map from string.");
}
return DoMapFromString(str);
}
virtual bool SupportMapFromXml() { return false; }
virtual bool XmlElementIsOfThisType(xml::XmlElementNode* node) {
return false;
}
std::unique_ptr<T> MapFromXml(xml::XmlElementNode* node) {
if (!SupportMapFromXml()) {
throw new Exception(u"This mapper does not support map from xml.");
}
if (!XmlElementIsOfThisType(node)) {
throw new Exception(u"This xml element is not of mapping type.");
}
return DoMapFromXml(node);
}
protected:
virtual std::unique_ptr<T> DoMapFromString(String str) { return nullptr; }
virtual std::unique_ptr<T> DoMapFromXml(xml::XmlElementNode* node) {
return nullptr;
}
};
} // namespace cru::ui::mapper
| 23.13253 | 76 | 0.703646 | [
"object"
] |
79acd9fee034df85aa5c6393345c765be179d20b | 38,030 | cpp | C++ | termsrv/newclient/rdpdr/w32proc.cpp | npocmaka/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 17 | 2020-11-13T13:42:52.000Z | 2021-09-16T09:13:13.000Z | termsrv/newclient/rdpdr/w32proc.cpp | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 2 | 2020-10-19T08:02:06.000Z | 2020-10-19T08:23:18.000Z | termsrv/newclient/rdpdr/w32proc.cpp | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 14 | 2020-11-14T09:43:20.000Z | 2021-08-28T08:59:57.000Z | /*++
Copyright (c) 1998-2000 Microsoft Corporation
Module Name:
w32proc.cpp
Abstract:
Contains the parent of the Win32 IO processing class hierarchy
for TS Device Redirection, W32ProcObj.
Author:
madan appiah (madana) 16-Sep-1998
Revision History:
--*/
#include <precom.h>
#define TRC_FILE "w32proc"
#include "rdpdrcom.h"
#include <winsock.h>
#include "dbt.h"
#include "w32proc.h"
#include "w32drprn.h"
#include "w32drman.h"
#include "w32drlpt.h"
#include "w32drcom.h"
#include "w32drive.h"
#include "drconfig.h"
#include "drdbg.h"
#include "thrpool.h"
W32ProcObj::W32ProcObj( VCManager *pVCM ) : ProcObj(pVCM)
/*++
Routine Description:
Constructor
Arguments:
pVCM - Virtual Channel IO Manager
Return Value:
NA
--*/
{
DC_BEGIN_FN("W32ProcObj::W32ProcObj");
//
// Initialize the member variables.
//
_pWorkerThread = NULL;
_bWin9xFlag = FALSE;
_hRdpDrModuleHandle = NULL;
_bLocalDevicesScanned = FALSE;
_isShuttingDown = FALSE;
//
// Unit-Test Functions that Tests Thread Pools in the Background
//
#if DBG
//ThreadPoolTestInit();
#endif
DC_END_FN();
}
W32ProcObj::~W32ProcObj(
VOID
)
/*++
Routine Description:
Destructor for the W32ProcObj object.
Arguments:
none.
Return Value:
None
--*/
{
DC_BEGIN_FN("W32ProcObj::~W32ProcObj");
//
// Shutdown the worker thread and cleanup if we are not already shut down.
//
if ((_pWorkerThread != NULL) && (_pWorkerThread->shutDownFlag == FALSE)) {
Shutdown();
}
DC_END_FN();
return;
}
ULONG
W32ProcObj::GetDWordParameter(
LPTSTR pszValueName,
PULONG pulValue
)
/*++
Routine Description:
Reads a parameter ULONG value from the registry.
Arguments:
pszValueName - pointer to the value name string.
pulValue - pointer to an ULONG parameter location.
Return Value:
Windows Error Code.
--*/
{
ULONG ulError;
HKEY hRootKey = HKEY_CURRENT_USER;
HKEY hKey = NULL;
ULONG ulType;
ULONG ulValueDataSize;
DC_BEGIN_FN("W32ProcObj::GetDWordParameter");
TryAgain:
ulError =
RegOpenKeyEx(
hRootKey,
REG_RDPDR_PARAMETER_PATH,
0L,
KEY_READ,
&hKey);
if (ulError != ERROR_SUCCESS) {
TRC_ALT((TB, _T("RegOpenKeyEx() failed, %ld."), ulError));
if( hRootKey == HKEY_CURRENT_USER ) {
//
// try with HKEY_LOCAL_MACHINE.
//
hRootKey = HKEY_LOCAL_MACHINE;
goto TryAgain;
}
goto Cleanup;
}
ulValueDataSize = sizeof(ULONG);
ulError =
RegQueryValueEx(
hKey,
pszValueName,
NULL,
&ulType,
(PBYTE)pulValue,
&ulValueDataSize);
if (ulError != ERROR_SUCCESS) {
TRC_ALT((TB, _T("RegQueryValueEx() failed, %ld."), ulError));
if( hRootKey == HKEY_CURRENT_USER ) {
//
// try with HKEY_LOCAL_MACHINE.
//
hRootKey = HKEY_LOCAL_MACHINE;
RegCloseKey( hKey );
hKey = NULL;
goto TryAgain;
}
goto Cleanup;
}
ASSERT(ulType == REG_DWORD);
ASSERT(ulValueDataSize == sizeof(ULONG));
TRC_NRM((TB, _T("Parameter Value, %lx."), *pulValue));
//
// successfully done.
//
Cleanup:
if( hKey != NULL ) {
RegCloseKey( hKey );
}
DC_END_FN();
return( ulError );
}
ULONG W32ProcObj::GetStringParameter(
IN LPTSTR valueName,
OUT DRSTRING value,
IN ULONG maxSize
)
/*++
Routine Description:
Return Configurable string parameter.
Arguments:
valueName - Name of value to retrieve.
value - Storage location for retrieved value.
maxSize - Number of bytes available in the "value" data
area.
Return Value:
Windows Error Code.
--*/
{
ULONG ulError;
HKEY hRootKey;
HKEY hKey = NULL;
ULONG ulType;
DC_BEGIN_FN("W32ProcObj::GetStringParameter");
//
// Start with HKCU.
//
hRootKey = HKEY_CURRENT_USER;
TryAgain:
//
// Open the reg key.
//
ulError =
RegOpenKeyEx(
hRootKey,
REG_RDPDR_PARAMETER_PATH,
0L,
KEY_READ,
&hKey);
if (ulError != ERROR_SUCCESS) {
TRC_ERR((TB, _T("RegOpenKeyEx %ld."), ulError));
//
// Try with HKEY_LOCAL_MACHINE.
//
if( hRootKey == HKEY_CURRENT_USER ) {
hRootKey = HKEY_LOCAL_MACHINE;
goto TryAgain;
}
goto Cleanup;
}
//
// Query the value.
//
ulError =
RegQueryValueEx(
hKey,
valueName,
NULL,
&ulType,
(PBYTE)value,
&maxSize);
if (ulError != ERROR_SUCCESS) {
TRC_ERR((TB, _T("RegQueryValueEx %ld."), ulError));
//
// Try with HKEY_LOCAL_MACHINE.
//
if( hRootKey == HKEY_CURRENT_USER ) {
hRootKey = HKEY_LOCAL_MACHINE;
RegCloseKey( hKey );
hKey = NULL;
goto TryAgain;
}
goto Cleanup;
}
ASSERT(ulType == REG_SZ);
TRC_NRM((TB, _T("Returning %s"), value));
//
// Successfully done.
//
Cleanup:
if( hKey != NULL ) {
RegCloseKey( hKey );
}
DC_END_FN();
return ulError;
}
ULONG W32ProcObj::Initialize()
/*++
Routine Description:
Initialize an instance of this class.
Arguments:
Return Value:
ERROR_SUCCESS on success. Windows error status, otherwise.
--*/
{
ULONG status = ERROR_SUCCESS;
DC_BEGIN_FN("W32ProcObj::Initialize");
//
// We are not shutting down.
//
_isShuttingDown = FALSE;
//
// Find out which version of the OS is being run.
//
OSVERSIONINFO osVersion;;
osVersion.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
if (!GetVersionEx(&osVersion)) {
status = GetLastError();
TRC_ERR((TB, _T("GetVersionEx: %08X"), status));
SetValid(FALSE);
goto CLEANUPANDEXIT;
}
//
// Are we a 9x OS?
//
if (osVersion.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS) {
_bWin9xFlag = TRUE;
}
//
// Get the background thread timeout value from the registry,
// if it is defined.
//
if (GetDWordParameter(
REGISTRY_BACKGROUNDTHREAD_TIMEOUT_NAME,
&_threadTimeout
) != ERROR_SUCCESS) {
_threadTimeout = REGISTRY_BACKGROUNDTHREAD_TIMEOUT_DEFAULT;
}
TRC_NRM((TB, _T("Thread timeout is %08X"), _threadTimeout));
//
// Instantiate the thread pool.
//
_threadPool = new ThreadPool(THRPOOL_DEFAULTMINTHREADS,
THRPOOL_DEFAULTMAXTHREADS, _threadTimeout);
if (_threadPool == NULL) {
status = ERROR_NOT_ENOUGH_MEMORY;
TRC_ERR((TB, L"Error allocating thread pool."));
SetValid(FALSE);
goto CLEANUPANDEXIT;
}
status = _threadPool->Initialize();
if (status != ERROR_SUCCESS) {
delete _threadPool;
_threadPool = NULL;
SetValid(FALSE);
goto CLEANUPANDEXIT;
}
//
// Create and resume the worker thread.
//
status = CreateWorkerThreadEntry(&_pWorkerThread);
if (status != ERROR_SUCCESS) {
SetValid(FALSE);
goto CLEANUPANDEXIT;
}
if (ResumeThread(_pWorkerThread->hWorkerThread) == 0xFFFFFFFF ) {
SetValid(FALSE);
status = GetLastError();
TRC_ERR((TB, _T("ResumeThread: %08X"), status));
goto CLEANUPANDEXIT;
}
//
// Call the parent's init function.
//
status = ProcObj::Initialize();
if (status != ERROR_SUCCESS) {
goto CLEANUPANDEXIT;
}
CLEANUPANDEXIT:
DC_END_FN();
return status;
}
VOID
W32ProcObj::Shutdown()
/*++
Routine Description:
Triggers the _hShutdownEvent event to terminate the worker thread and
cleans up all resources.
Arguments:
Return Value:
None
--*/
{
ULONG i;
DWORD waitResult;
DC_BEGIN_FN("W32ProcObj::Shutdown");
#if DBG
//ThreadPoolTestShutdown();
#endif
//
// Indicate that the object is in a shutdown state.
//
_isShuttingDown = TRUE;
//
// Wait for the worker thread to shut down.
//
if (_pWorkerThread != NULL) {
//
// Trigger worker thread shutdown and record that we are shutting down.
//
_pWorkerThread->shutDownFlag = TRUE;
SetEvent(_pWorkerThread->controlEvent);
//
// Wait for it to shut down. DebugBreak if we hit the timeout, even in
// free builds. By default, the timeout is infinite.
//
if (_pWorkerThread->hWorkerThread != NULL) {
TRC_NRM((TB, _T("Waiting for worker thread to shut down.")));
waitResult = WaitForSingleObject(
_pWorkerThread->hWorkerThread,
_threadTimeout
);
if (waitResult == WAIT_TIMEOUT) {
TRC_ERR((TB, _T("Thread timeout")));
DebugBreak();
}
else if (waitResult != WAIT_OBJECT_0) {
TRC_ERR((TB, _T("WaitForSingleObject: %08X"), waitResult));
ASSERT(FALSE);
}
}
//
// Remove all the threads in the thread pool.
//
if (_threadPool != NULL) {
_threadPool->RemoveAllThreads();
}
//
// Finish all outstanding IO requests and clean up respective
// request contexts. First object is the control event. Second
// object is the operation dispatch queue data ready event.
//
for (i=2; i<_pWorkerThread->waitableObjectCount; i++) {
PASYNCIOREQCONTEXT reqContext = _pWorkerThread->waitingReqs[i];
ASSERT(reqContext != NULL);
if (reqContext->ioCompleteFunc != NULL) {
reqContext->ioCompleteFunc(reqContext->clientContext,
ERROR_CANCELLED);
}
delete reqContext;
}
//
// Finish any pending operations in the worker thread's opearation
// dispatch queue.
//
//
// Clean up the control event and release the worker thread info. struct.
//
ASSERT(_pWorkerThread->controlEvent != NULL);
CloseHandle(_pWorkerThread->controlEvent);
if (_pWorkerThread->dispatchQueue != NULL) {
delete _pWorkerThread->dispatchQueue;
}
delete _pWorkerThread;
_pWorkerThread = NULL;
}
//
// Let go of the thread pool.
//
if (_threadPool != NULL) {
delete _threadPool;
_threadPool = NULL;
}
//
// Release attached DLL's
//
if (_hRdpDrModuleHandle != NULL) {
FreeLibrary( _hRdpDrModuleHandle );
_hRdpDrModuleHandle = NULL;
}
DC_END_FN();
return;
}
VOID
W32ProcObj::AnnounceDevicesToServer()
/*++
Routine Description:
Enumerate devices and announce them to the server.
Arguments:
Return Value:
--*/
{
DC_BEGIN_FN("W32ProcObj::AnnounceDevicesToServer");
DispatchAsyncIORequest(
(RDPAsyncFunc_StartIO)W32ProcObj::_AnnounceDevicesToServerFunc,
NULL,
NULL,
this
);
}
HANDLE W32ProcObj::_AnnounceDevicesToServerFunc(
W32ProcObj *obj,
DWORD *status
)
/*++
Routine Description:
Enumerate devices and announce them to the server from the
worker thread.
Arguments:
obj - Relevant W32ProcObj instance.
status - Return status.
Return Value:
NULL
--*/
{
obj->AnnounceDevicesToServerFunc(status);
return NULL;
}
VOID W32ProcObj::AnnounceDevicesToServerFunc(
DWORD *status
)
{
DC_BEGIN_FN("W32ProcObj::AnnounceDevicesToServerFunc");
ULONG count, i;
PRDPDR_HEADER pPacketHeader = NULL;
INT sz;
ASSERT(_initialized);
*status = ERROR_SUCCESS;
//
// If we haven't already scanned for local devices.
//
if (!_bLocalDevicesScanned) {
_bLocalDevicesScanned = TRUE;
//
// Invoke the enum functions.
//
count = DeviceEnumFunctionsCount();
for (i=0; i<count; i++) {
// Bail out if the shutdown flag is set.
if (_pWorkerThread->shutDownFlag == TRUE) {
TRC_NRM((TB, _T("Bailing out because shutdown flag is set.")));
*status = WAIT_TIMEOUT;
goto CLEANUPANDEXIT;
}
ASSERT(_DeviceEnumFunctions[i] != NULL);
_DeviceEnumFunctions[i](this, _deviceMgr);
}
}
//
// Send the announce packet to the server. _pVCMgr cleans
// up the packet on failure and on success.
//
pPacketHeader = GenerateAnnouncePacket(&sz, FALSE);
if (pPacketHeader) {
pPacketHeader->Component = RDPDR_CTYP_CORE;
pPacketHeader->PacketId = DR_CORE_DEVICELIST_ANNOUNCE;
_pVCMgr->ChannelWriteEx(pPacketHeader, sz);
}
CLEANUPANDEXIT:
DC_END_FN();
}
DWORD W32ProcObj::DispatchAsyncIORequest(
IN RDPAsyncFunc_StartIO ioStartFunc,
IN OPTIONAL RDPAsyncFunc_IOComplete ioCompleteFunc,
IN OPTIONAL RDPAsyncFunc_IOCancel ioCancelFunc,
IN OPTIONAL PVOID clientContext
)
/*++
Routine Description:
Dispatch an asynchronous IO function.
Arguments:
startFunc - Points to the function that will be called to initiate the IO.
finishFunc - Optionally, points to the function that will be called once
the IO has completed.
clientContext - Optional client information to be associated with the
IO request.
Return Value:
ERROR_SUCCESS or Windows error code.
--*/
{
PASYNCIOREQCONTEXT reqContext;
DWORD result;
DC_BEGIN_FN("W32ProcObj::DispatchAsyncIORequest");
//
// Assert that we are valid.
//
ASSERT(IsValid());
if (!IsValid()) {
DC_END_FN();
return ERROR_INVALID_FUNCTION;
}
//
// Instantiate the IO request context.
//
result = ERROR_SUCCESS;
reqContext = new ASYNCIOREQCONTEXT();
if (reqContext == NULL) {
TRC_ERR((TB, _T("Alloc failed.")));
result = ERROR_NOT_ENOUGH_MEMORY;
}
//
// Fill it in.
//
if (result == ERROR_SUCCESS) {
reqContext->ioStartFunc = ioStartFunc;
reqContext->ioCompleteFunc = ioCompleteFunc;
reqContext->ioCancelFunc = ioCancelFunc;
reqContext->clientContext = clientContext;
reqContext->instance = this;
}
//
// Shove it into the worker thread's operation dispatch queue.
//
if (result == ERROR_SUCCESS) {
if (!_pWorkerThread->dispatchQueue->Enqueue(
(W32DispatchQueueFunc)_DispatchAsyncIORequest_Private,
reqContext
)) {
result = GetLastError();
delete reqContext;
}
}
DC_END_FN();
return result;
}
VOID W32ProcObj::DispatchAsyncIORequest_Private(
IN PASYNCIOREQCONTEXT reqContext,
IN BOOL cancelled
)
/*++
Routine Description:
Handler for asynchronous IO request dispatching.
Arguments:
reqContext - Request context for this function.
cancelled - True if the queued request was cancelled and we need
to clean up.
Return Value:
--*/
{
HANDLE waitableObject;
DWORD result;
DC_BEGIN_FN("W32ProcObj::DispatchAsyncIORequest_Private");
//
// If we are being cancelled, call the cancel function. Otherwise, start the
// IO transaction.
//
if (!cancelled) {
waitableObject = reqContext->ioStartFunc(reqContext->clientContext, &result);
}
else {
TRC_NRM((TB, _T("Cancelling.")));
if (reqContext->ioCancelFunc != NULL) {
reqContext->ioCancelFunc(reqContext->clientContext);
}
waitableObject = NULL;
result = ERROR_CANCELLED;
}
//
// If we have a waitable object then add it to our list.
//
if (waitableObject != NULL) {
result = AddWaitableObjectToWorkerThread(
_pWorkerThread,
waitableObject,
reqContext
);
//
// If we couldn't add the waitable object because we have
// exceeded our max, then requeue the request, but do not
// signal new data in the queue. We will check for new
// data as soon as the waitable object count goes below the
// max.
//
if (result == ERROR_INVALID_INDEX) {
if (!_pWorkerThread->dispatchQueue->Requeue(
(W32DispatchQueueFunc)_DispatchAsyncIORequest_Private,
reqContext, FALSE)) {
result = GetLastError();
}
else {
result = ERROR_SUCCESS;
}
}
}
//
// Complete if IO is not pending and clean up the request context.
//
if (waitableObject == NULL) {
if (!cancelled) {
if (reqContext->ioCompleteFunc != NULL) {
reqContext->ioCompleteFunc(reqContext->clientContext, result);
}
}
delete reqContext;
}
DC_END_FN();
}
ULONG
W32ProcObj::CreateWorkerThreadEntry(
PTHREAD_INFO *ppThreadInfo
)
/*++
Routine Description:
Create a worker thread entry and start the worker thread.
Arguments:
ppThreadInfo - pointer a location where the newly created thread info is
returned.
Return Value:
Windows Status Code.
--*/
{
ULONG ulRetCode;
PTHREAD_INFO pThreadInfo = NULL;
DC_BEGIN_FN("W32ProcObj::CreateWorkerThreadEntry");
//
// Initialize return value.
//
*ppThreadInfo = NULL;
//
// Create the associated thread data structure.
//
pThreadInfo = new THREAD_INFO();
if (pThreadInfo == NULL) {
TRC_ERR((TB, _T("Failed to alloc thread chain info structure.")));
ulRetCode = ERROR_NOT_ENOUGH_MEMORY;
goto Cleanup;
}
//
// Instantiate the dispatch queue.
//
pThreadInfo->dispatchQueue = new W32DispatchQueue();
if (pThreadInfo->dispatchQueue == NULL) {
TRC_ERR((TB, _T("Failed to alloc thread chain info structure.")));
ulRetCode = ERROR_NOT_ENOUGH_MEMORY;
goto Cleanup;
}
ulRetCode = pThreadInfo->dispatchQueue->Initialize();
if (ulRetCode != ERROR_SUCCESS) {
delete pThreadInfo->dispatchQueue;
delete pThreadInfo;
pThreadInfo = NULL;
goto Cleanup;
}
//
// Create the control event and zero out the shutdown flag.
//
pThreadInfo->shutDownFlag = FALSE;
pThreadInfo->controlEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
if (pThreadInfo->controlEvent == NULL) {
TRC_ERR((TB, _T("CreateEvent %ld."), GetLastError()));
delete pThreadInfo->dispatchQueue;
delete pThreadInfo;
pThreadInfo = NULL;
ulRetCode = GetLastError();
goto Cleanup;
}
//
// Init waiting object info array.
//
memset(pThreadInfo->waitableObjects, 0, sizeof(pThreadInfo->waitableObjects));
memset(pThreadInfo->waitingReqs, 0, sizeof(pThreadInfo->waitingReqs));
//
// Set the first waitable object as the controller event object for
// worker thread shutdown.
//
pThreadInfo->waitableObjects[0] = pThreadInfo->controlEvent;
pThreadInfo->waitableObjectCount = 1;
//
// Set the second waitable object as the waitable event for the operation
// dispatch queue.
//
pThreadInfo->waitableObjects[1] = pThreadInfo->dispatchQueue->GetWaitableObject();
pThreadInfo->waitableObjectCount++;
//
// Create the worker thread.
//
pThreadInfo->hWorkerThread = CreateThread(
NULL, 0, _ObjectWorkerThread,
this, CREATE_SUSPENDED,
&pThreadInfo->ulThreadId
);
//
// If failure.
//
if (pThreadInfo->hWorkerThread == NULL) {
ulRetCode = GetLastError();
TRC_ERR((TB, _T("CreateThread failed, %d."), ulRetCode));
goto Cleanup;
}
//
// Success!
//
ulRetCode = ERROR_SUCCESS;
//
// Set the return value.
//
*ppThreadInfo = pThreadInfo;
//
// Set the thread pointer to NULL so we don't clean up.
//
pThreadInfo = NULL;
Cleanup:
//
// Clean up on error.
//
if (pThreadInfo != NULL) {
if (pThreadInfo->dispatchQueue != NULL) {
delete pThreadInfo->dispatchQueue;
}
ASSERT(ulRetCode != ERROR_SUCCESS);
ASSERT(pThreadInfo->controlEvent != NULL);
CloseHandle(pThreadInfo->controlEvent);
delete pThreadInfo;
}
DC_END_FN();
return ulRetCode;
}
VOID
W32ProcObj::ProcessWorkerThreadObject(
PTHREAD_INFO pThreadInfo,
ULONG offset
)
/*++
Routine Description:
Process a signalled worker thread waitable object.
Arguments:
pThreadInfo - pointer to the thread info structure that triggered this even.
offset - offset of object that is signaled.
Return Value:
None
--*/
{
HANDLE hWaitableObject;
PASYNCIOREQCONTEXT reqContext;
DC_BEGIN_FN("W32ProcObj::ProcessWorkerThreadObject");
//
// Check the validity of the waitable object.
//
if (offset >= pThreadInfo->waitableObjectCount) {
ASSERT(FALSE);
goto Cleanup;
}
//
// Get the parms for this waitable object.
//
hWaitableObject = pThreadInfo->waitableObjects[offset];
reqContext = pThreadInfo->waitingReqs[offset];
//
// Invoke the completion function and clean up the request context.
//
if (reqContext->ioCompleteFunc != NULL) {
reqContext->ioCompleteFunc(reqContext->clientContext, ERROR_SUCCESS);
}
delete reqContext;
//
// Move the last items to the now vacant spot and decrement the count.
//
pThreadInfo->waitableObjects[offset] =
pThreadInfo->waitableObjects[pThreadInfo->waitableObjectCount - 1];
pThreadInfo->waitingReqs[offset] =
pThreadInfo->waitingReqs[pThreadInfo->waitableObjectCount - 1];
//
// Clear the unused spot.
//
memset(&pThreadInfo->waitingReqs[pThreadInfo->waitableObjectCount - 1],
0,sizeof(pThreadInfo->waitingReqs[pThreadInfo->waitableObjectCount - 1]));
memset(&pThreadInfo->waitableObjects[pThreadInfo->waitableObjectCount - 1],
0,sizeof(pThreadInfo->waitableObjects[pThreadInfo->waitableObjectCount - 1]));
pThreadInfo->waitableObjectCount--;
//
// Check to see if there are any operations in the queue that are pending
// dispatch. This can happen if an operation was requeued because we
// exceeded the maximum number of waitable objects.
//
CheckForQueuedOperations(pThreadInfo);
Cleanup:
DC_END_FN();
return;
}
ULONG
W32ProcObj::ObjectWorkerThread(
VOID
)
/*++
Routine Description:
Worker Thread that manages waitable objects and their associated
callbacks. This function allows us to do the bulk of the work for
this module in the background so our impact on the client is minimal.
Arguments:
None.
Return Value:
None
--*/
{
ULONG waitResult;
ULONG objectOffset;
W32DispatchQueueFunc func;
PVOID clientData;
DC_BEGIN_FN("W32ProcObj::ObjectWorkerThread");
//
// Loop Forever.
//
for (;;) {
TRC_NRM((TB, _T("Entering wait with %d objects."),
_pWorkerThread->waitableObjectCount));
//
// Wait for all the waitable objects.
//
#ifndef OS_WINCE
waitResult = WaitForMultipleObjectsEx(
_pWorkerThread->waitableObjectCount,
_pWorkerThread->waitableObjects,
FALSE,
INFINITE,
FALSE
);
#else
waitResult = WaitForMultipleObjects(
_pWorkerThread->waitableObjectCount,
_pWorkerThread->waitableObjects,
FALSE,
INFINITE
);
#endif
//
// If the signalled object is the control object or the queue dispatch queue
// data ready object then we need to check for shutdown and for data in the
// dispatch queue.
//
objectOffset = waitResult - WAIT_OBJECT_0;
if ((waitResult == WAIT_FAILED) ||
(objectOffset == 0) ||
(objectOffset == 1)) {
if (_pWorkerThread->shutDownFlag) {
TRC_NRM((TB, _T("Shutting down.")));
break;
}
else {
CheckForQueuedOperations(_pWorkerThread);
}
}
else {
if (objectOffset < _pWorkerThread->waitableObjectCount) {
ProcessWorkerThreadObject(_pWorkerThread, objectOffset);
}
else {
ASSERT(FALSE);
}
}
}
//
// Cancel any outstanding IO requests.
//
TRC_NRM((TB, _T("Canceling outstanding IO.")));
while (_pWorkerThread->dispatchQueue->Dequeue(&func, &clientData)) {
func(clientData, TRUE);
}
DC_END_FN();
return 0;
}
DWORD WINAPI
W32ProcObj::_ObjectWorkerThread(
LPVOID lpParam
)
{
return ((W32ProcObj *)lpParam)->ObjectWorkerThread();
}
VOID W32ProcObj::_DispatchAsyncIORequest_Private(
IN PASYNCIOREQCONTEXT reqContext,
IN BOOL cancelled
)
{
reqContext->instance->DispatchAsyncIORequest_Private(
reqContext,
cancelled);
}
DWORD W32ProcObj::AddWaitableObjectToWorkerThread(
IN PTHREAD_INFO threadInfo,
IN HANDLE waitableObject,
IN PASYNCIOREQCONTEXT reqContext
)
/*++
Routine Description:
Add a waitable object to a worker thread.
Arguments:
threadInfo - Worker thread context.
waitableObject - Waitable object.
reqContext - Context for the IO request.
Return Value:
Returns ERROR_SUCCESS on success. Returns ERROR_INVALID_INDEX if there
isn't currently room for another waitable object in the specified
thread. Otherwise, windows error code is returned.
--*/
{
ULONG waitableObjectCount = threadInfo->waitableObjectCount;
DC_BEGIN_FN("W32ProcObj::AddWaitableObjectToWorkerThread");
//
// Make sure we don't run out of waitable objects.
//
if (waitableObjectCount < MAXIMUM_WAIT_OBJECTS) {
ASSERT(threadInfo->waitableObjects[waitableObjectCount] == NULL);
threadInfo->waitableObjects[waitableObjectCount] = waitableObject;
threadInfo->waitingReqs[waitableObjectCount] = reqContext;
threadInfo->waitableObjectCount++;
DC_END_FN();
return ERROR_SUCCESS;
}
else {
DC_END_FN();
return ERROR_INVALID_INDEX;
}
}
VOID
W32ProcObj::GetClientComputerName(
PBYTE pbBuffer,
PULONG pulBufferLen,
PBOOL pbUnicodeFlag,
PULONG pulCodePage
)
/*++
Routine Description:
Get Client Computer Name.
Arguments:
pbBuffer - pointer to a buffer where the computer name is returned.
pulBufferLen - length of the above buffer.
pbUnicodeFlag - pointer a BOOL location which is SET if the unicode returned
computer name is returned.
pulCodePage - pointer to a ULONG where the codepage value is returned if
ansi computer.
Return Value:
Window Error Code.
--*/
{
ULONG ulLen;
DC_BEGIN_FN("W32ProcObj::GetClientComputerName");
//
// check to see we have sufficient buffer.
//
ASSERT(*pulBufferLen >= ((MAX_COMPUTERNAME_LENGTH + 1) * sizeof(WCHAR)));
#ifndef OS_WINCE
if( _bWin9xFlag == TRUE ) {
//
// get ansi computer name.
//
CHAR achAnsiComputerName[MAX_COMPUTERNAME_LENGTH + 1];
ulLen = sizeof(achAnsiComputerName);
ulLen = GetComputerNameA( (LPSTR)achAnsiComputerName, &ulLen);
if( ulLen != 0 ) {
//
// Convert the string to unicode.
//
RDPConvertToUnicode(
(LPSTR)achAnsiComputerName,
(LPWSTR)pbBuffer,
*pulBufferLen );
}
}
else {
//
// get unicode computer name.
//
ULONG numChars = *pulBufferLen / sizeof(TCHAR);
ulLen = GetComputerNameW( (LPWSTR)pbBuffer, &numChars );
*pulBufferLen = numChars * sizeof(TCHAR);
}
#else
//
// get ansi computer name.
//
CHAR achAnsiComputerName[MAX_COMPUTERNAME_LENGTH + 1];
if (gethostname(achAnsiComputerName, sizeof(achAnsiComputerName)) == 0)
{
ulLen = strlen(achAnsiComputerName);
}
else {
ulLen = 0;
}
if( ulLen != 0 ) {
//
// Convert the string to unicode.
//
RDPConvertToUnicode(
(LPSTR)achAnsiComputerName,
(LPWSTR)pbBuffer,
*pulBufferLen );
}
#endif
if( ulLen == 0 ) {
ULONG ulError;
ulError = GetLastError();
ASSERT(ulError != ERROR_BUFFER_OVERFLOW);
TRC_ERR((TB, _T("GetComputerNameA() failed, %ld."), ulError));
*(LPWSTR)pbBuffer = L'\0';
}
//
// set return parameters.
//
*pbUnicodeFlag = TRUE;
*pulCodePage = 0;
*pulBufferLen = ((wcslen((LPWSTR)pbBuffer) + 1) * sizeof(WCHAR));
Cleanup:
DC_END_FN();
return;
}
VOID
W32ProcObj::CheckForQueuedOperations(
IN PTHREAD_INFO thread
)
/*++
Routine Description:
Check the operation dispatch queue for queued operations.
Arguments:
thread - Is the thread form which to dequeue the next operation.
Return Value:
ERROR_SUCCESS on success. Otherwise, Windows error code is returned.
--*/
{
W32DispatchQueueFunc func;
PVOID clientData;
DC_BEGIN_FN("W32ProcObj::CheckForQueuedOperations");
while (thread->dispatchQueue->Dequeue(&func, &clientData)) {
func(clientData, FALSE);
}
DC_END_FN();
}
void
W32ProcObj::OnDeviceChange(
IN WPARAM wParam,
IN LPARAM lParam)
/*++
Routine Description:
On Device Change notification
Arguments:
wParam device change notification type
lParam device change info
Return Value:
N/A
--*/
{
W32DeviceChangeParam *param = NULL;
BYTE *devBuffer = NULL;
DEV_BROADCAST_HDR *pDBHdr;
DWORD status = ERROR_OUTOFMEMORY;
DC_BEGIN_FN("W32ProcObj::OnDeviceChange");
//
// We only care about device arrival and removal.
//
if (wParam == DBT_DEVICEARRIVAL || wParam == DBT_DEVICEREMOVECOMPLETE) {
pDBHdr = (DEV_BROADCAST_HDR *)lParam;
if (pDBHdr != NULL && pDBHdr->dbch_devicetype == DBT_DEVTYP_VOLUME) {
DEV_BROADCAST_VOLUME * pDBVol = (DEV_BROADCAST_VOLUME *)lParam;
if (!(pDBVol->dbcv_flags & DBTF_MEDIA)) {
devBuffer = new BYTE[pDBHdr->dbch_size];
if (devBuffer != NULL) {
memcpy(devBuffer, (void*)lParam, pDBHdr->dbch_size);
param = new W32DeviceChangeParam(this, wParam, (LPARAM)devBuffer);
if (param != NULL) {
status = DispatchAsyncIORequest(
(RDPAsyncFunc_StartIO)W32ProcObj::_OnDeviceChangeFunc,
NULL,
NULL,
param
);
}
else {
status = GetLastError();
}
}
//
// Clean up
//
if (status != ERROR_SUCCESS) {
if (param != NULL) {
delete param;
}
if (devBuffer != NULL) {
delete devBuffer;
}
}
}
}
}
DC_END_FN();
}
HANDLE W32ProcObj::_OnDeviceChangeFunc(
W32DeviceChangeParam *param,
DWORD *status
)
/*++
Routine Description:
Handle device change notification from the worker thread.
Arguments:
param - Relevant W32DeviceChangeParam
status - Return status.
Return Value:
NULL
--*/
{
DC_BEGIN_FN("_OnDeviceChangeFunc");
ASSERT(param != NULL);
param->_instance->OnDeviceChangeFunc(status, param->_wParam, param->_lParam);
DC_END_FN();
delete ((void *)(param->_lParam));
delete param;
return NULL;
}
void
W32ProcObj::OnDeviceChangeFunc(
DWORD *status,
IN WPARAM wParam,
IN LPARAM lParam)
/*++
Routine Description:
On Device Change notification
Arguments:
status return status
wParam device change notification type
lParam device change info
Return Value:
N/A
--*/
{
DEV_BROADCAST_HDR *pDBHdr;
PRDPDR_HEADER pPacketHeader = NULL;
INT sz;
DC_BEGIN_FN("OnDeviceChangeFunc");
ASSERT(_initialized);
*status = ERROR_SUCCESS;
pDBHdr = (DEV_BROADCAST_HDR *)lParam;
switch (wParam) {
//
// Device arrival
//
case DBT_DEVICEARRIVAL:
//
// This is a volume device arrival message
//
if (pDBHdr->dbch_devicetype == DBT_DEVTYP_VOLUME) {
DEV_BROADCAST_VOLUME * pDBVol = (DEV_BROADCAST_VOLUME *)lParam;
if (!(pDBVol->dbcv_flags & DBTF_MEDIA)) {
DWORD unitMask = pDBVol->dbcv_unitmask;
W32Drive::EnumerateDrives(this, _deviceMgr, unitMask);
pPacketHeader = GenerateAnnouncePacket(&sz, TRUE);
if (pPacketHeader) {
pPacketHeader->Component = RDPDR_CTYP_CORE;
pPacketHeader->PacketId = DR_CORE_DEVICELIST_ANNOUNCE;
_pVCMgr->ChannelWrite(pPacketHeader, sz);
}
}
}
break;
//
// Device removal
//
case DBT_DEVICEREMOVECOMPLETE:
//
// This is a volume device removal message
//
if (pDBHdr->dbch_devicetype == DBT_DEVTYP_VOLUME) {
DEV_BROADCAST_VOLUME * pDBVol = (DEV_BROADCAST_VOLUME *)lParam;
if (!(pDBVol->dbcv_flags & DBTF_MEDIA)) {
DWORD unitMask = pDBVol->dbcv_unitmask;
W32Drive::RemoveDrives(this, _deviceMgr, unitMask);
pPacketHeader = GenerateDeviceRemovePacket(&sz);
if (pPacketHeader) {
pPacketHeader->Component = RDPDR_CTYP_CORE;
pPacketHeader->PacketId = DR_CORE_DEVICELIST_REMOVE;
_pVCMgr->ChannelWrite(pPacketHeader, sz);
}
}
}
break;
default:
return;
}
DC_END_FN();
}
| 24.054396 | 95 | 0.54578 | [
"object"
] |
79b72cae34ce74844d593b21aedc24e4fbea69a4 | 1,713 | cpp | C++ | CGR_Codeforces/b.cpp | JackBai0914/Competitive-Programming-Codebase | a1cabf0fa5072b07a7da25d66bf455eb45b0b7e9 | [
"MIT"
] | null | null | null | CGR_Codeforces/b.cpp | JackBai0914/Competitive-Programming-Codebase | a1cabf0fa5072b07a7da25d66bf455eb45b0b7e9 | [
"MIT"
] | null | null | null | CGR_Codeforces/b.cpp | JackBai0914/Competitive-Programming-Codebase | a1cabf0fa5072b07a7da25d66bf455eb45b0b7e9 | [
"MIT"
] | null | null | null | /*
* * * * * * * * * * * * * * * * * *
*
* @author: Xingjian Bai
* @date: 2020-10-10 16:01:05
* @description:
* /Users/jackbai/Desktop/OI/CGR_Codeforces/b.cpp
*
* @notes:
* g++ -O2 -fsanitize=address -ftrapv b.cpp
* * * * * * * * * * * * * * * * * */
#include <bits/stdc++.h>
#define F first
#define S second
#define mp make_pair
using namespace std;
typedef long long ll;
typedef long double ld;
typedef pair <int, int> pii;
const int MOD = 1000000007;
const ll INF = 1e18;
const ld eps = 1e-8;
#define FOR(i,a,b) for (int i = (a); i < (b); i ++)
#define F0R(i,a) FOR(i, 0, a)
#define ROF(i, a, b) for (int i = (b) - 1; i >= a; i --)
#define R0F(i, a) ROF(i, 0, a)
#define trav(a, x) for (auto& a: x)
#define debug(x) cerr << "(debug mod) " << #x << " = " << x << endl
int n, k;
string s;
vector <int> q;
int main() {
int t;
cin >> t;
while (t --) {
int old = 0, cnt = 0, ans = 0;
cin >> n >> k;
q.resize(0);
cin >> s;
if (n == 1) {
if (k == 0 && s[0] == 'L') printf("0\n");
else printf("1\n");
continue ;
}
int prev = -1;
F0R(i, s.size()) {
if (s[i] == 'W') {
old += 1 + (i > 0 && s[i - 1] == 'W');
if (prev != i - 1) {
if (prev == -1) cnt += i;
else q.push_back(i - prev - 1);
}
prev = i;
}
}
if (old == 0) {
printf("%d\n", max(0, 2 * min(k, n) - 1));
continue ;
}
cnt += s.size() - prev - 1;
sort(q.begin(), q.end());
int pter = 0;
while (pter < q.size() && k >= q[pter]) {
// debug(q[pter]);
ans += 2 * q[pter] + 1;
k -= q[pter];
pter ++;
}
if (pter < q.size())
ans += 2 * k;
else
ans += 2 * min(k, cnt);
printf("%d\n", ans + old);
}
return 0;
} | 21.4125 | 67 | 0.461179 | [
"vector"
] |
79c088d6490aeb54f7b1a2de2a82c70d00261e54 | 2,257 | cpp | C++ | third_party/di-cpp14/extension/policies/types_dumper.cpp | robhendriks/city-defence | 6567222087fc74bf374423d4aab5512cbe86ac07 | [
"MIT"
] | null | null | null | third_party/di-cpp14/extension/policies/types_dumper.cpp | robhendriks/city-defence | 6567222087fc74bf374423d4aab5512cbe86ac07 | [
"MIT"
] | null | null | null | third_party/di-cpp14/extension/policies/types_dumper.cpp | robhendriks/city-defence | 6567222087fc74bf374423d4aab5512cbe86ac07 | [
"MIT"
] | 1 | 2022-03-29T02:01:56.000Z | 2022-03-29T02:01:56.000Z | //
// Copyright (c) 2012-2016 Krzysztof Jusiak (krzysztof at jusiak dot net)
//
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
//<-
#include <iostream>
#include <memory>
#include <string>
#include <typeinfo>
#include <vector>
//->
#include <boost/di.hpp>
namespace di = boost::di;
//<-
auto int_1 = [] { return "first int"; };
auto int_2 = [] { return "second int"; };
struct i0 {
virtual ~i0(){};
};
struct c0 : i0 {};
struct c1 {
c1(std::shared_ptr<i0>, int) {}
};
struct c2 {
BOOST_DI_INJECT(c2, (named = int_1) int, (named = int_2) int, char) {}
};
struct c3 {
c3(std::shared_ptr<c1>, std::shared_ptr<c2>) {}
};
// doesn't work inside polices yet / tested with gcc-5.1 and clang-3.7
static std::vector<int> v = {0};
static int i = 1;
//->
/*<<define `types dumper` directly in configuration>>*/
class types_dumper : public di::config {
public:
static auto policies(...) noexcept {
return di::make_policies([](auto type) {
using T = decltype(type);
using arg = typename T::type;
using name = typename T::name;
using given = typename T::given;
auto tab = v[i - 1];
while (tab--) {
std::clog << " ";
}
std::clog << "(" << typeid(arg).name() << ((*(name*)(0))() ? std::string("[") + (*(name*)(0))() + std::string("]") : "")
<< " -> " << typeid(given).name() << ")" << std::endl;
auto ctor_size = T::arity::value;
while (ctor_size--) {
v.insert((v.begin() + i), v[i - 1] + 1);
}
++i;
});
}
};
int main() {
/*<<define injector>>*/
// clang-format off
auto injector = di::make_injector<types_dumper>(
di::bind<i0>().to<c0>()
, di::bind<int>().named(int_1).to(42)
, di::bind<int>().named(int_2).to(42)
);
// clang-format on
/*<<iterate through created objects with `types_dumper`>>*/
injector.create<c3>();
/*<< output [pre
(2c3 -> 2c3)
(St10shared_ptrI2c1E -> 2c1)
(St10shared_ptrI2i0E -> 2c0)
(i -> i)
(St10shared_ptrI2c2E -> 2c2)
(i[first int] -> i)
(i[second int] -> i)
(c -> c)
]>>*/
}
| 24.532609 | 126 | 0.548073 | [
"vector"
] |
79c983dd18b993c490b6b9b24ee33f1dc786fd2f | 812 | cpp | C++ | Questions Level-Wise/Medium/max-increase-to-keep-city-skyline.cpp | PrakharPipersania/LeetCode-Solutions | ea74534bbdcf1ca3ea4d88a1081582e0e15f50c7 | [
"MIT"
] | 2 | 2021-03-05T22:32:23.000Z | 2021-03-05T22:32:29.000Z | Questions Level-Wise/Medium/max-increase-to-keep-city-skyline.cpp | PrakharPipersania/LeetCode-Solutions | ea74534bbdcf1ca3ea4d88a1081582e0e15f50c7 | [
"MIT"
] | null | null | null | Questions Level-Wise/Medium/max-increase-to-keep-city-skyline.cpp | PrakharPipersania/LeetCode-Solutions | ea74534bbdcf1ca3ea4d88a1081582e0e15f50c7 | [
"MIT"
] | null | null | null | class Solution {
public:
int maxIncreaseKeepingSkyline(vector<vector<int>>& grid)
{
int count=0;
vector<int> lr(grid.size());
vector<int> tb(grid[0].size());
for(int i=0;i<grid.size();i++)
{
for(int j=0;j<grid[i].size();j++)
{
if(grid[i][j]>lr[i])
lr[i]=grid[i][j];
if(grid[i][j]>tb[j])
tb[j]=grid[i][j];
}
}
for(int i=0;i<grid.size();i++)
{
for(int j=0;j<grid[i].size();j++)
{
if(lr[i]>tb[j])
count+=tb[j]-grid[i][j];
else
count+=lr[i]-grid[i][j];
}
}
return count;
}
};
| 26.193548 | 62 | 0.343596 | [
"vector"
] |
79cec4c9ccad82d8fe1bf5cb9bb328d8198d0869 | 4,781 | cpp | C++ | nestedtensor/csrc/autograd_functions.cpp | SamuelMarks/nestedtensor | b8ab0e498013cb725084a3a769cd96aacbf02aac | [
"BSD-3-Clause"
] | 1 | 2021-07-16T16:09:51.000Z | 2021-07-16T16:09:51.000Z | nestedtensor/csrc/autograd_functions.cpp | SamuelMarks/nestedtensor | b8ab0e498013cb725084a3a769cd96aacbf02aac | [
"BSD-3-Clause"
] | null | null | null | nestedtensor/csrc/autograd_functions.cpp | SamuelMarks/nestedtensor | b8ab0e498013cb725084a3a769cd96aacbf02aac | [
"BSD-3-Clause"
] | null | null | null | #include <nestedtensor/csrc/nested_tensor_impl.h>
#include <nestedtensor/csrc/utils/nested_node_functions.h>
#include <torch/extension.h>
#include <torch/library.h>
using namespace torch::nn;
namespace F = torch::nn::functional;
namespace at {
Tensor NestedTensor_dropout(const Tensor& input, double p, bool train) {
return autograd_map_nested_tensor(
[&](const at::Tensor t) { return at::dropout(t, p, train); }, input);
}
Tensor NestedTensor_upsample_bilinear2d(
const Tensor& input,
IntArrayRef output_size,
bool align_corners,
c10::optional<double> scales_h,
c10::optional<double> scales_w) {
return autograd_map_nested_tensor(
[&](at::Tensor t) {
return at::upsample_bilinear2d(
t.unsqueeze(0),
output_size,
align_corners,
scales_h,
scales_w)
.squeeze(0);
},
input);
}
Tensor NestedTensor_clone(
const Tensor& src,
c10::optional<c10::MemoryFormat> optional_memory_format) {
return autograd_map_nested_tensor(
[&optional_memory_format](Tensor a) {
return at::clone(a, optional_memory_format);
},
src);
}
void check_dims_match_num_input_features(
const char* arg_name,
int64_t expected,
int64_t actual) {
TORCH_CHECK(
actual == expected,
arg_name,
" should contain ",
expected,
" elements not ",
actual);
}
std::vector<int64_t> make_reduce_dims(int64_t input_dim) {
std::vector<int64_t> result;
result.push_back(0);
for (int64_t i = 2; i < input_dim; i++) {
result.push_back(i);
}
return result;
}
std::vector<int64_t> make_scalar_shape(int64_t input_dim, int64_t n_input) {
std::vector<int64_t> result;
result.push_back(1);
result.push_back(n_input);
for (int64_t i = 2; i < input_dim; i++) {
result.push_back(1);
}
return result;
}
Tensor NestedTensor_batch_norm(
const Tensor& input,
const c10::optional<Tensor>& weight /* optional */,
const c10::optional<Tensor>& bias /* optional */,
const c10::optional<Tensor>& running_mean /* optional */,
const c10::optional<Tensor>& running_var /* optional */,
bool training,
double momentum,
double eps,
bool cudnn_enabled) {
auto opt_sizes = get_nested_tensor_impl(input)->opt_sizes();
TORCH_CHECK(opt_sizes[1], "batch norm requires regular second dimension.");
int64_t n_input = *opt_sizes[1];
if (running_mean) {
check_dims_match_num_input_features(
"running_mean", n_input, running_mean->numel());
} else if (!training) {
AT_ERROR("running_mean must be defined in evaluation mode");
}
if (running_var) {
check_dims_match_num_input_features(
"running_var", n_input, running_var->numel());
} else if (!training) {
AT_ERROR("running_var must be defined in evaluation mode");
}
if (weight) {
check_dims_match_num_input_features(
"weight", n_input, weight->numel());
}
if (bias) {
check_dims_match_num_input_features("bias", n_input, bias->numel());
}
auto scalar_shape = make_scalar_shape(input.dim(), n_input);
at::Tensor mean;
at::Tensor invstd;
at::Tensor save_mean;
at::Tensor save_invstd;
if (training) {
auto reduce_dims = make_reduce_dims(input.dim());
save_mean = at::mean(input, IntArrayRef(reduce_dims));
save_invstd =
1 / at::sqrt(at::var(input, IntArrayRef(reduce_dims), false) + eps);
if (running_mean) {
at::Tensor running_mean_(running_mean->getIntrusivePtr());
running_mean_ = running_mean_.detach();
running_mean_.copy_(
momentum * save_mean + (1 - momentum) * running_mean_);
}
if (running_var) {
Tensor unbiased_var = at::var(input, IntArrayRef(reduce_dims));
at::Tensor running_var_(running_var->getIntrusivePtr());
running_var_ = running_var_.detach();
running_var_.copy_(
momentum * unbiased_var + (1 - momentum) * running_var_);
}
mean = save_mean;
invstd = save_invstd;
} else {
mean = *running_mean;
invstd = 1 / at::sqrt(*running_var + eps);
}
Tensor output = input;
output = output - mean.reshape(IntArrayRef(scalar_shape));
output = output * invstd.reshape(IntArrayRef(scalar_shape));
if (weight) {
output = output * weight->reshape(IntArrayRef(scalar_shape));
}
if (bias) {
output = output + bias->reshape(IntArrayRef(scalar_shape));
}
return output;
}
TORCH_LIBRARY_IMPL(aten, AutogradNestedTensor, m) {
// nt_impl(m, "upsample_bilinear2d", NestedTensor_upsample_bilinear2d);
nt_impl(m, "clone", NestedTensor_clone);
nt_impl(m, "dropout", NestedTensor_dropout);
nt_impl(m, "batch_norm", NestedTensor_batch_norm);
}
} // namespace at
| 28.628743 | 77 | 0.667015 | [
"vector"
] |
79d43ce80b6670bc9c2c56aafcd3aad4aff24795 | 1,843 | cc | C++ | iqa/src/model/GetPredictResultRequest.cc | iamzken/aliyun-openapi-cpp-sdk | 3c991c9ca949b6003c8f498ce7a672ea88162bf1 | [
"Apache-2.0"
] | 89 | 2018-02-02T03:54:39.000Z | 2021-12-13T01:32:55.000Z | iqa/src/model/GetPredictResultRequest.cc | iamzken/aliyun-openapi-cpp-sdk | 3c991c9ca949b6003c8f498ce7a672ea88162bf1 | [
"Apache-2.0"
] | 89 | 2018-03-14T07:44:54.000Z | 2021-11-26T07:43:25.000Z | iqa/src/model/GetPredictResultRequest.cc | aliyun/aliyun-openapi-cpp-sdk | 0cf5861ece17dfb0bb251f13bf3fbdb39c0c6e36 | [
"Apache-2.0"
] | 69 | 2018-01-22T09:45:52.000Z | 2022-03-28T07:58:38.000Z | /*
* Copyright 2009-2017 Alibaba Cloud All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <alibabacloud/iqa/model/GetPredictResultRequest.h>
using AlibabaCloud::Iqa::Model::GetPredictResultRequest;
GetPredictResultRequest::GetPredictResultRequest() :
RpcServiceRequest("iqa", "2019-08-13", "GetPredictResult")
{
setMethod(HttpRequest::Method::Post);
}
GetPredictResultRequest::~GetPredictResultRequest()
{}
int GetPredictResultRequest::getTopK()const
{
return topK_;
}
void GetPredictResultRequest::setTopK(int topK)
{
topK_ = topK;
setParameter("TopK", std::to_string(topK));
}
std::string GetPredictResultRequest::getTraceTag()const
{
return traceTag_;
}
void GetPredictResultRequest::setTraceTag(const std::string& traceTag)
{
traceTag_ = traceTag;
setParameter("TraceTag", traceTag);
}
std::string GetPredictResultRequest::getQuestion()const
{
return question_;
}
void GetPredictResultRequest::setQuestion(const std::string& question)
{
question_ = question;
setBodyParameter("Question", question);
}
std::string GetPredictResultRequest::getProjectId()const
{
return projectId_;
}
void GetPredictResultRequest::setProjectId(const std::string& projectId)
{
projectId_ = projectId;
setParameter("ProjectId", projectId);
}
| 24.905405 | 75 | 0.745524 | [
"model"
] |
79db70c3595dbd307dfcebc2f3816704da844da2 | 2,714 | hpp | C++ | inst/include/geojsonsf/sf/sfc/utils/sfc_utils.hpp | layik/geojsonsf | 7c86ade17fcdd72a9b2bc7074a259282a20813d2 | [
"MIT"
] | 61 | 2018-04-02T12:01:19.000Z | 2022-01-25T14:30:56.000Z | inst/include/geojsonsf/sf/sfc/utils/sfc_utils.hpp | layik/geojsonsf | 7c86ade17fcdd72a9b2bc7074a259282a20813d2 | [
"MIT"
] | 75 | 2018-04-11T00:01:45.000Z | 2022-03-03T23:29:53.000Z | inst/include/geojsonsf/sf/sfc/utils/sfc_utils.hpp | layik/geojsonsf | 7c86ade17fcdd72a9b2bc7074a259282a20813d2 | [
"MIT"
] | 7 | 2018-04-15T10:33:33.000Z | 2021-12-09T12:02:35.000Z | #ifndef GEOJSONSF_SFC_UTILS_H
#define GEOJSONSF_SFC_UTILS_H
#include "geojsonsf/geojsonsf.h"
#include "geometries/bbox/bbox.hpp"
#include "sfheaders/sfc/sfc_attributes.hpp"
namespace geojsonsf {
namespace sfc {
namespace utils {
inline Rcpp::NumericVector start_bbox() {
Rcpp::NumericVector bbox(4); // xmin, ymin, xmax, ymax
bbox(0) = bbox(1) = bbox(2) = bbox(3) = NA_REAL;
return bbox;
}
inline Rcpp::NumericVector start_zm_range() {
Rcpp::NumericVector range(2);
range(0) = range(1) = NA_REAL;
return range;
}
inline Rcpp::List create_null_sfc() {
Rcpp::List empty_sfc(0);
std::string type = "GEOMETRY";
Rcpp::NumericVector bbox = start_bbox();
Rcpp::NumericVector z_range = start_zm_range();
Rcpp::NumericVector m_range = start_zm_range();
int n_empty = 0;
std::unordered_set< std::string > geometry_types{"GEOMETRY"};
// int epsg = geojsonsf::EPSG;
//std::string proj = geojsonsf::PROJ4STRING;
// Rcpp::String proj = geojsonsf::PROJ4STRING;
Rcpp::List crs = Rcpp::List::create(
Rcpp::_["input"] = geojsonsf::INPUT,
Rcpp::_["wkt"] = geojsonsf::WKT
);
sfheaders::sfc::attach_sfc_attributes(
empty_sfc, type, geometry_types, bbox, z_range, m_range, crs, n_empty
);
return empty_sfc;
}
inline void fetch_geometries(
Rcpp::List& sf,
Rcpp::List& res,
R_xlen_t& sfg_counter
) {
std::string geom_attr;
for (Rcpp::List::iterator it = sf.begin(); it != sf.end(); it++) {
switch( TYPEOF(*it) ) {
case VECSXP: {
Rcpp::List tmp = Rcpp::as< Rcpp::List >( *it );
if(Rf_isNull(tmp.attr("class"))) {
fetch_geometries(tmp, res, sfg_counter);
} else {
res[sfg_counter] = tmp;
sfg_counter++;
}
break;
}
case REALSXP: {
Rcpp::NumericVector tmp = Rcpp::as< Rcpp::NumericVector >( *it );
if(Rf_isNull(tmp.attr("class"))) {
Rcpp::stop("Geometry could not be determined");
} else {
res[sfg_counter] = tmp;
sfg_counter++;
}
break;
}
case INTSXP: {
Rcpp::IntegerVector tmp = Rcpp::as< Rcpp::IntegerVector >( *it );
if(Rf_isNull( tmp.attr( "class" ) ) ){
Rcpp::stop("Geometry could not be determined");
} else {
res[sfg_counter] = tmp;
sfg_counter++;
}
break;
}
case STRSXP: {
Rcpp::StringVector tmp = Rcpp::as< Rcpp::StringVector >( *it );
if(Rf_isNull( tmp.attr( "class" ) ) ) {
Rcpp::stop("Geometry could not be determined");
} else {
res[sfg_counter] = tmp;
sfg_counter++;
}
break;
}
default: {
res[0] = create_null_sfc();
//Rcpp::stop("Geometry could not be determined");
}
}
}
}
} // namespace utils
} // namespace sfc
} // namespace geojsonsf
#endif
| 23.396552 | 72 | 0.628592 | [
"geometry"
] |
0764e122bed049d5cdcca2789cb4f3079e319089 | 16,075 | hxx | C++ | Helpers.hxx | daviddoria/CriminisiLidarInpainting | e599d9bf4732b1d94991f6348ad1c8cf6e8bce30 | [
"Apache-2.0"
] | 2 | 2017-12-24T17:00:54.000Z | 2018-12-01T01:46:53.000Z | Helpers.hxx | daviddoria/CriminisiLidarInpainting | e599d9bf4732b1d94991f6348ad1c8cf6e8bce30 | [
"Apache-2.0"
] | null | null | null | Helpers.hxx | daviddoria/CriminisiLidarInpainting | e599d9bf4732b1d94991f6348ad1c8cf6e8bce30 | [
"Apache-2.0"
] | null | null | null | /*=========================================================================
*
* Copyright David Doria 2011 daviddoria@gmail.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0.txt
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*=========================================================================*/
#include "itkCastImageFilter.h"
// STL
#include <iomanip> // for setfill()
// VTK
#include <vtkImageData.h>
// Custom
#include "Mask.h"
namespace Helpers
{
/** Copy the input to the output*/
template<typename TImage>
void DeepCopy(typename TImage::Pointer input, typename TImage::Pointer output)
{
output->SetRegions(input->GetLargestPossibleRegion());
output->Allocate();
itk::ImageRegionConstIterator<TImage> inputIterator(input, input->GetLargestPossibleRegion());
itk::ImageRegionIterator<TImage> outputIterator(output, output->GetLargestPossibleRegion());
while(!inputIterator.IsAtEnd())
{
outputIterator.Set(inputIterator.Get());
++inputIterator;
++outputIterator;
}
}
/** Copy the input to the output*/
template<typename TImage>
void DeepCopyVectorImage(typename TImage::Pointer input, typename TImage::Pointer output)
{
output->SetRegions(input->GetLargestPossibleRegion());
output->SetNumberOfComponentsPerPixel(input->GetNumberOfComponentsPerPixel());
output->Allocate();
itk::ImageRegionConstIterator<TImage> inputIterator(input, input->GetLargestPossibleRegion());
itk::ImageRegionIterator<TImage> outputIterator(output, output->GetLargestPossibleRegion());
while(!inputIterator.IsAtEnd())
{
outputIterator.Set(inputIterator.Get());
++inputIterator;
++outputIterator;
}
}
// template <typename TPixelType>
// float PixelSquaredDifference(const TPixelType& pixel1, const TPixelType& pixel2)
// {
//
// // std::cout << "pixel1: " << pixel1 << " pixel2: " << pixel2
// // << " pixel1-pixel2: " << pixel1-pixel2
// // << " squared norm: " << (pixel1-pixel2).GetSquaredNorm() << std::endl;
//
// //return (pixel1-pixel2).GetSquaredNorm();
//
// float difference = 0;
// unsigned int componentsPerPixel = pixel1.GetSize();
// for(unsigned int i = 0; i < componentsPerPixel; ++i)
// {
// difference += (pixel1[i] - pixel2[i]) *
// (pixel1[i] - pixel2[i]);
// }
// return difference;
// }
template<typename T>
void ReplaceValue(typename T::Pointer image, const typename T::PixelType queryValue, const typename T::PixelType replacementValue)
{
// This function replaces all pixels in 'image' equal to 'queryValue' with 'replacementValue'
itk::ImageRegionIterator<T> imageIterator(image, image->GetLargestPossibleRegion());
imageIterator.GoToBegin();
while(!imageIterator.IsAtEnd())
{
if(imageIterator.Get() == queryValue)
{
imageIterator.Set(replacementValue);
}
++imageIterator;
}
}
template<typename T>
void WriteImage(typename T::Pointer image, std::string filename)
{
// This is a convenience function so that images can be written in 1 line instead of 4.
typename itk::ImageFileWriter<T>::Pointer writer = itk::ImageFileWriter<T>::New();
writer->SetFileName(filename);
writer->SetInput(image);
writer->Update();
}
template<typename T>
void WriteRGBImage(typename T::Pointer input, std::string filename)
{
typedef itk::Image<itk::CovariantVector<unsigned char, 3>, 2> RGBImageType;
RGBImageType::Pointer output = RGBImageType::New();
output->SetRegions(input->GetLargestPossibleRegion());
output->Allocate();
itk::ImageRegionConstIterator<T> inputIterator(input, input->GetLargestPossibleRegion());
itk::ImageRegionIterator<RGBImageType> outputIterator(output, output->GetLargestPossibleRegion());
while(!inputIterator.IsAtEnd())
{
itk::CovariantVector<unsigned char, 3> pixel;
for(unsigned int i = 0; i < 3; ++i)
{
pixel[i] = inputIterator.Get()[i];
}
outputIterator.Set(pixel);
++inputIterator;
++outputIterator;
}
typename itk::ImageFileWriter<RGBImageType>::Pointer writer = itk::ImageFileWriter<RGBImageType>::New();
writer->SetFileName(filename);
writer->SetInput(output);
writer->Update();
}
template <class T>
void CreateBlankPatch(typename T::Pointer patch, const unsigned int radius)
{
CreateConstantPatch<T>(patch, itk::NumericTraits< typename T::PixelType >::Zero, radius);
}
template <class T>
void CreateConstantPatch(typename T::Pointer patch, typename T::PixelType value, unsigned int radius)
{
try
{
typename T::IndexType start;
start.Fill(0);
typename T::SizeType size;
size.Fill(radius*2 + 1);
typename T::RegionType region(start, size);
patch->SetRegions(region);
patch->Allocate();
itk::ImageRegionIterator<T> imageIterator(patch, patch->GetLargestPossibleRegion());
while(!imageIterator.IsAtEnd())
{
imageIterator.Set(value);
++imageIterator;
}
}
catch( itk::ExceptionObject & err )
{
std::cerr << "ExceptionObject caught in CreateConstantPatch!" << std::endl;
std::cerr << err << std::endl;
exit(-1);
}
}
template <class T>
float MaxValue(typename T::Pointer image)
{
typedef typename itk::MinimumMaximumImageCalculator<T>
ImageCalculatorFilterType;
typename ImageCalculatorFilterType::Pointer imageCalculatorFilter
= ImageCalculatorFilterType::New ();
imageCalculatorFilter->SetImage(image);
imageCalculatorFilter->Compute();
return imageCalculatorFilter->GetMaximum();
}
template <class T>
float MaxValueLocation(typename T::Pointer image)
{
typedef typename itk::MinimumMaximumImageCalculator<T>
ImageCalculatorFilterType;
typename ImageCalculatorFilterType::Pointer imageCalculatorFilter
= ImageCalculatorFilterType::New ();
imageCalculatorFilter->SetImage(image);
imageCalculatorFilter->Compute();
return imageCalculatorFilter->GetIndexOfMaximum();
}
template <class T>
float MinValue(typename T::Pointer image)
{
typedef typename itk::MinimumMaximumImageCalculator<T>
ImageCalculatorFilterType;
typename ImageCalculatorFilterType::Pointer imageCalculatorFilter
= ImageCalculatorFilterType::New ();
imageCalculatorFilter->SetImage(image);
imageCalculatorFilter->Compute();
return imageCalculatorFilter->GetMinimum();
}
template <class T>
itk::Index<2> MinValueLocation(typename T::Pointer image)
{
typedef typename itk::MinimumMaximumImageCalculator<T>
ImageCalculatorFilterType;
typename ImageCalculatorFilterType::Pointer imageCalculatorFilter
= ImageCalculatorFilterType::New ();
imageCalculatorFilter->SetImage(image);
imageCalculatorFilter->Compute();
return imageCalculatorFilter->GetIndexOfMinimum();
}
template <class T>
void CopyPatchIntoImage(typename T::Pointer patch, typename T::Pointer image, Mask::Pointer mask, itk::Index<2> position)
{
try
{
// This function copies 'patch' into 'image' centered at 'position' only where the 'mask' is non-zero
// 'Mask' must be the same size as 'image'
if(mask->GetLargestPossibleRegion().GetSize() != image->GetLargestPossibleRegion().GetSize())
{
std::cerr << "mask and image must be the same size!" << std::endl;
exit(-1);
}
// The PasteFilter expects the lower left corner of the destination position, but we have passed the center pixel.
position[0] -= patch->GetLargestPossibleRegion().GetSize()[0]/2;
position[1] -= patch->GetLargestPossibleRegion().GetSize()[1]/2;
itk::ImageRegion<2> region = GetRegionInRadiusAroundPixel(position, patch->GetLargestPossibleRegion().GetSize()[0]/2);
itk::ImageRegionConstIterator<T> patchIterator(patch,patch->GetLargestPossibleRegion());
itk::ImageRegionConstIterator<Mask> maskIterator(mask,region);
itk::ImageRegionIterator<T> imageIterator(image, region);
while(!patchIterator.IsAtEnd())
{
if(mask->IsHole(maskIterator.GetIndex())) // we are in the target region
{
imageIterator.Set(patchIterator.Get());
}
++imageIterator;
++maskIterator;
++patchIterator;
}
}
catch( itk::ExceptionObject & err )
{
std::cerr << "ExceptionObject caught in CopyPatchIntoImage(patch, image, mask, position)!" << std::endl;
std::cerr << err << std::endl;
exit(-1);
}
}
template <class T>
void CopySelfPatchIntoValidRegion(typename T::Pointer image, const Mask::Pointer mask,
itk::ImageRegion<2> sourceRegion, itk::ImageRegion<2> destinationRegion)
{
try
{
assert(image->GetLargestPossibleRegion().IsInside(sourceRegion));
assert(mask->IsValid(sourceRegion));
assert(sourceRegion.GetSize() == destinationRegion.GetSize());
// Move the source region to the desintation region
itk::Offset<2> offset = destinationRegion.GetIndex() - sourceRegion.GetIndex();
sourceRegion.SetIndex(sourceRegion.GetIndex() + offset);
// Make the destination be entirely inside the image
destinationRegion.Crop(image->GetLargestPossibleRegion());
sourceRegion.Crop(image->GetLargestPossibleRegion());
// Move the source region back
sourceRegion.SetIndex(sourceRegion.GetIndex() - offset);
itk::ImageRegionConstIterator<T> sourceIterator(image, sourceRegion);
itk::ImageRegionIterator<T> destinationIterator(image, destinationRegion);
itk::ImageRegionConstIterator<Mask> maskIterator(mask, destinationRegion);
while(!sourceIterator.IsAtEnd())
{
if(mask->IsHole(maskIterator.GetIndex())) // we are in the target region
{
destinationIterator.Set(sourceIterator.Get());
}
++sourceIterator;
++maskIterator;
++destinationIterator;
}
}
catch( itk::ExceptionObject & err )
{
std::cerr << "ExceptionObject caught in CopySelfPatchIntoValidRegion!" << std::endl;
std::cerr << err << std::endl;
exit(-1);
}
}
template <class T>
void CopyPatchIntoImage(typename T::Pointer patch, typename T::Pointer image, itk::Index<2> position)
{
try
{
// This function copies 'patch' into 'image' centered at 'position'.
// The PasteFilter expects the lower left corner of the destination position, but we have passed the center pixel.
position[0] -= patch->GetLargestPossibleRegion().GetSize()[0]/2;
position[1] -= patch->GetLargestPossibleRegion().GetSize()[1]/2;
typedef itk::PasteImageFilter <T, T> PasteImageFilterType;
typename PasteImageFilterType::Pointer pasteFilter = PasteImageFilterType::New();
pasteFilter->SetInput(0, image);
pasteFilter->SetInput(1, patch);
pasteFilter->SetSourceRegion(patch->GetLargestPossibleRegion());
pasteFilter->SetDestinationIndex(position);
pasteFilter->InPlaceOn();
pasteFilter->Update();
image->Graft(pasteFilter->GetOutput());
}
catch( itk::ExceptionObject & err )
{
std::cerr << "ExceptionObject caught in CopyPatchIntoImage(patch, image, position)!" << std::endl;
std::cerr << err << std::endl;
exit(-1);
}
}
template <class T>
void CopyPatch(typename T::Pointer sourceImage, typename T::Pointer targetImage,
itk::Index<2> sourcePosition, itk::Index<2> targetPosition, unsigned int radius)
{
try
{
// Copy a patch of radius 'radius' centered at 'sourcePosition' from 'sourceImage' to 'targetImage' centered at 'targetPosition'
typedef itk::RegionOfInterestImageFilter<T,T> ExtractFilterType;
typename ExtractFilterType::Pointer extractFilter = ExtractFilterType::New();
extractFilter->SetRegionOfInterest(GetRegionInRadiusAroundPixel(sourcePosition, radius));
extractFilter->SetInput(sourceImage);
extractFilter->Update();
CopyPatchIntoImage<T>(extractFilter->GetOutput(), targetImage, targetPosition);
}
catch( itk::ExceptionObject & err )
{
std::cerr << "ExceptionObject caught in CopyPatch!" << std::endl;
std::cerr << err << std::endl;
exit(-1);
}
}
template <class T>
void WriteScaledScalarImage(typename T::Pointer image, std::string filename)
{
if(T::PixelType::Dimension > 1)
{
std::cerr << "Cannot write scaled scalar image with vector image input!" << std::endl;
return;
}
typedef itk::RescaleIntensityImageFilter<T, UnsignedCharScalarImageType> RescaleFilterType; // expected ';' before rescaleFilter
typename RescaleFilterType::Pointer rescaleFilter = RescaleFilterType::New();
rescaleFilter->SetInput(image);
rescaleFilter->SetOutputMinimum(0);
rescaleFilter->SetOutputMaximum(255);
rescaleFilter->Update();
typedef itk::ImageFileWriter<UnsignedCharScalarImageType> WriterType;
typename WriterType::Pointer writer = WriterType::New();
writer->SetFileName(filename);
writer->SetInput(rescaleFilter->GetOutput());
writer->Update();
}
template <typename TImage>
void ColorToGrayscale(typename TImage::Pointer colorImage, UnsignedCharScalarImageType::Pointer grayscaleImage)
{
grayscaleImage->SetRegions(colorImage->GetLargestPossibleRegion());
grayscaleImage->Allocate();
itk::ImageRegionConstIterator<TImage> colorImageIterator(colorImage, colorImage->GetLargestPossibleRegion());
itk::ImageRegionIterator<UnsignedCharScalarImageType> grayscaleImageIterator(grayscaleImage, grayscaleImage->GetLargestPossibleRegion());
typename TImage::PixelType largestPixel;
largestPixel.Fill(255);
float largestNorm = largestPixel.GetNorm();
while(!colorImageIterator.IsAtEnd())
{
grayscaleImageIterator.Set(colorImageIterator.Get().GetNorm()*(255./largestNorm));
++colorImageIterator;
++grayscaleImageIterator;
}
}
template <typename TImageType>
void DebugWriteSequentialImage(typename TImageType::Pointer image, const std::string& filePrefix, const unsigned int iteration)
{
std::stringstream padded;
padded << "Debug/" << filePrefix << "_" << std::setfill('0') << std::setw(4) << iteration << ".mha";
Helpers::WriteImage<TImageType>(image, padded.str());
}
template <typename TImageType>
void DebugWriteImageConditional(typename TImageType::Pointer image, const std::string& fileName, const bool condition)
{
if(condition)
{
WriteImage<TImageType>(image, fileName);
}
}
template <typename TImage>
void ITKScalarImageToScaledVTKImage(typename TImage::Pointer image, vtkImageData* outputImage)
{
//std::cout << "ITKScalarImagetoVTKImage()" << std::endl;
// Rescale and cast for display
typedef itk::RescaleIntensityImageFilter<TImage, UnsignedCharScalarImageType > RescaleFilterType;
typename RescaleFilterType::Pointer rescaleFilter = RescaleFilterType::New();
rescaleFilter->SetOutputMinimum(0);
rescaleFilter->SetOutputMaximum(255);
rescaleFilter->SetInput(image);
rescaleFilter->Update();
// Setup and allocate the VTK image
outputImage->SetNumberOfScalarComponents(1);
outputImage->SetScalarTypeToUnsignedChar();
outputImage->SetDimensions(image->GetLargestPossibleRegion().GetSize()[0],
image->GetLargestPossibleRegion().GetSize()[1],
1);
outputImage->AllocateScalars();
// Copy all of the scaled magnitudes to the output image
itk::ImageRegionConstIteratorWithIndex<UnsignedCharScalarImageType> imageIterator(rescaleFilter->GetOutput(), rescaleFilter->GetOutput()->GetLargestPossibleRegion());
imageIterator.GoToBegin();
while(!imageIterator.IsAtEnd())
{
unsigned char* pixel = static_cast<unsigned char*>(outputImage->GetScalarPointer(imageIterator.GetIndex()[0],
imageIterator.GetIndex()[1],0));
pixel[0] = imageIterator.Get();
++imageIterator;
}
outputImage->Modified();
}
}// end namespace | 32.474747 | 168 | 0.71098 | [
"vector"
] |
0765eb0a39a0a998ed302abecb5886386e0037e3 | 576 | cpp | C++ | Source/Initialization/InjectorMomentum.cpp | guj/WarpX | 7833e281dd9fa695a57d097eac31acef7ccaa3eb | [
"BSD-3-Clause-LBNL"
] | null | null | null | Source/Initialization/InjectorMomentum.cpp | guj/WarpX | 7833e281dd9fa695a57d097eac31acef7ccaa3eb | [
"BSD-3-Clause-LBNL"
] | null | null | null | Source/Initialization/InjectorMomentum.cpp | guj/WarpX | 7833e281dd9fa695a57d097eac31acef7ccaa3eb | [
"BSD-3-Clause-LBNL"
] | null | null | null | /* Copyright 2019-2020 Axel Huebl, Maxence Thevenet, Revathi Jambunathan
* Weiqun Zhang
*
* This file is part of WarpX.
*
* License: BSD-3-Clause-LBNL
*/
#include <InjectorMomentum.H>
#include <PlasmaInjector.H>
using namespace amrex;
InjectorMomentum::~InjectorMomentum ()
{
switch (type)
{
case Type::parser:
{
object.parser.m_ux_parser.clear();
object.parser.m_uy_parser.clear();
object.parser.m_uz_parser.clear();
break;
}
case Type::custom:
{
object.custom.clear();
break;
}
}
}
| 18.580645 | 72 | 0.621528 | [
"object"
] |
07699ab7d8a68a610f3d61b3b4e33859013f792d | 21,475 | cpp | C++ | private/shell/ext/cabview/folder.cpp | King0987654/windows2000 | 01f9c2e62c4289194e33244aade34b7d19e7c9b8 | [
"MIT"
] | 11 | 2017-09-02T11:27:08.000Z | 2022-01-02T15:25:24.000Z | private/shell/ext/cabview/folder.cpp | King0987654/windows2000 | 01f9c2e62c4289194e33244aade34b7d19e7c9b8 | [
"MIT"
] | null | null | null | private/shell/ext/cabview/folder.cpp | King0987654/windows2000 | 01f9c2e62c4289194e33244aade34b7d19e7c9b8 | [
"MIT"
] | 14 | 2019-01-16T01:01:23.000Z | 2022-02-20T15:54:27.000Z | //*******************************************************************************************
//
// Filename : folder.cpp
//
// CAB Files Shell Extension
//
// Copyright (c) 1994 - 1997 Microsoft Corporation. All rights reserved
//
//*******************************************************************************************
#include "pch.h"
#include "thisdll.h"
#include "thisguid.h"
#include "folder.h"
#include "enum.h"
#include "icon.h"
#include "menu.h"
#include "dataobj.h"
#include "cabitms.h"
#include "resource.h"
STDAPI StringToStrRet(LPCTSTR pszName, STRRET *pStrRet)
{
#ifdef UNICODE
pStrRet->uType = STRRET_WSTR;
return SHStrDup(pszName, &pStrRet->pOleStr);
#else
pStrRet->uType = STRRET_CSTR;
lstrcpyn(pStrRet->cStr, pszName, ARRAYSIZE(pStrRet->cStr));
return NOERROR;
#endif
}
STDMETHODIMP CCabFolder::QueryInterface(REFIID riid, void **ppv)
{
if (CLSID_CabFolder == riid)
{
// yuck - dataobject uses this when loading us from a stream:
// NOTE: we are doing an AddRef() in this case
*ppv = (CCabFolder*) this;
AddRef();
return S_OK;
}
else
{
static const QITAB qit[] = {
QITABENT(CCabFolder, IShellFolder2),
QITABENTMULTI(CCabFolder, IShellFolder, IShellFolder2),
QITABENT(CCabFolder, IPersistFolder2),
QITABENTMULTI(CCabFolder, IPersistFolder, IPersistFolder2),
QITABENTMULTI(CCabFolder, IPersist, IPersistFolder2),
{ 0 },
};
return QISearch(this, qit, riid, ppv);
}
}
STDMETHODIMP_(ULONG) CCabFolder::AddRef(void)
{
return(m_cRef.AddRef());
}
STDMETHODIMP_(ULONG) CCabFolder::Release(void)
{
if (!m_cRef.Release())
{
delete this;
return(0);
}
return(m_cRef.GetRef());
}
STDMETHODIMP CCabFolder::ParseDisplayName(HWND hwnd, LPBC pbc, LPOLESTR pszDisplayName, ULONG *pchEaten, LPITEMIDLIST *ppidl, ULONG *pdwAttributes)
{
return E_NOTIMPL;
}
//**********************************************************************
//
// Purpose:
//
// Creates an item enumeration object
// (an IEnumIDList interface) that can be used to
// enumerate the contents of a folder.
//
// Parameters:
//
// HWND hwndOwner - handle to the owner window
// DWORD grFlags - flags about which items to include
// IEnumIDList **ppenumIDList - address that receives IEnumIDList
// interface pointer
//********************************************************************
STDMETHODIMP CCabFolder::EnumObjects(HWND hwnd, DWORD grfFlags, IEnumIDList **ppenumIDList)
{
HRESULT hres;
CEnumCabObjs *pce = new CEnumCabObjs(this, grfFlags);
if (pce)
{
hres = pce->QueryInterface(IID_IEnumIDList, (void **)ppenumIDList);
}
else
{
*ppenumIDList = NULL;
hres = E_OUTOFMEMORY;
}
return hres;
}
STDMETHODIMP CCabFolder::BindToObject(LPCITEMIDLIST pidl, LPBC pbc, REFIID riid, void **ppvObj)
{
return E_NOTIMPL;
}
STDMETHODIMP CCabFolder::BindToStorage(LPCITEMIDLIST pidl, LPBC pbc, REFIID riid, void ** ppvObj)
{
return E_NOTIMPL;
}
//**********************************************************************
//
// CCabFolder::CompareIDs
//
// Purpose:
//
// Determines the relative ordering of two file
// objects or folders, given their item identifier lists
//
// Parameters:
//
// LPARAM lParam - type of comparison
// LPCITEMIDLIST pidl1 - address to ITEMIDLIST
// LPCITEMIDLIST pidl2 - address to ITEMIDLIST
//
//
// Comments:
//
//
//********************************************************************
STDMETHODIMP CCabFolder::CompareIDs(LPARAM lParam, LPCITEMIDLIST pidl1, LPCITEMIDLIST pidl2)
{
LPCABITEM pit1 = (LPCABITEM)pidl1;
LPCABITEM pit2 = (LPCABITEM)pidl2;
short nCmp = 0;
switch (lParam)
{
case CV_COL_NAME:
break;
case CV_COL_SIZE:
if (pit1->dwFileSize < pit2->dwFileSize)
{
nCmp = -1;
}
else if (pit1->dwFileSize > pit2->dwFileSize)
{
nCmp = 1;
}
break;
case CV_COL_TYPE:
{
STRRET srName1, srName2;
GetTypeOf(pit1, &srName1);
GetTypeOf(pit2, &srName2);
#ifdef UNICODE
// BUGBUG: check for NULL pOleStr's
nCmp = (SHORT)lstrcmp(srName1.pOleStr, srName2.pOleStr);
#else // UNICODE
nCmp = (SHORT)lstrcmp(srName1.cStr, srName2.cStr);
#endif // UNICODE
break;
}
case CV_COL_MODIFIED:
if (pit1->uFileDate < pit2->uFileDate)
{
nCmp = -1;
}
else if (pit1->uFileDate > pit2->uFileDate)
{
nCmp = 1;
}
else if (pit1->uFileTime < pit2->uFileTime)
{
nCmp = -1;
}
else if (pit1->uFileTime > pit2->uFileTime)
{
nCmp = 1;
}
break;
case CV_COL_PATH:
if (pit1->cPathChars == 0)
{
if (pit2->cPathChars != 0)
{
nCmp = -1;
}
}
else if (pit2->cPathChars == 0)
{
nCmp = 1;
}
else if (pit1->cPathChars <= pit2->cPathChars)
{
nCmp = (short) StrCmpN(pit1->szName, pit2->szName, pit1->cPathChars-1);
if ((nCmp == 0) && (pit1->cPathChars < pit2->cPathChars))
{
nCmp = -1;
}
}
else
{
nCmp = (short) StrCmpN(pit1->szName, pit2->szName, pit2->cPathChars-1);
if (nCmp == 0)
{
nCmp = 1;
}
}
break;
default:
break;
}
if (nCmp != 0)
{
return ResultFromShort(nCmp);
}
return ResultFromShort(lstrcmpi(pit1->szName + pit1->cPathChars, pit2->szName + pit2->cPathChars));
}
//**********************************************************************
//
// CCabFolder::CreateViewObject
//
// Purpose:
//
// IShellbrowser calls this to create a ShellView
// object
//
// Parameters:
//
// HWND hwndOwner -
//
// REFIID riid - interface ID
//
// void ** ppvObj - pointer to the Shellview object
//
// Return Value:
//
// NOERROR
// E_OUTOFMEMORY
// E_NOINTERFACE
//
//
// Comments:
//
// ShellBrowser interface calls this to request the ShellFolder
// to create a ShellView object
//
//********************************************************************
STDMETHODIMP CCabFolder::CreateViewObject(HWND hwndOwner, REFIID riid, void **ppvObj)
{
HRESULT hres;
if (riid == IID_IShellView)
{
SFV_CREATE sfvc;
sfvc.cbSize = sizeof(sfvc);
sfvc.pshf = this;
sfvc.psvOuter = NULL;
sfvc.psfvcb = NULL;
hres = SHCreateShellFolderView(&sfvc, (IShellView **)ppvObj);
}
else
{
*ppvObj = NULL;
hres = E_NOINTERFACE;
}
return hres;
}
// **************************************************************************************
//
// CCabFolder::GetAttributesOf
//
// Purpose
//
// Retrieves attributes of one of more file objects
//
// Parameters:
//
// UINT cidl - number of file objects
// LPCITEMIDLIST *apidl - pointer to array of ITEMIDLIST
// ULONG *rgfInOut - array of values that specify file object
// attributes
//
//
// Return Value:
//
// NOERROR
//
// Comments
//
// ***************************************************************************************
STDMETHODIMP CCabFolder::GetAttributesOf(UINT cidl, LPCITEMIDLIST *apidl, ULONG *rgfInOut)
{
*rgfInOut &= SFGAO_CANCOPY;
return NOERROR;
}
// **************************************************************************************
//
// CCabFolder::GetUIObjectOf
//
// Purpose
//
// Returns an interface that can be used to carry out actions on
// the specified file objects or folders
//
// Parameters:
//
// HWND hwndOwner - handle of the Owner window
//
// UINT cidl - Number of file objects
//
// LPCITEMIDLIST *apidl - array of file object pidls
//
// REFIID - Identifier of interface to return
//
// UINT * prgfInOut - reserved
//
// void **ppvObj - address that receives interface pointer
//
// Return Value:
//
// E_INVALIDARG
// E_NOINTERFACE
// E_OUTOFMEMORY
//
// Comments
// ***************************************************************************************
STDMETHODIMP CCabFolder::GetUIObjectOf(HWND hwndOwner, UINT cidl, LPCITEMIDLIST *apidl,
REFIID riid, UINT *prgfInOut, void **ppvObj)
{
IUnknown *pObj = NULL;
if (riid == IID_IExtractIcon)
{
if (cidl != 1)
{
return(E_INVALIDARG);
}
LPCABITEM pci = (LPCABITEM)*apidl;
pObj = (IUnknown *)(IExtractIcon *)(new CCabItemIcon(pci->szName));
}
else if (riid == IID_IContextMenu)
{
if (cidl < 1)
{
return(E_INVALIDARG);
}
pObj = (IUnknown *)(IContextMenu *)(new CCabItemMenu(hwndOwner, this,
(LPCABITEM *)apidl, cidl));
}
else if (riid == IID_IDataObject)
{
if (cidl < 1)
{
return(E_INVALIDARG);
}
pObj = (IUnknown *)(IDataObject *)(new CCabObj(hwndOwner, this,
(LPCABITEM *)apidl, cidl));
}
else
{
return E_NOINTERFACE;
}
if (!pObj)
{
return E_OUTOFMEMORY;
}
pObj->AddRef();
HRESULT hres = pObj->QueryInterface(riid, ppvObj);
pObj->Release();
return hres;
}
//*****************************************************************************
//
// CCabFolder::GetDisplayNameOf
//
// Purpose:
// Retrieves the display name for the specified file object or
// subfolder.
//
//
// Parameters:
//
// LPCITEMIDLIST pidl - pidl of the file object
// DWORD dwReserved - Value of the type of display name to
// return
// LPSTRRET lpName - address holding the name returned
//
//
// Comments:
//
//*****************************************************************************
STDMETHODIMP CCabFolder::GetDisplayNameOf(LPCITEMIDLIST pidl, DWORD dwReserved, LPSTRRET lpName)
{
LPCABITEM pit = (LPCABITEM)pidl;
GetNameOf(pit, lpName);
return NOERROR;
}
STDMETHODIMP CCabFolder::SetNameOf(HWND hwndOwner, LPCITEMIDLIST pidl, LPCOLESTR lpszName, DWORD dwRes, LPITEMIDLIST *ppidlOut)
{
return E_NOTIMPL;
}
struct _CVCOLINFO
{
UINT iColumn;
UINT iTitle;
UINT cchCol;
UINT iFmt;
} s_aCVColInfo[] = {
{CV_COL_NAME, IDS_CV_COL_NAME, 20, LVCFMT_LEFT},
{CV_COL_SIZE, IDS_CV_COL_SIZE, 10, LVCFMT_RIGHT},
{CV_COL_TYPE, IDS_CV_COL_TYPE, 20, LVCFMT_LEFT},
{CV_COL_MODIFIED, IDS_CV_COL_MODIFIED, 20, LVCFMT_LEFT},
{CV_COL_PATH, IDS_CV_COL_PATH, 30, LVCFMT_LEFT},
};
STDMETHODIMP CCabFolder::GetDetailsOf(LPCITEMIDLIST pidl, UINT iColumn, SHELLDETAILS *psd)
{
LPCABITEM pit = (LPCABITEM)pidl;
TCHAR szTemp[MAX_PATH];
if (iColumn >= CV_COL_MAX)
{
return E_NOTIMPL;
}
psd->str.uType = STRRET_CSTR;
psd->str.cStr[0] = '\0';
if (!pit)
{
TCHAR szTitle[MAX_PATH];
LoadString(g_ThisDll.GetInstance(), s_aCVColInfo[iColumn].iTitle, szTitle, ARRAYSIZE(szTitle));
StringToStrRet(szTitle, &(psd->str));
psd->fmt = s_aCVColInfo[iColumn].iFmt;
psd->cxChar = s_aCVColInfo[iColumn].cchCol;
return S_OK;
}
switch (iColumn)
{
case CV_COL_NAME:
GetNameOf(pit, &psd->str);
break;
case CV_COL_PATH:
GetPathOf(pit, &psd->str);
break;
case CV_COL_SIZE:
{
ULARGE_INTEGER ullSize = {pit->dwFileSize, 0};
StrFormatKBSize(ullSize.QuadPart, szTemp, ARRAYSIZE(szTemp));
StringToStrRet(szTemp, &(psd->str));
break;
}
case CV_COL_TYPE:
GetTypeOf(pit, &psd->str);
break;
case CV_COL_MODIFIED:
{
FILETIME ft, uft;
DosDateTimeToFileTime(pit->uFileDate, pit->uFileTime, &ft);
LocalFileTimeToFileTime(&ft, &uft); // Apply timezone
SHFormatDateTime(&uft, NULL, szTemp, ARRAYSIZE(szTemp));
StringToStrRet(szTemp, &(psd->str));
}
break;
}
return S_OK;
}
// *** IPersist methods ***
STDMETHODIMP CCabFolder::GetClassID(CLSID *pclsid)
{
*pclsid = CLSID_CabFolder;
return NOERROR;
}
// IPersistFolder
STDMETHODIMP CCabFolder::Initialize(LPCITEMIDLIST pidl)
{
if (m_pidlHere)
{
ILFree(m_pidlHere);
}
m_pidlHere = ILClone(pidl); // copy the pidl
return m_pidlHere ? S_OK : E_OUTOFMEMORY;
}
HRESULT CCabFolder::GetCurFolder(LPITEMIDLIST *ppidl)
{
if (m_pidlHere)
{
*ppidl = ILClone(m_pidlHere);
return *ppidl ? NOERROR : E_OUTOFMEMORY;
}
*ppidl = NULL;
return S_FALSE; // success but empty
}
//*****************************************************************************
//
// CCabFolder::CreateIDList
//
// Purpose:
//
// Creates an item identifier list for the objects in the namespace
//
//
//*****************************************************************************
LPITEMIDLIST CCabFolder::CreateIDList(LPCTSTR pszName, DWORD dwFileSize,
UINT uFileDate, UINT uFileTime, UINT uFileAttribs)
{
// We'll assume no name is longer than MAX_PATH
// Note the terminating NULL is already in the sizeof(CABITEM)
BYTE bBuf[sizeof(CABITEM) + (sizeof(TCHAR) * MAX_PATH) + sizeof(WORD)];
LPCABITEM pci = (LPCABITEM)bBuf;
UINT uNameLen = lstrlen(pszName);
if (uNameLen >= MAX_PATH)
{
uNameLen = MAX_PATH;
}
pci->wSize = (WORD)(sizeof(CABITEM) + (sizeof(TCHAR) * uNameLen));
pci->dwFileSize = dwFileSize;
pci->uFileDate = (USHORT)uFileDate;
pci->uFileTime = (USHORT)uFileTime;
pci->uFileAttribs = (USHORT)uFileAttribs & (FILE_ATTRIBUTE_READONLY|
FILE_ATTRIBUTE_HIDDEN |
FILE_ATTRIBUTE_SYSTEM |
FILE_ATTRIBUTE_ARCHIVE);
lstrcpyn(pci->szName, pszName, uNameLen+1);
pci->cPathChars = 0;
LPCTSTR psz = pszName;
while (*psz)
{
if ((*psz == TEXT(':')) || (*psz == TEXT('/')) || (*psz == TEXT('\\')))
{
pci->cPathChars = (USHORT)(psz - pszName) + 1;
}
psz = CharNext(psz);
}
// Terminate the IDList
*(WORD *)(((LPSTR)pci)+pci->wSize) = 0;
return(ILClone((LPCITEMIDLIST)pci));
}
//*****************************************************************************
//
// CCabFolder::GetPath
//
// Purpose:
//
// Get the Path for the current pidl
//
// Parameters:
//
// LPSTR szPath - return pointer for path string
//
// Comments:
//
//*****************************************************************************
BOOL CCabFolder::GetPath(LPTSTR szPath)
{
if (!m_pidlHere || !SHGetPathFromIDList(m_pidlHere, szPath))
{
*szPath = TEXT('\0');
return FALSE;
}
#ifdef UNICODE
// NOTE: we use GetShortPathName() to avoid losing characters during the
// UNICODE->ANSI->UNICODE roundtrip while calling FDICopy()
// NOTE: It is valid for GetShortPathName()'s src and dest pointers to be the same
// If this fails, we'll just ignore the error and try to use the long path name
GetShortPathName(szPath, szPath, MAX_PATH);
#endif // UNICODE
return(TRUE);
}
void CCabFolder::GetNameOf(LPCABITEM pit, LPSTRRET lpName)
{
lpName->uType = STRRET_CSTR;
lpName->cStr[0] = '\0';
SHFILEINFO sfi;
if (SHGetFileInfo(pit->szName + pit->cPathChars, 0, &sfi, sizeof(sfi),
SHGFI_USEFILEATTRIBUTES | SHGFI_DISPLAYNAME))
{
StringToStrRet(sfi.szDisplayName, lpName);
}
}
void CCabFolder::GetPathOf(LPCABITEM pit, LPSTRRET lpName)
{
TCHAR szPath[MAX_PATH];
lstrcpy(szPath, pit->szName);
szPath[pit->cPathChars] = TEXT('\0');
StringToStrRet(szPath, lpName);
}
void CCabFolder::GetTypeOf(LPCABITEM pit, LPSTRRET lpName)
{
lpName->uType = STRRET_CSTR;
lpName->cStr[0] = '\0';
SHFILEINFO sfi;
if (SHGetFileInfo(pit->szName + pit->cPathChars, 0, &sfi, sizeof(sfi),
SHGFI_USEFILEATTRIBUTES | SHGFI_TYPENAME))
{
StringToStrRet(sfi.szTypeName, lpName);
}
}
//*****************************************************************************
//
// CCabFolder::EnumToList
//
// Purpose:
//
// This notify callback is called by the FDI routines. It adds the
// file object from the cab file to the list.
//
// Parameters:
//
//
//
// Comments:
//
//*****************************************************************************
void CALLBACK CCabFolder::EnumToList(LPCTSTR pszFile, DWORD dwSize, UINT date,
UINT time, UINT attribs, LPARAM lParam)
{
CCabFolder *pThis = (CCabFolder *)lParam;
pThis->m_lItems.AddItem(pszFile, dwSize, date, time, attribs);
}
HRESULT CCabFolder::InitItems()
{
switch (m_lItems.GetState())
{
case CCabItemList::State_Init:
return NOERROR;
case CCabItemList::State_OutOfMem:
return E_OUTOFMEMORY;
case CCabItemList::State_UnInit:
default:
break;
}
// Force the list to initialize
m_lItems.InitList();
TCHAR szHere[MAX_PATH];
// the m_pidl has been set to current dir
// get the path to the current directory
if (!GetPath(szHere))
{
return(E_UNEXPECTED);
}
CCabItems ciHere(szHere);
if (!ciHere.EnumItems(EnumToList, (LPARAM)this))
{
return(E_UNEXPECTED);
}
return NOERROR;
}
HRESULT CabFolder_CreateInstance(REFIID riid, void **ppvObj)
{
HRESULT hres;
*ppvObj = NULL;
HINSTANCE hCabinetDll = LoadLibrary(TEXT("CABINET.DLL"));
if (hCabinetDll)
{
FreeLibrary(hCabinetDll);
CCabFolder *pfolder = new CCabFolder;
if (pfolder)
hres = pfolder->QueryInterface(riid, ppvObj);
else
hres = E_OUTOFMEMORY;
}
else
hres = E_UNEXPECTED;
return hres;
}
UINT CCabItemList::GetState()
{
if (m_uStep == 0)
{
if (m_dpaList)
{
return(State_Init);
}
return(State_OutOfMem);
}
return(State_UnInit);
}
BOOL CCabItemList::StoreItem(LPITEMIDLIST pidl)
{
if (pidl)
{
if (InitList() && DPA_InsertPtr(m_dpaList, 0x7fff, (LPSTR)pidl)>=0)
{
return(TRUE);
}
ILFree(pidl);
}
CleanList();
return FALSE;
}
BOOL CCabItemList::AddItems(LPCABITEM *apit, UINT cpit)
{
for (UINT i=0; i<cpit; ++i)
{
if (!StoreItem(ILClone((LPCITEMIDLIST)apit[i])))
{
return FALSE;
}
}
return(TRUE);
}
BOOL CCabItemList::AddItem(LPCTSTR pszName, DWORD dwFileSize,
UINT uFileDate, UINT uFileTime, UINT uFileAttribs)
{
return(StoreItem(CCabFolder::CreateIDList(pszName, dwFileSize, uFileDate, uFileTime,
uFileAttribs)));
}
int CCabItemList::FindInList(LPCTSTR pszName, DWORD dwFileSize,
UINT uFileDate, UINT uFileTime, UINT uFileAttribs)
{
// TODO: Linear search for now; binary later
for (int i=DPA_GetPtrCount(m_dpaList)-1; i>=0; --i)
{
if (lstrcmpi(pszName, (*this)[i]->szName) == 0)
{
break;
}
}
return(i);
}
BOOL CCabItemList::InitList()
{
switch (GetState())
{
case State_Init:
return(TRUE);
case State_OutOfMem:
return FALSE;
case State_UnInit:
default:
m_dpaList = DPA_Create(m_uStep);
m_uStep = 0;
return(InitList());
}
}
void CCabItemList::CleanList()
{
if (m_uStep != 0)
{
m_dpaList = NULL;
m_uStep = 0;
return;
}
if (!m_dpaList)
{
return;
}
for (int i=DPA_GetPtrCount(m_dpaList)-1; i>=0; --i)
{
ILFree((LPITEMIDLIST)((*this)[i]));
}
DPA_Destroy(m_dpaList);
m_dpaList = NULL;
}
| 24.021253 | 148 | 0.514366 | [
"object"
] |
077a9c33e4a24586e0ba087d9e8275c47d2c62fe | 5,604 | cpp | C++ | src/gdal_feature_defn.cpp | blairdgeo/node-gdal | a9bb3c082b30605ed1668dd9fe49afd25a7bb9d6 | [
"Apache-2.0"
] | 1 | 2015-07-04T20:09:20.000Z | 2015-07-04T20:09:20.000Z | src/gdal_feature_defn.cpp | blairdgeo/node-gdal | a9bb3c082b30605ed1668dd9fe49afd25a7bb9d6 | [
"Apache-2.0"
] | null | null | null | src/gdal_feature_defn.cpp | blairdgeo/node-gdal | a9bb3c082b30605ed1668dd9fe49afd25a7bb9d6 | [
"Apache-2.0"
] | null | null | null |
#include "gdal_common.hpp"
#include "gdal_feature_defn.hpp"
#include "gdal_field_defn.hpp"
#include "collections/feature_defn_fields.hpp"
namespace node_gdal {
Persistent<FunctionTemplate> FeatureDefn::constructor;
void FeatureDefn::Initialize(Handle<Object> target)
{
NanScope();
Local<FunctionTemplate> lcons = NanNew<FunctionTemplate>(FeatureDefn::New);
lcons->InstanceTemplate()->SetInternalFieldCount(1);
lcons->SetClassName(NanNew("FeatureDefn"));
NODE_SET_PROTOTYPE_METHOD(lcons, "toString", toString);
NODE_SET_PROTOTYPE_METHOD(lcons, "clone", clone);
ATTR(lcons, "name", nameGetter, READ_ONLY_SETTER);
ATTR(lcons, "fields", fieldsGetter, READ_ONLY_SETTER);
ATTR(lcons, "styleIgnored", styleIgnoredGetter, styleIgnoredSetter);
ATTR(lcons, "geomIgnored", geomIgnoredGetter, geomIgnoredSetter);
ATTR(lcons, "geomType", geomTypeGetter, geomTypeSetter);
target->Set(NanNew("FeatureDefn"), lcons->GetFunction());
NanAssignPersistent(constructor, lcons);
}
FeatureDefn::FeatureDefn(OGRFeatureDefn *def)
: ObjectWrap(),
this_(def),
owned_(true)
{
LOG("Created FeatureDefn [%p]", def);
}
FeatureDefn::FeatureDefn()
: ObjectWrap(),
this_(0),
owned_(true)
{
}
FeatureDefn::~FeatureDefn()
{
if(this_) {
LOG("Disposing FeatureDefn [%p] (%s)", this_, owned_ ? "owned" : "unowned");
if(owned_) this_->Release();
this_ = NULL;
LOG("Disposed FeatureDefn [%p]", this_);
}
}
/**
* Definition of a feature class or feature layer.
*
* @constructor
* @class gdal.FeatureDefn
*/
NAN_METHOD(FeatureDefn::New)
{
NanScope();
FeatureDefn *f;
if (!args.IsConstructCall()) {
NanThrowError("Cannot call constructor as function, you need to use 'new' keyword");
NanReturnUndefined();
}
if (args[0]->IsExternal()) {
Local<External> ext = args[0].As<External>();
void* ptr = ext->Value();
f = static_cast<FeatureDefn *>(ptr);
} else {
if (args.Length() != 0) {
NanThrowError("FeatureDefn constructor doesn't take any arguments");
NanReturnUndefined();
}
f = new FeatureDefn(new OGRFeatureDefn());
f->this_->Reference();
}
Handle<Value> fields = FeatureDefnFields::New(args.This());
args.This()->SetHiddenValue(NanNew("fields_"), fields);
f->Wrap(args.This());
NanReturnValue(args.This());
}
Handle<Value> FeatureDefn::New(OGRFeatureDefn *def)
{
NanEscapableScope();
return NanEscapeScope(FeatureDefn::New(def, false));
}
Handle<Value> FeatureDefn::New(OGRFeatureDefn *def, bool owned)
{
NanEscapableScope();
if (!def) {
return NanEscapeScope(NanNull());
}
//make a copy of featuredefn owned by a layer
// + no need to track when a layer is destroyed
// + no need to throw errors when a method trys to modify an owned read-only featuredefn
// - is slower
//TODO: cloning maybe unnecessary if reference counting is done right.
// def->Reference(); def->Release();
if (!owned) {
def = def->Clone();
}
FeatureDefn *wrapped = new FeatureDefn(def);
wrapped->owned_ = true;
def->Reference();
Handle<Value> ext = NanNew<External>(wrapped);
Handle<Object> obj = NanNew(FeatureDefn::constructor)->GetFunction()->NewInstance(1, &ext);
return NanEscapeScope(obj);
}
NAN_METHOD(FeatureDefn::toString)
{
NanScope();
NanReturnValue(NanNew("FeatureDefn"));
}
/**
* Clones the feature definition.
*
* @method clone
* @return {gdal.FeatureDefn}
*/
NAN_METHOD(FeatureDefn::clone)
{
NanScope();
FeatureDefn *def = ObjectWrap::Unwrap<FeatureDefn>(args.This());
NanReturnValue(FeatureDefn::New(def->this_->Clone()));
}
/**
* @readOnly
* @attribute name
* @type {String}
*/
NAN_GETTER(FeatureDefn::nameGetter)
{
NanScope();
FeatureDefn *def = ObjectWrap::Unwrap<FeatureDefn>(args.This());
NanReturnValue(SafeString::New(def->this_->GetName()));
}
/**
* WKB geometry type ({{#crossLink "Constants (WKB)"}}see table{{/crossLink}})
*
* @attribute geomType
* @type {String}
*/
NAN_GETTER(FeatureDefn::geomTypeGetter)
{
NanScope();
FeatureDefn *def = ObjectWrap::Unwrap<FeatureDefn>(args.This());
NanReturnValue(NanNew<Integer>(def->this_->GetGeomType()));
}
/**
* @attribute geomIgnored
* @type {Boolean}
*/
NAN_GETTER(FeatureDefn::geomIgnoredGetter)
{
NanScope();
FeatureDefn *def = ObjectWrap::Unwrap<FeatureDefn>(args.This());
NanReturnValue(NanNew<Boolean>(def->this_->IsGeometryIgnored()));
}
/**
* @attribute styleIgnored
* @type {Boolean}
*/
NAN_GETTER(FeatureDefn::styleIgnoredGetter)
{
NanScope();
FeatureDefn *def = ObjectWrap::Unwrap<FeatureDefn>(args.This());
NanReturnValue(NanNew<Boolean>(def->this_->IsStyleIgnored()));
}
/**
* @readOnly
* @attribute fields
* @type {gdal.FeatureDefnFields}
*/
NAN_GETTER(FeatureDefn::fieldsGetter)
{
NanScope();
NanReturnValue(args.This()->GetHiddenValue(NanNew("fields_")));
}
NAN_SETTER(FeatureDefn::geomTypeSetter)
{
NanScope();
FeatureDefn *def = ObjectWrap::Unwrap<FeatureDefn>(args.This());
if(!value->IsInt32()){
NanThrowError("geomType must be an integer");
return;
}
def->this_->SetGeomType(OGRwkbGeometryType(value->IntegerValue()));
}
NAN_SETTER(FeatureDefn::geomIgnoredSetter)
{
NanScope();
FeatureDefn *def = ObjectWrap::Unwrap<FeatureDefn>(args.This());
if(!value->IsBoolean()){
NanThrowError("geomIgnored must be a boolean");
return;
}
def->this_->SetGeometryIgnored(value->IntegerValue());
}
NAN_SETTER(FeatureDefn::styleIgnoredSetter)
{
NanScope();
FeatureDefn *def = ObjectWrap::Unwrap<FeatureDefn>(args.This());
if(!value->IsBoolean()){
NanThrowError("styleIgnored must be a boolean");
return;
}
def->this_->SetStyleIgnored(value->IntegerValue());
}
} // namespace node_gdal | 23.35 | 92 | 0.710742 | [
"geometry",
"object"
] |
077db37773f01a349bcf40a0f65f10813097d9e3 | 21,674 | cc | C++ | tensorflow/compiler/plugin/poplar/driver/passes/function_combiner.cc | chenzhengda/tensorflow | 8debb698097670458b5f21d728bc6f734a7b5a53 | [
"Apache-2.0"
] | 74 | 2020-07-06T17:11:39.000Z | 2022-01-28T06:31:28.000Z | tensorflow/compiler/plugin/poplar/driver/passes/function_combiner.cc | chenzhengda/tensorflow | 8debb698097670458b5f21d728bc6f734a7b5a53 | [
"Apache-2.0"
] | 9 | 2020-10-13T23:25:29.000Z | 2022-02-10T06:54:48.000Z | tensorflow/compiler/plugin/poplar/driver/passes/function_combiner.cc | chenzhengda/tensorflow | 8debb698097670458b5f21d728bc6f734a7b5a53 | [
"Apache-2.0"
] | 12 | 2020-07-08T07:27:17.000Z | 2021-12-27T08:54:27.000Z | /* Copyright 2020 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/compiler/plugin/poplar/driver/passes/function_combiner.h"
#include <map>
#include <set>
#include <vector>
#include "tensorflow/compiler/plugin/poplar/driver/passes/outline_remote_buffers.h"
#include "tensorflow/compiler/plugin/poplar/driver/tools/custom_ops/remote_parameter.h"
#include "tensorflow/compiler/plugin/poplar/driver/tools/isomorphic_functions_map.h"
#include "tensorflow/compiler/plugin/poplar/driver/tools/matcher_predicates.h"
#include "tensorflow/compiler/plugin/poplar/driver/tools/pipeline_util.h"
#include "tensorflow/compiler/plugin/poplar/driver/tools/util.h"
#include "tensorflow/compiler/xla/service/hlo_casting_utils.h"
#include "tensorflow/compiler/xla/service/hlo_creation_utils.h"
#include "tensorflow/compiler/xla/service/hlo_module.h"
#include "tensorflow/compiler/xla/service/hlo_reachability.h"
#include "tensorflow/compiler/xla/service/hlo_value.h"
#include "tensorflow/compiler/xla/shape_util.h"
#include "tensorflow/compiler/xla/status_macros.h"
#include "tensorflow/core/lib/core/errors.h"
#include "tensorflow/core/lib/core/status.h"
#include "tensorflow/core/lib/strings/str_util.h"
namespace xla {
namespace poplarplugin {
namespace {
bool InputsOutputsOnSameShard(const HloInstruction* inst) {
if (!inst->has_sharding()) {
return false;
}
auto optional_device = inst->sharding().UniqueDevice();
if (!optional_device) {
return false;
}
return absl::c_all_of(
inst->operands(), [&optional_device](const HloInstruction* operand) {
return operand->sharding().UniqueDevice() == optional_device;
});
}
bool IsFunctionForCombining(const HloInstruction* inst) {
return IsFunction(inst) && InputsOutputsOnSameShard(inst) &&
(GetFunctionNumberModifiedRemoteBufferInputs(inst) ||
GetFunctionNumberUnmodifiedRemoteBufferInputs(inst)) &&
AllUsersUniqueGTEs(inst);
}
bool AllInstructionIndependent(
const HloReachabilityMap& reachability_map,
const std::vector<HloInstruction*>& function_keys,
const SingleShardIsomorphicFunctions& iso_functions) {
// Compare all the possible pairs of functions.
for (HloInstruction* key1 : function_keys) {
for (HloInstruction* key2 : function_keys) {
for (HloInstruction* func1 : iso_functions.at(key1)) {
for (HloInstruction* func2 : iso_functions.at(key2)) {
if (func1 != func2 && reachability_map.IsConnected(func1, func2)) {
return false;
}
}
}
}
}
return true;
}
// Key for which functions can be combined together.
// In order for functions to be combined they need to occur the same number of
// times to make sure the code is still only generated once.
// Take the remote buffer inputs into into account to make sure to only combine
// functions which will cause the same number of syncronisations.
struct CrossShardFunctionKey {
int64 num_occurrences;
int64 num_modified_remote_buffer_inputs;
int64 num_unmodified_remote_buffer_inputs;
bool operator<(const CrossShardFunctionKey& other) const {
return std::make_tuple(num_occurrences, num_modified_remote_buffer_inputs,
num_unmodified_remote_buffer_inputs) <
std::make_tuple(other.num_occurrences,
other.num_modified_remote_buffer_inputs,
other.num_unmodified_remote_buffer_inputs);
}
};
// When combining functions, prefer to merge the larger functions first (note
// that the remote buffers will be in the function shape).
struct SizeSortedHloPtrComparator {
bool operator()(const HloInstruction* a, const HloInstruction* b) const {
const int64 a_size = GetByteSizeOfTotalShape(a->shape());
const int64 b_size = GetByteSizeOfTotalShape(b->shape());
if (a_size != b_size) {
return a_size > b_size;
}
return HloPtrComparator()(a, b);
}
};
// Structure used to store functions on a single shard in decreasing output
// size.
using SizeSortedFunctions =
std::set<HloInstruction*, SizeSortedHloPtrComparator>;
// Structure to map from a shard to set of functions.
using ShardToFunctions = std::map<int64, SizeSortedFunctions>;
// Structure which maps all the functions which can be combined together across
// the shards.
using CrossShardFunctions = std::map<CrossShardFunctionKey, ShardToFunctions>;
} // namespace
FunctionsToCombine FunctionCombiner::GetFunctionsToCombine(
HloComputation* comp) {
FunctionsToCombine outputs;
// Find identical functions within each shard which have remote buffer
// inputs/outputs.
SingleShardIsomorphicFunctions iso_functions;
for (HloInstruction* inst : comp->MakeInstructionPostOrder()) {
if (IsFunctionForCombining(inst)) {
iso_functions.insert(inst);
}
}
if (iso_functions.empty()) {
return outputs;
}
// Match up the functions between shards which should be considered to be
// merged.
CrossShardFunctions cross_shard_functions;
for (auto& pair : iso_functions) {
HloInstruction* functions_key = pair.first;
const int64 shard = *functions_key->sharding_unique_device();
const int64 num_modified_remote_buffer_inputs =
GetFunctionNumberModifiedRemoteBufferInputs(functions_key);
const int64 num_unmodified_remote_buffer_inputs =
GetFunctionNumberUnmodifiedRemoteBufferInputs(functions_key);
CrossShardFunctionKey cross_shard_key{pair.second->size(),
num_modified_remote_buffer_inputs,
num_unmodified_remote_buffer_inputs};
cross_shard_functions[cross_shard_key][shard].insert(functions_key);
}
if (cross_shard_functions.empty()) {
return outputs;
}
auto reachability_map = HloReachabilityMap::Build(comp);
VLOG(2) << cross_shard_functions.size();
std::vector<std::vector<HloInstruction*>> per_combination_functions;
for (auto& pair : cross_shard_functions) {
auto& shard_to_functions = pair.second;
// Keep picking functions from each shard to merge until there are no more
// candidates.
while (shard_to_functions.size() > 1) {
std::vector<HloInstruction*> functions_to_merge;
std::vector<int64> keys_to_erase;
// Get the largest function from each shard.
for (auto& func_pairs : shard_to_functions) {
auto func_itr = func_pairs.second.begin();
functions_to_merge.push_back(*func_itr);
// Each function key can only be merged once.
func_pairs.second.erase(func_itr);
// Mark that no more functions from this shard can be merged.
if (func_pairs.second.empty()) {
keys_to_erase.push_back(func_pairs.first);
}
}
// Make sure all the functions are independent of each other to allow for
// them to be combined.
const bool all_independent = AllInstructionIndependent(
*reachability_map.get(), functions_to_merge, iso_functions);
if (all_independent) {
per_combination_functions.push_back(functions_to_merge);
}
for (int64 shard : keys_to_erase) {
shard_to_functions.erase(shard);
}
}
}
outputs.reserve(per_combination_functions.size());
for (auto& keys : per_combination_functions) {
VLOG(2) << "Can combine the functions:";
std::vector<Functions> output;
for (HloInstruction* key : keys) {
auto& functions = iso_functions.at(key);
VLOG(2) << "* " << key->ToString() << " which appears "
<< functions.size() << " times.";
output.push_back(functions);
}
outputs.push_back(output);
}
return outputs;
}
FunctionCombiner::Permutations FunctionCombiner::GetInputsOutputsPermutation(
const std::vector<HloInstruction*>& functions) {
CHECK_GE(functions.size(), 1);
const int64 num_functions = functions.size();
const HloInstruction* function = functions[0];
// All the functions are expected to have the same number of remote buffers
// (see CrossShardFunctionKey).
const int64 num_modified_remote_buffer_inputs =
GetFunctionNumberModifiedRemoteBufferInputs(function);
const int64 num_unmodified_remote_buffer_inputs =
GetFunctionNumberUnmodifiedRemoteBufferInputs(function);
const int64 num_remote_buffer_inputs =
num_modified_remote_buffer_inputs + num_unmodified_remote_buffer_inputs;
std::vector<int64> old_to_new_inputs_permutation;
std::vector<int64> old_to_new_outputs_permutation;
{
int64 next_modified_remote_buffer_input = 0;
int64 next_unmodified_remote_buffer_input =
num_modified_remote_buffer_inputs * num_functions;
int64 next_input = num_remote_buffer_inputs * num_functions;
for (const HloInstruction* func : functions) {
for (int64 operand_idx = 0; operand_idx != func->operand_count();
++operand_idx) {
if (operand_idx < num_modified_remote_buffer_inputs) {
old_to_new_inputs_permutation.push_back(
next_modified_remote_buffer_input++);
} else if (operand_idx < num_remote_buffer_inputs) {
old_to_new_inputs_permutation.push_back(
next_unmodified_remote_buffer_input++);
} else {
old_to_new_inputs_permutation.push_back(next_input++);
}
}
}
VLOG(2) << "Inputs permutation "
<< absl::StrJoin(old_to_new_inputs_permutation, ",");
}
{
int64 next_modified_remote_buffer_output = 0;
int64 next_output = num_modified_remote_buffer_inputs * num_functions;
for (const HloInstruction* func : functions) {
const int64 num_outputs = ShapeUtil::TupleElementCount(func->shape());
for (int64 output_idx = 0; output_idx != num_outputs; ++output_idx) {
if (output_idx < num_modified_remote_buffer_inputs) {
old_to_new_outputs_permutation.push_back(
next_modified_remote_buffer_output++);
} else {
old_to_new_outputs_permutation.push_back(next_output++);
}
}
}
VLOG(2) << "Outputs permutation "
<< absl::StrJoin(old_to_new_outputs_permutation, ",");
}
return {old_to_new_inputs_permutation, old_to_new_outputs_permutation};
}
StatusOr<std::vector<HloInstruction*>> FunctionCombiner::CombineFunctions(
const std::vector<Functions>& per_shard_functions) {
const int64 num_functions = per_shard_functions.size();
// Get a function from each shard which is being combined.
std::vector<HloInstruction*> functions(num_functions);
absl::c_transform(per_shard_functions, functions.begin(),
[](const Functions& shard_functions) {
return *std::begin(shard_functions);
});
HloInstruction* func = functions[0];
HloComputation* parent = func->parent();
HloModule* module = func->GetModule();
// Make sure all functions output a tuple.
for (HloInstruction* function : functions) {
TF_RETURN_IF_ERROR(FixRootInstruction(function->to_apply()).status());
}
// Work out how to permute the inputs/outputs.
auto permutation = GetInputsOutputsPermutation(functions);
// All the functions are expected to have the same number of remote buffers
// (see CrossShardFunctionKey).
const int64 num_modified_remote_buffer_inputs =
GetFunctionNumberModifiedRemoteBufferInputs(func);
const int64 num_unmodified_remote_buffer_inputs =
GetFunctionNumberUnmodifiedRemoteBufferInputs(func);
// Clone the functions into a single computation.
HloCloneContext context(module);
auto builder = HloComputation::Builder(func->to_apply()->name());
auto get_operands =
[&context](HloInstruction* old_inst) -> std::vector<HloInstruction*> {
std::vector<HloInstruction*> new_operands(old_inst->operand_count());
absl::c_transform(old_inst->operands(), new_operands.begin(),
[&context](HloInstruction* old_operand) {
return context.GetInstruction(old_operand);
});
return new_operands;
};
auto copy_control_dependencies = [&context](HloInstruction* old_inst,
HloInstruction* new_inst) {
// Find the new control predecessors in the clone context.
for (auto* old_control_pred : old_inst->control_predecessors()) {
auto* new_control_pred = context.GetInstruction(old_control_pred);
new_control_pred->AddControlDependencyTo(new_inst);
}
};
auto post_process = [&context, ©_control_dependencies](
HloInstruction* old_inst, HloInstruction* new_inst) {
old_inst->SetupDerivedInstruction(new_inst);
context.MapInstruction(old_inst, new_inst);
copy_control_dependencies(old_inst, new_inst);
};
std::vector<HloInstruction*> old_roots;
int64 function_start_parameter_idx = 0;
for (int64 func_idx = 0; func_idx != num_functions; ++func_idx) {
HloInstruction* function = functions[func_idx];
HloComputation* comp = function->to_apply();
for (HloInstruction* old_inst : comp->MakeInstructionPostOrder()) {
if (old_inst->opcode() == HloOpcode::kParameter) {
const int64 parameter_number =
function_start_parameter_idx + old_inst->parameter_number();
const int64 new_parameter_number =
permutation.old_to_new_inputs_permutation.at(parameter_number);
// Create a parameter.
HloInstruction* new_inst =
builder.AddInstruction(HloInstruction::CreateParameter(
new_parameter_number, old_inst->shape(), old_inst->name()));
post_process(old_inst, new_inst);
} else {
HloInstruction* new_inst =
builder.AddInstruction(old_inst->CloneWithNewOperands(
old_inst->shape(), get_operands(old_inst)));
post_process(old_inst, new_inst);
if (old_inst == comp->root_instruction()) {
CHECK_EQ(old_inst->opcode(), HloOpcode::kTuple);
old_roots.push_back(old_inst);
}
}
}
function_start_parameter_idx += function->operand_count();
}
CHECK_EQ(old_roots.size(), num_functions);
// Create GTEs from each root and then create a single root tuple instruction
// with all the outputs correctly permuted.
std::vector<HloInstruction*> all_outputs;
for (int64 func_idx = 0; func_idx != num_functions; ++func_idx) {
HloInstruction* function = functions[func_idx];
HloInstruction* old_root = function->to_apply()->root_instruction();
HloInstruction* new_root = context.GetInstruction(old_root);
const int64 shard = *new_root->sharding().UniqueDevice();
const int64 num_outputs = ShapeUtil::TupleElementCount(new_root->shape());
for (int64 output_idx = 0; output_idx != num_outputs; ++output_idx) {
const HloInstruction* operand = new_root->operand(output_idx);
HloInstruction* gte =
builder.AddInstruction(HloInstruction::CreateGetTupleElement(
operand->shape(), new_root, output_idx));
operand->SetupDerivedInstruction(gte);
all_outputs.push_back(gte);
}
}
// Permute the outputs to the right order.
all_outputs =
Permute(all_outputs, permutation.old_to_new_outputs_permutation);
// Create the root instruction.
HloInstruction* root =
builder.AddInstruction(HloInstruction::CreateTuple(all_outputs));
// Get the new sharding for the output.
std::vector<HloSharding> outputs_sharding;
for (HloInstruction* output : all_outputs) {
const HloSharding& sharding = output->sharding();
if (sharding.IsTuple()) {
auto& tuple_sharding = sharding.tuple_elements();
outputs_sharding.insert(outputs_sharding.end(), tuple_sharding.begin(),
tuple_sharding.end());
} else {
outputs_sharding.push_back(sharding);
}
}
HloSharding output_sharding =
HloSharding::Tuple(root->shape(), outputs_sharding);
root->set_sharding(output_sharding);
// Create a copy of the computation to outline.
HloComputation* outlined_computation =
module->AddEmbeddedComputation(builder.Build(root));
// For each set of functions across the shards, replace them with a combined
// function.
std::vector<Functions::iterator> per_shard_iterators;
absl::c_transform(per_shard_functions,
std::back_inserter(per_shard_iterators),
[](const Functions& shard_functions) {
return std::begin(shard_functions);
});
std::vector<HloInstruction*> combined_functions;
for (int64 i = 0; i != per_shard_functions[0].size(); ++i) {
// Get a function from each shard, their operands and output GTEs.
std::vector<HloInstruction*> operands;
std::vector<HloInstruction*> gtes;
VLOG(2) << "Combining functions: ";
for (int64 func_num = 0; func_num != num_functions; ++func_num) {
HloInstruction* function = *per_shard_iterators[func_num];
VLOG(2) << "* " << function->ToString();
functions[func_num] = function;
// Get the operands.
operands.insert(operands.end(), function->operands().begin(),
function->operands().end());
// Get the output GTEs.
const int64 num_outputs = ShapeUtil::TupleElementCount(function->shape());
for (int64 output_idx = 0; output_idx != num_outputs; ++output_idx) {
TF_ASSIGN_OR_RETURN(HloInstruction * gte,
GetUniqueGTEUser(function, output_idx));
gtes.push_back(gte);
}
// Move the iterator for the next function.
++per_shard_iterators[func_num];
}
// Permute the operands.
operands = Permute(operands, permutation.old_to_new_inputs_permutation);
// Create a new call with the new computations and the new sharding.
HloInstruction* new_function = parent->AddInstruction(
functions[0]->CloneWithNewOperands(root->shape(), operands));
new_function->SetAndSanitizeName(
absl::StrCat(functions[0]->name(), "_combined"));
HloComputation* new_computation =
module->AddEmbeddedComputation(outlined_computation->Clone());
new_function->set_to_apply(new_computation);
new_function->set_sharding(output_sharding);
functions[0]->SetupDerivedInstruction(new_function);
// Set the information about remote buffers.
TF_ASSIGN_OR_RETURN(PoplarBackendConfig config,
new_function->backend_config<PoplarBackendConfig>());
auto* function_config =
config.mutable_call_config()->mutable_function_config();
function_config->set_num_modified_remote_buffer_inputs(
num_modified_remote_buffer_inputs * num_functions);
function_config->set_num_unmodified_remote_buffer_inputs(
num_unmodified_remote_buffer_inputs * num_functions);
function_config->set_unique_sharding(false);
TF_RETURN_IF_ERROR(new_function->set_backend_config(config));
// Permute the GTEs to the right order.
gtes = Permute(gtes, permutation.old_to_new_outputs_permutation);
// Rewire all the GTEs to use the new function call at the right tuple
// index.
for (int64 output_idx = 0; output_idx != gtes.size(); ++output_idx) {
HloInstruction* gte = gtes.at(output_idx);
TF_RETURN_IF_ERROR(
gte->ReplaceOperandWithDifferentShape(0, new_function));
gte->set_tuple_index(output_idx);
}
// Copy over any control dependencies and remove the old functions.
for (HloInstruction* function : functions) {
TF_RETURN_IF_ERROR(new_function->CopyAllControlDepsFrom(function));
TF_RETURN_IF_ERROR(function->DropAllControlDeps());
TF_RETURN_IF_ERROR(parent->RemoveInstruction(function));
}
VLOG(2) << "New function is " << new_function->ToString();
combined_functions.push_back(new_function);
}
return combined_functions;
}
StatusOr<bool> FunctionCombiner::RunOnComputation(HloComputation* comp) {
auto functions_to_combine = GetFunctionsToCombine(comp);
std::vector<std::vector<HloInstruction*>> combined_functions;
for (auto& per_shard_functions : functions_to_combine) {
TF_ASSIGN_OR_RETURN(auto combined, CombineFunctions(per_shard_functions));
combined_functions.push_back(combined);
}
return functions_to_combine.size();
}
StatusOr<bool> FunctionCombiner::Run(HloModule* module) {
VLOG(2) << "Before FunctionCombiner:";
XLA_VLOG_LINES(2, module->ToString());
bool changed = false;
// Run it for all resource updates.
for (HloComputation* comp : module->MakeComputationPostOrder()) {
if (IsPopOpsFusion(comp)) {
continue;
}
TF_ASSIGN_OR_RETURN(const bool computation_changed, RunOnComputation(comp));
changed |= computation_changed;
}
if (changed) {
TF_RETURN_IF_ERROR(module->RemoveUnusedComputations());
VLOG(3) << "After FunctionCombiner:";
XLA_VLOG_LINES(3, module->ToString());
} else {
VLOG(2) << "No changes were made.";
}
return changed;
}
} // namespace poplarplugin
} // namespace xla
| 38.842294 | 87 | 0.7055 | [
"shape",
"vector"
] |
077e23fdb332fe245fab33d3a0dfc20cad1f7279 | 20,247 | cpp | C++ | transports/lib/astartehttpendpoint.cpp | hemeraos/hyperdrive | d7f472203eeae7e5cb7283f92192d05c9a7d2b63 | [
"Apache-2.0"
] | null | null | null | transports/lib/astartehttpendpoint.cpp | hemeraos/hyperdrive | d7f472203eeae7e5cb7283f92192d05c9a7d2b63 | [
"Apache-2.0"
] | null | null | null | transports/lib/astartehttpendpoint.cpp | hemeraos/hyperdrive | d7f472203eeae7e5cb7283f92192d05c9a7d2b63 | [
"Apache-2.0"
] | 1 | 2021-02-08T15:48:36.000Z | 2021-02-08T15:48:36.000Z | #include "astartehttpendpoint.h"
#include "astartehttpendpoint_p.h"
#include "astartecrypto.h"
#include "astarteverifycertificateoperation.h"
#include "hyperdrivemqttclientwrapper.h"
#include <QtCore/QDir>
#include <QtCore/QDebug>
#include <QtCore/QLoggingCategory>
#include <QtCore/QFile>
#include <QtCore/QJsonArray>
#include <QtCore/QJsonDocument>
#include <QtCore/QJsonObject>
#include <QtCore/QSettings>
#include <QtCore/QTimer>
#include <QtNetwork/QNetworkAccessManager>
#include <QtNetwork/QNetworkReply>
#include <QtNetwork/QNetworkRequest>
#include <HemeraCore/CommonOperations>
#include <HemeraCore/Fingerprints>
#include <HemeraCore/Literals>
#include <HemeraCore/FetchSystemConfigOperation>
#include <HemeraCore/SetSystemConfigOperation>
#include <private/HemeraCore/hemeraasyncinitobject_p.h>
#include <hyperdriveconfig.h>
#include <hyperdriveutils.h>
#define RETRY_INTERVAL 15000
Q_LOGGING_CATEGORY(astarteHttpEndpointDC, "astarte.httpendpoint", DEBUG_MESSAGES_DEFAULT_LEVEL)
namespace Astarte {
constexpr const char *pathToAstarteEndpointConfiguration() { return "/var/lib/astarte/endpoint/"; }
QString pathToAstarteEndpointConfiguration(const QString &endpointName)
{ return QStringLiteral("%1%2").arg(QLatin1String(pathToAstarteEndpointConfiguration()), endpointName); }
PairOperation::PairOperation(HTTPEndpoint *parent)
: Hemera::Operation(parent)
, m_endpoint(parent)
{
}
PairOperation::~PairOperation()
{
}
void PairOperation::startImpl()
{
// Before anything else, we need to check if we have an available keystore.
if (!Crypto::instance()->isKeyStoreAvailable()) {
// Let's build one.
Hemera::Operation *op = Crypto::instance()->generateAstarteKeyStore();
connect(op, &Hemera::Operation::finished, this, [this, op] {
if (op->isError()) {
// That's ugly.
setFinishedWithError(op->errorName(), op->errorMessage());
return;
}
initiatePairing();
});
} else {
// Let's just go
initiatePairing();
}
}
void PairOperation::initiatePairing()
{
// FIXME: This should be done using Global configuration!!
QSettings settings(QStringLiteral("%1/endpoint_crypto.conf").arg(pathToAstarteEndpointConfiguration(m_endpoint->d_func()->endpointName)),
QSettings::IniFormat);
if (settings.value(QStringLiteral("apiKey")).toString().isEmpty()) {
Hemera::FetchSystemConfigOperation *apiKeyOp = new Hemera::FetchSystemConfigOperation(QStringLiteral("hemera_astarte_apikey"));
connect(apiKeyOp, &Hemera::Operation::finished, this, [this, apiKeyOp] {
QString apiKey = apiKeyOp->value();
if (apiKeyOp->isError() || apiKey.isEmpty()) {
performFakeAgentPairing();
} else {
{
QSettings settings(QStringLiteral("%1/endpoint_crypto.conf").arg(pathToAstarteEndpointConfiguration(m_endpoint->d_func()->endpointName)),
QSettings::IniFormat);
settings.setValue(QStringLiteral("apiKey"), apiKey);
}
performPairing();
}
});
} else {
performPairing();
}
}
void PairOperation::performFakeAgentPairing()
{
qWarning() << "Fake agent pairing!";
QJsonObject o;
o.insert(QStringLiteral("hwId"), QLatin1String(m_endpoint->d_func()->hardwareId));
QByteArray deviceIDPayload = QJsonDocument(o).toJson(QJsonDocument::Compact);
QNetworkReply *r = m_endpoint->sendRequest(QStringLiteral("/devices/apikeysFromDevice"), deviceIDPayload, Crypto::CustomerAuthenticationDomain);
qCDebug(astarteHttpEndpointDC) << "I'm sending: " << deviceIDPayload.constData();
connect(r, &QNetworkReply::finished, this, [this, r, deviceIDPayload] {
if (r->error() != QNetworkReply::NoError) {
qCWarning(astarteHttpEndpointDC) << "Pairing error! Error: " << r->error();
setFinishedWithError(Hemera::Literals::literal(Hemera::Literals::Errors::failedRequest()), r->errorString());
r->deleteLater();
return;
}
QJsonDocument doc = QJsonDocument::fromJson(r->readAll());
r->deleteLater();
qCDebug(astarteHttpEndpointDC) << "Got the ok!";
if (!doc.isObject()) {
qCWarning(astarteHttpEndpointDC) << "Parsing pairing result error!";
setFinishedWithError(Hemera::Literals::literal(Hemera::Literals::Errors::badRequest()), QStringLiteral("Parsing pairing result error!"));
return;
}
qCDebug(astarteHttpEndpointDC) << "Payload is " << doc.toJson().constData();
QJsonObject pairData = doc.object();
if (!pairData.contains(QStringLiteral("apiKey"))) {
qCWarning(astarteHttpEndpointDC) << "Missing apiKey in the pairing routine!";
setFinishedWithError(Hemera::Literals::literal(Hemera::Literals::Errors::badRequest()),
QStringLiteral("Missing apiKey in the pairing routine!"));
return;
}
// Ok, we need to write the files now.
{
QSettings settings(QStringLiteral("%1/endpoint_crypto.conf").arg(pathToAstarteEndpointConfiguration(m_endpoint->d_func()->endpointName)),
QSettings::IniFormat);
settings.setValue(QStringLiteral("apiKey"), pairData.value(QStringLiteral("apiKey")).toString());
new Hemera::SetSystemConfigOperation(QStringLiteral("hemera_astarte_apikey"), pairData.value(QStringLiteral("apiKey")).toString());
}
// That's all, folks!
performPairing();
});
}
void PairOperation::performPairing()
{
QFile csr(Crypto::instance()->pathToCertificateRequest());
if (!csr.open(QIODevice::ReadOnly)) {
qCWarning(astarteHttpEndpointDC) << "Could not open CSR for reading! Aborting.";
setFinishedWithError(Hemera::Literals::literal(Hemera::Literals::Errors::notFound()), QStringLiteral("Could not open CSR for reading! Aborting."));
}
QByteArray deviceIDPayload = csr.readAll();
QNetworkReply *r = m_endpoint->sendRequest(QStringLiteral("/pairing"), deviceIDPayload, Crypto::DeviceAuthenticationDomain);
qCDebug(astarteHttpEndpointDC) << "I'm sending: " << deviceIDPayload.constData();
connect(r, &QNetworkReply::finished, this, [this, r, deviceIDPayload] {
if (r->error() != QNetworkReply::NoError) {
qCWarning(astarteHttpEndpointDC) << "Pairing error!";
setFinishedWithError(Hemera::Literals::literal(Hemera::Literals::Errors::failedRequest()), r->errorString());
r->deleteLater();
return;
}
QJsonDocument doc = QJsonDocument::fromJson(r->readAll());
r->deleteLater();
qCDebug(astarteHttpEndpointDC) << "Got the ok!";
if (!doc.isObject()) {
qCWarning(astarteHttpEndpointDC) << "Parsing pairing result error!";
setFinishedWithError(Hemera::Literals::literal(Hemera::Literals::Errors::badRequest()), QStringLiteral("Parsing pairing result error!"));
return;
}
qCDebug(astarteHttpEndpointDC) << "Payload is " << doc.toJson().constData();
QJsonObject pairData = doc.object();
if (!pairData.contains(QStringLiteral("clientCrt"))) {
qCWarning(astarteHttpEndpointDC) << "Missing certificate in the pairing routine!";
setFinishedWithError(Hemera::Literals::literal(Hemera::Literals::Errors::badRequest()), QStringLiteral("Missing certificate in the pairing routine!"));
return;
}
// Ok, we need to write the files now.
{
QFile generatedCertificate(QStringLiteral("%1/mqtt_broker.crt").arg(pathToAstarteEndpointConfiguration(m_endpoint->d_func()->endpointName)));
if (!generatedCertificate.open(QIODevice::WriteOnly | QIODevice::Truncate)) {
qCWarning(astarteHttpEndpointDC) << "Could not write certificate!";
setFinishedWithError(Hemera::Literals::literal(Hemera::Literals::Errors::badRequest()), generatedCertificate.errorString());
return;
}
generatedCertificate.write(pairData.value(QStringLiteral("clientCrt")).toVariant().toByteArray());
generatedCertificate.flush();
generatedCertificate.close();
}
{
QSettings settings(QStringLiteral("%1/mqtt_broker.conf").arg(pathToAstarteEndpointConfiguration(m_endpoint->d_func()->endpointName)),
QSettings::IniFormat);
}
// That's all, folks!
setFinished();
});
}
void HTTPEndpointPrivate::connectToEndpoint()
{
QUrl infoEndpoint = endpoint;
infoEndpoint.setPath(endpoint.path() + QStringLiteral("/info"));
QNetworkRequest req(infoEndpoint);
req.setSslConfiguration(sslConfiguration);
req.setRawHeader("Authorization", agentKey);
req.setRawHeader("X-Astarte-Transport-Provider", "Hemera");
req.setRawHeader("X-Astarte-Transport-Version", QStringLiteral("%1.%2.%3")
.arg(Hyperdrive::StaticConfig::hyperdriveMajorVersion())
.arg(Hyperdrive::StaticConfig::hyperdriveMinorVersion())
.arg(Hyperdrive::StaticConfig::hyperdriveReleaseVersion())
.toLatin1());
QNetworkReply *reply = nam->get(req);
qCDebug(astarteHttpEndpointDC) << "Connecting to our endpoint! " << infoEndpoint;
Q_Q(HTTPEndpoint);
QObject::connect(reply, &QNetworkReply::finished, q, [this, q, reply] {
if (reply->error() != QNetworkReply::NoError) {
int retryInterval = Hyperdrive::Utils::randomizedInterval(RETRY_INTERVAL, 1.0);
qCWarning(astarteHttpEndpointDC) << "Error while connecting! Retrying in " << (retryInterval / 1000) << " seconds. error: " << reply->error();
// We never give up. If we couldn't connect, we reschedule this in 15 seconds.
QTimer::singleShot(retryInterval, q, SLOT(connectToEndpoint()));
reply->deleteLater();
return;
}
QJsonDocument doc = QJsonDocument::fromJson(reply->readAll());
reply->deleteLater();
if (!doc.isObject()) {
return;
}
qCDebug(astarteHttpEndpointDC) << "Connected! " << doc.toJson(QJsonDocument::Indented);
QJsonObject rootReplyObj = doc.object();
endpointVersion = rootReplyObj.value(QStringLiteral("version")).toString();
// Get configuration
QSettings settings(QStringLiteral("%1/mqtt_broker.conf").arg(pathToAstarteEndpointConfiguration(endpointName)),
QSettings::IniFormat);
mqttBroker = QUrl::fromUserInput(rootReplyObj.value(QStringLiteral("url")).toString());
// Initialize cryptography
auto processCryptoStatus = [this, q] (bool ready) {
if (!ready) {
qCWarning(astarteHttpEndpointDC) << "Could not initialize signature system!!";
if (!q->isReady()) {
q->setInitError(Hemera::Literals::literal(Hemera::Literals::Errors::failedRequest()),
HTTPEndpoint::tr("Could not initialize signature system!"));
}
return;
}
qCInfo(astarteHttpEndpointDC) << "Signature system initialized correctly!";
if (!q->isReady()) {
q->setReady();
}
};
if (Crypto::instance()->isReady()) {
processCryptoStatus(true);
} else if (Crypto::instance()->hasInitError()) {
processCryptoStatus(false);
} else {
QObject::connect(Crypto::instance()->init(), &Hemera::Operation::finished, q, [this, q, processCryptoStatus] (Hemera::Operation *op) {
processCryptoStatus(!op->isError());
});
}
});
}
HTTPEndpoint::HTTPEndpoint(const QUrl& endpoint, const QSslConfiguration &sslConfiguration, QObject* parent)
: Endpoint(*new HTTPEndpointPrivate(this), endpoint, parent)
{
Q_D(HTTPEndpoint);
d->nam = new QNetworkAccessManager(this);
d->sslConfiguration = sslConfiguration;
d->endpointName = endpoint.host();
}
HTTPEndpoint::~HTTPEndpoint()
{
}
QUrl HTTPEndpoint::endpoint() const
{
Q_D(const HTTPEndpoint);
return d->endpoint;
}
void HTTPEndpoint::initImpl()
{
Q_D(HTTPEndpoint);
// FIXME: This should be done using Global configuration!!
QDir confDir(QLatin1String(Hyperdrive::StaticConfig::hyperspaceConfigurationDir()));
for (const QString &conf : confDir.entryList(QStringList() << QStringLiteral("transport-astarte.conf"))) {
QSettings settings(confDir.absoluteFilePath(conf), QSettings::IniFormat);
settings.beginGroup(QStringLiteral("AstarteTransport")); {
d->agentKey = settings.value(QStringLiteral("agentKey")).toString().toLatin1();
d->brokerCa = settings.value(QStringLiteral("brokerCa"), QStringLiteral("/etc/ssl/certs/ca-bundle.trust.crt")).toString();
d->ignoreSslErrors = settings.value(QStringLiteral("ignoreSslErrors"), false).toBool();
if (settings.contains(QStringLiteral("pairingCa"))) {
d->sslConfiguration.setCaCertificates(QSslCertificate::fromPath(settings.value(QStringLiteral("pairingCa")).toString()));
}
} settings.endGroup();
}
// Grab the hw id
Hemera::ByteArrayOperation *hwIdOperation = Hemera::Fingerprints::globalHardwareId();
connect(hwIdOperation, &Hemera::Operation::finished, this, [this, hwIdOperation] {
if (hwIdOperation->isError()) {
setInitError(Hemera::Literals::literal(Hemera::Literals::Errors::unhandledRequest()), QStringLiteral("Could not retrieve hardware id!"));
} else {
Q_D(HTTPEndpoint);
d->hardwareId = hwIdOperation->result();
// Verify the configuration directory is up.
if (!QFileInfo::exists(pathToAstarteEndpointConfiguration(d->endpointName))) {
// Create
qCDebug(astarteHttpEndpointDC) << "Creating Astarte endpoint configuration directory for " << d->endpointName;
QDir dir;
if (!dir.mkpath(pathToAstarteEndpointConfiguration(d->endpointName))) {
setInitError(Hemera::Literals::literal(Hemera::Literals::Errors::failedRequest()), QStringLiteral("Could not create configuration directory!"));
}
}
// Let's connect to our endpoint, shall we?
d->connectToEndpoint();
}
});
connect(d->nam, &QNetworkAccessManager::sslErrors, this, [this] (QNetworkReply *reply, const QList<QSslError> &errors) {
Q_D(const HTTPEndpoint);
qCWarning(astarteHttpEndpointDC) << "SslErrors: " << errors;
if (d->ignoreSslErrors) {
reply->ignoreSslErrors(errors);
}
});
}
QNetworkReply *HTTPEndpoint::sendRequest(const QString& relativeEndpoint, const QByteArray& payload, Crypto::AuthenticationDomain authenticationDomain)
{
Q_D(const HTTPEndpoint);
// Build the endpoint
QUrl target = d->endpoint;
target.setPath(d->endpoint.path() + relativeEndpoint);
QNetworkRequest req(target);
req.setHeader(QNetworkRequest::ContentTypeHeader, QStringLiteral("application/json"));
req.setSslConfiguration(d->sslConfiguration);
qWarning() << "La richiesta lo zio" << relativeEndpoint << payload << authenticationDomain;
// Authentication?
if (authenticationDomain == Crypto::DeviceAuthenticationDomain) {
// FIXME: This should be done using Global configuration!!
QSettings settings(QStringLiteral("%1/endpoint_crypto.conf").arg(pathToAstarteEndpointConfiguration(d->endpointName)),
QSettings::IniFormat);
req.setRawHeader("X-API-Key", settings.value(QStringLiteral("apiKey")).toString().toLatin1());
req.setRawHeader("X-Hardware-ID", d->hardwareId);
req.setRawHeader("X-Astarte-Transport-Provider", "Hemera");
req.setRawHeader("X-Astarte-Transport-Version", QStringLiteral("%1.%2.%3")
.arg(Hyperdrive::StaticConfig::hyperdriveMajorVersion())
.arg(Hyperdrive::StaticConfig::hyperdriveMinorVersion())
.arg(Hyperdrive::StaticConfig::hyperdriveReleaseVersion())
.toLatin1());
qWarning() << "Lozio";
qWarning() << "Setting X-API-Key:" << settings.value(QStringLiteral("apiKey")).toString();
} else if (authenticationDomain == Crypto::CustomerAuthenticationDomain) {
qWarning() << "Authorization lo zio";
req.setRawHeader("Authorization", d->agentKey);
req.setRawHeader("X-Astarte-Transport-Provider", "Hemera");
req.setRawHeader("X-Astarte-Transport-Version", QStringLiteral("%1.%2.%3")
.arg(Hyperdrive::StaticConfig::hyperdriveMajorVersion())
.arg(Hyperdrive::StaticConfig::hyperdriveMinorVersion())
.arg(Hyperdrive::StaticConfig::hyperdriveReleaseVersion())
.toLatin1());
}
return d->nam->post(req, payload);
}
Hemera::Operation* HTTPEndpoint::pair(bool force)
{
if (!force && isPaired()) {
return new Hemera::FailureOperation(Hemera::Literals::literal(Hemera::Literals::Errors::badRequest()),
tr("This device is already paired to this Astarte endpoint"));
}
return new PairOperation(this);
}
Hemera::Operation* HTTPEndpoint::verifyCertificate()
{
Q_D(const HTTPEndpoint);
QFile cert(QStringLiteral("%1/mqtt_broker.crt").arg(pathToAstarteEndpointConfiguration(d->endpointName)));
return new VerifyCertificateOperation(cert, this);
}
Hyperdrive::MQTTClientWrapper *HTTPEndpoint::createMqttClientWrapper()
{
if (!isReady() || mqttBrokerUrl().isEmpty()) {
return nullptr;
}
Q_D(const HTTPEndpoint);
// Create the client ID
QList < QSslCertificate > certificates = QSslCertificate::fromPath(QStringLiteral("%1/mqtt_broker.crt")
.arg(pathToAstarteEndpointConfiguration(d->endpointName)), QSsl::Pem);
if (certificates.size() != 1) {
qCWarning(astarteHttpEndpointDC) << "Could not retrieve device certificate!";
return nullptr;
}
QByteArray customerId = certificates.first().subjectInfo(QSslCertificate::CommonName).first().toLatin1();
Hyperdrive::MQTTClientWrapper *c = new Hyperdrive::MQTTClientWrapper(mqttBrokerUrl(), customerId, this);
c->setCleanSession(false);
c->setPublishQoS(Hyperdrive::MQTTClientWrapper::AtMostOnceQoS);
c->setSubscribeQoS(Hyperdrive::MQTTClientWrapper::AtMostOnceQoS);
c->setKeepAlive(300);
c->setIgnoreSslErrors(d->ignoreSslErrors);
// SSL
c->setMutualSSLAuthentication(d->brokerCa, Crypto::pathToPrivateKey(),
QStringLiteral("%1/mqtt_broker.crt").arg(pathToAstarteEndpointConfiguration(d->endpointName)));
QSettings settings(QStringLiteral("%1/mqtt_broker.conf").arg(pathToAstarteEndpointConfiguration(d->endpointName)),
QSettings::IniFormat);
return c;
}
QString HTTPEndpoint::endpointVersion() const
{
Q_D(const HTTPEndpoint);
return d->endpointVersion;
}
QUrl HTTPEndpoint::mqttBrokerUrl() const
{
Q_D(const HTTPEndpoint);
return d->mqttBroker;
}
bool HTTPEndpoint::isPaired() const
{
Q_D(const HTTPEndpoint);
return QFile::exists(QStringLiteral("%1/mqtt_broker.crt").arg(pathToAstarteEndpointConfiguration(d->endpointName)));
}
}
#include "moc_astartehttpendpoint.cpp"
| 42.805497 | 164 | 0.640984 | [
"object"
] |
0782f855c10b50480d87b509f39bb55a98ae05d7 | 3,411 | cpp | C++ | posix-tests/rx-test.cpp | Mogball/rx-cpp | 445d704cc818223188168976251b62d299d83274 | [
"MIT"
] | 11 | 2015-05-31T17:19:20.000Z | 2021-07-01T00:34:57.000Z | posix-tests/rx-test.cpp | Mogball/rx-cpp | 445d704cc818223188168976251b62d299d83274 | [
"MIT"
] | null | null | null | posix-tests/rx-test.cpp | Mogball/rx-cpp | 445d704cc818223188168976251b62d299d83274 | [
"MIT"
] | 1 | 2020-07-10T18:25:57.000Z | 2020-07-10T18:25:57.000Z | #include <iostream>
#include <map>
#include <vector>
#include "rx.h"
#include <stdlib.h>
using namespace std;
using namespace textutil;
template <class T>
ostream& operator<< (ostream& os, const vector<T>& v) {
for (auto& val: v) os << val << ' ';
return os;
}
template <class T>
ostream& operator<< (ostream& os, const map<string,T>& v) {
for (auto& p: v) os << p.first << ':' << p.second << ' ';
return os;
}
typedef map<string,string> StringMap;
int main()
{
// custom string literal!
Rxp d("[a-z]+");
bool ok = d.matches("hello dolly");
if (! ok) {
cerr << "did not match" << endl;
return 1;
}
// a Useful Quote
const char *text =
"Some people, when confronted with a problem, think "
"\"I know, I'll use regular expressions.\" "
"Now they have two problems.";
Rxp words("%a+",Rx::lua);
const char *s2 = "baad! bad! argh";
// equivalent to Lua's string.find
int start=0,end;
if (words.find(s2,start,end)) {
cout << string(s2,end-start) << endl;
}
// --> baad
// looping over a word match
// explictly using a match
Rx::match m(words,s2);
while (m.matches()) {
cout << m[0] << endl;
m.next();
}
// sexier version of the above, applied to the Useful Quote
// all words longer than 6 chars
for (auto M: words.gmatch(text)) {
if (M[0].size() > 6)
cout << M[0] << endl;
}
// fill a vector with matches!
vector<string> strings;
words.gmatch(text).append_to(strings);
cout << strings << endl;
// --> Some people when confronted with a problem think ...
vector<int> numbers;
Rxp digits("%d+",Rx::lua);
digits.gmatch("10 and a 20 plus 30 any 40").append_to(numbers);
cout << numbers << endl;
// --> 10 20 30 40
// fill a map with matches - uses M[1] and M[2]
Rxp word_pairs("(%a+)=([^;]+)",Rx::lua);
StringMap config;
word_pairs.gmatch("dog=juno;owner=angela").fill_map(config);
cout << config << endl;
// --> dog:juno owner:angela
// the 3 kinds of global substitution:
// (1) the replacement is a string with group references
Rxp R2("<(%a+)>",Rx::lua);
auto S = "hah <hello> you, hello <dolly> yes!";
cout << R2.gsub(S,"[%1]") << endl;
// -> hah [hello] you, hello [dolly] yes!
// (2) the replacement is an associative array
StringMap lookup = {
{"bonzo","BONZO"},
{"dog","DOG"}
};
Rxp R3("%$(%a+)",Rx::lua);
string res = R3.gsub("$bonzo is here, $dog! Look sharp!",lookup);
cout << res << endl;
// --> BONZO is here, DOG! Look sharp!
// result of lookup may be anything that std::to_string can convert
map<string,int> ints = {{"frodo",50},{"bilbo",120}};
res = R3.gsub("$frodo and $bilbo",ints);
cout << res << endl;
// --> 50 and 120
// (3) the replacement is a function which receives a reference to
// the match object
// this will be prettier in C++14 (since GCC 4.9) using a generic 'auto' lambda.
res = R3.gsub_fun("$HOME and $PATH",[](const Rx::match& m) {
auto res = getenv(m.group().c_str()); // we want a 'safe' getenv!
return res ? res : "";
});
cout << res << endl;
// --> /home/steve and /home/steve/bin:/usr/local/sbin:/.....
return 0;
}
| 28.663866 | 84 | 0.553797 | [
"object",
"vector"
] |
0783218be0dcb1bd9079d4085393bfdb94326569 | 4,469 | cpp | C++ | src/keyboard_control.cpp | rhogroup/rflex | ce9ba63dcfdb99acebfab7216ae6f0fe6d055a65 | [
"MIT"
] | 1 | 2018-02-21T14:23:35.000Z | 2018-02-21T14:23:35.000Z | src/keyboard_control.cpp | rhogroup/rflex | ce9ba63dcfdb99acebfab7216ae6f0fe6d055a65 | [
"MIT"
] | null | null | null | src/keyboard_control.cpp | rhogroup/rflex | ce9ba63dcfdb99acebfab7216ae6f0fe6d055a65 | [
"MIT"
] | null | null | null | /*
* Motor Controller using keyboard inputs
* Keval Patel - September 26, 2013
*
* Player - One Hell of a Robot Server
* Copyright (C) 2000
* Brian Gerkey, Kasper Stoy, Richard Vaughan, & Andrew Howard
*
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*/
#include "ros/ros.h"
#include "std_msgs/String.h"
#include "geometry_msgs/Twist.h"
#include <iostream>
using namespace std;
/**
* This file is just a simple motor control command file
* Usage: The keys W,S,A,D serve as input keys to move the rover
* Forward, Backward, Left and Right respectively.
* *"W"*
* *A*S*D*
* Thus:-
* W = FORWARD
* S = BACKWARD
* A = LEFT
* D = RIGHT
*/
#define MOVE_FORWARD keyboardInput == 'w'
#define MOVE_BACKWARD keyboardInput == 's'
#define TURN_LEFT keyboardInput == 'a'
#define TURN_RIGHT keyboardInput == 'd'
int main(int argc, char **argv)
{
ros::init(argc, argv, "keyboard_control");
// Variable in which the keyboard input character is stored
char keyboardInput;
/**
* NodeHandle is the main access point to communications with the ROS system.
* The first NodeHandle constructed will fully initialize this node, and the last
* NodeHandle destructed will close down the node.
*/
ros::NodeHandle n;
/**
* The advertise() function is how you tell ROS that you want to
* publish on a given topic name. This invokes a call to the ROS
* master node, which keeps a registry of who is publishing and who
* is subscribing. After this advertise() call is made, the master
* node will notify anyone who is trying to subscribe to this topic name,
* and they will in turn negotiate a peer-to-peer connection with this
* node. advertise() returns a Publisher object which allows you to
* publish messages on that topic through a call to publish(). Once
* all copies of the returned Publisher object are destroyed, the topic
* will be automatically unadvertised.
*
* The second parameter to advertise() is the size of the message queue
* used for publishing messages. If messages are published more quickly
* than we can send them, the number here specifies how many messages to
* buffer up before throwing some away.
*/
ros::Publisher command_pub = n.advertise<geometry_msgs::Twist>("/cmd_vel", 10);
ros::Rate loop_rate(10);
while (ros::ok())
{
// As user to provide with the input
cout << "Please enter a the direction you want to move \nForward- W \nBackward- S\nLeft - A\nRight- D\nStop-Any key\n";
cin >> keyboardInput;
geometry_msgs::Twist velocityMessage;
/* Check to see which command to execute, then input numbers accordingly
* We care about linear.x, positive- forward negative- backward
* We care about angular.z, positive- left negative-right
*/
if(MOVE_FORWARD)
{
velocityMessage.linear.x = 1;
velocityMessage.angular.z = 0;
}
else if(MOVE_BACKWARD)
{
velocityMessage.linear.x = -0.2;
velocityMessage.angular.z = 0;
}
else if(TURN_LEFT)
{
velocityMessage.linear.x = 0;
velocityMessage.angular.z = 0.2;
}
else if(TURN_RIGHT)
{
velocityMessage.linear.x = 0;
velocityMessage.angular.z = -0.2;
}
//if we receive an H or any non-valid letter we stop the rover
else
{
velocityMessage.linear.x = 0;
velocityMessage.angular.z = 0;
}
/**
* The publish() function is how you send messages. The parameter
* is the message object. The type of this object must agree with the type
* given as a template parameter to the advertise<>() call, as was done
* in the constructor above.
*/
command_pub.publish(velocityMessage);
ros::spinOnce();
loop_rate.sleep();
}
return 0;
}
| 32.620438 | 123 | 0.68606 | [
"object"
] |
07875fdfd27ce5f1795a1e4cec768a73b259568e | 3,666 | cc | C++ | tests/unit/lib/observers/ParameterObserverTest_unittest.cc | vinnik-dmitry07/shogun | 376bf8f500d3856f5ffe6f145dff84cbf55de104 | [
"BSD-3-Clause"
] | 2,753 | 2015-01-02T11:34:13.000Z | 2022-03-25T07:04:27.000Z | tests/unit/lib/observers/ParameterObserverTest_unittest.cc | vinnik-dmitry07/shogun | 376bf8f500d3856f5ffe6f145dff84cbf55de104 | [
"BSD-3-Clause"
] | 2,404 | 2015-01-02T19:31:41.000Z | 2022-03-09T10:58:22.000Z | tests/unit/lib/observers/ParameterObserverTest_unittest.cc | vinnik-dmitry07/shogun | 376bf8f500d3856f5ffe6f145dff84cbf55de104 | [
"BSD-3-Clause"
] | 1,156 | 2015-01-03T01:57:21.000Z | 2022-03-26T01:06:28.000Z | /*
* This software is distributed under BSD 3-clause license (see LICENSE file).
*
* Authors: Giovanni De Toni
*
*/
#include <gtest/gtest.h>
#include <shogun/lib/config.h>
#include <shogun/lib/observers/ParameterObserverLogger.h>
#include <vector>
using namespace shogun;
class MockEmitter : public SGObject
{
public:
MockEmitter() : SGObject()
{
}
virtual ~MockEmitter()
{
}
virtual const char* get_name() const
{
return "MockEmitter";
}
void emit_value()
{
AnyParameterProperties p(
"Name of the observed value", ParameterProperties::READONLY);
AnyParameterProperties p2(
"Name of the observed value", ParameterProperties::AUTO);
AnyParameterProperties p3(
"Name of the observed value", ParameterProperties::NONE);
observe<int32_t>(1, "test", 1, p);
observe<int32_t>(1, "a", 1, p);
observe<int32_t>(1, "b", 1, p2);
observe<int32_t>(1, "None", 1, p3);
}
};
class ParameterObserverTest : public ::testing::Test
{
protected:
void SetUp() override
{
test_params = {"a", "b"};
test_params_not_found = {"k", "j"};
test_params_properties = {ParameterProperties::AUTO,
ParameterProperties::READONLY};
}
void TearDown() override
{
}
std::vector<std::string> test_params;
std::vector<std::string> test_params_not_found;
std::vector<ParameterProperties> test_params_properties;
MockEmitter emitter;
};
TEST_F(ParameterObserverTest, filter_empty)
{
std::shared_ptr<ParameterObserver> observer(new ParameterObserverLogger());
emitter.subscribe(observer);
emitter.emit_value();
EXPECT_EQ(observer->get<int32_t>("num_observations"), 4);
emitter.unsubscribe(observer);
}
TEST_F(ParameterObserverTest, filter_found)
{
std::shared_ptr<ParameterObserver> observer(
new ParameterObserverLogger(test_params));
emitter.subscribe(observer);
emitter.emit_value();
EXPECT_EQ(observer->get<int32_t>("num_observations"), 2);
emitter.unsubscribe(observer);
}
TEST_F(ParameterObserverTest, filter_not_found)
{
std::shared_ptr<ParameterObserver> observer(
new ParameterObserverLogger(test_params_not_found));
emitter.subscribe(observer);
emitter.emit_value();
EXPECT_EQ(observer->get<int32_t>("num_observations"), 0);
emitter.unsubscribe(observer);
}
TEST_F(ParameterObserverTest, filter_found_property)
{
std::shared_ptr<ParameterObserver> observer(
new ParameterObserverLogger(test_params_properties));
emitter.subscribe(observer);
emitter.emit_value();
EXPECT_EQ(observer->get<int32_t>("num_observations"), 3);
emitter.unsubscribe(observer);
}
TEST_F(ParameterObserverTest, filter_not_found_property)
{
test_params_properties.pop_back();
std::shared_ptr<ParameterObserver> observer(
new ParameterObserverLogger(test_params_properties));
emitter.subscribe(observer);
emitter.emit_value();
EXPECT_EQ(observer->get<int32_t>("num_observations"), 1);
emitter.unsubscribe(observer);
}
TEST_F(ParameterObserverTest, filter_found_property_and_name)
{
test_params_properties.pop_back();
std::shared_ptr<ParameterObserver> observer(
new ParameterObserverLogger(test_params, test_params_properties));
emitter.subscribe(observer);
emitter.emit_value();
EXPECT_EQ(observer->get<int32_t>("num_observations"), 1);
emitter.unsubscribe(observer);
}
TEST_F(ParameterObserverTest, filter_all_property)
{
std::vector<ParameterProperties> test_all_property = {
ParameterProperties::ALL};
std::shared_ptr<ParameterObserver> observer(
new ParameterObserverLogger(test_all_property));
emitter.subscribe(observer);
emitter.emit_value();
EXPECT_EQ(observer->get<int32_t>("num_observations"), 4);
emitter.unsubscribe(observer);
} | 25.636364 | 78 | 0.753682 | [
"vector"
] |
0787b85c123110054421ea1d6d0f9c7660811117 | 11,059 | cpp | C++ | autode/ext/src/optimisers.cpp | tlestang/autodE | 56fd4c78e7d7e78c5747428190211ff69dc6d94a | [
"MIT"
] | 90 | 2020-03-13T15:03:35.000Z | 2022-03-14T13:41:04.000Z | autode/ext/src/optimisers.cpp | skphy/autodE | fd80995206ac601299d2f78105d0fe4deee8c2cf | [
"MIT"
] | 117 | 2020-06-13T00:11:06.000Z | 2022-03-24T08:54:16.000Z | autode/ext/src/optimisers.cpp | skphy/autodE | fd80995206ac601299d2f78105d0fe4deee8c2cf | [
"MIT"
] | 26 | 2020-08-14T04:52:53.000Z | 2022-03-06T13:04:17.000Z | #include "optimisers.h"
#include "utils.h"
#include "points.h"
#include <stdexcept>
#include <cmath>
namespace autode {
void SDOptimiser::step(autode::Molecule &molecule, double step_factor){
// Perform a SD step in the direction of the gradient
for (int i = 0; i < 3 * molecule.n_atoms; i++) {
molecule.coords[i] -= step_factor * molecule.grad[i];
}
}
void SDOptimiser::trust_step(autode::Molecule &molecule,
double step_factor,
double trust_radius){
// Perform a SD step in the direction of the gradient with a maximum
// absolute displacement of the trust radius
double max_abs_delta = 0.0;
for (int i = 0; i < 3 * molecule.n_atoms; i++) {
max_abs_delta = std::max(max_abs_delta,
std::abs(step_factor * molecule.grad[i]));
}
// std::cout << max_abs_delta << "\n\n\n\n" << std::endl;
double trust_factor = std::min(trust_radius / max_abs_delta, 1.0);
for (int i = 0; i < 3 * molecule.n_atoms; i++) {
molecule.coords[i] -= step_factor * trust_factor * molecule.grad[i];
}
}
void SDOptimiser::run(autode::Potential &potential,
autode::Molecule &molecule,
int max_iterations,
double energy_tol,
double init_step_size) {
/*
* Steepest decent optimiser
*
* Arguments:
* potential:
*
* molecule:
*
* max_iterations: Maximum number of macro iterations
* (total = max_iterations * max_micro_iterations)
*
* energy_tol: ΔE between iterations to signal convergence
*
* init_step_size: (Å)
*/
double max_micro_iterations = 20;
double curr_energy = 99999999.9;
double curr_micro_energy;
int iteration = 0;
while (std::abs(molecule.energy - curr_energy) > energy_tol
and iteration <= max_iterations){
curr_energy = molecule.energy;
int micro_iteration = 0;
double step_size = init_step_size;
// Recompute the energy and gradient
potential.set_energy_and_grad(molecule);
// Run a set of micro iterations as a line search in the steepest
// decent direction: -∇V
while (micro_iteration < max_micro_iterations){
curr_micro_energy = molecule.energy;
step(molecule, step_size);
potential.set_energy(molecule);
// Prevent very small step sizes
if (step_size < 1E-3){
break;
}
// Backtrack if the energy rises
if (micro_iteration == 0
and molecule.energy > curr_micro_energy){
step(molecule, -step_size);
molecule.energy = curr_micro_energy;
step_size *= 0.5;
continue;
}
if (molecule.energy > curr_micro_energy){
// Energy has risen but at least one step has been taken
// so return the previous step
step(molecule, -step_size);
break;
}
micro_iteration += 1;
} // Micro
iteration += 1;
} // Macro
}
void SDDihedralOptimiser::check_dihedrals(autode::Molecule &molecule) {
/* Ensure that there is at least one dihedral to minimise on
*
* Arguments:
*
* molecule:
*/
if (molecule._dihedrals.empty()){
throw std::runtime_error("Cannot run a dihedral minimisation "
"without any dihedrals!");
}
}
void SDDihedralOptimiser::step(autode::Molecule &molecule,
double step_factor) {
/*
* Apply a set of dihedral rotations given a new gradient
*
* Arguments:
*
* molecule:
*
* step_factor: Multiplier on the SD step
*/
for (auto &dihedral: molecule._dihedrals){
dihedral.angle = -step_factor * dihedral.grad;
molecule.rotate(dihedral);
}
}
void GridDihedralOptimiser::run(autode::Potential &potential,
autode::Molecule &molecule,
int max_num_points,
double energy_tol,
double init_step_size) {
/* Complete optimisation of the dihedral surface using a grid with
* a spacing defined by max_num_points^(1/n_dihedrals), plus a final
* steepest decent (SD) minimisation. Can be 1D, 2D... nD grid
*
* Arguments:
* potential:
*
* molecule:
*
* max_num_points: Maximum number of points in the grid, optimiser
* may exceed this number of evaluations
*
* energy_tol: Tolerance on the final SD minimisation
*
* init_step_size: For SD
*/
SDDihedralOptimiser::check_dihedrals(molecule);
n_angles = static_cast<int>(molecule._dihedrals.size());
if (n_angles == 0){
// Nothing to be done with no dihedrals to rotate
return;
}
if (n_angles > 5){
throw std::runtime_error("Number of points required to use a "
"reasonably spaced grid is huge. Not "
"supported");
}
num_1d_points = autode::utils::fpowi(max_num_points, n_angles);
num_points = autode::utils::powi(num_1d_points, n_angles);
molecule.zero_dihedrals();
// Spacing is taken over 0 -> 2π - π/3, as the dihedral is periodic
spacing = 5.2 / static_cast<double>(num_1d_points);
/* Generate a counter wheel for each dihedral, which when it reaches
* num_1d_points then the adjacent wheel is incremented etc.
*
* | |
* | 0 0 0 ... |
* | |
*
* Initialised at 0 on every angle
*/
counter = std::vector<int>(n_angles, 0);
std::vector<double> min_coords;
double min_energy = 99999999.9;
for (int i=0; i < num_points; i++){
apply_single_rotation(molecule, i);
potential.set_energy(molecule);
if (molecule.energy < min_energy) {
min_coords = std::vector<double>(molecule.coords);
min_energy = molecule.energy;
}
}
molecule.coords = min_coords;
// Perform a steepest decent optimisation from this point
SDDihedralOptimiser::run(potential,
molecule,
100,
energy_tol,
init_step_size);
}
void GridDihedralOptimiser::step(autode::Molecule &molecule,
double step_factor) {
// Take a step on the grid
SDDihedralOptimiser::step(molecule, step_factor);
}
void GridDihedralOptimiser::apply_single_rotation(autode::Molecule &molecule,
int curr_step) {
/* Apply a single rotation to one dihedral in sequence, depending on
* the value of the counter
*
* Arguments:
*
* molecule:
*
*
* curr_step: Current step on the N-dimensional grid
*/
for (int j=0; j < n_angles; j++){
int value = ((curr_step
/ autode::utils::powi(num_1d_points, j)
) % num_1d_points);
if (value == num_1d_points - 1){
counter[j] = 0;
continue;
}
if (value != counter[j]){
molecule._dihedrals[j].angle = spacing;
molecule.rotate(molecule._dihedrals[j]);
counter[j] = value;
break;
}
}
}
void SGlobalDihedralOptimiser::run(autode::Potential &potential,
autode::Molecule &molecule,
int max_init_points,
double energy_tol,
double init_step_size) {
/* Stochastic global minimisation
*
* Arguments:
*
* potential:
*
* molecule:
*
* max_init_points: Number of initial points to start SD
* optimisations from, each of which is subject to
* a fast (few step) optimisation
*
* energy_tol: Energy tolerance on the final SD minimisation
*
*
* init_step_size: Initial step size for all (search + final)
* optimisations
*/
SDDihedralOptimiser::check_dihedrals(molecule);
std::vector<double> min_coords;
double min_energy = 99999999.9;
// Generate a set of points in a n-dimensional space, where n is the
// number of dihedrals in the system
CubePointGenerator generator = CubePointGenerator(max_init_points, molecule._dihedrals.size());
generator.run(1E-4, 0.01, 200);
for (int iteration=0; iteration < max_init_points; iteration++){
for (size_t i=0; i < molecule._dihedrals.size(); i++){
molecule._dihedrals[i].angle = generator.points[iteration][i];
molecule.rotate(molecule._dihedrals[i]);
}
// Apply a steepest decent minimisation for a few steps
SDDihedralOptimiser::run(potential,
molecule,
10,
1E-1,
init_step_size);
if (molecule.energy < min_energy) {
min_coords = std::vector<double>(molecule.coords);
min_energy = molecule.energy;
}
}
// Set the minimum energy coordinates
molecule.coords = min_coords;
}
void SGlobalDihedralOptimiser::step(autode::Molecule &molecule,
double step_factor) {
// Apply a steepest decent step
SDDihedralOptimiser::step(molecule, step_factor);
}
} | 33.110778 | 103 | 0.496609 | [
"vector"
] |
078b12b70df198624a354fcc50bcb2ecaa25e3cc | 3,969 | cpp | C++ | pasa-plugins/slclust/src/graph.cpp | tafujino/PASApipeline | 4e7cac908e8c951c60814e8c26ccc9d69e2cfdb7 | [
"BSD-3-Clause"
] | 4 | 2019-01-16T12:05:05.000Z | 2021-11-17T08:38:21.000Z | pasa-plugins/slclust/src/graph.cpp | tafujino/PASApipeline | 4e7cac908e8c951c60814e8c26ccc9d69e2cfdb7 | [
"BSD-3-Clause"
] | null | null | null | pasa-plugins/slclust/src/graph.cpp | tafujino/PASApipeline | 4e7cac908e8c951c60814e8c26ccc9d69e2cfdb7 | [
"BSD-3-Clause"
] | 7 | 2015-03-24T14:23:58.000Z | 2020-01-15T16:54:10.000Z | #include "graph.h"
// constructor
//currently using default
// destructor
// rlease memory allocated for graph nodes:
Graph::~Graph () {
for (unsigned int i=0; i < allNodes.size(); i++) {
delete allNodes[i];
}
}
void Graph::addLinkedNodes (string a, string b) {
if (VERBOSE >= debug)
cout << "Adding nodes: " << a << ", " << b << endl;
Graphnode* a_node = getGraphnode(a);
Graphnode* b_node = getGraphnode(b);
a_node->addLinkedNode(b_node);
b_node->addLinkedNode(a_node);
}
Graphnode* Graph::getGraphnode (string s) {
if (VERBOSE >= debug)
cout << "Getting graphnode for : " << s << endl;
map<string, int>::iterator p;
// see if (s) already exists:
p = nodeLookup.find(s);
Graphnode* s_node;
if (p != nodeLookup.end()) {
if (VERBOSE >= debug)
cout << "Found it." << endl;
int s_index = p->second;
s_node = allNodes[s_index];
} else {
if (VERBOSE >= debug)
cout << "Didn't find it, inserting node." << endl;
s_node = new Graphnode(s);
int s_index = allNodes.size();
allNodes.push_back(s_node);
if (VERBOSE >= debug)
cout << "Added new node with " << s << " at position: " << s_index << endl;
nodeLookup[s] = s_index;
}
return (s_node);
}
void Graph::printClusters () {
vector<string> cluster;
for (unsigned int i=0; i < allNodes.size(); i++) {
Graphnode* g = allNodes[i];
if (g->marked) {
continue; // already in another cluster
}
if (!g->marked) {
if (VERBOSE >= debug)
cout << "Starting graph traversal from node[" << i << "]: " << g->toString() << endl;
traverseGraph(g, cluster);
}
// cout << "Cluster : ";
for (unsigned int j=0; j < cluster.size(); j++) {
cout << cluster[j] << " ";
}
cout << endl;
cluster.clear(); // init for next cluster
}
}
void Graph::traverseGraph (Graphnode* g, vector<string>& cluster) {
if (g->marked) {
return;
}
cluster.push_back(g->getNodename());
g->marked = true;
vector<Graphnode*>& linkednodes = g->getLinkedNodes();
for (unsigned int i=0; i < linkednodes.size(); i++) {
traverseGraph(linkednodes[i], cluster);
}
}
/* Apply the Jaccard Coefficient */
Graph* Graph::applyJaccardCoeff (float coeff) {
Graph* gph = new Graph();
int num_nodes = allNodes.size();
for (unsigned int i=0; i < allNodes.size(); i++) {
if (VERBOSE >= info) {
cerr << "\rJaccard: examining node " << (i+1) << " of " << num_nodes << " ";
}
Graphnode* g = allNodes[i];
// examine each pair of linked nodes
vector<Graphnode*>& linkednodes = g->getLinkedNodes();
for (unsigned int j=0; j < linkednodes.size(); j++) {
Graphnode* linkednode = linkednodes[j];
if (calclinkcoeff(g, linkednode) >= coeff) {
gph->addLinkedNodes(g->getNodename(), linkednode->getNodename());
}
}
}
return (gph);
}
float Graph::calclinkcoeff (Graphnode* a_node, Graphnode* b_node) {
vector<Graphnode*>& a_links = a_node->getLinkedNodes();
int num_a_links = a_node->numLinkedNodes();
int num_b_links = b_node->numLinkedNodes();
// determine number shared vertices:
map<string,bool> b_map = b_node->getLinkedNodeNameMap();
int num_common = 0;
for (unsigned int i=0; i < a_links.size(); i++) {
string a_link_name = a_links[i]->getNodename();
if (b_map.find(a_link_name) != b_map.end()) {
// found it:
num_common++;
}
}
int total_num_vertices = num_a_links + num_b_links - num_common;
int total_in_common = num_common + 2; // a and b aren't included in common count
float linkcoeff = (float)total_in_common/total_num_vertices;
if (VERBOSE >= debug) {
cerr << "Link score between " << a_node->getNodename() << " and "
<< b_node->getNodename() << " = " << linkcoeff << endl;
}
return (linkcoeff);
}
| 22.942197 | 93 | 0.586042 | [
"vector"
] |
078dad87cbd5881e2a7462d28f18a9fd22c6e634 | 57,503 | cpp | C++ | test/unittest/rtps/builtin/BuiltinDataSerializationTests.cpp | timmylinux/Fast-DDS | e6e7eac5a642f606fdaa40a0a2a16617ae9384da | [
"Apache-2.0"
] | 575 | 2015-01-22T20:05:04.000Z | 2020-06-01T10:06:12.000Z | test/unittest/rtps/builtin/BuiltinDataSerializationTests.cpp | timmylinux/Fast-DDS | e6e7eac5a642f606fdaa40a0a2a16617ae9384da | [
"Apache-2.0"
] | 1,110 | 2015-04-20T19:30:34.000Z | 2020-06-01T08:13:52.000Z | test/unittest/rtps/builtin/BuiltinDataSerializationTests.cpp | timmylinux/Fast-DDS | e6e7eac5a642f606fdaa40a0a2a16617ae9384da | [
"Apache-2.0"
] | 273 | 2015-08-10T23:34:42.000Z | 2020-05-28T13:03:32.000Z | // Copyright 2020 Proyectos y Sistemas de Mantenimiento SL (eProsima).
//
// 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 <gmock/gmock.h>
#include <gtest/gtest.h>
#include <fastrtps/rtps/builtin/data/WriterProxyData.h>
#include <fastrtps/rtps/builtin/data/ReaderProxyData.h>
#include <fastrtps/rtps/network/NetworkFactory.h>
#include <fastdds/core/policy/ParameterSerializer.hpp>
namespace eprosima {
namespace fastrtps {
namespace rtps {
constexpr size_t max_unicast_locators = 4u;
constexpr size_t max_multicast_locators = 1u;
NetworkFactory network;
/*** Auxiliary functions ***/
inline uint32_t string_cdr_serialized_size(
const std::string& str)
{
// Size including NUL char at the end
uint32_t str_siz = static_cast<uint32_t>(str.size()) + 1;
// Align to next 4 byte
str_siz = (str_siz + 3u) & ~3u;
// str_length + str_data
return 4u + str_siz;
}
uint32_t manual_content_filter_cdr_serialized_size(
const std::string& content_filtered_topic_name,
const std::string& related_topic_name,
const std::string& filter_class_name,
const std::string& filter_expression,
const std::vector<std::string>& expression_parameters)
{
uint32_t ret_val = 0;
// p_id + p_length
ret_val = 2 + 2;
// content_filtered_topic_name
ret_val += string_cdr_serialized_size(content_filtered_topic_name);
// related_topic_name
ret_val += string_cdr_serialized_size(related_topic_name);
// filter_class_name
ret_val += string_cdr_serialized_size(filter_class_name);
// filter_expression
// str_len + null_char + str_data
ret_val += 4 + 1 + static_cast<uint32_t>(filter_expression.size());
// align
ret_val = (ret_val + 3) & ~3;
// expression_parameters
// sequence length
ret_val += 4;
// Add all parameters
for (const std::string& param : expression_parameters)
{
ret_val += string_cdr_serialized_size(param);
}
return ret_val;
}
void assert_is_empty_content_filter(
const fastdds::rtps::ContentFilterProperty& filter_property)
{
ASSERT_EQ("", filter_property.content_filtered_topic_name.to_string());
ASSERT_EQ("", filter_property.related_topic_name.to_string());
ASSERT_EQ("", filter_property.filter_class_name.to_string());
ASSERT_EQ("", filter_property.filter_expression);
ASSERT_EQ(0, filter_property.expression_parameters.size());
}
TEST(BuiltinDataSerializationTests, ok_with_defaults)
{
{
WriterProxyData in(max_unicast_locators, max_multicast_locators);
WriterProxyData out(max_unicast_locators, max_multicast_locators);
// Topic and type name cannot be empty
in.topicName("TEST");
in.typeName("TestType");
// Perform serialization
uint32_t msg_size = in.get_serialized_size(true);
CDRMessage_t msg(msg_size);
EXPECT_TRUE(in.writeToCDRMessage(&msg, true));
// Perform deserialization
msg.pos = 0;
EXPECT_TRUE(out.readFromCDRMessage(&msg, network, true));
// EXPECT_EQ(in, out);
}
{
ReaderProxyData in(max_unicast_locators, max_multicast_locators);
ReaderProxyData out(max_unicast_locators, max_multicast_locators);
// Topic and type name cannot be empty
in.topicName("TEST");
in.typeName("TestType");
// Perform serialization
uint32_t msg_size = in.get_serialized_size(true);
CDRMessage_t msg(msg_size);
EXPECT_TRUE(in.writeToCDRMessage(&msg, true));
// Perform deserialization
msg.pos = 0;
EXPECT_TRUE(out.readFromCDRMessage(&msg, network, true));
}
}
// Regression test for redmine issue #10547
TEST(BuiltinDataSerializationTests, ignore_unsupported_type_info)
{
// DATA(w)
{
// This was captured with wireshark from OpenDDS iShapes 3.16
octet data_w_buffer[] =
{
// Encapsulation
0x00, 0x03, 0x00, 0x00,
// Topic name
0x05, 0x00, 0x0c, 0x00,
0x07, 0x00, 0x00, 0x00, 0x43, 0x69, 0x72, 0x63, 0x6c, 0x65, 0x00, 0x00,
// Type information
0x75, 0x00, 0x50, 0x00,
0x4c, 0x00, 0x00, 0x00, 0x01, 0x10, 0x00, 0x40, 0x24, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00,
0x14, 0x00, 0x00, 0x00, 0xf1, 0x80, 0x99, 0x5e, 0xfc, 0xdb, 0xda, 0xbe, 0xd5, 0xb3, 0x3d, 0xe3,
0xea, 0x3a, 0x4b, 0x00, 0x53, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x02, 0x10, 0x00, 0x40, 0x18, 0x00, 0x00, 0x00, 0x14, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
// Type name
0x07, 0x00, 0x10, 0x00,
0x0a, 0x00, 0x00, 0x00, 0x53, 0x68, 0x61, 0x70, 0x65, 0x54, 0x79, 0x70, 0x65, 0x00, 0x00, 0x00,
// Reliability
0x1a, 0x00, 0x0c, 0x00,
0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xe1, 0xf5, 0x05,
// Data representation
0x73, 0x00, 0x08, 0x00,
0x01, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00,
// Endpoint GUID
0x5a, 0x00, 0x10, 0x00,
0x01, 0x03, 0x08, 0x00, 0x27, 0x5c, 0x4f, 0x05, 0x0f, 0x19, 0x05, 0xea, 0x00, 0x00, 0x00, 0x02,
// Multicast locator
0x30, 0x00, 0x18, 0x00,
0x01, 0x00, 0x00, 0x00, 0xe9, 0x1c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0xef, 0xff, 0x00, 0x02,
// Unicast locator
0x2f, 0x00, 0x18, 0x00,
0x01, 0x00, 0x00, 0x00, 0x3e, 0xcd, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0xc0, 0xa8, 0x01, 0xb4,
// Sentinel
0x01, 0x00, 0x00, 0x00
};
CDRMessage_t msg(0);
msg.init(data_w_buffer, static_cast<uint32_t>(sizeof(data_w_buffer)));
msg.length = msg.max_size;
WriterProxyData out(max_unicast_locators, max_multicast_locators);
EXPECT_NO_THROW(EXPECT_TRUE(out.readFromCDRMessage(&msg, network, false)));
}
// DATA(r)
{
// This was captured with wireshark from OpenDDS iShapes 3.16
uint8_t data_r_buffer[] =
{
// Encapsulation
0x00, 0x03, 0x00, 0x00,
// Topic name
0x05, 0x00, 0x0c, 0x00,
0x07, 0x00, 0x00, 0x00, 0x43, 0x69, 0x72, 0x63, 0x6c, 0x65, 0x00, 0x00,
// Type information
0x75, 0x00, 0x50, 0x00,
0x4c, 0x00, 0x00, 0x00, 0x01, 0x10, 0x00, 0x40, 0x24, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00,
0x14, 0x00, 0x00, 0x00, 0xf1, 0x80, 0x99, 0x5e, 0xfc, 0xdb, 0xda, 0xbe, 0xd5, 0xb3, 0x3d, 0xe3,
0xea, 0x3a, 0x4b, 0x00, 0x53, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x02, 0x10, 0x00, 0x40, 0x18, 0x00, 0x00, 0x00, 0x14, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
// Type name
0x07, 0x00, 0x10, 0x00,
0x0a, 0x00, 0x00, 0x00, 0x53, 0x68, 0x61, 0x70, 0x65, 0x54, 0x79, 0x70, 0x65, 0x00, 0x00, 0x00,
// Reliability
0x1a, 0x00, 0x0c, 0x00,
0x01, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0x7f, 0xff, 0xff, 0xff, 0x7f,
// Endpoint GUID
0x5a, 0x00, 0x10, 0x00,
0x01, 0x03, 0x08, 0x00, 0x27, 0x5c, 0x4f, 0x05, 0x0f, 0x40, 0x29, 0x9d, 0x00, 0x00, 0x00, 0x07,
// Data representation
0x73, 0x00, 0x08, 0x00,
0x02, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00,
// Multicast locator
0x30, 0x00, 0x18, 0x00,
0x01, 0x00, 0x00, 0x00, 0xe9, 0x1c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0xef, 0xff, 0x00, 0x02,
// Unicast locator
0x2f, 0x00, 0x18, 0x00,
0x01, 0x00, 0x00, 0x00, 0x45, 0x95, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0xc0, 0xa8, 0x01, 0xb4,
// Type consistency
0x74, 0x00, 0x08, 0x00,
0x02, 0x00, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00,
// Sentinel
0x01, 0x00, 0x00, 0x00
};
CDRMessage_t msg(0);
msg.init(data_r_buffer, static_cast<uint32_t>(sizeof(data_r_buffer)));
msg.length = msg.max_size;
ReaderProxyData out(max_unicast_locators, max_multicast_locators);
EXPECT_NO_THROW(EXPECT_TRUE(out.readFromCDRMessage(&msg, network, false)));
}
}
// Regression test for redmine issue #10955
TEST(BuiltinDataSerializationTests, ignore_unsupported_type_object)
{
// DATA(w)
{
// This was captured with wireshark from RTI Shapes Demo 5.3.1
octet data_w_buffer[] =
{
// Encapsulation
0x00, 0x03, 0x00, 0x00,
// Endpoint GUID
0x5a, 0x00, 0x10, 0x00,
0xc0, 0xa8, 0x01, 0x3a, 0x00, 0x00, 0x41, 0xa4, 0x00, 0x00, 0x00, 0x01, 0x80, 0x00, 0x00, 0x42,
// Topic name
0x05, 0x00, 0x10, 0x00,
0x0c, 0x00, 0x00, 0x00, 0x72, 0x74, 0x69, 0x2f, 0x64, 0x69, 0x73, 0x74, 0x6c, 0x6f, 0x67, 0x00,
// Type name
0x07, 0x00, 0x20, 0x00,
0x19, 0x00, 0x00, 0x00, 0x63, 0x6f, 0x6d, 0x3a, 0x3a, 0x72, 0x74, 0x69, 0x3a, 0x3a, 0x64, 0x6c,
0x3a, 0x3a, 0x4c, 0x6f, 0x67, 0x4d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x00, 0x00, 0x00, 0x00,
// Type object
0x72, 0x00, 0xfc, 0x04,
0x01, 0x7f, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0xd0, 0x04, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00,
0x00, 0x00, 0x04, 0x00, 0x18, 0x00, 0x00, 0x00, 0x01, 0x7f, 0x08, 0x00, 0x64, 0x00, 0x00, 0x00,
0x28, 0x04, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x52, 0x54, 0x49, 0x00, 0x01, 0x00, 0x00, 0x00,
0x00, 0x00, 0x04, 0x00, 0x18, 0x00, 0x00, 0x00, 0x01, 0x7f, 0x08, 0x00, 0x64, 0x00, 0x00, 0x00,
0x04, 0x04, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x44, 0x4c, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00,
0x00, 0x00, 0x04, 0x00, 0x18, 0x00, 0x00, 0x00, 0x01, 0x7f, 0x08, 0x00, 0x64, 0x00, 0x00, 0x00,
0xe8, 0x02, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x41, 0x44, 0x4d, 0x49, 0x4e, 0x00, 0x00, 0x00,
0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00, 0x16, 0x00, 0x00, 0x00, 0x01, 0x7f, 0x08, 0x00,
0x09, 0x00, 0x00, 0x00, 0xd0, 0x01, 0x00, 0x00, 0x01, 0x7f, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00,
0x24, 0x00, 0x00, 0x00, 0x02, 0x00, 0x16, 0x00, 0x00, 0x00, 0x00, 0x00, 0x8c, 0x51, 0x83, 0x23,
0x55, 0x8c, 0x53, 0x3a, 0x10, 0x00, 0x00, 0x00, 0x43, 0x6f, 0x6d, 0x6d, 0x61, 0x6e, 0x64, 0x52,
0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x00, 0x01, 0x7f, 0x08, 0x00, 0x01, 0x00, 0x00, 0x00,
0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x7f, 0x08, 0x00, 0x64, 0x00, 0x00, 0x00,
0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x7f, 0x08, 0x00, 0x65, 0x00, 0x00, 0x00,
0x70, 0x01, 0x00, 0x00, 0x05, 0x00, 0x00, 0x00, 0x01, 0x7f, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00,
0x2c, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x16, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0xfe, 0x29, 0x56, 0xb1, 0x97, 0x58, 0xdf, 0x3f, 0x0d, 0x00, 0x00, 0x00,
0x68, 0x6f, 0x73, 0x74, 0x41, 0x6e, 0x64, 0x41, 0x70, 0x70, 0x49, 0x64, 0x00, 0x00, 0x00, 0x00,
0x01, 0x7f, 0x08, 0x00, 0x01, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x02, 0x7f, 0x00, 0x00, 0x01, 0x7f, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x34, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x16, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0xfe, 0x29, 0x56, 0xb1, 0x97, 0x58, 0xdf, 0x3f, 0x17, 0x00, 0x00, 0x00, 0x6f, 0x72, 0x69, 0x67,
0x69, 0x6e, 0x61, 0x74, 0x6f, 0x72, 0x48, 0x6f, 0x73, 0x74, 0x41, 0x6e, 0x64, 0x41, 0x70, 0x70,
0x49, 0x64, 0x00, 0x00, 0x01, 0x7f, 0x08, 0x00, 0x01, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x02, 0x7f, 0x00, 0x00, 0x01, 0x7f, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00,
0x1c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x05, 0x00, 0x05, 0x00,
0x0b, 0x00, 0x00, 0x00, 0x69, 0x6e, 0x76, 0x6f, 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x00, 0x00,
0x01, 0x7f, 0x08, 0x00, 0x01, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x02, 0x7f, 0x00, 0x00, 0x01, 0x7f, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x2c, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x0e, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0xd9, 0xdc, 0x15, 0x0b, 0x91, 0x99, 0x13, 0x0e, 0x0e, 0x00, 0x00, 0x00, 0x63, 0x6f, 0x6d, 0x6d,
0x61, 0x6e, 0x64, 0x52, 0x65, 0x73, 0x75, 0x6c, 0x74, 0x00, 0x00, 0x00, 0x01, 0x7f, 0x08, 0x00,
0x01, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x7f, 0x00, 0x00,
0x01, 0x7f, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x24, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x04, 0x00, 0x00, 0x00, 0x13, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x16, 0xdc, 0x5c, 0x98,
0xa5, 0x08, 0x32, 0x91, 0x08, 0x00, 0x00, 0x00, 0x6d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x00,
0x01, 0x7f, 0x08, 0x00, 0x01, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x02, 0x7f, 0x00, 0x00, 0x02, 0x7f, 0x00, 0x00, 0x02, 0x7f, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00,
0x0e, 0x00, 0x00, 0x00, 0x01, 0x7f, 0x08, 0x00, 0x05, 0x00, 0x00, 0x00, 0xd8, 0x00, 0x00, 0x00,
0x01, 0x7f, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x24, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0e, 0x00,
0x00, 0x00, 0x00, 0x00, 0xd9, 0xdc, 0x15, 0x0b, 0x91, 0x99, 0x13, 0x0e, 0x0e, 0x00, 0x00, 0x00,
0x43, 0x6f, 0x6d, 0x6d, 0x61, 0x6e, 0x64, 0x52, 0x65, 0x73, 0x75, 0x6c, 0x74, 0x00, 0x00, 0x00,
0x01, 0x7f, 0x08, 0x00, 0x01, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x01, 0x7f, 0x08, 0x00, 0x64, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00,
0x01, 0x7f, 0x08, 0x00, 0x65, 0x00, 0x00, 0x00, 0x78, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x19, 0x00, 0x00, 0x00, 0x52, 0x54, 0x49, 0x5f, 0x44, 0x4c, 0x5f, 0x43,
0x4f, 0x4d, 0x4d, 0x41, 0x4e, 0x44, 0x5f, 0x52, 0x45, 0x53, 0x55, 0x4c, 0x54, 0x5f, 0x4f, 0x4b,
0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x24, 0x00, 0x00, 0x00, 0x52, 0x54, 0x49, 0x5f,
0x44, 0x4c, 0x5f, 0x43, 0x4f, 0x4d, 0x4d, 0x41, 0x4e, 0x44, 0x5f, 0x52, 0x45, 0x53, 0x55, 0x4c,
0x54, 0x5f, 0x4e, 0x4f, 0x54, 0x5f, 0x53, 0x55, 0x50, 0x50, 0x4f, 0x52, 0x54, 0x45, 0x44, 0x00,
0x02, 0x00, 0x00, 0x00, 0x1c, 0x00, 0x00, 0x00, 0x52, 0x54, 0x49, 0x5f, 0x44, 0x4c, 0x5f, 0x43,
0x4f, 0x4d, 0x4d, 0x41, 0x4e, 0x44, 0x5f, 0x52, 0x45, 0x53, 0x55, 0x4c, 0x54, 0x5f, 0x45, 0x52,
0x52, 0x4f, 0x52, 0x00, 0x02, 0x7f, 0x00, 0x00, 0x02, 0x7f, 0x00, 0x00, 0x02, 0x7f, 0x00, 0x00,
0x00, 0x00, 0x04, 0x00, 0x16, 0x00, 0x00, 0x00, 0x01, 0x7f, 0x08, 0x00, 0x09, 0x00, 0x00, 0x00,
0xe0, 0x00, 0x00, 0x00, 0x01, 0x7f, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x24, 0x00, 0x00, 0x00,
0x00, 0x00, 0x16, 0x00, 0x00, 0x00, 0x00, 0x00, 0xfe, 0x29, 0x56, 0xb1, 0x97, 0x58, 0xdf, 0x3f,
0x0d, 0x00, 0x00, 0x00, 0x48, 0x6f, 0x73, 0x74, 0x41, 0x6e, 0x64, 0x41, 0x70, 0x70, 0x49, 0x64,
0x00, 0x00, 0x00, 0x00, 0x01, 0x7f, 0x08, 0x00, 0x01, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x01, 0x7f, 0x08, 0x00, 0x64, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x01, 0x7f, 0x08, 0x00, 0x65, 0x00, 0x00, 0x00, 0x80, 0x00, 0x00, 0x00,
0x02, 0x00, 0x00, 0x00, 0x01, 0x7f, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00,
0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x05, 0x00, 0x05, 0x00, 0x0d, 0x00, 0x00, 0x00,
0x72, 0x74, 0x70, 0x73, 0x5f, 0x68, 0x6f, 0x73, 0x74, 0x5f, 0x69, 0x64, 0x00, 0x00, 0x00, 0x00,
0x01, 0x7f, 0x08, 0x00, 0x01, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x02, 0x7f, 0x00, 0x00, 0x01, 0x7f, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x1c, 0x00, 0x00, 0x00,
0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x05, 0x00, 0x05, 0x00, 0x0c, 0x00, 0x00, 0x00,
0x72, 0x74, 0x70, 0x73, 0x5f, 0x61, 0x70, 0x70, 0x5f, 0x69, 0x64, 0x00, 0x01, 0x7f, 0x08, 0x00,
0x01, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x7f, 0x00, 0x00,
0x02, 0x7f, 0x00, 0x00, 0x02, 0x7f, 0x00, 0x00, 0x02, 0x7f, 0x00, 0x00, 0x02, 0x7f, 0x00, 0x00,
0x00, 0x00, 0x04, 0x00, 0x13, 0x00, 0x00, 0x00, 0x01, 0x7f, 0x08, 0x00, 0x08, 0x00, 0x00, 0x00,
0x74, 0x00, 0x00, 0x00, 0x01, 0x7f, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x2c, 0x00, 0x00, 0x00,
0x02, 0x00, 0x13, 0x00, 0x00, 0x00, 0x00, 0x00, 0x16, 0xdc, 0x5c, 0x98, 0xa5, 0x08, 0x32, 0x91,
0x16, 0x00, 0x00, 0x00, 0x73, 0x74, 0x72, 0x69, 0x6e, 0x67, 0x5f, 0x32, 0x30, 0x34, 0x38, 0x5f,
0x63, 0x68, 0x61, 0x72, 0x61, 0x63, 0x74, 0x65, 0x72, 0x00, 0x00, 0x00, 0x01, 0x7f, 0x08, 0x00,
0x01, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x7f, 0x08, 0x00,
0x64, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x0c, 0x00, 0x0c, 0x00, 0x65, 0x00, 0x04, 0x00,
0x00, 0x00, 0x00, 0x00, 0x01, 0x7f, 0x08, 0x00, 0xc8, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00,
0x00, 0x08, 0x00, 0x00, 0x02, 0x7f, 0x00, 0x00, 0x02, 0x7f, 0x00, 0x00, 0x01, 0x7f, 0x08, 0x00,
0x01, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x16, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x8c, 0x51, 0x83, 0x23, 0x55, 0x8c, 0x53, 0x3a, 0x02, 0x7f, 0x00, 0x00,
// Sentinel
0x01, 0x00, 0x00, 0x00
};
CDRMessage_t msg(0);
msg.init(data_w_buffer, static_cast<uint32_t>(sizeof(data_w_buffer)));
msg.length = msg.max_size;
WriterProxyData out(max_unicast_locators, max_multicast_locators);
EXPECT_NO_THROW(EXPECT_TRUE(out.readFromCDRMessage(&msg, network, false)));
}
}
/*!
* \test RTPS-CFT-CFP-01 Tests serialization of `ContentFilterProperty_t` works successfully without parameters.
*/
TEST(BuiltinDataSerializationTests, contentfilterproperty_without_parameters)
{
ReaderProxyData in(max_unicast_locators, max_multicast_locators);
ReaderProxyData out(max_unicast_locators, max_multicast_locators);
// Topic and type name cannot be empty
in.topicName("TEST");
in.typeName("TestType");
// Fill ContentFilterProperty_t without parameters.
fastdds::rtps::ContentFilterProperty::AllocationConfiguration content_filter_allocation;
fastdds::rtps::ContentFilterProperty content_filter_property(content_filter_allocation);
content_filter_property.content_filtered_topic_name = "CFP_TEST";
content_filter_property.related_topic_name = "TEST";
content_filter_property.filter_class_name = "MyFilterClass";
content_filter_property.filter_expression = "This is a custom test filter expression";
in.content_filter(content_filter_property);
// Perform serialization
uint32_t msg_size = in.get_serialized_size(true);
CDRMessage_t msg(msg_size);
EXPECT_TRUE(in.writeToCDRMessage(&msg, true));
// Perform deserialization
msg.pos = 0;
EXPECT_TRUE(out.readFromCDRMessage(&msg, network, true));
ASSERT_EQ(in.content_filter().content_filtered_topic_name, out.content_filter().content_filtered_topic_name);
ASSERT_EQ(in.content_filter().related_topic_name, out.content_filter().related_topic_name);
ASSERT_EQ(in.content_filter().filter_class_name, out.content_filter().filter_class_name);
ASSERT_EQ(in.content_filter().filter_expression, out.content_filter().filter_expression);
ASSERT_EQ(in.content_filter().expression_parameters.size(), out.content_filter().expression_parameters.size());
}
/*!
* \test RTPS-CFT-CFP-02 Tests serialization of `ContentFilterProperty_t` works successfully with parameters.
*/
TEST(BuiltinDataSerializationTests, contentfilterproperty_with_parameters)
{
ReaderProxyData in(max_unicast_locators, max_multicast_locators);
ReaderProxyData out(max_unicast_locators, max_multicast_locators);
// Topic and type name cannot be empty
in.topicName("TEST");
in.typeName("TestType");
// Fill ContentFilterProperty_t without parameters.
fastdds::rtps::ContentFilterProperty::AllocationConfiguration content_filter_allocation;
fastdds::rtps::ContentFilterProperty content_filter_property(content_filter_allocation);
content_filter_property.content_filtered_topic_name = "CFP_TEST";
content_filter_property.related_topic_name = "TEST";
content_filter_property.filter_class_name = "MyFilterClass";
content_filter_property.filter_expression = "%1 a custom test filter expression: %2 %3 %4";
content_filter_property.expression_parameters.push_back("parameter 1");
content_filter_property.expression_parameters.push_back("parameter 2");
content_filter_property.expression_parameters.push_back("parameter 3");
content_filter_property.expression_parameters.push_back("parameter 4");
in.content_filter(content_filter_property);
// Perform serialization
uint32_t msg_size = in.get_serialized_size(true);
CDRMessage_t msg(msg_size);
EXPECT_TRUE(in.writeToCDRMessage(&msg, true));
// Perform deserialization
msg.pos = 0;
EXPECT_TRUE(out.readFromCDRMessage(&msg, network, true));
ASSERT_EQ(in.content_filter().content_filtered_topic_name, out.content_filter().content_filtered_topic_name);
ASSERT_EQ(in.content_filter().related_topic_name, out.content_filter().related_topic_name);
ASSERT_EQ(in.content_filter().filter_class_name, out.content_filter().filter_class_name);
ASSERT_EQ(in.content_filter().filter_expression, out.content_filter().filter_expression);
ASSERT_EQ(in.content_filter().expression_parameters.size(), out.content_filter().expression_parameters.size());
ASSERT_EQ(in.content_filter().expression_parameters[0], out.content_filter().expression_parameters[0]);
ASSERT_EQ(in.content_filter().expression_parameters[1], out.content_filter().expression_parameters[1]);
ASSERT_EQ(in.content_filter().expression_parameters[2], out.content_filter().expression_parameters[2]);
ASSERT_EQ(in.content_filter().expression_parameters[3], out.content_filter().expression_parameters[3]);
}
/*!
* \test RTPS-CFT-CFP-03 Tests serialization of `ContentFilterProperty_t` fails with a wrong `contentFilteredTopicName`.
*/
TEST(BuiltinDataSerializationTests, contentfilterproperty_wrong_topic_name_ser)
{
// Empty value
{
ReaderProxyData in(max_unicast_locators, max_multicast_locators);
ReaderProxyData out(max_unicast_locators, max_multicast_locators);
// Topic and type name cannot be empty
in.topicName("TEST");
in.typeName("TestType");
// Fill ContentFilterProperty_t without parameters.
fastdds::rtps::ContentFilterProperty::AllocationConfiguration content_filter_allocation;
fastdds::rtps::ContentFilterProperty content_filter_property(content_filter_allocation);
content_filter_property.related_topic_name = "TEST";
content_filter_property.filter_class_name = "MyFilterClass";
content_filter_property.filter_expression = "This is a custom test filter expression";
in.content_filter(content_filter_property);
// Perform serialization
uint32_t msg_size = in.get_serialized_size(true);
CDRMessage_t msg(msg_size);
EXPECT_FALSE(in.writeToCDRMessage(&msg, true));
}
}
/*!
* \test RTPS-CFT-CFP-04 Tests deserialization of `ContentFilterProperty_t` doesn't do anything with a CDRMessage_t
* containing a wrong `contentFilteredTopicName`.
*/
TEST(BuiltinDataSerializationTests, contentfilterproperty_wrong_topic_name_deser)
{
// Empty value
{
ReaderProxyData out(max_unicast_locators, max_multicast_locators);
// Perform serialization
CDRMessage_t msg(400);
EXPECT_TRUE(fastdds::dds::ParameterList::writeEncapsulationToCDRMsg(&msg));
const std::string content_filtered_topic_name;
const std::string related_topic_name("TEST");
const std::string filter_class_name("MyFilterClass");
const std::string filter_expression("This is a custom test filter expression");
const std::vector<std::string> expression_parameters = {};
// Manual serialization of a ContentFilterProperty.
{
uint32_t len = manual_content_filter_cdr_serialized_size(
content_filtered_topic_name,
related_topic_name,
filter_class_name,
filter_expression,
expression_parameters
);
EXPECT_TRUE(fastrtps::rtps::CDRMessage::addUInt16(&msg, fastdds::dds::PID_CONTENT_FILTER_PROPERTY));
EXPECT_TRUE(fastrtps::rtps::CDRMessage::addUInt16(&msg, static_cast<uint16_t>(len - 4)));
// content_filtered_topic_name
EXPECT_TRUE(fastrtps::rtps::CDRMessage::add_string(&msg, content_filtered_topic_name));
// related_topic_name
EXPECT_TRUE(fastrtps::rtps::CDRMessage::add_string(&msg, related_topic_name));
// filter_class_name
EXPECT_TRUE(fastrtps::rtps::CDRMessage::add_string(&msg, filter_class_name));
// filter_expression
EXPECT_TRUE(fastrtps::rtps::CDRMessage::add_string(&msg, filter_expression));
// expression_parameters
// sequence length
uint32_t num_params = static_cast<uint32_t>(expression_parameters.size());
EXPECT_TRUE(fastrtps::rtps::CDRMessage::addUInt32(&msg, num_params));
// Add all parameters
for (const std::string& param : expression_parameters)
{
EXPECT_TRUE(fastrtps::rtps::CDRMessage::add_string(&msg, param));
}
}
EXPECT_TRUE(fastdds::dds::ParameterSerializer<Parameter_t>::add_parameter_sentinel(&msg));
msg.pos = 0;
EXPECT_TRUE(out.readFromCDRMessage(&msg, network, true));
assert_is_empty_content_filter(out.content_filter());
}
// Larger string than 256 characters.
{
ReaderProxyData out(max_unicast_locators, max_multicast_locators);
// Perform serialization
CDRMessage_t msg(400);
EXPECT_TRUE(fastdds::dds::ParameterList::writeEncapsulationToCDRMsg(&msg));
const std::string content_filtered_topic_name(260, 'a');
const std::string related_topic_name("TEST");
const std::string filter_class_name("MyFilterClass");
const std::string filter_expression("This is a custom test filter expression");
const std::vector<std::string> expression_parameters = {};
// Manual serialization of a ContentFilterProperty.
{
uint32_t len = manual_content_filter_cdr_serialized_size(
content_filtered_topic_name,
related_topic_name,
filter_class_name,
filter_expression,
expression_parameters
);
EXPECT_TRUE(fastrtps::rtps::CDRMessage::addUInt16(&msg, fastdds::dds::PID_CONTENT_FILTER_PROPERTY));
EXPECT_TRUE(fastrtps::rtps::CDRMessage::addUInt16(&msg, static_cast<uint16_t>(len - 4)));
// content_filtered_topic_name
EXPECT_TRUE(fastrtps::rtps::CDRMessage::add_string(&msg, content_filtered_topic_name));
// related_topic_name
EXPECT_TRUE(fastrtps::rtps::CDRMessage::add_string(&msg, related_topic_name));
// filter_class_name
EXPECT_TRUE(fastrtps::rtps::CDRMessage::add_string(&msg, filter_class_name));
// filter_expression
EXPECT_TRUE(fastrtps::rtps::CDRMessage::add_string(&msg, filter_expression));
// expression_parameters
// sequence length
uint32_t num_params = static_cast<uint32_t>(expression_parameters.size());
EXPECT_TRUE(fastrtps::rtps::CDRMessage::addUInt32(&msg, num_params));
// Add all parameters
for (const std::string& param : expression_parameters)
{
EXPECT_TRUE(fastrtps::rtps::CDRMessage::add_string(&msg, param));
}
}
EXPECT_TRUE(fastdds::dds::ParameterSerializer<Parameter_t>::add_parameter_sentinel(&msg));
msg.pos = 0;
EXPECT_TRUE(out.readFromCDRMessage(&msg, network, true));
assert_is_empty_content_filter(out.content_filter());
}
}
/*!
* \test RTPS-CFT-CFP-05 Tests serialization of `ContentFilterProperty_t` fails with a wrong `relatedTopicName`.
*/
TEST(BuiltinDataSerializationTests, contentfilterproperty_wrong_related_topic_name_ser)
{
// Empty value
{
ReaderProxyData in(max_unicast_locators, max_multicast_locators);
ReaderProxyData out(max_unicast_locators, max_multicast_locators);
// Topic and type name cannot be empty
in.topicName("TEST");
in.typeName("TestType");
// Fill ContentFilterProperty_t without parameters.
fastdds::rtps::ContentFilterProperty::AllocationConfiguration content_filter_allocation;
fastdds::rtps::ContentFilterProperty content_filter_property(content_filter_allocation);
content_filter_property.content_filtered_topic_name = "CFT_TEST";
content_filter_property.filter_class_name = "MyFilterClass";
content_filter_property.filter_expression = "This is a custom test filter expression";
in.content_filter(content_filter_property);
// Perform serialization
uint32_t msg_size = in.get_serialized_size(true);
CDRMessage_t msg(msg_size);
EXPECT_FALSE(in.writeToCDRMessage(&msg, true));
}
}
/*!
* \test RTPS-CFT-CFP-06 Tests deserialization of `ContentFilterProperty_t` doesn't do anything with a CDRMessage_t
* containing a wrong `relatedTopicName`.
*/
TEST(BuiltinDataSerializationTests, contentfilterproperty_wrong_related_topic_name_deser)
{
// Empty value
{
ReaderProxyData out(max_unicast_locators, max_multicast_locators);
// Perform serialization
CDRMessage_t msg(400);
EXPECT_TRUE(fastdds::dds::ParameterList::writeEncapsulationToCDRMsg(&msg));
const std::string content_filtered_topic_name("CFT_TEST");
const std::string related_topic_name;
const std::string filter_class_name("MyFilterClass");
const std::string filter_expression("This is a custom test filter expression");
const std::vector<std::string> expression_parameters = {};
// Manual serialization of a ContentFilterProperty.
{
uint32_t len = manual_content_filter_cdr_serialized_size(
content_filtered_topic_name,
related_topic_name,
filter_class_name,
filter_expression,
expression_parameters
);
EXPECT_TRUE(fastrtps::rtps::CDRMessage::addUInt16(&msg, fastdds::dds::PID_CONTENT_FILTER_PROPERTY));
EXPECT_TRUE(fastrtps::rtps::CDRMessage::addUInt16(&msg, static_cast<uint16_t>(len - 4)));
// content_filtered_topic_name
EXPECT_TRUE(fastrtps::rtps::CDRMessage::add_string(&msg, content_filtered_topic_name));
// related_topic_name
EXPECT_TRUE(fastrtps::rtps::CDRMessage::add_string(&msg, related_topic_name));
// filter_class_name
EXPECT_TRUE(fastrtps::rtps::CDRMessage::add_string(&msg, filter_class_name));
// filter_expression
EXPECT_TRUE(fastrtps::rtps::CDRMessage::add_string(&msg, filter_expression));
// expression_parameters
// sequence length
uint32_t num_params = static_cast<uint32_t>(expression_parameters.size());
EXPECT_TRUE(fastrtps::rtps::CDRMessage::addUInt32(&msg, num_params));
// Add all parameters
for (const std::string& param : expression_parameters)
{
EXPECT_TRUE(fastrtps::rtps::CDRMessage::add_string(&msg, param));
}
}
EXPECT_TRUE(fastdds::dds::ParameterSerializer<Parameter_t>::add_parameter_sentinel(&msg));
msg.pos = 0;
EXPECT_TRUE(out.readFromCDRMessage(&msg, network, true));
assert_is_empty_content_filter(out.content_filter());
}
// Larger string than 256 characters.
{
ReaderProxyData out(max_unicast_locators, max_multicast_locators);
// Perform serialization
CDRMessage_t msg(400);
EXPECT_TRUE(fastdds::dds::ParameterList::writeEncapsulationToCDRMsg(&msg));
const std::string content_filtered_topic_name("CFT_TEST");
const std::string related_topic_name(260, 'a');
const std::string filter_class_name("MyFilterClass");
const std::string filter_expression("This is a custom test filter expression");
const std::vector<std::string> expression_parameters = {};
// Manual serialization of a ContentFilterProperty.
{
uint32_t len = manual_content_filter_cdr_serialized_size(
content_filtered_topic_name,
related_topic_name,
filter_class_name,
filter_expression,
expression_parameters
);
EXPECT_TRUE(fastrtps::rtps::CDRMessage::addUInt16(&msg, fastdds::dds::PID_CONTENT_FILTER_PROPERTY));
EXPECT_TRUE(fastrtps::rtps::CDRMessage::addUInt16(&msg, static_cast<uint16_t>(len - 4)));
// content_filtered_topic_name
EXPECT_TRUE(fastrtps::rtps::CDRMessage::add_string(&msg, content_filtered_topic_name));
// related_topic_name
EXPECT_TRUE(fastrtps::rtps::CDRMessage::add_string(&msg, related_topic_name));
// filter_class_name
EXPECT_TRUE(fastrtps::rtps::CDRMessage::add_string(&msg, filter_class_name));
// filter_expression
EXPECT_TRUE(fastrtps::rtps::CDRMessage::add_string(&msg, filter_expression));
// expression_parameters
// sequence length
uint32_t num_params = static_cast<uint32_t>(expression_parameters.size());
EXPECT_TRUE(fastrtps::rtps::CDRMessage::addUInt32(&msg, num_params));
// Add all parameters
for (const std::string& param : expression_parameters)
{
EXPECT_TRUE(fastrtps::rtps::CDRMessage::add_string(&msg, param));
}
}
EXPECT_TRUE(fastdds::dds::ParameterSerializer<Parameter_t>::add_parameter_sentinel(&msg));
msg.pos = 0;
EXPECT_TRUE(out.readFromCDRMessage(&msg, network, true));
assert_is_empty_content_filter(out.content_filter());
}
}
/*!
* \test RTPS-CFT-CFP-07 Tests serialization of `ContentFilterProperty_t` when `filterClassName` is empty.
*/
TEST(BuiltinDataSerializationTests, contentfilterproperty_empty_filter_class)
{
ReaderProxyData in(max_unicast_locators, max_multicast_locators);
ReaderProxyData out(max_unicast_locators, max_multicast_locators);
// Topic and type name cannot be empty
in.topicName("TEST");
in.typeName("TestType");
// Fill ContentFilterProperty_t without parameters.
fastdds::rtps::ContentFilterProperty::AllocationConfiguration content_filter_allocation;
fastdds::rtps::ContentFilterProperty content_filter_property(content_filter_allocation);
content_filter_property.content_filtered_topic_name = "CFP_TEST";
content_filter_property.related_topic_name = "TEST";
content_filter_property.filter_class_name = "";
content_filter_property.filter_expression = "This is a custom test filter expression";
in.content_filter(content_filter_property);
// Perform serialization
uint32_t msg_size = in.get_serialized_size(true);
CDRMessage_t msg(msg_size);
EXPECT_TRUE(in.writeToCDRMessage(&msg, true));
// Perform deserialization
msg.pos = 0;
EXPECT_TRUE(out.readFromCDRMessage(&msg, network, true));
assert_is_empty_content_filter(out.content_filter());
}
/*!
* \test RTPS-CFT-CFP-08 Tests deserialization of `ContentFilterProperty_t` doesn't do anything with a CDRMessage_t containing a wrong
*`filterClassName`.
*/
TEST(BuiltinDataSerializationTests, contentfilterproperty_wrong_filter_class_deser)
{
// Empty value
{
ReaderProxyData out(max_unicast_locators, max_multicast_locators);
// Perform serialization
CDRMessage_t msg(400);
EXPECT_TRUE(fastdds::dds::ParameterList::writeEncapsulationToCDRMsg(&msg));
const std::string content_filtered_topic_name("CFT_TEST");
const std::string related_topic_name("TEST");
const std::string filter_class_name;
const std::string filter_expression("This is a custom test filter expression");
const std::vector<std::string> expression_parameters = {};
// Manual serialization of a ContentFilterProperty.
{
uint32_t len = manual_content_filter_cdr_serialized_size(
content_filtered_topic_name,
related_topic_name,
filter_class_name,
filter_expression,
expression_parameters
);
EXPECT_TRUE(fastrtps::rtps::CDRMessage::addUInt16(&msg, fastdds::dds::PID_CONTENT_FILTER_PROPERTY));
EXPECT_TRUE(fastrtps::rtps::CDRMessage::addUInt16(&msg, static_cast<uint16_t>(len - 4)));
// content_filtered_topic_name
EXPECT_TRUE(fastrtps::rtps::CDRMessage::add_string(&msg, content_filtered_topic_name));
// related_topic_name
EXPECT_TRUE(fastrtps::rtps::CDRMessage::add_string(&msg, related_topic_name));
// filter_class_name
EXPECT_TRUE(fastrtps::rtps::CDRMessage::add_string(&msg, filter_class_name));
// filter_expression
EXPECT_TRUE(fastrtps::rtps::CDRMessage::add_string(&msg, filter_expression));
// expression_parameters
// sequence length
uint32_t num_params = static_cast<uint32_t>(expression_parameters.size());
EXPECT_TRUE(fastrtps::rtps::CDRMessage::addUInt32(&msg, num_params));
// Add all parameters
for (const std::string& param : expression_parameters)
{
EXPECT_TRUE(fastrtps::rtps::CDRMessage::add_string(&msg, param));
}
}
EXPECT_TRUE(fastdds::dds::ParameterSerializer<Parameter_t>::add_parameter_sentinel(&msg));
msg.pos = 0;
EXPECT_TRUE(out.readFromCDRMessage(&msg, network, true));
assert_is_empty_content_filter(out.content_filter());
}
// Larger string than 256 characters.
{
ReaderProxyData out(max_unicast_locators, max_multicast_locators);
// Perform serialization
CDRMessage_t msg(400);
EXPECT_TRUE(fastdds::dds::ParameterList::writeEncapsulationToCDRMsg(&msg));
const std::string content_filtered_topic_name("CFT_TEST");
const std::string related_topic_name("TEST");
const std::string filter_class_name(260, 'a');
const std::string filter_expression("This is a custom test filter expression");
const std::vector<std::string> expression_parameters = {};
// Manual serialization of a ContentFilterProperty.
{
uint32_t len = manual_content_filter_cdr_serialized_size(
content_filtered_topic_name,
related_topic_name,
filter_class_name,
filter_expression,
expression_parameters
);
EXPECT_TRUE(fastrtps::rtps::CDRMessage::addUInt16(&msg, fastdds::dds::PID_CONTENT_FILTER_PROPERTY));
EXPECT_TRUE(fastrtps::rtps::CDRMessage::addUInt16(&msg, static_cast<uint16_t>(len - 4)));
// content_filtered_topic_name
EXPECT_TRUE(fastrtps::rtps::CDRMessage::add_string(&msg, content_filtered_topic_name));
// related_topic_name
EXPECT_TRUE(fastrtps::rtps::CDRMessage::add_string(&msg, related_topic_name));
// filter_class_name
EXPECT_TRUE(fastrtps::rtps::CDRMessage::add_string(&msg, filter_class_name));
// filter_expression
EXPECT_TRUE(fastrtps::rtps::CDRMessage::add_string(&msg, filter_expression));
// expression_parameters
// sequence length
uint32_t num_params = static_cast<uint32_t>(expression_parameters.size());
EXPECT_TRUE(fastrtps::rtps::CDRMessage::addUInt32(&msg, num_params));
// Add all parameters
for (const std::string& param : expression_parameters)
{
EXPECT_TRUE(fastrtps::rtps::CDRMessage::add_string(&msg, param));
}
}
EXPECT_TRUE(fastdds::dds::ParameterSerializer<Parameter_t>::add_parameter_sentinel(&msg));
msg.pos = 0;
EXPECT_TRUE(out.readFromCDRMessage(&msg, network, true));
assert_is_empty_content_filter(out.content_filter());
}
}
/*!
* \test RTPS-CFT-CFP-09 Tests serialization of `ContentFilterProperty_t` when `filterExpression` is empty.
*/
TEST(BuiltinDataSerializationTests, contentfilterproperty_empty_filter_expression)
{
ReaderProxyData in(max_unicast_locators, max_multicast_locators);
ReaderProxyData out(max_unicast_locators, max_multicast_locators);
// Topic and type name cannot be empty
in.topicName("TEST");
in.typeName("TestType");
// Fill ContentFilterProperty_t without parameters.
fastdds::rtps::ContentFilterProperty::AllocationConfiguration content_filter_allocation;
fastdds::rtps::ContentFilterProperty content_filter_property(content_filter_allocation);
content_filter_property.content_filtered_topic_name = "CFP_TEST";
content_filter_property.related_topic_name = "TEST";
content_filter_property.filter_class_name = "MyFilterClass";
content_filter_property.filter_expression = "";
in.content_filter(content_filter_property);
// Perform serialization
uint32_t msg_size = in.get_serialized_size(true);
CDRMessage_t msg(msg_size);
EXPECT_TRUE(in.writeToCDRMessage(&msg, true));
// Perform deserialization
msg.pos = 0;
EXPECT_TRUE(out.readFromCDRMessage(&msg, network, true));
assert_is_empty_content_filter(out.content_filter());
}
/*!
* \test RTPS-CFT-CFP-10 Tests deserialization of `ContentFilterProperty_t` doesn't do anything with a CDRMessage_t
* containing a wrong `filterExpression`.
*/
TEST(BuiltinDataSerializationTests, contentfilterproperty_wrong_filter_expression_deser)
{
// Empty value
{
ReaderProxyData out(max_unicast_locators, max_multicast_locators);
// Perform serialization
CDRMessage_t msg(400);
EXPECT_TRUE(fastdds::dds::ParameterList::writeEncapsulationToCDRMsg(&msg));
const std::string content_filtered_topic_name("CFT_TEST");
const std::string related_topic_name("TEST");
const std::string filter_class_name("MyFilterClass");
const std::string filter_expression;
const std::vector<std::string> expression_parameters = {};
// Manual serialization of a ContentFilterProperty.
{
uint32_t len = manual_content_filter_cdr_serialized_size(
content_filtered_topic_name,
related_topic_name,
filter_class_name,
filter_expression,
expression_parameters
);
EXPECT_TRUE(fastrtps::rtps::CDRMessage::addUInt16(&msg, fastdds::dds::PID_CONTENT_FILTER_PROPERTY));
EXPECT_TRUE(fastrtps::rtps::CDRMessage::addUInt16(&msg, static_cast<uint16_t>(len - 4)));
// content_filtered_topic_name
EXPECT_TRUE(fastrtps::rtps::CDRMessage::add_string(&msg, content_filtered_topic_name));
// related_topic_name
EXPECT_TRUE(fastrtps::rtps::CDRMessage::add_string(&msg, related_topic_name));
// filter_class_name
EXPECT_TRUE(fastrtps::rtps::CDRMessage::add_string(&msg, filter_class_name));
// filter_expression
EXPECT_TRUE(fastrtps::rtps::CDRMessage::add_string(&msg, filter_expression));
// expression_parameters
// sequence length
uint32_t num_params = static_cast<uint32_t>(expression_parameters.size());
EXPECT_TRUE(fastrtps::rtps::CDRMessage::addUInt32(&msg, num_params));
// Add all parameters
for (const std::string& param : expression_parameters)
{
EXPECT_TRUE(fastrtps::rtps::CDRMessage::add_string(&msg, param));
}
}
EXPECT_TRUE(fastdds::dds::ParameterSerializer<Parameter_t>::add_parameter_sentinel(&msg));
msg.pos = 0;
EXPECT_TRUE(out.readFromCDRMessage(&msg, network, true));
assert_is_empty_content_filter(out.content_filter());
}
}
/*!
* \test RTPS-CFT-CFP-11 Tests serialization of `ContentFilterProperty_t` fails with a wrong `CDRMessage_t`
*/
TEST(BuiltinDataSerializationTests, contentfilterproperty_wrong_cdr_message_ser)
{
fastdds::rtps::ContentFilterProperty::AllocationConfiguration content_filter_allocation;
fastdds::rtps::ContentFilterProperty content_filter_property(content_filter_allocation);
content_filter_property.content_filtered_topic_name = "CFP_TEST";
content_filter_property.related_topic_name = "TEST";
content_filter_property.filter_class_name = "MyFilterClass";
content_filter_property.filter_expression = "This is a custom test filter expression";
// Not initialized
{
CDRMessage_t msg(0);
ASSERT_FALSE(fastdds::dds::ParameterSerializer<fastdds::rtps::ContentFilterProperty>::add_to_cdr_message(
content_filter_property, &msg));
}
//Empty buffer but not enough memory.
{
CDRMessage_t msg(20);
ASSERT_FALSE(fastdds::dds::ParameterSerializer<fastdds::rtps::ContentFilterProperty>::add_to_cdr_message(
content_filter_property, &msg));
}
// Used buffer but not enough memory left.
{
CDRMessage_t msg(30);
msg.pos = 10;
ASSERT_FALSE(fastdds::dds::ParameterSerializer<fastdds::rtps::ContentFilterProperty>::add_to_cdr_message(
content_filter_property, &msg));
}
}
/*!
* \test RTPS-CFT-CFP-12 Tests deserialization of `ContentFilterProperty_t` fails with a wrong `CDRMessage_t`
*/
TEST(BuiltinDataSerializationTests, contentfilterproperty_wrong_cdr_message_deser)
{
fastdds::rtps::ContentFilterProperty::AllocationConfiguration content_filter_allocation;
fastdds::rtps::ContentFilterProperty content_filter_property(content_filter_allocation);
const std::string content_filtered_topic_name("CFT_TEST");
const std::string related_topic_name("TEST");
const std::string filter_class_name("MyFilterClass");
const std::string filter_expression("This is a custom test filter expression");
const std::vector<std::string> expression_parameters = {};
uint16_t len = static_cast<uint16_t>(manual_content_filter_cdr_serialized_size(
content_filtered_topic_name,
related_topic_name,
filter_class_name,
filter_expression,
expression_parameters
));
// Not initialized
{
CDRMessage_t msg(0);
ASSERT_FALSE(fastdds::dds::ParameterSerializer<fastdds::rtps::ContentFilterProperty>::read_from_cdr_message(
content_filter_property, &msg, len));
}
//Empty buffer but not enough memory.
{
CDRMessage_t msg(20);
fastrtps::rtps::CDRMessage::addUInt16(&msg, fastdds::dds::PID_CONTENT_FILTER_PROPERTY);
fastrtps::rtps::CDRMessage::addUInt16(&msg, len - 4);
// content_filtered_topic_name
fastrtps::rtps::CDRMessage::add_string(&msg, content_filtered_topic_name);
// related_topic_name
fastrtps::rtps::CDRMessage::add_string(&msg, related_topic_name);
// filter_class_name
fastrtps::rtps::CDRMessage::add_string(&msg, filter_class_name);
// filter_expression
fastrtps::rtps::CDRMessage::add_string(&msg, filter_expression);
ASSERT_FALSE(fastdds::dds::ParameterSerializer<fastdds::rtps::ContentFilterProperty>::read_from_cdr_message(
content_filter_property, &msg, len));
}
// Used buffer but not enough memory left.
{
CDRMessage_t msg(30);
msg.pos = 10;
fastrtps::rtps::CDRMessage::addUInt16(&msg, fastdds::dds::PID_CONTENT_FILTER_PROPERTY);
fastrtps::rtps::CDRMessage::addUInt16(&msg, len - 4);
// content_filtered_topic_name
fastrtps::rtps::CDRMessage::add_string(&msg, content_filtered_topic_name);
// related_topic_name
fastrtps::rtps::CDRMessage::add_string(&msg, related_topic_name);
// filter_class_name
fastrtps::rtps::CDRMessage::add_string(&msg, filter_class_name);
// filter_expression
fastrtps::rtps::CDRMessage::add_string(&msg, filter_expression);
msg.pos = 10;
ASSERT_FALSE(fastdds::dds::ParameterSerializer<fastdds::rtps::ContentFilterProperty>::read_from_cdr_message(
content_filter_property, &msg, len));
}
}
/*!
* \test RTPS-CFT-CFP-13 Tests the interoperability with RTI in the propagation of the RTPS's `ContentFilterProperty_t`.
*/
TEST(BuiltinDataSerializationTests, contentfilterproperty_interoperability)
{
// pcap file located in task #14171. Captured from RTI Shapes Demo 6.1.0
octet data_r_buffer[] =
{
// Encapsulation
0x00, 0x03, 0x00, 0x00,
// Endpoing guid
0x5a, 0x00, 0x10, 0x00, 0x01, 0x01, 0x96, 0x4b, 0xa1, 0x2e, 0xb6, 0x10, 0xeb, 0x47, 0x54, 0x76,
0x80, 0x00, 0x00, 0x07,
// Protocol version
0x15, 0x00, 0x04, 0x00, 0x02, 0x03, 0x00, 0x00,
// Vendor id
0x16, 0x00, 0x04, 0x00, 0x01, 0x01, 0x00, 0x00,
// Product version
0x00, 0x80, 0x04, 0x00, 0x06, 0x01, 0x00, 0x00,
// Topic name
0x05, 0x00, 0x0c, 0x00, 0x07, 0x00, 0x00, 0x00, 0x53, 0x71, 0x75, 0x61, 0x72, 0x65, 0x00, 0x00,
// Type name
0x07, 0x00, 0x10, 0x00, 0x0a, 0x00, 0x00, 0x00, 0x53, 0x68, 0x61, 0x70, 0x65, 0x54, 0x79, 0x70,
0x65, 0x00, 0x00, 0x00,
// Content filter property
0x35, 0x00, 0x7c, 0x00, 0x10, 0x00, 0x00, 0x00, 0x43, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x46,
0x69, 0x6c, 0x74, 0x65, 0x72, 0x5f, 0x30, 0x00, 0x07, 0x00, 0x00, 0x00, 0x53, 0x71, 0x75, 0x61,
0x72, 0x65, 0x00, 0x00, 0x07, 0x00, 0x00, 0x00, 0x44, 0x44, 0x53, 0x53, 0x51, 0x4c, 0x00, 0x00,
0x28, 0x00, 0x00, 0x00, 0x78, 0x20, 0x3e, 0x20, 0x25, 0x30, 0x20, 0x61, 0x6e, 0x64, 0x20, 0x78,
0x20, 0x3c, 0x20, 0x25, 0x31, 0x20, 0x61, 0x6e, 0x64, 0x20, 0x79, 0x20, 0x3e, 0x20, 0x25, 0x32,
0x20, 0x61, 0x6e, 0x64, 0x20, 0x79, 0x20, 0x3c, 0x20, 0x25, 0x33, 0x00, 0x04, 0x00, 0x00, 0x00,
0x04, 0x00, 0x00, 0x00, 0x31, 0x30, 0x30, 0x00, 0x04, 0x00, 0x00, 0x00, 0x32, 0x30, 0x30, 0x00,
0x04, 0x00, 0x00, 0x00, 0x31, 0x30, 0x30, 0x00, 0x04, 0x00, 0x00, 0x00, 0x32, 0x30, 0x30, 0x00,
//
0x18, 0x00, 0x04, 0x00, 0xff, 0xff, 0xff, 0xff,
// Data representation
0x73, 0x00, 0x0c, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x07, 0x00, 0x00, 0x00,
// Group entity id
0x53, 0x00, 0x04, 0x00, 0x80, 0x00, 0x00, 0x09,
// Persistence guid
0x02, 0x80, 0x10, 0x00, 0x01, 0x01, 0x96, 0x4b, 0xa1, 0x2e, 0xb6, 0x10, 0xeb, 0x47, 0x54, 0x76,
0x80, 0x00, 0x00, 0x07,
//
0x09, 0x80, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00,
// Type consistency
0x74, 0x00, 0x08, 0x00, 0x01, 0x00, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00,
//
0x15, 0x80, 0x08, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
// Type object
0x21, 0x80, 0xa0, 0x01, 0x01, 0x00, 0x00, 0x00, 0x10, 0x04, 0x00, 0x00, 0x92, 0x01, 0x00, 0x00,
0x78, 0xda, 0x63, 0xac, 0xe7, 0x60, 0x00, 0x81, 0x27, 0xcc, 0x0c, 0x0c, 0x2c, 0x60, 0x16, 0x0b,
0x83, 0x18, 0x90, 0x64, 0x04, 0x8a, 0x73, 0x02, 0xe9, 0x2f, 0x50, 0x36, 0x08, 0x68, 0x80, 0x49,
0x31, 0x30, 0x79, 0xb9, 0xba, 0x83, 0xad, 0x41, 0x42, 0xc3, 0x59, 0x08, 0xc8, 0x0e, 0xce, 0x48,
0x2c, 0x48, 0x0d, 0xa9, 0x2c, 0x48, 0x75, 0xad, 0x28, 0x49, 0xcd, 0x4b, 0x49, 0x4d, 0x81, 0xea,
0x61, 0x64, 0x80, 0x99, 0x09, 0xe1, 0x83, 0xc4, 0x05, 0xe0, 0x26, 0x30, 0x30, 0x1c, 0x7d, 0xbd,
0xf1, 0xde, 0xb1, 0x90, 0xbf, 0x99, 0x20, 0xb9, 0x54, 0x20, 0xbf, 0x05, 0x88, 0x99, 0x30, 0xec,
0x83, 0x98, 0xc1, 0x07, 0x65, 0x3f, 0x39, 0xfd, 0xa0, 0x31, 0xf9, 0xd7, 0x15, 0x7e, 0x90, 0xdb,
0xd2, 0x32, 0x73, 0x72, 0xbc, 0x33, 0xf3, 0x52, 0x18, 0xb0, 0xd8, 0xc7, 0x54, 0x8f, 0x30, 0x47,
0x02, 0x2a, 0xc6, 0x0a, 0xc4, 0x9c, 0x40, 0xc8, 0x06, 0xa4, 0x13, 0xf3, 0xd2, 0x73, 0x52, 0x71,
0xe8, 0x83, 0x61, 0xf4, 0xb0, 0xf0, 0x60, 0x44, 0x98, 0xa9, 0x80, 0x14, 0x16, 0x30, 0x7f, 0x70,
0x21, 0x87, 0x05, 0x9e, 0x30, 0x40, 0xe6, 0x83, 0xd4, 0xbd, 0x81, 0x8a, 0xc1, 0xcc, 0x56, 0x01,
0xb1, 0xa1, 0x6a, 0x84, 0xa1, 0xf4, 0x55, 0xd3, 0x5f, 0xd3, 0xd6, 0x6d, 0x9b, 0x08, 0x76, 0x7b,
0x72, 0x7e, 0x4e, 0x7e, 0x11, 0x01, 0x3f, 0x8b, 0xc0, 0xec, 0x00, 0xfb, 0x9b, 0x15, 0x1c, 0xae,
0x15, 0x44, 0xea, 0x61, 0x42, 0xd2, 0x53, 0x49, 0x40, 0x8f, 0x0c, 0x54, 0x8c, 0x19, 0xaa, 0x07,
0x14, 0x06, 0xc5, 0xa0, 0x30, 0x28, 0xce, 0xac, 0x22, 0x26, 0x7c, 0x85, 0xa1, 0x6a, 0x40, 0xa6,
0x95, 0x20, 0x85, 0x81, 0x0e, 0xd8, 0x1d, 0xc2, 0x28, 0x7e, 0x17, 0x05, 0x99, 0x5d, 0x52, 0x94,
0x99, 0x97, 0x1e, 0x6f, 0x68, 0x64, 0x11, 0x9f, 0x9c, 0x91, 0x58, 0x94, 0x98, 0x5c, 0x92, 0x5a,
0xc4, 0x40, 0x20, 0xac, 0x79, 0x80, 0x30, 0x15, 0x2a, 0x03, 0x12, 0x3f, 0x01, 0x15, 0x6f, 0x60,
0x40, 0x75, 0x0b, 0x1f, 0x54, 0x1e, 0x94, 0x4e, 0x2e, 0xa0, 0xc5, 0x07, 0x2c, 0x05, 0xc2, 0xd2,
0x1f, 0x1f, 0x2c, 0xae, 0xdd, 0x10, 0x89, 0x10, 0x9f, 0x1b, 0x14, 0x90, 0xe2, 0xbb, 0x00, 0x49,
0x0d, 0x37, 0xc8, 0x1c, 0x7f, 0x1f, 0x4f, 0x97, 0x78, 0x37, 0x4f, 0x1f, 0x1f, 0x48, 0x7c, 0x09,
0x02, 0x71, 0x48, 0x90, 0xa3, 0x5f, 0x70, 0x80, 0x63, 0x90, 0xab, 0x5f, 0x08, 0x54, 0x06, 0x12,
0x2f, 0xa0, 0x14, 0xe7, 0xe1, 0x1f, 0xe4, 0x19, 0xe5, 0xef, 0x17, 0xe2, 0xe8, 0x13, 0xef, 0xe1,
0x18, 0xe2, 0xec, 0x01, 0x53, 0xc0, 0x0c, 0x8d, 0xc3, 0x30, 0xd7, 0xa0, 0x10, 0x4f, 0x67, 0x54,
0x59, 0x98, 0x3f, 0x61, 0x6e, 0x44, 0xce, 0x87, 0xb0, 0xbc, 0x0c, 0x92,
// Sentinel
0x07, 0x00, 0x16, 0x2a, 0x83, 0x1a, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00
};
CDRMessage_t msg(0);
msg.init(data_r_buffer, static_cast<uint32_t>(sizeof(data_r_buffer)));
msg.length = msg.max_size;
ReaderProxyData out(max_unicast_locators, max_multicast_locators);
EXPECT_NO_THROW(EXPECT_TRUE(out.readFromCDRMessage(&msg, network, false)));
ASSERT_EQ("ContentFilter_0", out.content_filter().content_filtered_topic_name.to_string());
ASSERT_EQ("Square", out.content_filter().related_topic_name.to_string());
ASSERT_EQ("DDSSQL", out.content_filter().filter_class_name.to_string());
ASSERT_EQ("x > %0 and x < %1 and y > %2 and y < %3", out.content_filter().filter_expression);
ASSERT_EQ(4, out.content_filter().expression_parameters.size());
ASSERT_EQ("100", out.content_filter().expression_parameters[0].to_string());
ASSERT_EQ("200", out.content_filter().expression_parameters[1].to_string());
ASSERT_EQ("100", out.content_filter().expression_parameters[2].to_string());
ASSERT_EQ("200", out.content_filter().expression_parameters[3].to_string());
}
} // namespace rtps
} // namespace fastrtps
} // namespace eprosima
int main(
int argc,
char** argv)
{
testing::InitGoogleMock(&argc, argv);
return RUN_ALL_TESTS();
}
| 50.797703 | 134 | 0.658192 | [
"object",
"vector"
] |
079d74d363d54eb84d9110cf32b2f6fad6362991 | 2,577 | cpp | C++ | src/triangle-rasterizer-demo/src/trdInstructions.cpp | frmr/triangle-rasterizer-demo | 963f32435ebae5b7fbe6fa212709bdc3ea66ac36 | [
"MIT"
] | null | null | null | src/triangle-rasterizer-demo/src/trdInstructions.cpp | frmr/triangle-rasterizer-demo | 963f32435ebae5b7fbe6fa212709bdc3ea66ac36 | [
"MIT"
] | null | null | null | src/triangle-rasterizer-demo/src/trdInstructions.cpp | frmr/triangle-rasterizer-demo | 963f32435ebae5b7fbe6fa212709bdc3ea66ac36 | [
"MIT"
] | null | null | null | #include "trdInstructions.hpp"
void trd::Instructions::draw(const Settings& settings, tr::ColorBuffer& buffer)
{
std::vector<tf::String> lines;
lines.push_back(tf::String("WASD: Move camera"));
lines.push_back(tf::String("Space: Move camera up"));
lines.push_back(tf::String("Ctrl: Move camera down"));
lines.push_back(tf::String("F12: Take screenshot"));
lines.push_back(tf::String(""));
lines.push_back(tf::String("P: Pause animation {}", { settings.getPauseAnimation() ? "Paused" : "Not paused" }));
lines.push_back(tf::String("R: Resolution {}x{}", { std::to_string(settings.getScreenSize().width), std::to_string(settings.getScreenSize().height) }));
lines.push_back(tf::String("L: Tile size {}x{}", { std::to_string(settings.getTileSize().width), std::to_string(settings.getTileSize().height) }));
lines.push_back(tf::String("T: Threads {}", { std::to_string(settings.getNumThreads()) }));
lines.push_back(tf::String("H: Horizontal FOV {}", { std::to_string(settings.getFov()) }));
lines.push_back(tf::String("F: Fragment shader mode {}", { convertRenderModeToString(settings.getRenderMode()) }));
lines.push_back(tf::String("M: Texture mapping {}", { convertTextureModeToString(settings.getTextureMode()) }));
lines.push_back(tf::String("B: Bilinear filtering {}", { settings.getBilinearFiltering() ? "On" : "Off" }));
lines.push_back(tf::String("I: Instructions {}", { settings.getInstructionsEnabled() ? "Show" : "Hide" }));
lines.push_back(tf::String("C: Frame rate counter {}", { settings.getFrameRateEnabled() ? "Show" : "Hide" }));
lines.push_back(tf::String("F11: Fullscreen {}", { settings.getFullscreen() ? "Yes" : "No" }));
drawText(lines, tr::Color(255, 255, 255, 255), Corner::BottomLeft, settings.getScreenSize(), buffer);
}
tf::String trd::Instructions::convertRenderModeToString(const RenderMode renderMode)
{
switch (renderMode)
{
case RenderMode::Lit: return "Lit";
case RenderMode::FullBright: return "Full bright";
case RenderMode::Depth: return "Depth";
case RenderMode::Normals: return "Normals";
default: return "";
}
}
tf::String trd::Instructions::convertTextureModeToString(const TextureMode textureMode)
{
switch (textureMode)
{
case TextureMode::Off: return "Off";
case TextureMode::Affine: return "Affine";
case TextureMode::Perspective: return "Perspective";
default: return "";
}
}
| 52.591837 | 167 | 0.649205 | [
"vector"
] |
079ed1628496930e302f8915204f9d52b6c12110 | 8,247 | cpp | C++ | StudyWatch_SDK_healthwearableApp/Source/sdk/src/eda_application.cpp | analogdevicesinc/ApplicationsWaveTool | 0c1f236dd0745caa3187841ee1a882f209ac3ebe | [
"Apache-2.0"
] | 2 | 2019-03-11T15:24:51.000Z | 2022-03-07T09:42:05.000Z | StudyWatch_SDK_healthwearableApp/Source/sdk/src/eda_application.cpp | analogdevicesinc/ApplicationsWaveTool | 0c1f236dd0745caa3187841ee1a882f209ac3ebe | [
"Apache-2.0"
] | null | null | null | StudyWatch_SDK_healthwearableApp/Source/sdk/src/eda_application.cpp | analogdevicesinc/ApplicationsWaveTool | 0c1f236dd0745caa3187841ee1a882f209ac3ebe | [
"Apache-2.0"
] | 1 | 2021-03-16T08:26:05.000Z | 2021-03-16T08:26:05.000Z | #include "eda_application.hpp"
eda_application::~eda_application(void) {
}
eda_application::eda_application(watch *sdk) :
m2m2_application(sdk),
eda_stream(M2M2_ADDR_MED_EDA_STREAM, this) {}
/*!
\brief Fetches a human-readable string describing the application.
*/
std::string eda_application::get_name(void) {
return "EDA application";
}
/*!
\brief Fetches the address of the application.
*/
M2M2_ADDR_ENUM_t eda_application::get_address(void) {
return M2M2_ADDR_MED_EDA;
};
/*!
\brief Read from a set of ECG LCFGs.
This function takes a vector of addresses to read, and returns a vector of
(field, value) pairs which contain the addresses and values read.
\note If an invalid list of addresses is given (i.e. an empty list), or an
error occured on the device, a vector of size 1 with a (address, value) pair
of 0 is returned.
\note The SDK does not perform any validation on the correctness of the addresses
given.
\see ECG_application::lcfg_write
\see ECG_application::load_lcfg
*/
std::vector<std::pair<uint8_t, uint32_t>> eda_application::lcfg_read(
std::vector<uint8_t> addresses //!< A vector of lcfg addresses to be read.
) {
if (addresses.size() == 0) {
// return a single pair of zeroes
return std::vector<std::pair<uint8_t, uint32_t>> {{0, 0}};
}
// Assemble this packet the old school way to fill out the variable-length list of lcfg operations
uint16_t pkt_size = (offsetof(m2m2_hdr_t, data)) + offsetof(eda_app_lcfg_op_hdr_t, ops) +
addresses.size() * sizeof(eda_app_lcfg_op_t);
std::vector<uint8_t> pkt(pkt_size);
m2m2_hdr_t *p_hdr = (m2m2_hdr_t *) &pkt[0];
eda_app_lcfg_op_hdr_t *p_ops_hdr = (eda_app_lcfg_op_hdr_t *) &p_hdr->data[0];
eda_app_lcfg_op_t *p_ops = (eda_app_lcfg_op_t *) &p_ops_hdr->ops[0];
p_hdr->length = pkt_size;
p_ops_hdr->command = M2M2_APP_COMMON_CMD_READ_LCFG_REQ;
p_ops_hdr->num_ops = addresses.size();
for (unsigned int i = 0; i < addresses.size(); i++) {
p_ops[i].field = addresses[i];
p_ops[i].value = 0x0000;
}
auto resp = this->sync_send(pkt);
std::vector<std::pair<uint8_t, uint32_t>> ret_vals;
p_hdr = (m2m2_hdr_t *) &resp[0];
p_ops_hdr = (eda_app_lcfg_op_hdr_t *) &p_hdr->data[0];
if (p_ops_hdr->status != M2M2_APP_COMMON_STATUS_OK) {
// return a single pair of zeroes
return std::vector<std::pair<uint8_t, uint32_t>> {{0, 0}};
}
p_ops = (eda_app_lcfg_op_t *) &p_ops_hdr->ops[0];
for (unsigned int i = 0; i < p_ops_hdr->num_ops; i++) {
std::pair<uint8_t, uint32_t> v;
v.first = p_ops[i].field;
v.second = p_ops[i].value;
ret_vals.push_back(v);
}
return ret_vals;
}
/*!
\brief Write to a set of lcfgs.
This function takes a vector of (field, value) pairs to write, and returns
a vector of (field, value) pairs which contain the field and values written.
\note If an invalid list of addresses is given (i.e. an empty list), or an
error occured on the device, a vector of size 1 with a (address, value) pair
of 0 is returned.
\note The SDK does not perform any validation on the correctness of the addresses
or values given.
\see ECG_application::lcfg_read
\see ECG_application::load_lcfg
*/
std::vector<std::pair<uint8_t, uint32_t>> eda_application::lcfg_write(
std::vector<std::pair<uint8_t, uint32_t>> addr_vals //!< A vector of lcfg (field,value) pairs to be written.
) {
if (addr_vals.size() == 0) {
// return a single pair of zeroes
return std::vector<std::pair<uint8_t, uint32_t>> {{0, 0}};
}
// Assemble this packet the old school way to fill out the variable-length list of register operations
uint16_t pkt_size = offsetof(m2m2_hdr_t, data)
+ offsetof(eda_app_lcfg_op_hdr_t, ops)
+ addr_vals.size() * sizeof(eda_app_lcfg_op_t);
std::vector<uint8_t> pkt(pkt_size);
m2m2_hdr_t *p_hdr = (m2m2_hdr_t *) &pkt[0];
eda_app_lcfg_op_hdr_t *p_ops_hdr = (eda_app_lcfg_op_hdr_t *) &p_hdr->data[0];
eda_app_lcfg_op_t *p_ops = (eda_app_lcfg_op_t *) &p_ops_hdr->ops[0];
p_hdr->length = pkt_size;
p_ops_hdr->command = M2M2_APP_COMMON_CMD_WRITE_LCFG_REQ;
p_ops_hdr->num_ops = addr_vals.size();
for (unsigned int i = 0; i < addr_vals.size(); i++) {
p_ops[i].field = addr_vals[i].first;
p_ops[i].value = addr_vals[i].second;
}
auto resp = this->sync_send(pkt);
std::vector<std::pair<uint8_t, uint32_t>> ret_vals;
p_hdr = (m2m2_hdr_t *) &resp[0];
p_ops_hdr = (eda_app_lcfg_op_hdr_t *) &p_hdr->data[0];
if (p_ops_hdr->status != M2M2_APP_COMMON_STATUS_OK) {
// return a single pair of zeroes
return std::vector<std::pair<uint8_t, uint32_t>> {{0, 0}};
}
p_ops = (eda_app_lcfg_op_t *) &p_ops_hdr->ops[0];
for (unsigned int i = 0; i < p_ops_hdr->num_ops; i++) {
std::pair<uint8_t, uint32_t> v;
v.first = p_ops[i].field;
v.second = p_ops[i].value;
ret_vals.push_back(v);
}
return ret_vals;
}
ret::sdk_status eda_application::dcb_set_lcfg(void) {
m2m2_pkt<eda_app_dcb_lcfg_t> pkt(this->get_address());
pkt.payload.command = M2M2_APP_COMMON_CMD_SET_LCFG_REQ;
auto resp = this->sync_send(pkt.pack());
pkt.unpack(resp);
if (pkt.payload.status == M2M2_APP_COMMON_STATUS_OK) {
return ret::SDK_OK;
}
else {
return ret::SDK_ERR;
}
}
ret::sdk_status eda_application::dynamic_scaling(bool isEnable, uint16_t minScale, uint16_t maxScale, uint16_t lprtiasel)
{
m2m2_pkt<eda_app_dynamic_scale_t> pkt(this->get_address());
pkt.payload.command = M2M2_EDA_APP_CMD_DYNAMIC_SCALE_REQ;
pkt.payload.dscale = static_cast<uint8_t>(isEnable);
pkt.payload.minscale = minScale;
pkt.payload.maxscale = maxScale;
pkt.payload.lprtia = lprtiasel;
auto resp = this->sync_send(pkt.pack());
pkt.unpack(resp);
if (pkt.payload.status == M2M2_APP_COMMON_STATUS_OK) {
return ret::SDK_OK;
}
else {
return ret::SDK_ERR;
}
}
ret::sdk_status eda_application::set_dft_num(uint8_t dftnum)
{
m2m2_pkt<eda_app_set_dft_num_t> pkt(this->get_address());
pkt.payload.command = M2M2_EDA_APP_CMD_SET_DFT_NUM_REQ;
pkt.payload.dftnum = dftnum;
auto resp = this->sync_send(pkt.pack());
pkt.unpack(resp);
if (pkt.payload.status == M2M2_APP_COMMON_STATUS_OK) {
return ret::SDK_OK;
}
else {
return ret::SDK_ERR;
}
}
ret::sdk_status eda_application::write_dcb_config(std::vector<std::pair<uint16_t, uint16_t>> addr_vals)
{
if (addr_vals.size() == 0 || addr_vals.size() > MAXEDADCBSIZE) {
// return a single pair of zeroes
return ret::SDK_ERR;
}
uint8_t addrs;
uint16_t value;
uint32_t dcb_data_value;
m2m2_pkt<m2m2_dcb_eda_data_t> pkt(this->get_address());
pkt.payload.command = M2M2_DCB_COMMAND_WRITE_CONFIG_REQ;
pkt.payload.size = addr_vals.size();
for (unsigned int i = 0; i < addr_vals.size(); i++) {
addrs = addr_vals[i].first;
value = addr_vals[i].second;
dcb_data_value = static_cast<uint32_t>(addrs | (value << 16));
pkt.payload.dcbdata[i] = dcb_data_value;
}
auto resp = this->sync_send(pkt.pack());
pkt.unpack(resp);
if (pkt.payload.status == M2M2_DCB_STATUS_OK) {
return ret::SDK_OK;
}
else {
return ret::SDK_ERR;
}
}
std::vector<std::pair<uint16_t, uint16_t>> eda_application::read_dcb_config(void)
{
uint32_t dcb_data_value;
m2m2_pkt<m2m2_dcb_eda_data_t> pkt(this->get_address());
pkt.payload.command = M2M2_DCB_COMMAND_READ_CONFIG_REQ;
auto resp = this->sync_send(pkt.pack());
pkt.unpack(resp);
std::vector<std::pair<uint16_t, uint16_t>> ret_vals;
for (unsigned int i = 0; i < pkt.payload.size; i++) {
std::pair<uint16_t, uint16_t> v;
dcb_data_value = pkt.payload.dcbdata[i];
v.first = dcb_data_value & 0xffff;
v.second = (dcb_data_value >> 16) & 0xffff;
ret_vals.push_back(v);
}
return ret_vals;
}
ret::sdk_status eda_application::dcb_delete_config(void)
{
m2m2_pkt<m2m2_dcb_eda_data_t> pkt(this->get_address());
pkt.payload.command = M2M2_DCB_COMMAND_ERASE_CONFIG_REQ;
pkt.payload.status = M2M2_DCB_STATUS_ERR_NOT_CHKD;
auto resp = this->sync_send(pkt.pack());
pkt.unpack(resp);
if (pkt.payload.status == M2M2_DCB_STATUS_OK) {
#if Debug
std::cout << "ret::SDK_OK" << std::endl;
#endif
return ret::SDK_OK;
}
else {
#if Debug
std::cout << "ret::SDK_ERR_DEVICE_ERR" << std::endl;
#endif
return ret::SDK_ERR_DEVICE_ERR;
}
} | 30.544444 | 121 | 0.705832 | [
"vector"
] |
07a37092344b67c185f12c0a8f63a462fb8e2754 | 831 | hpp | C++ | src/frontends/onnx/frontend/src/op/depth_to_space.hpp | ryanloney/openvino-1 | 4e0a740eb3ee31062ba0df88fcf438564f67edb7 | [
"Apache-2.0"
] | 1,127 | 2018-10-15T14:36:58.000Z | 2020-04-20T09:29:44.000Z | src/frontends/onnx/frontend/src/op/depth_to_space.hpp | ryanloney/openvino-1 | 4e0a740eb3ee31062ba0df88fcf438564f67edb7 | [
"Apache-2.0"
] | 439 | 2018-10-20T04:40:35.000Z | 2020-04-19T05:56:25.000Z | src/frontends/onnx/frontend/src/op/depth_to_space.hpp | ryanloney/openvino-1 | 4e0a740eb3ee31062ba0df88fcf438564f67edb7 | [
"Apache-2.0"
] | 414 | 2018-10-17T05:53:46.000Z | 2020-04-16T17:29:53.000Z | // Copyright (C) 2018-2022 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
//
#pragma once
#include "ngraph/node.hpp"
#include "onnx_import/core/node.hpp"
namespace ngraph {
namespace onnx_import {
namespace op {
namespace set_1 {
/// \brief Permutes input tensor data from depth into blocks of spatial data.
///
/// \note Values from the depth dimension (assuming NCHW layout) are moved in
/// spatial blocks to the height and width dimensions.
///
/// \param[in] node The ONNX input node describing operation.
///
/// \return OutputVector containing Tensor with shape:
/// [N, C/(blocksize * blocksize), H * blocksize, W * blocksize]
OutputVector depth_to_space(const Node& node);
} // namespace set_1
} // namespace op
} // namespace onnx_import
} // namespace ngraph
| 26.806452 | 83 | 0.687124 | [
"shape"
] |
07a6d16eb04410f1174b21812fbbb9c634ee5b0b | 25,162 | cpp | C++ | sp/volna.cpp | reguly/volna | d5aedfb583ac6533eede847b0b5714c4d3c458cf | [
"BSD-2-Clause"
] | 3 | 2021-07-08T23:53:52.000Z | 2022-01-25T11:55:28.000Z | sp/volna.cpp | reguly/volna | d5aedfb583ac6533eede847b0b5714c4d3c458cf | [
"BSD-2-Clause"
] | 1 | 2019-12-02T17:31:28.000Z | 2019-12-02T17:31:28.000Z | sp/volna.cpp | DanGiles/volna | 0008584b0457478da8b1a69ca7d0d2a81b644d89 | [
"BSD-2-Clause"
] | 7 | 2018-02-05T19:34:34.000Z | 2021-11-01T08:46:34.000Z | /*Copyright 2018, Frederic Dias, Serge Guillas, Istvan Reguly
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "volna_common.h"
#include "volna_util.h"
#include "EvolveValuesRK2_1.h"
#include "EvolveValuesRK2_2.h"
#include "simulation_1.h"
#include "limits.h"
#include "Friction_manning.h"
#include "zero_bathy.h"
//
// Sequential OP2 function declarations
//
#include "op_seq.h"
//these are not const, we just don't want to pass them around
LocationData locationData;
double timestamp = 0.0;
int itercount = 0;
// Constants
float CFL, g, EPS, Mn, Radius;
int spherical;
bool new_format = true;
// Store maximum elevation and speed in global variable, for the sake of max search
op_dat currentMaxElevation = NULL;
op_dat currentMaxSpeed = NULL;
op_dat physical_vars = NULL;
//
// Checks if error occured during hdf5 process and prints error message
//
void __check_hdf5_error(herr_t err, const char *file, const int line){
if (err < 0) {
printf("%s(%i) : OP2_HDF5_error() Runtime API error %d.\n", file,
line, (int) err);
exit(-1);
}
}
void print_info() {
op_printf("\nPlease specify the OP2 HDF5 data file "
"name, which was created with volna2hdf5 tool, e.g. volna2hdf5 script_filename.vln. \n"
"Use Volna configuration script filename with the *.h5 extension and "
"specify the output filetype: 0 - HDF5, 1 - VTK ASCII, 2 - VTK Binary \n"
"e.g. ./volna script_filename.h5 1 \n"
"or ./volna script_filename.h5 0 \n"
"or mpirun -np 8 ./volna_mpi script_filename.h5 1 \n");
}
int main(int argc, char **argv) {
op_init(argc, argv, 2);
if(argc < 3) {
op_printf("Wrong parameters! \n");
print_info();
exit(-1);
}
for ( int n = 1; n < argc; n++ )
{
if ( strncmp ( argv[n], "old-format", 10 ) == 0 ) {
new_format = false;
op_printf("Using old format bathymetry\n");
}
}
const char *filename_h5 = argv[1];
int writeOption = atoi(argv[2]); // 0 - HDF5, 1 - VTK ASCII, 2 - VTK Binary
EPS = 1e-6; //machine epsilon, for doubles 1e-11
hid_t file;
file = H5Fopen(filename_h5, H5F_ACC_RDONLY, H5P_DEFAULT);
//Some simulation parameters when using InitGaussianLandslide and InitBore
GaussianLandslideParams gaussian_landslide_params;
BoreParams bore_params;
//Parameters for the rectangualr domain special case
RectangleDomainParams rect_params;
//Read the above parameters
check_hdf5_error( H5LTread_dataset_float(file, "BoreParamsx0", &bore_params.x0) );
check_hdf5_error( H5LTread_dataset_float(file, "BoreParamsHl", &bore_params.Hl) );
check_hdf5_error( H5LTread_dataset_float(file, "BoreParamsul", &bore_params.ul) );
check_hdf5_error( H5LTread_dataset_float(file, "BoreParamsvl", &bore_params.vl) );
check_hdf5_error( H5LTread_dataset_float(file, "BoreParamsS", &bore_params.S) );
check_hdf5_error( H5LTread_dataset_float(file, "GaussianLandslideParamsA", &gaussian_landslide_params.A) );
check_hdf5_error( H5LTread_dataset_float(file, "GaussianLandslideParamsv", &gaussian_landslide_params.v) );
check_hdf5_error( H5LTread_dataset_float(file, "GaussianLandslideParamslx", &gaussian_landslide_params.lx) );
check_hdf5_error( H5LTread_dataset_float(file, "GaussianLandslideParamsly", &gaussian_landslide_params.ly) );
check_hdf5_error( H5LTread_dataset_int(file, "nx", &rect_params.nx) );
check_hdf5_error( H5LTread_dataset_int(file, "ny", &rect_params.ny) );
check_hdf5_error( H5LTread_dataset_float(file, "xmin", &rect_params.xmin) );
check_hdf5_error( H5LTread_dataset_float(file, "xmax", &rect_params.xmax) );
check_hdf5_error( H5LTread_dataset_float(file, "ymin", &rect_params.ymin) );
check_hdf5_error( H5LTread_dataset_float(file, "ymax", &rect_params.ymax) );
int num_events = 0;
int num_outputLocation = 0;
check_hdf5_error(H5LTread_dataset_int(file, "numEvents", &num_events));
std::vector<TimerParams> timers(num_events);
std::vector<EventParams> events(num_events);
//Read Event "objects" (Init and Output events) into timers and events
read_events_hdf5(file, num_events, &timers, &events, &num_outputLocation);
check_hdf5_error(H5Fclose(file));
/*
* Define OP2 sets - Read mesh and geometry data from HDF5
*/
op_set nodes = op_decl_set_hdf5(filename_h5, "nodes");
op_set edges = op_decl_set_hdf5(filename_h5, "edges");
op_set cells = op_decl_set_hdf5(filename_h5, "cells");
/*
* Define OP2 set maps
*/
op_map cellsToCells = op_decl_map_hdf5(cells, cells, N_NODESPERCELL,
filename_h5,
"cellsToCells");
op_map cellsToNodes = op_decl_map_hdf5(cells, nodes, N_NODESPERCELL,
filename_h5,
"cellsToNodes");
op_map edgesToCells = op_decl_map_hdf5(edges, cells, N_CELLSPEREDGE,
filename_h5,
"edgesToCells");
op_map cellsToEdges = op_decl_map_hdf5(cells, edges, N_NODESPERCELL,
filename_h5,
"cellsToEdges");
// When using OutputLocation events we have already computed the cell
// index of the points so we don't have to locate the cell every time
op_set outputLocation = NULL;
op_map outputLocation_map = NULL;
op_dat outputLocation_dat = NULL;
if (num_outputLocation) {
outputLocation = op_decl_set_hdf5(filename_h5, "outputLocation");
outputLocation_map = op_decl_map_hdf5(outputLocation, cells, 1,
filename_h5,
"outputLocation_map");
}
/*
* Define OP2 datasets
*/
op_dat cellCenters = op_decl_dat_hdf5(cells, MESH_DIM, "float",
filename_h5,
"cellCenters");
op_dat edgeCenters = op_decl_dat_hdf5(edges, MESH_DIM, "float",
filename_h5,
"edgeCenters");
op_dat cellVolumes = op_decl_dat_hdf5(cells, 1, "float",
filename_h5,
"cellVolumes");
op_dat edgeNormals = op_decl_dat_hdf5(edges, MESH_DIM, "float",
filename_h5,
"edgeNormals");
op_dat edgeLength = op_decl_dat_hdf5(edges, 1, "float",
filename_h5,
"edgeLength");
op_dat nodeCoords = op_decl_dat_hdf5(nodes, MESH_DIM, "float",
filename_h5,
"nodeCoords");
op_dat values = op_decl_dat_hdf5(cells, N_STATEVAR, "float",
filename_h5,
"values");
op_dat isBoundary = op_decl_dat_hdf5(edges, 1, "int",
filename_h5,
"isBoundary");
//op_dats storing InitBathymetry and InitEta event files
op_dat temp_initEta = NULL;
op_dat temp_initU = NULL;
op_dat temp_initV = NULL;
op_dat* temp_initBathymetry = NULL; // Store initBathymtery in an array: there might be more input files for different timesteps
int n_initBathymetry = 0; // Number of initBathymetry files
op_set bathy_nodes;
op_set lifted_cells;
op_map liftedcellsToBathyNodes;
op_map liftedcellsToCells;
op_dat bathy_xy;
op_dat initial_zb = NULL;
/*
* Read constants from HDF5
*/
op_get_const_hdf5("CFL", 1, "float", (char *) &CFL, filename_h5);
op_get_const_hdf5("Mn", 1, "float", (char *) &Mn, filename_h5);
op_get_const_hdf5("Spherical", 1, "int", (char *) &spherical, filename_h5);
// Final time: as defined by Volna the end of real-time simulation
float ftime_tmp, dtmax_tmp;
op_get_const_hdf5("ftime", 1, "float", (char *) &ftime_tmp, filename_h5);
op_get_const_hdf5("dtmax", 1, "float", (char *) &dtmax_tmp, filename_h5);
double ftime = ftime_tmp;
double dtmax = dtmax_tmp;
op_get_const_hdf5("g", 1, "float", (char *) &g, filename_h5);
op_decl_const(1, "float", &CFL);
op_decl_const(1, "float", &EPS);
op_decl_const(1, "float", &g);
op_decl_const(1, "float", &Mn);
op_decl_const(1, "int", &spherical);
Radius = 6378136.6;
op_decl_const(1, "float", &Radius);
printf("Mn = %f, CFL = %f \n", Mn, CFL);
if (spherical){
printf("Spherical Polar coordinates \n");
printf("Radius of the Earth = %f \n", Radius);
} else {
printf("Cartesian coordinates \n");
}
//Read InitBathymetry and InitEta event data when they come from files
for (unsigned int i = 0; i < events.size(); i++) {
if (!strcmp(events[i].className.c_str(), "InitEta")) {
if (strcmp(events[i].streamName.c_str(), ""))
temp_initEta = op_decl_dat_hdf5(cells, 1, "float",
filename_h5,
"initEta");
} else if (!strcmp(events[i].className.c_str(), "InitU")) {
if (strcmp(events[i].streamName.c_str(), ""))
temp_initU = op_decl_dat_hdf5(cells, 1, "float",
filename_h5,
"initU");
} else if (!strcmp(events[i].className.c_str(), "InitV")) {
if (strcmp(events[i].streamName.c_str(), ""))
temp_initV = op_decl_dat_hdf5(cells, 1, "float",
filename_h5,
"initV");
} else if (!strcmp(events[i].className.c_str(), "InitBathymetry")) {
if (strcmp(events[i].streamName.c_str(), "")){
op_set bathy_set = cells;
if (new_format) {
bathy_nodes = op_decl_set_hdf5(filename_h5, "bathy_nodes");
lifted_cells = op_decl_set_hdf5(filename_h5, "liftedCells");
liftedcellsToBathyNodes = op_decl_map_hdf5(lifted_cells, bathy_nodes, N_NODESPERCELL,
filename_h5,
"liftedcellsToBathynodes");
liftedcellsToCells = op_decl_map_hdf5(lifted_cells, cells, 1,
filename_h5,
"liftedcellsToCells");
bathy_xy = op_decl_dat_hdf5(bathy_nodes, MESH_DIM, "float",
filename_h5,
"bathy_xy");
initial_zb = op_decl_dat_hdf5(cells, 1, "float",
filename_h5,
"initial_zb");
bathy_set = bathy_nodes;
}
// If one initBathymetry file is used
if (strstr(events[i].streamName.c_str(), "%i") == NULL){
n_initBathymetry = 1;
temp_initBathymetry = (op_dat*) malloc(sizeof(op_dat));
temp_initBathymetry[0] = op_decl_dat_hdf5(bathy_set, 1, "float",
filename_h5,
"initBathymetry");
// If more initBathymetry files are used
} else{
if(timers[i].iend != INT_MAX) {
n_initBathymetry = (timers[i].iend - timers[i].istart) / timers[i].istep + 1;
} else {
int tmp_iend = ftime/dtmax;
n_initBathymetry = (tmp_iend-timers[i].istart)/timers[i].istep + 1;
}
op_printf("Reading %d consecutive InitBathymetry data arrays... ", n_initBathymetry);
temp_initBathymetry = (op_dat*) malloc(n_initBathymetry * sizeof(op_dat));
for(int k=0; k<n_initBathymetry; k++) {
char dat_name[255];
// iniBathymetry data is stored with sequential numbering instead of iteration step numbering!
sprintf(dat_name,"initBathymetry%d",k);
temp_initBathymetry[k] = op_decl_dat_hdf5(bathy_set, 1, "float",
filename_h5,
dat_name);
}
op_printf("done.\n");
}
}
}
}
for (unsigned int i = 0; i < events.size(); i++) {
if (!strcmp(events[i].className.c_str(), "InitBathyRelative")) {
if (!new_format || n_initBathymetry < 1) {
printf("Error, trying to use InitBathyRelative with new-format or without an initial InitBathymetry event\n");
exit(-1);
}
initial_zb = temp_initBathymetry[0];
}
}
if (op_is_root()) op_diagnostic_output();
/*
* Partitioning
*/
// op_partition("PARMETIS", "GEOM", NULL, NULL, cellCenters);
// op_partition("PTSCOTCH", "GEOM", NULL, NULL, cellCenters);
// op_partition("", "", NULL, NULL, NULL);
// op_partition("PARMETIS", "KWAY", NULL, edgesToCells, NULL);
op_partition("PTSCOTCH", "KWAY", NULL, edgesToCells, NULL);
// op_partition("PARMETIS", "GEOMKWAY", edges, edgesToCells, cellCenters);
// op_partition("PARMETIS", "KWAY", NULL, NULL, NULL);
// op_partition("PARMETIS", "KWAY", edges, edgesToCells, cellCenters);
// op_partition("PTSCOTCH", "KWAY", NULL, cellsToEdges, NULL);
// op_partition("PTSCOTCH", "KWAY", NULL, edgesToCells, NULL);
// op_partition("PTSCOTCH", "KWAY", NULL, cellsToEdges, NULL);
// Timer variables
double cpu_t1, cpu_t2, wall_t1, wall_t2;
op_timers(&cpu_t1, &wall_t1);
float *tmp_elem = NULL;
if (num_outputLocation)
outputLocation_dat = op_decl_dat_temp(outputLocation, 5, "float",
tmp_elem,"outputLocation_dat");
float zmin;
op_dat z_zero = op_decl_dat_temp(cells, 1, "float",tmp_elem,"z_zero");
//Very first Init loop
processEvents(&timers, &events, 1/*firstTime*/, 1/*update timers*/, 0.0/*=dt*/, 1/*remove finished events*/, 2/*init loop, not pre/post*/, cells, values, cellVolumes, cellCenters, nodeCoords, cellsToNodes, temp_initEta, temp_initU, temp_initV, bathy_nodes, lifted_cells, liftedcellsToBathyNodes, liftedcellsToCells, bathy_xy, initial_zb, temp_initBathymetry, z_zero, n_initBathymetry, &zmin, outputLocation_map, outputLocation_dat, writeOption);
/*
* Declaring temporary dats
*/
op_dat values_new = op_decl_dat_temp(cells, 4, "float",tmp_elem,"values_new"); //tmp - cells - dim 4
op_dat GradientatCell = op_decl_dat_temp(cells, 8, "float", tmp_elem, "GradientatCell");
//SpaceDiscretization
op_dat bathySource = op_decl_dat_temp(edges, 4, "float", tmp_elem, "bathySource"); //temp - edges - dim 2 (left & right)
op_dat edgeFluxes = op_decl_dat_temp(edges, 3, "float", tmp_elem, "edgeFluxes"); //temp - edges - dim 4
//NumericalFluxes
op_dat maxEdgeEigenvalues = op_decl_dat_temp(edges, 1, "float", tmp_elem, "maxEdgeEigenvalues"); //temp - edges - dim 1
//EvolveValuesRK22
op_dat Lw_n = op_decl_dat_temp(cells, 4, "float", tmp_elem, "Lw_n"); //temp - cells - dim 4
op_dat Lw_1 = op_decl_dat_temp(cells, 4, "float", tmp_elem, "Lw_1"); //temp - cells - dim 4
op_dat w_1 = op_decl_dat_temp(cells, 4, "float", tmp_elem, "w_1"); //temp - cells - dim 4
// q contains the max and min values of the physical variables surrounding each cell
op_dat q = op_decl_dat_temp(cells, 8, "float", tmp_elem, "q"); //temp - cells - dim 8
// lim is the limiter value for each physical variable defined on each cell
op_dat lim = op_decl_dat_temp(cells, 4, "float", tmp_elem, "lim"); //temp - cells - dim 4
double timestep;
while (timestamp < ftime) {
//process post_update==false events (usually Init events)
processEvents(&timers, &events, 0, 0, 0.0, 0, 0, cells, values, cellVolumes, cellCenters, nodeCoords, cellsToNodes, temp_initEta, temp_initU, temp_initV, bathy_nodes, lifted_cells, liftedcellsToBathyNodes, liftedcellsToCells, bathy_xy, initial_zb, temp_initBathymetry, z_zero, n_initBathymetry, &zmin, outputLocation_map, outputLocation_dat, writeOption);
{
float minTimestep = INFINITY;
if (!spherical){
spaceDiscretization(values, Lw_n, &minTimestep,
bathySource, edgeFluxes, maxEdgeEigenvalues,
edgeNormals, edgeLength, cellVolumes, isBoundary,
cells, edges, edgesToCells, cellsToEdges, cellsToCells, edgeCenters, cellCenters, GradientatCell, q, lim, &zmin);
} else {
spaceDiscretization_sph(values, Lw_n, &minTimestep,
bathySource, edgeFluxes, maxEdgeEigenvalues,
edgeNormals, edgeLength, cellVolumes, isBoundary,
cells, edges, edgesToCells, cellsToEdges, cellsToCells, edgeCenters, cellCenters, GradientatCell, q, lim, &zmin);
}
#ifdef DEBUG
printf("Return of SpaceDiscretization #1 midPointConservative H %g U %g V %g Zb %g \n", normcomp(Lw_n, 0), normcomp(Lw_n, 1),normcomp(Lw_n, 2),normcomp(Lw_n, 3));
#endif
float dT = CFL * minTimestep;
dT= dT < dtmax ? dT : dtmax;
op_par_loop(EvolveValuesRK2_1, "EvolveValuesRK2_1", cells,
op_arg_gbl(&dT,1,"float", OP_READ),
op_arg_dat(Lw_n, -1, OP_ID, 4, "float", OP_READ),
op_arg_dat(values, -1, OP_ID, 4, "float", OP_READ),
op_arg_dat(w_1, -1, OP_ID, 4, "float", OP_WRITE));
#ifdef DEBUG
printf("Return of SpaceDiscretization #1 midPointConservative H %g U %g V %g Zb %g \n", normcomp(w_1, 0), normcomp(w_1, 1),normcomp(w_1, 2),normcomp(w_1, 3));
#endif
float dummy = -1.0f;
if (!spherical){
spaceDiscretization(w_1, Lw_1, &dummy,
bathySource, edgeFluxes, maxEdgeEigenvalues,
edgeNormals, edgeLength, cellVolumes, isBoundary,
cells, edges, edgesToCells, cellsToEdges,
cellsToCells, edgeCenters, cellCenters, GradientatCell, q, lim, &zmin);
} else {
spaceDiscretization_sph(w_1, Lw_1, &dummy,
bathySource, edgeFluxes, maxEdgeEigenvalues,
edgeNormals, edgeLength, cellVolumes, isBoundary,
cells, edges, edgesToCells, cellsToEdges,
cellsToCells, edgeCenters, cellCenters, GradientatCell, q, lim, &zmin);
}
op_par_loop(EvolveValuesRK2_2, "EvolveValuesRK2_2", cells,
op_arg_gbl(&dT,1,"float", OP_READ),
op_arg_dat(Lw_1, -1, OP_ID, 4, "float", OP_READ),
op_arg_dat(values, -1, OP_ID, 4, "float", OP_READ),
op_arg_dat(w_1, -1, OP_ID, 4, "float", OP_READ),
op_arg_dat(values_new, -1, OP_ID, 4, "float", OP_WRITE));
timestep=dT;
op_par_loop(Friction_manning, "Friction_manning", cells,
op_arg_gbl(&dT,1,"float", OP_READ),
op_arg_gbl(&Mn,1,"float", OP_READ),
op_arg_dat(values_new, -1, OP_ID, 4, "float", OP_RW));
op_par_loop(simulation_1, "simulation_1", cells,
op_arg_dat(values, -1, OP_ID, 4, "float", OP_WRITE),
op_arg_dat(values_new, -1, OP_ID, 4, "float", OP_READ));
}
itercount++;
timestamp += timestep;
processEvents(&timers, &events, 0, 1, timestep, 1, 1, cells, values, cellVolumes, cellCenters, nodeCoords, cellsToNodes,temp_initEta, temp_initU, temp_initV, bathy_nodes, lifted_cells, liftedcellsToBathyNodes, liftedcellsToCells, bathy_xy, initial_zb, temp_initBathymetry, z_zero, n_initBathymetry, &zmin, outputLocation_map, outputLocation_dat, writeOption);
}
op_timers(&cpu_t2, &wall_t2);
op_timing_output();
op_printf("Main simulation runtime = \n%lf\n",wall_t2-wall_t1);
if(op_is_root()) {
int compressed = 0;
if (locationData.n_points>0) {
int len = locationData.time[0].size();
int same = 1;
for (int i = 1; i < locationData.n_points; i++) {
if (locationData.time[0].size() != locationData.time[i].size()) same = 0;
}
if (same) compressed = 1;
}
if (compressed) {
int len = locationData.time[0].size();
int pts = locationData.n_points;
int pts1 = locationData.n_points+1;
//float *loc_data = (float*)malloc((locationData.n_points+1)*len*sizeof(float));
float *loc_data = (float*)malloc((pts1*3)*len*sizeof(float));
for (int i = 0; i < len; i++) {
loc_data[i*pts1] = locationData.time[0][i];
for (int j = 0; j < pts; j++) {
loc_data[i*pts1+1+j] = locationData.value[j][i];
}
}
/*loop for storing U*/
for (int i = 0; i < len; i++) {
loc_data[i*pts1+pts1*len] = locationData.time[0][i];
for (int j = 0; j < pts; j++) {
loc_data[i*pts1+pts1*len+1+j] = locationData.allvalues[j][4*i+1];
}
}
/*loop for storing V*/
for (int i = 0; i < len; i++) {
loc_data[i*pts1+2*pts1*len] = locationData.time[0][i];
for (int j = 0; j < pts; j++) {
loc_data[i*pts1+2*pts1*len+1+j] = locationData.allvalues[j][4*i+2];
}
}
write_locations_hdf5(loc_data, pts1,len, "gauges.h5");
write_locations_hdf5(loc_data+pts1*len, pts1,len, "gauges_U.h5");
write_locations_hdf5(loc_data+2*pts1*len, pts1,len, "gauges_V.h5");
} else {
for (int i = 0; i < locationData.n_points; i++) {
FILE* fp;
fp = fopen(locationData.filename[i].c_str(), "w");
if(fp == NULL) {
op_printf("can't open file for write %s\n",locationData.filename[i].c_str());
exit(-1);
}
for(unsigned int j=0; j<locationData.time[i].size() ; j++) {
fprintf(fp, "%1.10f %10.20g\n", locationData.time[i][j], locationData.value[i][j]);
}
if(fclose(fp)) {
op_printf("can't close file %s\n",locationData.filename[i].c_str());
exit(-1);
}
}
}
locationData.filename.clear();
locationData.time.clear();
locationData.value.clear();
locationData.allvalues.clear();
}
for (int i = 0; i < timers.size(); i++) {
if (timers[i].step == -1 && strcmp(events[i].className.c_str(), "OutputMaxElevation") == 0) {
strcpy((char*)currentMaxElevation->name, "values");
OutputSimulation(writeOption, &events[i], &timers[i], nodeCoords, cellsToNodes, currentMaxElevation, cells, &zmin);
strcpy((char*)currentMaxElevation->name, "maxElevation");
}
}
for (int i = 0; i < timers.size(); i++) {
if (timers[i].step == -1 && strcmp(events[i].className.c_str(), "OutputMaxSpeed") == 0) {
strcpy((char*)currentMaxSpeed->name, "values");
OutputSimulation(writeOption, &events[i], &timers[i], nodeCoords, cellsToNodes, currentMaxSpeed, cells, &zmin);
strcpy((char*)currentMaxSpeed->name, "maxSpeed");
}
}
/*
* Free temporary dats
*/
//simulation
if (op_free_dat_temp(values_new) < 0)
op_printf("Error: temporary op_dat %s cannot be removed\n",values_new->name);
if (op_free_dat_temp(GradientatCell) < 0)
op_printf("Error: temporary op_dat %s cannot be removed\n",GradientatCell->name);
//EvolveValuesRK2
/*if (op_free_dat_temp(midPointConservative) < 0)
op_printf("Error: temporary op_dat %s cannot be removed\n",midPointConservative->name);
if (op_free_dat_temp(outConservative) < 0)
op_printf("Error: temporary op_dat %s cannot be removed\n",outConservative->name);
if (op_free_dat_temp(midPointConservative3) < 0)
op_printf("Error: temporary op_dat %s cannot be removed\n",midPointConservative3->name);
if (op_free_dat_temp(inConservative) < 0)
op_printf("Error: temporary op_dat %s cannot be removed\n",inConservative->name);
*/
if (op_free_dat_temp(Lw_n) < 0)
op_printf("Error: temporary op_dat %s cannot be removed\n",Lw_n->name);
if (op_free_dat_temp(Lw_1) < 0)
op_printf("Error: temporary op_dat %s cannot be removed\n",Lw_1->name);
if (op_free_dat_temp(w_1) < 0)
op_printf("Error: temporary op_dat %s cannot be removed\n",w_1->name);
//SpaceDiscretization
if (op_free_dat_temp(bathySource) < 0)
op_printf("Error: temporary op_dat %s cannot be removed\n",bathySource->name);
if (op_free_dat_temp(edgeFluxes) < 0)
op_printf("Error: temporary op_dat %s cannot be removed\n",edgeFluxes->name);
//NumericalFluxes
if (op_free_dat_temp(maxEdgeEigenvalues) < 0)
op_printf("Error: temporary op_dat %s cannot be removed\n",maxEdgeEigenvalues->name);
if (op_free_dat_temp(q)< 0)
op_printf("Error: temporary op_dat %s cannot be removed\n",q->name);
if (op_free_dat_temp(lim)< 0)
op_printf("Error: temporary op_dat %s cannot be removed\n",lim->name);
op_timers(&cpu_t2, &wall_t2);
op_timing_output();
op_printf("Max total runtime = \n%lf\n",wall_t2-wall_t1);
op_exit();
return 0;
}
| 45.336937 | 755 | 0.648478 | [
"mesh",
"geometry",
"vector"
] |
07aaf69f2980f4d87d6765374882a1d2de61e491 | 719 | cpp | C++ | VoteCountBooth.cpp | ChandanSP1123/ObserverPatternCpp | 1748e413c999d2974c319e3ae96ac270267d0d09 | [
"MIT"
] | null | null | null | VoteCountBooth.cpp | ChandanSP1123/ObserverPatternCpp | 1748e413c999d2974c319e3ae96ac270267d0d09 | [
"MIT"
] | null | null | null | VoteCountBooth.cpp | ChandanSP1123/ObserverPatternCpp | 1748e413c999d2974c319e3ae96ac270267d0d09 | [
"MIT"
] | null | null | null | #include "VoteCountBooth.hpp"
#include "algorithm"
void VoteCountBooth::Subscribe(Observer *Object)
{
ObserverList.push_back(Object);
}
void VoteCountBooth::Unsubscribe(Observer *Object)
{
ObserverList.erase(std::remove_if(ObserverList.begin(), ObserverList.end(), [&](Observer *a)
{ return a == Object; }));
}
void VoteCountBooth::Notify()
{
for (std::vector<Observer *>::const_iterator i = ObserverList.begin(); i != ObserverList.end(); i++)
{
(*i)->update(CandidateData.votecount, CandidateData.Name);
}
}
void VoteCountBooth::UpdateData(int count, char *name)
{
CandidateData.Name = name;
CandidateData.votecount = count;
Notify();
} | 25.678571 | 104 | 0.655076 | [
"object",
"vector"
] |
07ae691e4d935d72396a286b02384db2f593c6f1 | 10,755 | cpp | C++ | 02_Triangle/Source/Sample/SampleApp.cpp | n-suudai/D3D11Sample | ade7976b67d306c07ae29d2f9dd3becfb9770e33 | [
"MIT"
] | null | null | null | 02_Triangle/Source/Sample/SampleApp.cpp | n-suudai/D3D11Sample | ade7976b67d306c07ae29d2f9dd3becfb9770e33 | [
"MIT"
] | null | null | null | 02_Triangle/Source/Sample/SampleApp.cpp | n-suudai/D3D11Sample | ade7976b67d306c07ae29d2f9dd3becfb9770e33 | [
"MIT"
] | null | null | null | #include "SampleApp.hpp"
// DXGI & D3D11 のライブラリをリンク
#pragma comment(lib, "dxgi.lib")
#pragma comment(lib, "d3d11.lib")
using Vertex = Vertex_PositionColor;
const Vertex g_vertices[] = {
{ { 0.0f, 0.5f, 0.5f, 1.0f },{ 1.0f, 1.0f, 0.0f, 1.0f } },
{ { 0.5f, -0.5f, 0.5f, 1.0f },{ 1.0f, 1.0f, 0.0f, 1.0f } },
{ { -0.5f, -0.5f, 0.5f, 1.0f },{ 1.0f, 1.0f, 0.0f, 1.0f } },
};
SampleApp::SampleApp(IApp* pApp)
: m_pApp(pApp)
, m_BufferCount(2)
, m_BufferFormat(DXGI_FORMAT_R8G8B8A8_UNORM)
, m_FeatureLevel(D3D_FEATURE_LEVEL_11_1)
{
}
SampleApp::~SampleApp()
{
Term();
}
// 初期化
bool SampleApp::Init()
{
ResultUtil result;
// ウィンドウハンドルを取得
HWND hWnd = reinterpret_cast<HWND>(m_pApp->GetWindowHandle());
// 描画領域のサイズを取得
const Size2D& clientSize = m_pApp->GetClientSize();
// ファクトリーを生成
result = CreateDXGIFactory(IID_PPV_ARGS(&m_Factory));
if (!result)
{
ShowErrorMessage(result, "CreateDXGIFactory");
return false;
}
// デバイス&コンテキストを生成
{
// BGRAサポートを有効化
uint32_t createDeviceFlags = D3D11_CREATE_DEVICE_BGRA_SUPPORT;
#if defined(DEBUG) || defined(_DEBUG)
createDeviceFlags |= D3D11_CREATE_DEVICE_DEBUG;
#endif
D3D_FEATURE_LEVEL featureLevels[] = {
D3D_FEATURE_LEVEL_11_1,
D3D_FEATURE_LEVEL_11_0,
};
result = D3D11CreateDevice(
nullptr,
D3D_DRIVER_TYPE_HARDWARE, // ハードウェア ドライバー を使用
nullptr,
createDeviceFlags,
featureLevels,
_countof(featureLevels),
D3D11_SDK_VERSION,
&m_Device,
&m_FeatureLevel,
&m_Context
);
if (!result)
{
ShowErrorMessage(result, "D3D11CreateDevice");
return false;
}
}
// スワップチェインを生成
{
// 使用可能なMSAAを取得
DXGI_SAMPLE_DESC sampleDesc;
ZeroMemory(&sampleDesc, sizeof(sampleDesc));
for (int i = 1; i <= D3D11_MAX_MULTISAMPLE_SAMPLE_COUNT; i <<= 1)
{
UINT Quality;
if (SUCCEEDED(m_Device->CheckMultisampleQualityLevels(DXGI_FORMAT_D24_UNORM_S8_UINT, i, &Quality)))
{
if (0 < Quality)
{
sampleDesc.Count = i;
sampleDesc.Quality = Quality - 1;
}
}
}
// スワップチェインを生成
DXGI_SWAP_CHAIN_DESC swapChainDesc;
ZeroMemory(&swapChainDesc, sizeof(swapChainDesc));
swapChainDesc.BufferDesc.Width = static_cast<UINT>(clientSize.width);
swapChainDesc.BufferDesc.Height = static_cast<UINT>(clientSize.height);
swapChainDesc.BufferDesc.RefreshRate.Numerator = 60;
swapChainDesc.BufferDesc.RefreshRate.Denominator = 1;
swapChainDesc.BufferDesc.ScanlineOrdering = DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED;
swapChainDesc.BufferDesc.Scaling = DXGI_MODE_SCALING_CENTERED;
swapChainDesc.BufferDesc.Format = m_BufferFormat;
swapChainDesc.SampleDesc = sampleDesc;
swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT | DXGI_USAGE_SHADER_INPUT;
swapChainDesc.BufferCount = m_BufferCount;
swapChainDesc.Windowed = TRUE;
swapChainDesc.OutputWindow = hWnd;
swapChainDesc.Flags = DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH;
result = m_Factory->CreateSwapChain(
m_Device.Get(),
&swapChainDesc,
&m_SwapChain
);
if (!result)
{
ShowErrorMessage(result, "m_Factory->CreateSwapChain");
return false;
}
}
// バックバッファを生成
if (!CreateBackBuffer(clientSize))
{
return false;
}
// 頂点バッファを生成
if (!CreateVertexBuffer(g_vertices, sizeof(g_vertices)))
{
return false;
}
// シェーダーを生成
if (!CreateShader("Resource\\Shader\\VertexShader.cso", "Resource\\Shader\\PixelShader.cso"))
{
return false;
}
return true;
}
// 解放
void SampleApp::Term()
{
}
// 更新処理
void SampleApp::Update()
{
}
// 描画処理
void SampleApp::Render()
{
// 指定色でクリア
{
// red, green, blue, alpha
FLOAT clearColor[4] = { 0.0f, 0.125f, 0.3f, 1.0f };
m_Context->ClearRenderTargetView(m_RenderTargetView.Get(), clearColor);
}
// 入力レイアウトを設定
m_Context->IASetInputLayout(m_InputLayout.Get());
// 入力レイアウトに頂点バッファを設定
{
UINT stride = sizeof(Vertex_PositionColor);
UINT offset = 0;
ID3D11Buffer* pVertexBuffers[] = {
m_VertexBuffer.Get()
};
m_Context->IASetVertexBuffers(
0,
_countof(pVertexBuffers),
pVertexBuffers,
&stride,
&offset
);
}
// プリミティブトポロジーの設定
m_Context->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
// 頂点シェーダーを設定
m_Context->VSSetShader(m_VertexShader.Get(), nullptr, 0);
// ピクセルシェーダーを設定
m_Context->PSSetShader(m_PixelShader.Get(), nullptr, 0);
// 描画
m_Context->Draw(_countof(g_vertices), 0);
// 結果をウインドウに反映
ResultUtil result = m_SwapChain->Present(0, 0);
if (!result)
{
ShowErrorMessage(result, "m_SwapChain->Present");
}
}
// リサイズ
void SampleApp::OnResize(const Size2D& newSize)
{
// バックバッファを再生成
CreateBackBuffer(newSize);
}
// キー
void SampleApp::OnKey(KEY_CODE key, bool isDown)
{
if (key == KEY_CODE_ESCAPE && isDown)
{
m_pApp->PostQuit();
}
}
// マウスボタン
void SampleApp::OnMouse(const Position2D& position, MOUSE_BUTTON button, bool isDown)
{
position; button; isDown;
}
// マウスホイール
void SampleApp::OnMouseWheel(const Position2D& position, s32 wheelDelta)
{
position; wheelDelta;
}
// バックバッファを作成
bool SampleApp::CreateBackBuffer(const Size2D& newSize)
{
ResultUtil result;
// バックバッファを破棄
m_Context->OMSetRenderTargets(0, nullptr, nullptr);
m_RenderTargetView.Reset();
// バッファのサイズを変更
result = m_SwapChain->ResizeBuffers(
m_BufferCount,
static_cast<UINT>(newSize.width),
static_cast<UINT>(newSize.height),
m_BufferFormat,
DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH
);
if (!result)
{
ShowErrorMessage(result, "m_SwapChain->ResizeBuffers");
return false;
}
// レンダーターゲットを生成
{
ComPtr<ID3D11Texture2D> backBuffer;
result = m_SwapChain->GetBuffer(0, IID_PPV_ARGS(&backBuffer));
if (!result)
{
ShowErrorMessage(result, "m_SwapChain->GetBuffer");
return false;
}
result = m_Device->CreateRenderTargetView(
backBuffer.Get(),
nullptr,
&m_RenderTargetView
);
if (!result)
{
ShowErrorMessage(result, "m_Device->CreateRenderTargetView");
return false;
}
}
// レンダーターゲットを設定
ID3D11RenderTargetView* pRenderTargetViews[] = {
m_RenderTargetView.Get()
};
m_Context->OMSetRenderTargets(_countof(pRenderTargetViews), pRenderTargetViews, nullptr);
// ビューポートを設定
D3D11_VIEWPORT viewport;
viewport.Width = static_cast<FLOAT>(newSize.width);
viewport.Height = static_cast<FLOAT>(newSize.height);
viewport.MinDepth = 0.0f;
viewport.MaxDepth = 1.0f;
viewport.TopLeftX = 0.0f;
viewport.TopLeftY = 0.0f;
m_Context->RSSetViewports(1, &viewport);
return true;
}
// シェーダーを作成
bool SampleApp::CreateShader(const std::string& vertexShader, const std::string& pixelShader)
{
ResultUtil result;
// VertexShader
{
std::vector<BYTE> vertexShaderData;
if (!ReadFile(vertexShader, vertexShaderData))
{
return false;
}
result = m_Device->CreateVertexShader(
vertexShaderData.data(),
vertexShaderData.size(),
nullptr,
&m_VertexShader
);
if (!result)
{
ShowErrorMessage(result, "m_Device->CreateVertexShader");
return false;
}
// InputLayout
{
result = m_Device->CreateInputLayout(
Vertex::pInputElementDescs,
Vertex::InputElementCount,
vertexShaderData.data(),
vertexShaderData.size(),
&m_InputLayout
);
if (!result)
{
ShowErrorMessage(result, "m_Device->CreateInputLayout");
return false;
}
}
}
// PixelShader
{
std::vector<BYTE> pixelShaderData;
if (!ReadFile(pixelShader, pixelShaderData))
{
return false;
}
result = m_Device->CreatePixelShader(
pixelShaderData.data(),
pixelShaderData.size(),
nullptr,
&m_PixelShader
);
if (!result)
{
ShowErrorMessage(result, "m_Device->CreatePixelShader");
return false;
}
}
return true;
}
// 頂点バッファを作成
bool SampleApp::CreateVertexBuffer(const void* pVertices, UINT byteWidth)
{
// バッファの設定
D3D11_BUFFER_DESC bufferDesc;
ZeroMemory(&bufferDesc, sizeof(bufferDesc));
bufferDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
bufferDesc.ByteWidth = byteWidth;
bufferDesc.CPUAccessFlags = 0;
bufferDesc.MiscFlags = 0;
bufferDesc.StructureByteStride = 0;
bufferDesc.Usage = D3D11_USAGE_DEFAULT;
// サブリソースの設定
D3D11_SUBRESOURCE_DATA subresourceData;
ZeroMemory(&subresourceData, sizeof(subresourceData));
subresourceData.pSysMem = pVertices;
subresourceData.SysMemPitch = 0;
subresourceData.SysMemSlicePitch = 0;
ResultUtil result = m_Device->CreateBuffer(
&bufferDesc,
&subresourceData,
&m_VertexBuffer
);
if (!result)
{
ShowErrorMessage(result, "m_Device->CreateBuffer");
return false;
}
return true;
}
// ファイルの読み込み(バイナリ)
bool SampleApp::ReadFile(const std::string& fileName, std::vector<BYTE>& out)
{
out.clear();
std::ifstream file(fileName, std::ios::binary);
if (file.fail())
{
return false;
}
file.unsetf(std::ios::skipws);
std::streampos fileSize;
file.seekg(0, std::ios::end);
fileSize = file.tellg();
file.seekg(0, std::ios::beg);
out.reserve(fileSize);
out.insert(
out.begin(),
std::istream_iterator<BYTE>(file),
std::istream_iterator<BYTE>()
);
return true;
}
// エラーメッセージ表示
void SampleApp::ShowErrorMessage(const ResultUtil& result, const std::string& text)
{
m_pApp->ShowMessageBox(
result.GetText() + "\n\n" + text,
"エラー"
);
}
| 23.741722 | 111 | 0.601209 | [
"render",
"vector"
] |
07b4720e6392dae1471a8f75607f84271c152049 | 33,141 | cpp | C++ | src/formatvalue.cpp | panzi/formatstring | 8c7cb73cd69e29c3289924de7bb51e28cd032f79 | [
"Unlicense",
"MIT"
] | 37 | 2015-01-08T15:53:05.000Z | 2021-11-08T08:51:59.000Z | src/formatvalue.cpp | panzi/formatstring | 8c7cb73cd69e29c3289924de7bb51e28cd032f79 | [
"Unlicense",
"MIT"
] | 1 | 2021-02-21T07:49:37.000Z | 2021-02-22T09:09:57.000Z | src/formatvalue.cpp | panzi/formatstring | 8c7cb73cd69e29c3289924de7bb51e28cd032f79 | [
"Unlicense",
"MIT"
] | 1 | 2016-07-13T10:25:04.000Z | 2016-07-13T10:25:04.000Z | #include "formatstring/formatvalue.h"
#include <vector>
namespace formatstring {
namespace impl {
template<typename Char>
struct basic_grouping;
template<>
struct basic_grouping<char> {
static const std::locale non_grouping_locale;
static const std::locale thousands_grouping_locale;
};
#ifdef FORMATSTRING_CHAR16_SUPPORT
template<>
struct basic_grouping<char16_t> {
static const std::locale non_grouping_locale;
static const std::locale thousands_grouping_locale;
};
#endif
#ifdef FORMATSTRING_CHAR32_SUPPORT
template<>
struct basic_grouping<char32_t> {
static const std::locale non_grouping_locale;
static const std::locale thousands_grouping_locale;
};
#endif
template<>
struct basic_grouping<wchar_t> {
static const std::locale non_grouping_locale;
static const std::locale thousands_grouping_locale;
};
template<typename Char>
struct basic_names {
typedef Char char_type;
static const Char* const TRUE_LOWER;
static const Char* const TRUE_UPPER;
static const Char* const FALSE_LOWER;
static const Char* const FALSE_UPPER;
};
typedef basic_names<char> names;
#ifdef FORMATSTRING_CHAR16_SUPPORT
typedef basic_names<char16_t> u16names;
#endif
#ifdef FORMATSTRING_CHAR32_SUPPORT
typedef basic_names<char32_t> u32names;
#endif
typedef basic_names<wchar_t> wnames;
template<typename Char>
inline void fill(std::basic_ostream<Char>& out, Char fill, std::size_t width) {
for (; width > 0; -- width) { out.put(fill); }
}
template<typename Char>
void sepfill(std::basic_ostream<Char>& out, std::size_t width, std::size_t numlen) {
std::size_t place = width + numlen;
// (x % 4) == (x & 3)
if ((place & 3) == 0) {
out.put('0');
}
for (; width > 0; -- width, -- place) {
if ((place & 3) == 0) {
out.put(',');
}
else {
out.put('0');
}
}
}
template<typename Char>
struct repr_char {
static inline void write_prefix(std::basic_ostream<Char>& out) {
(void)out;
}
};
template<>
struct repr_char<wchar_t> {
static inline void write_prefix(std::wostream& out) {
out.put('L');
}
};
#ifdef FORMATSTRING_CHAR16_SUPPORT
template<>
struct repr_char<char16_t> {
static inline void write_prefix(std::basic_ostream<char16_t>& out) {
out.put('u');
}
};
#endif
#ifdef FORMATSTRING_CHAR32_SUPPORT
template<>
struct repr_char<char32_t> {
static inline void write_prefix(std::basic_ostream<char32_t>& out) {
out.put('U');
}
};
#endif
}
}
using namespace formatstring;
template<> const char* const impl::names::TRUE_LOWER = "true";
template<> const char* const impl::names::TRUE_UPPER = "TRUE";
template<> const char* const impl::names::FALSE_LOWER = "false";
template<> const char* const impl::names::FALSE_UPPER = "FALSE";
#ifdef FORMATSTRING_CHAR16_SUPPORT
template<> const char16_t* const impl::u16names::TRUE_LOWER = u"true";
template<> const char16_t* const impl::u16names::TRUE_UPPER = u"TRUE";
template<> const char16_t* const impl::u16names::FALSE_LOWER = u"false";
template<> const char16_t* const impl::u16names::FALSE_UPPER = u"FALSE";
#endif
#ifdef FORMATSTRING_CHAR32_SUPPORT
template<> const char32_t* const impl::u32names::TRUE_LOWER = U"true";
template<> const char32_t* const impl::u32names::TRUE_UPPER = U"TRUE";
template<> const char32_t* const impl::u32names::FALSE_LOWER = U"false";
template<> const char32_t* const impl::u32names::FALSE_UPPER = U"FALSE";
#endif
template<> const wchar_t* const impl::wnames::TRUE_LOWER = L"true";
template<> const wchar_t* const impl::wnames::TRUE_UPPER = L"TRUE";
template<> const wchar_t* const impl::wnames::FALSE_LOWER = L"false";
template<> const wchar_t* const impl::wnames::FALSE_UPPER = L"FALSE";
template<typename Char>
struct group_thousands : public std::numpunct<Char> {
std::string do_grouping() const { return "\03"; }
Char do_thousands_sep() const { return ','; }
Char do_decimal_point() const { return '.'; }
};
template<typename Char>
struct no_grouping : public group_thousands<Char> {
std::string do_grouping() const { return ""; }
};
template<typename Char>
void formatstring::repr_char(std::basic_ostream<Char>& out, Char value) {
impl::repr_char<Char>::write_prefix(out);
out.put('\'');
switch (value) {
case '\0': out.put('\\'); out.put('0'); break;
case '\a': out.put('\\'); out.put('a'); break;
case '\b': out.put('\\'); out.put('b'); break;
case '\t': out.put('\\'); out.put('t'); break;
case '\n': out.put('\\'); out.put('n'); break;
case '\v': out.put('\\'); out.put('v'); break;
case '\f': out.put('\\'); out.put('f'); break;
case '\r': out.put('\\'); out.put('r'); break;
case '\'': out.put('\\'); out.put('\''); break;
case '\\': out.put('\\'); out.put('\\'); break;
default: out.put(value); break;
}
out.put('\'');
}
template<typename Char>
void formatstring::repr_string(std::basic_ostream<Char>& out, const Char* value) {
impl::repr_char<Char>::write_prefix(out);
out.put('"');
for (; *value; ++ value) {
Char ch = *value;
switch (ch) {
case '\0': out.put('\\'); out.put('0'); break;
case '\a': out.put('\\'); out.put('a'); break;
case '\b': out.put('\\'); out.put('b'); break;
case '\t': out.put('\\'); out.put('t'); break;
case '\n': out.put('\\'); out.put('n'); break;
case '\v': out.put('\\'); out.put('v'); break;
case '\f': out.put('\\'); out.put('f'); break;
case '\r': out.put('\\'); out.put('r'); break;
case '"': out.put('\\'); out.put('"'); break;
case '?':
// prevent trigraphs from being interpreted inside string literals
out.put('?');
if (*(value + 1) == '?') {
out.put('\\');
}
break;
case '\\': out.put('\\'); out.put('\\'); break;
default: out.put(ch); break;
}
}
out.put('"');
}
template<typename Char>
void formatstring::format_bool(std::basic_ostream<Char>& out, bool value, const BasicFormatSpec<Char>& spec) {
if (spec.isNumberType()) {
format_integer<Char,unsigned int>(out, value ? 1 : 0, spec);
}
else {
const Char* str = spec.upperCase ?
(value ? impl::basic_names<Char>::TRUE_UPPER : impl::basic_names<Char>::FALSE_UPPER) :
(value ? impl::basic_names<Char>::TRUE_LOWER : impl::basic_names<Char>::FALSE_LOWER);
BasicFormatSpec<Char> strspec = spec;
strspec.type = BasicFormatSpec<Char>::String;
format_string(out, str, strspec);
}
}
template<typename Char>
void formatstring::repr_bool(std::basic_ostream<Char>& out, bool value) {
const Char* str = value ? impl::basic_names<Char>::TRUE_LOWER : impl::basic_names<Char>::FALSE_LOWER;
out.write(str, std::char_traits<Char>::length(str));
}
template<typename Char, typename Int, typename UInt = typename std::make_unsigned<Int>::type>
void formatstring::format_integer(std::basic_ostream<Char>& out, Int value, const BasicFormatSpec<Char>& spec) {
typedef BasicFormatSpec<Char> Spec;
if (spec.type == Spec::Character) {
Char str[2] = {(Char)value, 0};
Spec strspec = spec;
strspec.type = Spec::String;
format_string(out, str, strspec);
return;
}
else if (spec.isFloatType()) {
format_float<Char,double>(out, value, spec);
return;
}
bool negative = value < 0;
UInt abs = negative ? -value : value;
std::basic_string<Char> prefix;
switch (spec.sign) {
case Spec::NegativeOnly:
case Spec::DefaultSign:
if (negative) {
prefix += (Char)'-';
}
break;
case Spec::Always:
prefix += negative ? (Char)'-' : (Char)'+';
break;
case Spec::SpaceForPositive:
prefix += negative ? (Char)'-' : (Char)' ';
break;
}
std::basic_ostringstream<Char> buffer;
buffer.imbue(spec.thoudsandsSeperator ? impl::basic_grouping<Char>::thousands_grouping_locale : impl::basic_grouping<Char>::non_grouping_locale);
switch (spec.type) {
case Spec::Generic:
case Spec::Dec:
case Spec::String:
buffer << abs;
break;
case Spec::Bin:
if (spec.alternate) {
prefix += (Char)'0';
prefix += spec.upperCase ? (Char)'B' : (Char)'b';
}
if (abs == 0) {
buffer.put('0');
}
else {
UInt bit = (UInt)1 << ((sizeof(abs) * 8) - 1);
while ((abs & bit) == 0) {
bit >>= 1;
}
while (bit != 0) {
buffer.put((abs & bit) ? '1' : '0');
bit >>= 1;
}
}
break;
case Spec::Oct:
if (spec.alternate) {
prefix += (Char)'0';
prefix += spec.upperCase ? (Char)'O' : (Char)'o';
}
buffer.setf(std::ios::oct, std::ios::basefield);
buffer << abs;
break;
case Spec::Hex:
if (spec.alternate) {
prefix += (Char)'0';
prefix += spec.upperCase ? (Char)'X' : (Char)'x';
}
buffer.setf(std::ios::hex, std::ios::basefield);
if (spec.upperCase) {
buffer.setf(std::ios::uppercase);
}
buffer << abs;
break;
default:
break;
}
std::basic_string<Char> num = buffer.str();
typename std::basic_string<Char>::size_type length = prefix.size() + num.size();
if (length < spec.width) {
std::size_t padding = spec.width - length;
switch (spec.alignment) {
case Spec::Left:
out.write(prefix.c_str(), prefix.size());
out.write(num.c_str(), num.size());
impl::fill(out, spec.fill, padding);
break;
case Spec::Right:
case Spec::DefaultAlignment:
impl::fill(out, spec.fill, padding);
out.write(prefix.c_str(), prefix.size());
out.write(num.c_str(), num.size());
break;
case Spec::Center:
{
std::size_t before = padding / 2;
impl::fill(out, spec.fill, before);
out.write(prefix.c_str(), prefix.size());
out.write(num.c_str(), num.size());
impl::fill(out, spec.fill, padding - before);
break;
}
case Spec::AfterSign:
out.write(prefix.c_str(), prefix.size());
if (spec.thoudsandsSeperator && spec.fill == '0') {
impl::sepfill(out, padding, num.size());
}
else {
impl::fill(out, spec.fill, padding);
}
out.write(num.c_str(), num.size());
break;
}
}
else {
out.write(prefix.c_str(), prefix.size());
out.write(num.c_str(), num.size());
}
}
#if !defined(FORMATSTRING_IOS_HEXFLOAT_SUPPORT) && defined(FORMATSTRING_PRINTF_HEXFLOAT_SUPPORT)
template<typename Float>
inline std::string format_hexfloat(Float value, const FormatSpec& spec) {
if (spec.alignment == FormatSpec::AfterSign) {
if (spec.width > 3 && spec.fill != '0') {
throw std::runtime_error("unsupported hexfloat format for snprintf fallback");
}
const char *fmt = std::is_same<Float,long double>::value ?
(spec.upperCase ? "%0*.*LA" : "%0*.*La") :
(spec.upperCase ? "%0*.*A" : "%0*.*a");
std::size_t n = std::max(spec.width + 1, 64);
std::vector<char> buf(n, '\0');
int count = std::snprintf(buf.data(), n, fmt, spec.width, spec.precision, value);
if (count < 2 || count >= n) {
throw std::runtime_error("unexpected snprintf fail while processing hexfloat format");
}
return buf.data();
}
const char *fmt = std::is_same<Float,long double>::value ?
(spec.upperCase ? "%.*LA" : "%.*La") :
(spec.upperCase ? "%.*A" : "%.*a");
std::size_t n = std::max(spec.precision, 0) + 64;
std::vector<char> buf(n, '\0');
int count = std::snprintf(buf.data(), n, fmt, spec.precision, value);
if (count < 2 || count >= n) {
throw std::runtime_error("unexpected snprintf fail while processing hexfloat format");
}
return buf.data();
}
template<typename Float>
inline std::wstring format_hexfloat(Float value, const WFormatSpec& spec) {
if (spec.alignment == WFormatSpec::AfterSign) {
if (spec.width > 3 && spec.fill != L'0') {
throw std::runtime_error("unsupported hexfloat format for swprintf fallback");
}
const wchar_t *fmt = std::is_same<Float,long double>::value ?
(spec.upperCase ? L"%0*.*LA" : L"%0*.*La") :
(spec.upperCase ? L"%0*.*A" : L"%0*.*a");
std::size_t n = std::max(spec.width + 1, 64);
std::vector<wchar_t> buf(n, '\0');
int count = std::swprintf(buf.data(), n, fmt, spec.width, spec.precision, value);
if (count < 2 || count >= n) {
throw std::runtime_error("unexpected printf fail while processing hexfloat format");
}
return buf.data();
}
const wchar_t *fmt = std::is_same<Float,long double>::value ?
(spec.upperCase ? L"%.*LA" : L"%.*La") :
(spec.upperCase ? L"%.*A" : L"%.*a");
std::size_t n = std::max(spec.width+1, 64);
std::vector<wchar_t> buf(n, '\0');
int count = std::swprintf(buf.data(), n, fmt, spec.precision, value);
if (count < 2 || count >= n) {
throw std::runtime_error("unexpected printf fail while processing hexfloat format");
}
return buf.data();
}
#ifdef FORMATSTRING_CHAR16_SUPPORT
template<typename Float>
inline std::basic_string<char16_t> format_hexfloat(Float value, const U16FormatSpec& spec) {
(void)value;
(void)spec;
throw std::runtime_error("STL implementation does not support std::ios::hexfloat.");
}
#endif
#ifdef FORMATSTRING_CHAR32_SUPPORT
template<typename Float>
inline std::basic_string<char32_t> format_hexfloat(Float value, const U32FormatSpec& spec) {
(void)value;
(void)spec;
throw std::runtime_error("STL implementation does not support std::ios::hexfloat.");
}
#endif
#endif
template<typename Char, typename Float>
void formatstring::format_float(std::basic_ostream<Char>& out, Float value, const BasicFormatSpec<Char>& spec) {
typedef BasicFormatSpec<Char> Spec;
if (!spec.isFloatType() && spec.type != Spec::Generic) {
throw std::invalid_argument("Cannot use floating point numbers with non-decimal format specifier.");
}
bool negative = std::signbit(value);
Float abs = negative ? -value : value;
std::basic_string<Char> prefix;
switch (spec.sign) {
case Spec::NegativeOnly:
case Spec::DefaultSign:
if (negative) {
prefix += (Char)'-';
}
break;
case Spec::Always:
prefix += negative ? (Char)'-' : (Char)'+';
break;
case Spec::SpaceForPositive:
prefix += negative ? (Char)'-' : (Char)' ';
break;
}
std::basic_string<Char> num;
if (std::isnan(abs)) {
if (spec.upperCase) {
Char buffer[] = {'N', 'A', 'N', 0};
num = buffer;
}
else {
Char buffer[] = {'n', 'a', 'n', 0};
num = buffer;
}
if (spec.type == Spec::Percentage) {
num += (Char)'%';
}
}
else if (std::isinf(abs)) {
if (spec.upperCase) {
Char buffer[] = {'I', 'N', 'F', 0};
num = buffer;
}
else {
Char buffer[] = {'i', 'n', 'f', 0};
num = buffer;
}
if (spec.type == Spec::Percentage) {
num += (Char)'%';
}
}
#if !defined(FORMATSTRING_IOS_HEXFLOAT_SUPPORT) && defined(FORMATSTRING_PRINTF_HEXFLOAT_SUPPORT)
else if (spec.type == Spec::HexFloat) {
num = format_hexfloat(abs, spec);
}
#endif
else {
std::basic_ostringstream<Char> buffer;
buffer.imbue(spec.thoudsandsSeperator ? impl::basic_grouping<Char>::thousands_grouping_locale : impl::basic_grouping<Char>::non_grouping_locale);
if (spec.upperCase) {
buffer.setf(std::ios::uppercase);
}
switch (spec.type) {
case Spec::Exp:
buffer.setf(std::ios::scientific, std::ios::floatfield);
buffer.precision(spec.precision);
buffer << abs;
break;
case Spec::Fixed:
buffer.setf(std::ios::fixed, std::ios::floatfield);
buffer.precision(spec.precision);
buffer << abs;
break;
case Spec::Generic:
case Spec::General:
{
// XXX: not 100% correct. it doesn't skip trailing 0s after the decimal point
int exponent = std::log10(abs);
int precision = spec.precision < 1 ? 1 : spec.precision;
if (-4 <= exponent && exponent < precision) {
buffer.setf(std::ios::fixed, std::ios::floatfield);
precision = precision - 1 - exponent;
}
else {
buffer.setf(std::ios::scientific, std::ios::floatfield);
precision = precision - 1;
}
buffer.precision(precision);
buffer << abs;
break;
}
case Spec::Percentage:
buffer.setf(std::ios::fixed, std::ios::floatfield);
buffer.precision(spec.precision);
buffer << (abs * 100);
buffer.put('%');
break;
case Spec::HexFloat:
#ifdef FORMATSTRING_IOS_HEXFLOAT_SUPPORT
buffer.setf(std::ios::hexfloat, std::ios::floatfield);
buffer.precision(spec.precision);
buffer << abs;
break;
#else
throw std::runtime_error("STL implementation does not support std::ios::hexfloat.");
#endif
default:
break;
}
num = buffer.str();
}
typename std::basic_string<Char>::size_type length = prefix.size() + num.size();
if (length < spec.width) {
std::size_t padding = spec.width - length;
switch (spec.alignment) {
case Spec::Left:
out.write(prefix.c_str(), prefix.size());
out.write(num.c_str(), num.size());
impl::fill(out, spec.fill, padding);
break;
case Spec::Right:
case Spec::DefaultAlignment:
impl::fill(out, spec.fill, padding);
out.write(prefix.c_str(), prefix.size());
out.write(num.c_str(), num.size());
break;
case Spec::Center:
{
std::size_t before = padding / 2;
impl::fill(out, spec.fill, before);
out.write(prefix.c_str(), prefix.size());
out.write(num.c_str(), num.size());
impl::fill(out, spec.fill, padding - before);
break;
}
case Spec::AfterSign:
out.write(prefix.c_str(), prefix.size());
if (spec.thoudsandsSeperator && spec.fill == '0' && std::isfinite(abs)) {
Char chars[] = { (Char)'.', (Char)'e', 0 };
if (spec.upperCase) {
chars[1] = (Char)'E';
}
std::size_t pos = num.find_first_of(chars);
impl::sepfill(out, padding, pos == std::basic_string<Char>::npos ? num.size() : pos);
}
else {
impl::fill(out, spec.fill, padding);
}
out.write(num.c_str(), num.size());
break;
}
}
else {
out.write(prefix.c_str(), prefix.size());
out.write(num.c_str(), num.size());
}
}
template<typename Char>
void formatstring::format_string(std::basic_ostream<Char>& out, const Char value[], const BasicFormatSpec<Char>& spec) {
typedef BasicFormatSpec<Char> Spec;
if (spec.sign != Spec::DefaultSign) {
throw std::invalid_argument("Sign not allowed with string or character");
}
if (spec.thoudsandsSeperator) {
throw std::invalid_argument("Cannot specify ',' for string");
}
if (spec.alternate && spec.type != Spec::Character) {
throw std::invalid_argument("Alternate form (#) not allowed in string format specifier");
}
switch (spec.type) {
case Spec::Generic:
case Spec::String:
break;
default:
throw std::invalid_argument("Invalid format specifier for string or character");
}
std::size_t length = std::char_traits<Char>::length(value);
if (spec.width > 0 && length < (std::size_t)spec.width) {
std::size_t padding = spec.width - length;
switch (spec.alignment) {
case Spec::AfterSign:
throw std::invalid_argument("'=' alignment not allowed in string or character format specifier");
case Spec::Left:
case Spec::DefaultAlignment:
out.write(value, length);
impl::fill(out, spec.fill, padding);
break;
case Spec::Right:
impl::fill(out, spec.fill, padding);
out.write(value, length);
break;
case Spec::Center:
std::size_t before = padding / 2;
impl::fill(out, spec.fill, before);
out.write(value, length);
impl::fill(out, spec.fill, padding - before);
break;
}
}
else {
out.write(value, length);
}
}
template<typename Char>
void formatstring::format_int_char(std::basic_ostream<Char>& out, typename std::char_traits<Char>::int_type value, const BasicFormatSpec<Char>& spec) {
if (spec.type == BasicFormatSpec<Char>::Generic || spec.isStringType()) {
Char str[2] = { (Char)value, 0 };
BasicFormatSpec<Char> strspec = spec;
strspec.type = BasicFormatSpec<Char>::String;
format_string(out, str, strspec);
}
else {
format_integer(out, value, spec);
}
}
template void repr_bool<char>(std::ostream& out, bool value);
template void repr_bool<wchar_t>(std::wostream& out, bool value);
template void repr_char<char>(std::ostream& out, char value);
template void repr_char<wchar_t>(std::wostream& out, wchar_t value);
template void repr_string<char>(std::ostream& out, const char* value);
template void repr_string<wchar_t>(std::wostream& out, const wchar_t* value);
template void format_bool<char>(std::ostream& out, bool value, const FormatSpec& spec);
template void format_bool<wchar_t>(std::wostream& out, bool value, const WFormatSpec& spec);
template void format_int_char<char>(std::ostream& out, std::char_traits<char>::int_type value, const FormatSpec& spec);
template void format_int_char<wchar_t>(std::wostream& out, std::char_traits<wchar_t>::int_type value, const WFormatSpec& spec);
template void format_string<char>(std::ostream& out, const char value[], const FormatSpec& spec);
template void format_string<wchar_t>(std::wostream& out, const wchar_t value[], const WFormatSpec& spec);
template void format_float<char,float>(std::ostream& out, float value, const FormatSpec& spec);
template void format_float<wchar_t,float>(std::wostream& out, float value, const WFormatSpec& spec);
template void format_float<char,double>(std::ostream& out, double value, const FormatSpec& spec);
template void format_float<wchar_t,double>(std::wostream& out, double value, const WFormatSpec& spec);
template void format_float<char,long double>(std::ostream& out, long double value, const FormatSpec& spec);
template void format_float<wchar_t,long double>(std::wostream& out, long double value, const WFormatSpec& spec);
template void format_integer<char,char>(std::ostream& out, char value, const FormatSpec& spec);
template void format_integer<char,short>(std::ostream& out, short value, const FormatSpec& spec);
template void format_integer<char,int>(std::ostream& out, int value, const FormatSpec& spec);
template void format_integer<char,long>(std::ostream& out, long value, const FormatSpec& spec);
template void format_integer<char,long long>(std::ostream& out, long long value, const FormatSpec& spec);
template void format_integer<char,signed char>(std::ostream& out, signed char value, const FormatSpec& spec);
template void format_integer<char,unsigned char>(std::ostream& out, unsigned char value, const FormatSpec& spec);
template void format_integer<char,unsigned short>(std::ostream& out, unsigned short value, const FormatSpec& spec);
template void format_integer<char,unsigned int>(std::ostream& out, unsigned int value, const FormatSpec& spec);
template void format_integer<char,unsigned long>(std::ostream& out, unsigned long value, const FormatSpec& spec);
template void format_integer<char,unsigned long long>(std::ostream& out, unsigned long long value, const FormatSpec& spec);
template void format_integer<wchar_t,wchar_t>(std::wostream& out, wchar_t value, const WFormatSpec& spec);
template void format_integer<wchar_t,char>(std::wostream& out, char value, const WFormatSpec& spec);
template void format_integer<wchar_t,short>(std::wostream& out, short value, const WFormatSpec& spec);
template void format_integer<wchar_t,int>(std::wostream& out, int value, const WFormatSpec& spec);
template void format_integer<wchar_t,long>(std::wostream& out, long value, const WFormatSpec& spec);
template void format_integer<wchar_t,long long>(std::wostream& out, long long value, const WFormatSpec& spec);
template void format_integer<wchar_t,signed char>(std::wostream& out, signed char value, const WFormatSpec& spec);
template void format_integer<wchar_t,unsigned char>(std::wostream& out, unsigned char value, const WFormatSpec& spec);
template void format_integer<wchar_t,unsigned short>(std::wostream& out, unsigned short value, const WFormatSpec& spec);
template void format_integer<wchar_t,unsigned int>(std::wostream& out, unsigned int value, const WFormatSpec& spec);
template void format_integer<wchar_t,unsigned long>(std::wostream& out, unsigned long value, const WFormatSpec& spec);
template void format_integer<wchar_t,unsigned long long>(std::wostream& out, unsigned long long value, const WFormatSpec& spec);
const std::locale impl::basic_grouping<char>::non_grouping_locale(std::locale(), new no_grouping<char>());
const std::locale impl::basic_grouping<char>::thousands_grouping_locale(std::locale(), new group_thousands<char>());
#ifdef FORMATSTRING_CHAR16_SUPPORT
template void repr_bool<char16_t>(std::basic_ostream<char16_t>& out, bool value);
template void repr_char<char16_t>(std::basic_ostream<char16_t>& out, char16_t value);
template void repr_string<char16_t>(std::basic_stream<char16_t>& out, const char16_t* value);
template void format_bool<char16_t>(std::basic_stream<char16_t>& out, bool value, const U16FormatSpec& spec);
template void format_int_char<char16_t>(std::basic_ostream<char16_t>& out, std::char_traits<char16_t>::int_type value, const U16FormatSpec& spec);
template void format_string<char16_t>(std::basic_ostream<char16_t>& out, const char16_t value[], const U16FormatSpec& spec);
template void format_float<char16_t,float>(std::basic_ostream<char16_t>& out, float value, const U16FormatSpec& spec);
template void format_float<char16_t,double>(std::basic_ostream<char16_t>& out, double value, const U16FormatSpec& spec);
template void format_float<char16_t,long double>(std::basic_ostream<char16_t>& out, long double value, const U16FormatSpec& spec);
template void format_integer<char16_t,char16_t>(std::basic_ostream<char16_t>& out, char16_t value, const U16FormatSpec& spec);
template void format_integer<char16_t,char>(std::basic_ostream<char16_t>& out, char value, const U16FormatSpec& spec);
template void format_integer<char16_t,short>(std::basic_ostream<char16_t>& out, short value, const U16FormatSpec& spec);
template void format_integer<char16_t,int>(std::basic_ostream<char16_t>& out, int value, const U16FormatSpec& spec);
template void format_integer<char16_t,long>(std::basic_ostream<char16_t>& out, long value, const U16FormatSpec& spec);
template void format_integer<char16_t,long long>(std::basic_ostream<char16_t>& out, long long value, const U16FormatSpec& spec);
template void format_integer<char16_t,signed char>(std::basic_ostream<char16_t>& out, signed char value, const U16FormatSpec& spec);
template void format_integer<char16_t,unsigned char>(std::basic_ostream<char16_t>& out, unsigned char value, const U16FormatSpec& spec);
template void format_integer<char16_t,unsigned short>(std::basic_ostream<char16_t>& out, unsigned short value, const U16FormatSpec& spec);
template void format_integer<char16_t,unsigned int>(std::basic_ostream<char16_t>& out, unsigned int value, const U16FormatSpec& spec);
template void format_integer<char16_t,unsigned long>(std::basic_ostream<char16_t>& out, unsigned long value, const U16FormatSpec& spec);
template void format_integer<char16_t,unsigned long long>(std::basic_ostream<char16_t>& out, unsigned long long value, const U16FormatSpec& spec);
const std::locale impl::basic_grouping<char16_t>::non_grouping_locale(std::locale(), new no_grouping<char16_t>());
const std::locale impl::basic_grouping<char16_t>::thousands_grouping_locale(std::locale(), new group_thousands<char16_t>());
#endif
#ifdef FORMATSTRING_CHAR32_SUPPORT
template void repr_bool<char32_t>(std::basic_ostream<char32_t>& out, bool value);
template void repr_char<char32_t>(std::basic_ostream<char32_t>& out, char32_t value);
template void repr_string<char32_t>(std::basic_stream<char32_t>& out, const char32_t* value);
template void format_bool<char32_t>(std::basic_stream<char32_t>& out, bool value, const U32FormatSpec& spec);
template void format_int_char<char32_t>(std::basic_ostream<char32_t>& out, std::char_traits<char32_t>::int_type value, const U32FormatSpec& spec);
template void format_string<char32_t>(std::basic_ostream<char32_t>& out, const char32_t value[], const U32FormatSpec& spec);
template void format_float<char32_t,float>(std::basic_ostream<char32_t>& out, float value, const U32FormatSpec& spec);
template void format_float<char32_t,double>(std::basic_ostream<char32_t>& out, double value, const U32FormatSpec& spec);
template void format_float<char32_t,long double>(std::basic_ostream<char32_t>& out, long double value, const U32FormatSpec& spec);
template void format_integer<char32_t,char32_t>(std::basic_ostream<char32_t>& out, char32_t value, const U32FormatSpec& spec);
template void format_integer<char32_t,char>(std::basic_ostream<char16_t>& out, char value, const U32FormatSpec& spec);
template void format_integer<char32_t,short>(std::basic_ostream<char32_t>& out, short value, const U32FormatSpec& spec);
template void format_integer<char32_t,int>(std::basic_ostream<char32_t>& out, int value, const U32FormatSpec& spec);
template void format_integer<char32_t,long>(std::basic_ostream<char32_t>& out, long value, const U32FormatSpec& spec);
template void format_integer<char32_t,long long>(std::basic_ostream<char32_t>& out, long long value, const U32FormatSpec& spec);
template void format_integer<char32_t,signed char>(std::basic_ostream<char32_t>& out, signed char value, const U32FormatSpec& spec);
template void format_integer<char32_t,unsigned char>(std::basic_ostream<char32_t>& out, unsigned char value, const U32FormatSpec& spec);
template void format_integer<char32_t,unsigned short>(std::basic_ostream<char32_t>& out, unsigned short value, const U32FormatSpec& spec);
template void format_integer<char32_t,unsigned int>(std::basic_ostream<char32_t>& out, unsigned int value, const U32FormatSpec& spec);
template void format_integer<char32_t,unsigned long>(std::basic_ostream<char32_t>& out, unsigned long value, const U32FormatSpec& spec);
template void format_integer<char32_t,unsigned long long>(std::basic_ostream<char32_t>& out, unsigned long long value, const U32FormatSpec& spec);
const std::locale impl::basic_grouping<char32_t>::non_grouping_locale(std::locale(), new no_grouping<char32_t>());
const std::locale impl::basic_grouping<char32_t>::thousands_grouping_locale(std::locale(), new group_thousands<char32_t>());
#endif
const std::locale impl::basic_grouping<wchar_t>::non_grouping_locale(std::locale(), new no_grouping<wchar_t>());
const std::locale impl::basic_grouping<wchar_t>::thousands_grouping_locale(std::locale(), new group_thousands<wchar_t>());
| 40.21966 | 153 | 0.631846 | [
"vector"
] |
07b4cb33e4bdea4c9a116aaa6986db32974889b9 | 11,090 | cpp | C++ | VectorEngine/BlueWave.Interop.Asio/AsioDriver.cpp | allenwp/vector-engine | 498d1a0c3eac15e4b8aca3486b42b5e0af790b82 | [
"MIT"
] | 24 | 2020-02-28T21:34:13.000Z | 2022-01-06T10:03:41.000Z | VectorEngine/BlueWave.Interop.Asio/AsioDriver.cpp | allenwp/vector-engine | 498d1a0c3eac15e4b8aca3486b42b5e0af790b82 | [
"MIT"
] | null | null | null | VectorEngine/BlueWave.Interop.Asio/AsioDriver.cpp | allenwp/vector-engine | 498d1a0c3eac15e4b8aca3486b42b5e0af790b82 | [
"MIT"
] | 2 | 2020-02-28T22:53:05.000Z | 2021-08-10T06:35:37.000Z | //
// BlueWave.Interop.Asio by Rob Philpott. Please send all bugs/enhancements to
// rob@bigdevelopments.co.uk. This file and the code contained within is freeware and may be
// distributed and edited without restriction. You may be bound by licencing restrictions
// imposed by Steinberg - check with them prior to distributing anything.
//
#include "stdio.h"
#include "BufferSize.h"
#include "Channel.h"
#include "InstalledDriver.h"
#include "AsioDriver.h"
#include "Channel.h"
#include <vcclr.h>
using namespace System::Diagnostics;
namespace BlueWave
{
namespace Interop
{
namespace Asio
{
array<InstalledDriver^>^ AsioDriver::InstalledDrivers::get()
{
// if we don't know what drivers are installed, ask the InstalledDriver class
if (!_installedDrivers) _installedDrivers = InstalledDriver::GetInstalledDriversFromRegistry();
// and return
return _installedDrivers;
}
// static forward to instance method
void BufferSwitch(long bufferIndex, ASIOBool directProcess)
{
AsioDriver::Instance->OnBufferSwitch(bufferIndex, directProcess);
}
// static forward to instance method
long AsioMessage(long a, long b , void* c , double* d)
{
return AsioDriver::Instance->OnAsioMessage(a, b, c, d);
}
// static forward to instance method
ASIOTime* BufferSwitchTimeInfo(ASIOTime* params, long doubleBufferIndex, ASIOBool directProcess)
{
return AsioDriver::Instance->OnBufferSwitchTimeInfo(params, doubleBufferIndex, directProcess);
}
// static forward to instance method
void SampleRateDidChange(ASIOSampleRate rate)
{
AsioDriver::Instance->OnSampleRateDidChange(rate);
}
// selects a driver into our singleton instance
AsioDriver^ AsioDriver::SelectDriver(InstalledDriver^ installedDriver)
{
// create a new instance of the driver (this will become the singleton)
_instance = gcnew AsioDriver();
// a default maximum of 32 input and output channels unless otherwise told
_instance->InternalSelectDriver(installedDriver);
// and return the instance
return _instance;
}
void AsioDriver::InternalSelectDriver(InstalledDriver^ installedDriver)
{
#if ENABLETRACE
TextWriterTraceListener^ myWriter = gcnew TextWriterTraceListener( "Trace.log" );
Trace::Listeners->Add( myWriter );
#endif
// initialize COM lib
CoInitialize(0);
long inputs, outputs;
// class and interface id for Asio driver
CLSID m_clsid;
// convert from managed string to unmanaged chaos string
pin_ptr<const wchar_t> clsid = PtrToStringChars(installedDriver->ClsId);
// convert string from registry to CLSID
CLSIDFromString((LPOLESTR)clsid, &m_clsid);
// and actually create the object and return its interface (clsid used twice)
LPVOID pAsio = NULL;
HRESULT rc = CoCreateInstance(m_clsid, NULL, CLSCTX_INPROC_SERVER, m_clsid, &pAsio);
// cast the result back to our ASIO interface
_pDriver = (IAsio*) pAsio;
// and we're ready to use it
if (_pDriver->init(0) == ASIOTrue)
{
// get the number of inputs and outputs supported by the driver
_pDriver->getChannels(&inputs, &outputs);
// and remember these (with a host specified ceiling)
_nInputs = inputs;
_nOutputs = outputs;
// create the ASIO callback struct
_pCallbacks = new ASIOCallbacks();
// and convert our delegates to unmanaged typedefs
_pCallbacks->bufferSwitch = BufferSwitch;
_pCallbacks->asioMessage = AsioMessage;
_pCallbacks->bufferSwitchTimeInfo = BufferSwitchTimeInfo;
_pCallbacks->sampleRateDidChange = SampleRateDidChange;
}
else
{
throw gcnew ApplicationException("Driver did not initialise properly");
}
}
// return the singleton instance
AsioDriver^ AsioDriver::Instance::get()
{
return _instance;
}
int AsioDriver::Version::get()
{
// make sure a driver has been engaged
CheckInitialised();
// refer to driver
return _pDriver->getDriverVersion();
}
String^ AsioDriver::DriverName::get()
{
// make sure a driver has been engaged
CheckInitialised();
// refer to driver
char driverName[1000];
_pDriver->getDriverName(driverName);
return gcnew String(driverName);
}
String^ AsioDriver::ErrorMessage::get()
{
// make sure a driver has been engaged
CheckInitialised();
// refer to driver
char errorMessage[1000];
_pDriver->getErrorMessage(errorMessage);
return gcnew String(errorMessage);
}
int AsioDriver::NumberInputChannels::get()
{
// make sure a driver has been engaged
CheckInitialised();
// we got this earlier on
return _nInputs;
}
int AsioDriver::NumberOutputChannels::get()
{
// make sure a driver has been engaged
CheckInitialised();
// we got this earlier on
return _nOutputs;
}
BufferSize^ AsioDriver::BufferSizex::get()
{
// make sure a driver has been engaged
CheckInitialised();
return gcnew BufferSize(_pDriver);
}
double AsioDriver::SampleRate::get()
{
// make sure a driver has been engaged
CheckInitialised();
// refer to driver
double rate;
_pDriver->getSampleRate(&rate);
return rate;
}
void AsioDriver::SetSampleRate(double rate)
{
// make sure a driver has been engaged
CheckInitialised();
_pDriver->setSampleRate(rate);
}
void AsioDriver::CreateBuffers(bool useMaxBufferSize)
{
// we need the total number of channels here
int totalChannels = _nInputs + _nOutputs;
// create our input and output channel arrays
_inputChannels = gcnew array<Channel^>(_nInputs);
_outputChannels = gcnew array<Channel^>(_nOutputs);
// each channel needs a buffer info
ASIOBufferInfo* pBufferInfos = new ASIOBufferInfo[totalChannels];
// now create each input channel and set up its buffer
for (int index = 0; index < _nInputs; index++)
{
pBufferInfos[index].isInput = 1;
pBufferInfos[index].channelNum = index;
pBufferInfos[index].buffers[0] = 0;
pBufferInfos[index].buffers[1] = 0;
}
// and do the same for output channels
for (int index = 0; index < _nOutputs; index++)
{
pBufferInfos[index + _nInputs].isInput = 0;
pBufferInfos[index + _nInputs].channelNum = index;
pBufferInfos[index + _nInputs].buffers[0] = 0;
pBufferInfos[index + _nInputs].buffers[1] = 0;
}
int bufferSize;
if (useMaxBufferSize)
{
// use the drivers maximum buffer size
bufferSize = BufferSizex->m_nMaxSize;
}
else
{
// use the drivers preferred buffer size
bufferSize = BufferSizex->m_nPreferredSize;
}
// get the driver to create its buffers
_pDriver->createBuffers(pBufferInfos, totalChannels, bufferSize, _pCallbacks);
// now go and create the managed channel objects to manipulate these buffers
for (int index = 0; index < _nInputs; index++)
{
_inputChannels[index] = gcnew Channel(_pDriver, true, index,
pBufferInfos[index].buffers[0],
pBufferInfos[index].buffers[1],
bufferSize);
}
for (int index = 0; index < _nOutputs; index++)
{
_outputChannels[index] = gcnew Channel(_pDriver, false, index,
pBufferInfos[index + _nInputs].buffers[0],
pBufferInfos[index + _nInputs].buffers[1],
bufferSize);
}
_outputReadySupport = _pDriver->outputReady();
#if ENABLETRACE
Trace::WriteLine(String::Format("outputReady(): {0}", _outputReadySupport));
#endif
}
void AsioDriver::DisposeBuffers()
{
// make sure a driver has been engaged
CheckInitialised();
_pDriver->disposeBuffers();
}
array<Channel^>^ AsioDriver::InputChannels::get()
{
// make sure a driver has been engaged
CheckInitialised();
return _inputChannels;
}
array<Channel^>^ AsioDriver::OutputChannels::get()
{
// make sure a driver has been engaged
CheckInitialised();
return _outputChannels;
}
void AsioDriver::Start()
{
// make sure a driver has been engaged
CheckInitialised();
_pDriver->start();
}
void AsioDriver::Stop()
{
// make sure a driver has been engaged
CheckInitialised();
_pDriver->stop();
}
void AsioDriver::Release()
{
// only if a driver has been engaged
if (_pDriver != NULL)
{
// release COM object
_pDriver->Release();
_pDriver = NULL;
}
// release COM lib
CoUninitialize();
#if ENABLETRACE
// flush all trace info to disk
Trace::Flush();
#endif
}
void AsioDriver::ShowControlPanel()
{
// make sure a driver has been engaged
CheckInitialised();
_pDriver->controlPanel();
}
void AsioDriver::OnBufferSwitch(long doubleBufferIndex, ASIOBool directProcess)
{
#if ENABLETRACE
Trace::WriteLine(String::Format("OnBufferSwitch({0}, {1})", doubleBufferIndex, directProcess));
#endif
// a buffer switch is occuring, first off,
// tell all channels what buffer needs to be read/written
for (int index = 0; index < _nInputs; index++)
{
_inputChannels[index]->SetDoubleBufferIndex(doubleBufferIndex);
}
for (int index = 0; index < _nOutputs; index++)
{
_outputChannels[index]->SetDoubleBufferIndex(doubleBufferIndex);
}
// next we raise an event so that the caller can do their buffer manipulation
if (_bufferUpdateEvent != nullptr)
{
_bufferUpdateEvent(this, gcnew EventArgs());
}
// notify driver we're done, see ASIO SDK for further explanation
if (_outputReadySupport == ASE_OK)
_pDriver->outputReady();
}
ASIOTime* AsioDriver::OnBufferSwitchTimeInfo(ASIOTime* params, long doubleBufferIndex, ASIOBool directProcess)
{
// no implementation
return nullptr;
}
void AsioDriver::OnSampleRateDidChange(ASIOSampleRate rate)
{
// no implementation
}
long AsioDriver::OnAsioMessage(long selector, long value, void* message, double* opt)
{
#if ENABLETRACE
Trace::WriteLine(String::Format("OnAsioMessage({0})", selector));
#endif
switch (selector)
{
case kAsioSelectorSupported:
switch (value)
{
case kAsioEngineVersion:
return 1;
case kAsioResetRequest:
return 0;
case kAsioBufferSizeChange:
return 0;
case kAsioResyncRequest:
return 0;
case kAsioLatenciesChanged:
return 0;
case kAsioSupportsTimeInfo:
return 1;
case kAsioSupportsTimeCode:
return 1;
}
case kAsioEngineVersion:
return 2;
case kAsioResetRequest:
return 1;
case kAsioBufferSizeChange:
return 0;
case kAsioResyncRequest:
return 0;
case kAsioLatenciesChanged:
return 0;
case kAsioSupportsTimeInfo:
return 0;
case kAsioSupportsTimeCode:
return 0;
}
return 0;
}
void AsioDriver::CheckInitialised()
{
if (_pDriver == NULL)
{
throw gcnew ApplicationException("Select driver first");
}
}
}
}
} | 25.790698 | 113 | 0.676105 | [
"object"
] |
07bdcae7bed47f89f6fa910139dd033ed090f694 | 7,122 | cpp | C++ | src/tdme/audio/AudioStream.cpp | mahula/tdme2 | 0f74d35ae5d2cd33b1a410c09f0d45f250ca7a64 | [
"BSD-3-Clause"
] | null | null | null | src/tdme/audio/AudioStream.cpp | mahula/tdme2 | 0f74d35ae5d2cd33b1a410c09f0d45f250ca7a64 | [
"BSD-3-Clause"
] | null | null | null | src/tdme/audio/AudioStream.cpp | mahula/tdme2 | 0f74d35ae5d2cd33b1a410c09f0d45f250ca7a64 | [
"BSD-3-Clause"
] | null | null | null | #include <tdme/audio/AudioStream.h>
#if defined(__APPLE__)
#include <OpenAL/al.h>
#elif defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__linux__) || defined(_WIN32) || defined(__HAIKU__)
#include <AL/al.h>
#endif
#include <array>
#include <string>
#include <vector>
#include <tdme/utils/ByteBuffer.h>
#include <tdme/audio/Audio.h>
#include <tdme/math/Vector3.h>
#include <tdme/os/filesystem/FileSystemException.h>
#include <tdme/utils/Console.h>
using std::array;
using std::string;
using std::vector;
using std::to_string;
using std::string;
using tdme::audio::AudioStream;
using tdme::utils::ByteBuffer;
using tdme::audio::Audio;
using tdme::math::Vector3;
using tdme::utils::Console;
AudioStream::AudioStream(const string& id) : AudioEntity(id)
{
initiated = false;
alSourceId = Audio::ALSOURCEID_NONE;
sampleRate = 0;
channels = 0;
data = nullptr;
format = -1;
}
AudioStream::~AudioStream() {
}
void AudioStream::setParameters(uint32_t sampleRate, uint8_t channels, const uint32_t bufferSize) {
this->sampleRate = sampleRate;
this->channels = channels;
if (this->data != nullptr) delete data;
this->data = ByteBuffer::allocate(bufferSize);
}
bool AudioStream::isPlayingBuffers() {
ALint state;
alGetSourcei(alSourceId, AL_SOURCE_STATE, &state);
return state == AL_PLAYING;
}
bool AudioStream::isPlaying()
{
return isPlayingBuffers() == true || playing == true;
}
void AudioStream::rewind()
{
}
void AudioStream::play()
{
if (initiated == false)
return;
//
stop();
// update AL properties
updateProperties();
ALsizei buffersToPlay = 0;
for (auto i = 0; i < alBufferIds.size(); i++) {
data->clear();
fillBuffer(data);
// skip if no more data is available
if (data->getPosition() == 0) break;
// otherwise upload
alBufferData(alBufferIds[i], format, data->getBuffer(), data->getPosition(), sampleRate);
//
if (alGetError() != AL_NO_ERROR) {
Console::println(string("AudioStream::play(): '"+ id + "': Could not upload buffer"));
}
buffersToPlay++;
}
alSourceQueueBuffers(alSourceId, buffersToPlay, alBufferIds.data());
if (alGetError() != AL_NO_ERROR) {
Console::println(string("AudioStream::play(): '" + id + "': Could not queue buffers"));
}
alSourcePlay(alSourceId);
if (alGetError() != AL_NO_ERROR) {
Console::println(string("AudioStream::play(): '"+ id + "': Could not play source"));
}
//
playing = true;
}
void AudioStream::pause()
{
if (initiated == false)
return;
alSourcePause(alSourceId);
if (alGetError() != AL_NO_ERROR) {
Console::println(string("AudioStream::pause(): '" + id + "': Could not pause"));
}
}
void AudioStream::stop()
{
if (initiated == false)
return;
alSourceStop(alSourceId);
if (alGetError() != AL_NO_ERROR) {
Console::println(string("AudioStream::stop(): '" + id + "': Could not stop"));
}
// determine queued buffers
ALint queuedBuffers;
alGetSourcei(alSourceId, AL_BUFFERS_QUEUED, &queuedBuffers);
if (alGetError() != AL_NO_ERROR) {
Console::println(string("AudioStream::stop(): '" + id + "': Could not determine queued buffers"));
}
// unqueue buffers
if (queuedBuffers > 0) {
vector<uint32_t> removedBuffers;
removedBuffers.resize(queuedBuffers);
alSourceUnqueueBuffers(alSourceId, queuedBuffers, removedBuffers.data());
if (alGetError() != AL_NO_ERROR) {
Console::println(string("AudioStream::stop(): '" + id + "': Could not unqueue buffers"));
}
}
//
playing = false;
}
bool AudioStream::initialize()
{
switch (channels) {
case(1): format = AL_FORMAT_MONO16; break;
case(2): format = AL_FORMAT_STEREO16; break;
default:
Console::println(string("AudioStream::initialize(): '" + id + "': Unsupported number of channels"));
}
alGenBuffers(alBufferIds.size(), alBufferIds.data());
if (alGetError() != AL_NO_ERROR) {
Console::println(string("AudioStream::initialize(): '" + id + "': Could not generate buffer"));
return false;
}
// create source
alGenSources(1, &alSourceId);
if (alGetError() != AL_NO_ERROR) {
Console::println(string("AudioStream::initialize(): '" + id + "': Could not generate source"));
dispose();
return false;
}
// initiate sound properties
updateProperties();
initiated = true;
return true;
}
void AudioStream::update()
{
if (initiated == false)
return;
// determine processed buffers
int32_t processedBuffers;
alGetSourcei(alSourceId, AL_BUFFERS_PROCESSED, &processedBuffers);
if (alGetError() != AL_NO_ERROR) {
Console::println(string("AudioStream::update(): '" + id + "': Could not determine processed buffers"));
}
if (isPlayingBuffers() == false && playing == true) {
play();
} else {
while (processedBuffers > 0) {
// get a processed buffer id and unqueue it
uint32_t processedBufferId;
alSourceUnqueueBuffers(alSourceId, 1, &processedBufferId);
if (alGetError() != AL_NO_ERROR) {
Console::println(string("AudioStream::update(): '" + id + "': Could not unqueue buffers"));
}
// fill processed buffer again
data->clear();
fillBuffer(data);
// stop buffer if not filled
if (data->getPosition() == 0) {
playing = false;
} else {
// upload buffer data
alBufferData(processedBufferId, format, data->getBuffer(), data->getPosition(), sampleRate);
if (alGetError() != AL_NO_ERROR) {
Console::println(string("AudioStream::update(): '" + id + "': Could not upload buffer"));
}
// queue it
alSourceQueueBuffers(alSourceId, 1, &processedBufferId);
if (alGetError() != AL_NO_ERROR) {
Console::println(string("AudioStream::update(): '" + id + "': Could not queue buffer"));
}
// stop buffer if not filled completely
if (data->getPosition() < data->getCapacity()) {
playing = false;
}
}
// processed it
processedBuffers--;
}
}
// update AL properties
updateProperties();
}
void AudioStream::updateProperties()
{
// update sound properties
alSourcef(alSourceId, AL_PITCH, pitch);
alSourcef(alSourceId, AL_GAIN, gain);
alSourcefv(alSourceId, AL_POSITION, sourcePosition.getArray().data());
alSourcefv(alSourceId, AL_DIRECTION, sourceDirection.getArray().data());
alSourcefv(alSourceId, AL_VELOCITY, sourceVelocity.getArray().data());
if (fixed == true) {
alSourcef(alSourceId, AL_ROLLOFF_FACTOR, 0.0f);
alSourcei(alSourceId, AL_SOURCE_RELATIVE, AL_TRUE);
} else {
alSourcef(alSourceId, AL_ROLLOFF_FACTOR, 1.0f);
alSourcei(alSourceId, AL_SOURCE_RELATIVE, AL_FALSE);
}
}
void AudioStream::dispose()
{
if (initiated == false)
return;
if (alSourceId != Audio::ALSOURCEID_NONE) {
alDeleteSources(1, &alSourceId);
if (alGetError() != AL_NO_ERROR) {
Console::println(string("AudioStream::dispose(): '" + id + "': Could not delete source"));
}
alSourceId = Audio::ALSOURCEID_NONE;
}
// if (alBufferIds != nullptr) {
alDeleteBuffers(alBufferIds.size(), alBufferIds.data());
if (alGetError() != AL_NO_ERROR) {
Console::println(string("AudioStream::dispose(): '" + id + "': Could not delete buffers"));
}
// alBufferIds = nullptr;
// }
if (data != nullptr) {
delete data;
data = nullptr;
}
initiated = false;
}
| 26.875472 | 136 | 0.683235 | [
"vector"
] |
07beef4ea3d63a886d6a0e2f5ec2f8dca8b82c07 | 1,855 | hpp | C++ | miniFE-sycl/src/Vector.hpp | BeauJoh/HeCBench | 594b845171d686dc951971ce36ed59cf114dd2b4 | [
"BSD-3-Clause"
] | 58 | 2020-08-06T18:53:44.000Z | 2021-10-01T07:59:46.000Z | miniFE-sycl/src/Vector.hpp | BeauJoh/HeCBench | 594b845171d686dc951971ce36ed59cf114dd2b4 | [
"BSD-3-Clause"
] | 2 | 2020-12-04T12:35:02.000Z | 2021-03-04T22:49:25.000Z | miniFE-sycl/src/Vector.hpp | BeauJoh/HeCBench | 594b845171d686dc951971ce36ed59cf114dd2b4 | [
"BSD-3-Clause"
] | 13 | 2020-08-19T13:44:18.000Z | 2021-09-08T04:25:34.000Z | #ifndef _Vector_hpp_
#define _Vector_hpp_
//@HEADER
// ************************************************************************
//
// MiniFE: Simple Finite Element Assembly and Solve
// Copyright (2006-2013) Sandia Corporation
//
// Under terms of Contract DE-AC04-94AL85000, there is a non-exclusive
// license for use of this work by or on behalf of the U.S. Government.
//
// This library is free software; you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as
// published by the Free Software Foundation; either version 2.1 of the
// License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
// USA
//
// ************************************************************************
//@HEADER
#include <vector>
namespace miniFE {
template<typename Scalar,
typename LocalOrdinal,
typename GlobalOrdinal>
struct Vector {
typedef Scalar ScalarType;
typedef LocalOrdinal LocalOrdinalType;
typedef GlobalOrdinal GlobalOrdinalType;
Vector(GlobalOrdinal startIdx, LocalOrdinal local_sz)
: startIndex(startIdx),
local_size(local_sz),
coefs(local_size)
{
#pragma omp parallel for
for(MINIFE_LOCAL_ORDINAL i=0; i < local_size; ++i) {
coefs[i] = 0;
}
}
~Vector()
{
}
GlobalOrdinal startIndex;
LocalOrdinal local_size;
std::vector<Scalar> coefs;
};
}//namespace miniFE
#endif
| 26.884058 | 75 | 0.667385 | [
"vector"
] |
07cc007e427ba7c6486fdc753b1d2e7621a69609 | 845 | cpp | C++ | Leetcode/C++ Solutions/Arrays/firstMissingPositive.cpp | Mostofa-Najmus-Sakib/Applied-Algorithm | bc656fd655617407856e0ce45b68585fa81c5035 | [
"MIT"
] | 1 | 2020-01-06T02:21:56.000Z | 2020-01-06T02:21:56.000Z | Leetcode/C++ Solutions/Arrays/firstMissingPositive.cpp | Mostofa-Najmus-Sakib/Applied-Algorithm | bc656fd655617407856e0ce45b68585fa81c5035 | [
"MIT"
] | null | null | null | Leetcode/C++ Solutions/Arrays/firstMissingPositive.cpp | Mostofa-Najmus-Sakib/Applied-Algorithm | bc656fd655617407856e0ce45b68585fa81c5035 | [
"MIT"
] | 3 | 2021-02-22T17:41:01.000Z | 2022-01-13T05:03:19.000Z | /*
LeetCode Problem 41. First Missing Positive
Link: https://leetcode.com/problems/first-missing-positive/
Written by: Mostofa Adib Shakib
Language: C++
*/
class Solution {
public:
int firstMissingPositive(vector<int>& nums) {
int smallestPositive = 1;
sort(nums.begin(), nums.end()); // sort the array into ascending order
nums.erase( unique( nums.begin(), nums.end() ) , nums.end() ); // remove duplicate elements from the array
for (int i = 0; i < nums.size(); i++) {
if (nums[i] <= 0) {
continue;
}
else if ( nums[i] == smallestPositive ) {
smallestPositive++;
}
else {
break;
}
}
return smallestPositive;
}
}; | 27.258065 | 119 | 0.504142 | [
"vector"
] |
07cc57f775efc2898521a3ef825f338ac7f2a6cc | 4,664 | hpp | C++ | test_tf2/test/permuter.hpp | ymd-stella/geometry2 | 0188f9bdac47c32cd0563b41d24d13d79ce9437e | [
"BSD-3-Clause"
] | null | null | null | test_tf2/test/permuter.hpp | ymd-stella/geometry2 | 0188f9bdac47c32cd0563b41d24d13d79ce9437e | [
"BSD-3-Clause"
] | null | null | null | test_tf2/test/permuter.hpp | ymd-stella/geometry2 | 0188f9bdac47c32cd0563b41d24d13d79ce9437e | [
"BSD-3-Clause"
] | 1 | 2020-11-14T17:08:06.000Z | 2020-11-14T17:08:06.000Z | /*
* Copyright (c) 2009, Willow Garage, 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 the name of the Willow Garage, Inc. 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.
*/
/** \author Tully Foote */
#ifndef ROSTEST_PERMUTER_HPP
#define ROSTEST_PERMUTER_HPP
#include <mutex>
#include <vector>
namespace rostest
{
/** \brief A base class for storing pointers to generic data types
*/
class PermuteOptionBase
{
public:
virtual void reset() = 0;
virtual bool step() = 0;
virtual ~PermuteOptionBase() {};
};
/**\brief A class to hold a set of option values and currently used state
* This class holds
*/
template<class T>
class PermuteOption : public PermuteOptionBase
{
public:
PermuteOption(const std::vector<T>& options, T* output)
{
options_ = options;
output_ = output;
reset();
}
virtual ~PermuteOption(){};
void reset()
{
std::lock_guard<std::mutex> lock(access_mutex_);
current_element_ = options_.begin();
*output_ = *current_element_;
}
bool step()
{
std::lock_guard<std::mutex> lock(access_mutex_);
current_element_++;
if (current_element_ == options_.end())
return false;
*output_ = *current_element_;
return true;
}
private:
/// Local storage of the possible values
std::vector<T> options_;
/// The output variable
T* output_;
typedef typename std::vector<T>::iterator V_T_iterator;
/// The last updated element
V_T_iterator current_element_;
std::mutex access_mutex_;
};
/** \brief A class to provide easy permutation of options
* This class provides a way to collapse independent
* permutations of options into a single loop.
*/
class Permuter
{
public:
/** \brief Destructor to clean up allocated data */
virtual ~Permuter(){ clearAll();};
/** \brief Add a set of values and an output to the iteration
* @param values The set of possible values for this output
* @param output The value to set at each iteration
*/
template<class T>
void addOptionSet(const std::vector<T>& values, T* output)
{
std::lock_guard<std::mutex> lock(access_mutex_);
options_.emplace_back(std::make_unique<PermuteOption<T>>(values, output));
reset();
}
/** \brief Reset the internal counters */
void reset()
{
for (unsigned int level= 0; level < options_.size(); level++)
{
options_[level]->reset();
}
}
/** \brief Iterate to the next value in the iteration
* Returns true unless done iterating.
*/
bool step()
{
std::lock_guard<std::mutex> lock(access_mutex_);
// base case just iterating
for (size_t level = 0; level < options_.size(); level++)
{
if(options_[level]->step())
{
//printf("stepping level %d returning true \n", level);
return true;
}
else
{
//printf("reseting level %d\n", level);
options_[level]->reset();
}
}
return false;
}
/** \brief Clear all stored data */
void clearAll()
{
std::lock_guard<std::mutex> lock(access_mutex_);
options_.clear();
}
private:
std::vector<std::unique_ptr<PermuteOptionBase>> options_; ///< Store all the option objects
std::mutex access_mutex_;
};
}
#endif //ROSTEST_PERMUTER_HPP
| 27.435294 | 93 | 0.689108 | [
"vector"
] |
07d072471c7ff72cce0bffbcbcfbb5e388e71b9c | 4,390 | cpp | C++ | pagemodular.cpp | Maou-Senpai/referenCe | 839837d88053c96f31ae37356316ca7b30adb95e | [
"MIT"
] | null | null | null | pagemodular.cpp | Maou-Senpai/referenCe | 839837d88053c96f31ae37356316ca7b30adb95e | [
"MIT"
] | null | null | null | pagemodular.cpp | Maou-Senpai/referenCe | 839837d88053c96f31ae37356316ca7b30adb95e | [
"MIT"
] | null | null | null | //Header Files
#include "pagemodular.h"
// Initializes dictionaries
PageModular::PageModular()
{
}
// FUNCTION NAME: showPage()
//
// PARAMETERS: None
//
// RETURN VALUE: None
//
// CALLS TO: mainwindow.ui
//
// CALLED FROM: none
//
// METHOD:
//
// Creates the elements of the page
void PageModular::showPage()
{
addHeader("Modular Programming");
addParagraphTitle("Header File");
addParagraph("This is used to separate function definitions into a new file.");
addExampleByFile("Sample Header File (header.h)", ":/cpp/content/header.h");
addParagraph("To include the header file, use: #include \"headerFileName.h\". The files should be located in the same folder.");
addExampleByFile("Sample Code Including header.h", ":/cpp/content/header.cpp");
sampleSimulation1();
}
// FUNCTION NAME: getDictionaries(std::vector<std::vector<dictionary *> *> *)
//
// PARAMETERS: std::vector<std::vector<dictionary *> *> *
//
// RETURN VALUE: None
//
// CALLS TO: mainwindow.ui
//
// CALLED FROM: none
//
// METHOD:
//
// To be used for the search function
// This will be called by the mainwindow
void PageModular::getDictionaries(std::vector<std::vector<dictionary *> *> *)
{
// No Dictionaries Here
}
// FUNCTION NAME: sample1Simulation()
//
// PARAMETERS: None
//
// RETURN VALUE: None
//
// CALLS TO: mainwindow.ui
//
// CALLED FROM: none
//
// METHOD:
//
// This is a sample simulation of the first sample code
// Modified to make it work in Qt
void PageModular::sampleSimulation1()
{
CustomString collectText;
int choice, num1, num2, ans = 0;
printMenu(&collectText);
collectText.appendText("Input Choice: 2\n");
choice = 2;
collectText.appendText("Input First Number: 5\n");
num1 = 5;
collectText.appendText("Input Second Number: 3\n");
num2 = 3;
if (choice == 1) ans = add(num1, num2);
else if (choice == 2) ans = subtract(num1, num2);
else if (choice == 3) ans = multiply(num1, num2);
else if (choice == 4) ans = divide(num1, num2);
collectText.appendText("\nAnswer: ");
collectText.appendText(ans);
addExample("Sample Simulation", collectText.getCustomString());
}
// FUNCTION NAME: add(int x, int y)
//
// PARAMETERS: int x - operand 1
// int y - operand 2
//
// RETURN VALUE: sum of x and y
//
// CALLS TO: mainwindow.ui
//
// CALLED FROM: none
//
// METHOD:
//
// This function adds the user input.
int PageModular::add(int x, int y) {
int tempAns = x + y;
return tempAns;
}
// FUNCTION NAME: subtract(int x, int y)
//
// PARAMETERS: int x - operand 1
// int y - operand 2
//
// RETURN VALUE: difference of x and y
//
// CALLS TO: mainwindow.ui
//
// CALLED FROM: none
//
// METHOD:
//
// This function computes the difference of the user input.
int PageModular::subtract(int x, int y) {
int tempAns = x - y;
return tempAns;
}
// FUNCTION NAME: multiply(int x, int y)
//
// PARAMETERS: int x - operand 1
// int y - operand 2
//
// RETURN VALUE: multiplication of x and y
//
// CALLS TO: mainwindow.ui
//
// CALLED FROM: none
//
// METHOD:
//
// This function computes the multiplication of the user input.
int PageModular::multiply(int x, int y) {
int tempAns = x * y;
return tempAns;
}
// FUNCTION NAME: divide(int x, int y)
//
// PARAMETERS: int x - operand 1
// int y - operand 2
//
// RETURN VALUE: division of x and y
//
// CALLS TO: mainwindow.ui
//
// CALLED FROM: none
//
// METHOD:
//
// This function computes the division of the user input.
int PageModular::divide(int x, int y) {
int tempAns = x / y;
return tempAns;
}
// FUNCTION NAME: printMenu(CustomString *collectText)
//
// PARAMETERS: CustomString *collectText
//
// RETURN VALUE: None
//
// CALLS TO: mainwindow.ui
//
// CALLED FROM: none
//
// METHOD:
//
// This function shows a menu for the user to pick an operation
void PageModular::printMenu(CustomString *collectText) {
collectText->appendText("Pick An Operation:\n");
collectText->appendText("1: Addition\n");
collectText->appendText("2: Subtraction\n");
collectText->appendText("3: Multiplication\n");
collectText->appendText("4: Division\n\n");
}
| 22.512821 | 133 | 0.624146 | [
"vector"
] |
07d830675101a2066e54beb2edcb74c7288db16a | 44,541 | cpp | C++ | Engine/Plugins/Media/MfMedia/Source/MfMedia/Private/Mf/MfMediaUtils.cpp | windystrife/UnrealEngine_NVIDIAGameWork | b50e6338a7c5b26374d66306ebc7807541ff815e | [
"MIT"
] | 1 | 2022-01-29T18:36:12.000Z | 2022-01-29T18:36:12.000Z | Engine/Plugins/Media/MfMedia/Source/MfMedia/Private/Mf/MfMediaUtils.cpp | windystrife/UnrealEngine_NVIDIAGameWork | b50e6338a7c5b26374d66306ebc7807541ff815e | [
"MIT"
] | null | null | null | Engine/Plugins/Media/MfMedia/Source/MfMedia/Private/Mf/MfMediaUtils.cpp | windystrife/UnrealEngine_NVIDIAGameWork | b50e6338a7c5b26374d66306ebc7807541ff815e | [
"MIT"
] | null | null | null | // Copyright 1998-2017 Epic Games, Inc. All Rights Reserved.
#include "MfMediaUtils.h"
#if MFMEDIA_SUPPORTED_PLATFORM
#include "HAL/FileManager.h"
#include "HAL/PlatformProcess.h"
#include "Misc/FileHelper.h"
#include "Serialization/Archive.h"
#include "Serialization/ArrayReader.h"
#include "MfMediaByteStream.h"
#include "MfMediaPrivate.h"
#if PLATFORM_WINDOWS
#include "AllowWindowsPlatformTypes.h"
#else
#include "XboxOneAllowPlatformTypes.h"
#endif
namespace MfMedia
{
TComPtr<IMFMediaType> CreateOutputType(const GUID& MajorType, const GUID& SubType, bool AllowNonStandardCodecs)
{
TComPtr<IMFMediaType> OutputType;
{
HRESULT Result = ::MFCreateMediaType(&OutputType);
if (FAILED(Result))
{
UE_LOG(LogMfMedia, Warning, TEXT("Failed to create %s output type: %s"), *MajorTypeToString(MajorType), *ResultToString(Result));
return NULL;
}
Result = OutputType->SetUINT32(MF_MT_ALL_SAMPLES_INDEPENDENT, TRUE);
if (FAILED(Result))
{
UE_LOG(LogMfMedia, Warning, TEXT("Failed to initialize %s output type: %s"), *MajorTypeToString(MajorType), *ResultToString(Result));
return NULL;
}
}
if (MajorType == MFMediaType_Audio)
{
#if PLATFORM_XBOXONE
// filter unsupported audio formats (XboxOne only supports AAC)
if (SubType != MFAudioFormat_AAC)
{
UE_LOG(LogMfMedia, Warning, TEXT("Skipping unsupported audio type %s (%s) \"%s\""), *SubTypeToString(SubType), *GuidToString(SubType), *FourccToString(SubType.Data1));
return NULL;
}
#else
// filter unsupported audio formats
if (FMemory::Memcmp(&SubType.Data2, &MFMPEG4Format_Base.Data2, 12) == 0)
{
if (AllowNonStandardCodecs)
{
UE_LOG(LogMfMedia, Verbose, TEXT("Allowing non-standard MP4 audio type %s (%s) \"%s\""), *SubTypeToString(SubType), *GuidToString(SubType), *FourccToString(SubType.Data1));
}
else
{
const bool DocumentedFormat =
(SubType.Data1 == WAVE_FORMAT_ADPCM) ||
(SubType.Data1 == WAVE_FORMAT_ALAW) ||
(SubType.Data1 == WAVE_FORMAT_MULAW) ||
(SubType.Data1 == WAVE_FORMAT_IMA_ADPCM) ||
(SubType.Data1 == MFAudioFormat_AAC.Data1) ||
(SubType.Data1 == MFAudioFormat_MP3.Data1) ||
(SubType.Data1 == MFAudioFormat_PCM.Data1);
const bool UndocumentedFormat =
(SubType.Data1 == WAVE_FORMAT_WMAUDIO2) ||
(SubType.Data1 == WAVE_FORMAT_WMAUDIO3) ||
(SubType.Data1 == WAVE_FORMAT_WMAUDIO_LOSSLESS);
if (!DocumentedFormat && !UndocumentedFormat)
{
UE_LOG(LogMfMedia, Warning, TEXT("Skipping non-standard MP4 audio type %s (%s) \"%s\""), *SubTypeToString(SubType), *GuidToString(SubType), *FourccToString(SubType.Data1));
return NULL;
}
}
}
else if (FMemory::Memcmp(&SubType.Data2, &MFAudioFormat_Base.Data2, 12) != 0)
{
if (AllowNonStandardCodecs)
{
UE_LOG(LogMfMedia, Verbose, TEXT("Allowing non-standard audio type %s (%s) \"%s\""), *SubTypeToString(SubType), *GuidToString(SubType), *FourccToString(SubType.Data1));
}
else
{
UE_LOG(LogMfMedia, Warning, TEXT("Skipping non-standard audio type %s (%s) \"%s\""), *SubTypeToString(SubType), *GuidToString(SubType), *FourccToString(SubType.Data1));
return NULL;
}
}
#endif //PLATFORM_XBOXONE
// configure audio output
if (FAILED(OutputType->SetGUID(MF_MT_MAJOR_TYPE, MFMediaType_Audio)) ||
FAILED(OutputType->SetGUID(MF_MT_SUBTYPE, MFAudioFormat_PCM)) ||
FAILED(OutputType->SetUINT32(MF_MT_AUDIO_BITS_PER_SAMPLE, 16u)))
//FAILED(OutputType->SetGUID(MF_MT_SUBTYPE, MFAudioFormat_Float)) ||
//FAILED(OutputType->SetUINT32(MF_MT_AUDIO_BITS_PER_SAMPLE, 32u)))
{
UE_LOG(LogMfMedia, Warning, TEXT("Failed to initialize audio output type"));
return NULL;
}
}
else if (MajorType == MFMediaType_SAMI)
{
// configure caption output
const HRESULT Result = OutputType->SetGUID(MF_MT_MAJOR_TYPE, MFMediaType_SAMI);
if (FAILED(Result))
{
UE_LOG(LogMfMedia, Warning, TEXT("Failed to initialize caption output type: %s"), *ResultToString(Result));
return NULL;
}
}
else if (MajorType == MFMediaType_Video)
{
#if PLATFORM_XBOXONE
// filter unsupported video types (XboxOne only supports H.264)
if ((SubType != MFVideoFormat_H264) && (SubType == MFVideoFormat_H264_ES))
{
UE_LOG(LogMfMedia, Warning, TEXT("Unsupported video type %s (%s) \"%i\""), *SubTypeToString(SubType), *GuidToString(SubType), *FourccToString(SubType.Data1));
return NULL;
}
#else
// filter unsupported video types
if (FMemory::Memcmp(&SubType.Data2, &MFVideoFormat_Base.Data2, 12) != 0)
{
if (AllowNonStandardCodecs)
{
UE_LOG(LogMfMedia, Verbose, TEXT("Allowing non-standard video type %s (%s) \"%s\""), *SubTypeToString(SubType), *GuidToString(SubType), *FourccToString(SubType.Data1));
}
else
{
UE_LOG(LogMfMedia, Warning, TEXT("Skipping non-standard video type %s (%s) \"%s\""), *SubTypeToString(SubType), *GuidToString(SubType), *FourccToString(SubType.Data1));
return NULL;
}
}
if ((SubType == MFVideoFormat_HEVC) && !FWindowsPlatformMisc::VerifyWindowsVersion(10, 0))
{
UE_LOG(LogMfMedia, Warning, TEXT("Your Windows version is %s"), *FPlatformMisc::GetOSVersion());
if ((SubType == MFVideoFormat_HEVC) && !FWindowsPlatformMisc::VerifyWindowsVersion(6, 2))
{
UE_LOG(LogMfMedia, Warning, TEXT("HEVC video type requires Windows 10 or newer"));
return NULL;
}
UE_LOG(LogMfMedia, Warning, TEXT("HEVC video type requires Windows 10 or newer (game must be manifested for Windows 10)"));
}
#endif //PLATFORM_XBOXONE
// configure video output
HRESULT Result = OutputType->SetGUID(MF_MT_MAJOR_TYPE, MFMediaType_Video);
if (FAILED(Result))
{
UE_LOG(LogMfMedia, Warning, TEXT("Failed to set video output type: %s"), *ResultToString(Result));
return NULL;
}
#if PLATFORM_XBOXONE
Result = OutputType->SetGUID(MF_MT_SUBTYPE, MFVideoFormat_NV12); // XboxOne only supports NV12
#else
Result = OutputType->SetGUID(MF_MT_SUBTYPE, (SubType == MFVideoFormat_RGB32) ? MFVideoFormat_RGB32 : MFVideoFormat_NV12);
#endif
if (FAILED(Result))
{
UE_LOG(LogMfMedia, Warning, TEXT("Failed to set video output sub-type: %s"), *ResultToString(Result));
return NULL;
}
}
else
{
return NULL; // unsupported input type
}
return OutputType;
}
FString FourccToString(unsigned long Fourcc)
{
return FString::Printf(TEXT("%c%c%c%c"),
(Fourcc >> 24) & 0xff,
(Fourcc >> 16) & 0xff,
(Fourcc >> 8) & 0xff,
Fourcc & 0xff
);
}
FString GuidToString(const GUID& Guid)
{
return FString::Printf(TEXT("%08x-%04x-%04x-%08x%08x"),
Guid.Data1,
Guid.Data2,
Guid.Data3,
*((unsigned long*)&Guid.Data4[0]),
*((unsigned long*)&Guid.Data4[4])
);
}
FString MajorTypeToString(const GUID& MajorType)
{
if (MajorType == MFMediaType_Default) return TEXT("Default");
if (MajorType == MFMediaType_Audio) return TEXT("Audio");
if (MajorType == MFMediaType_Video) return TEXT("Video");
if (MajorType == MFMediaType_Protected) return TEXT("Protected");
if (MajorType == MFMediaType_SAMI) return TEXT("SAMI");
if (MajorType == MFMediaType_Script) return TEXT("Script");
if (MajorType == MFMediaType_Image) return TEXT("Image");
if (MajorType == MFMediaType_HTML) return TEXT("HTML");
if (MajorType == MFMediaType_Binary) return TEXT("Binary");
if (MajorType == MFMediaType_FileTransfer) return TEXT("FileTransfer");
if (MajorType == MFMediaType_Stream) return TEXT("Stream");
return GuidToString(MajorType);
}
FString MediaEventToString(MediaEventType Event)
{
switch (Event)
{
case MEUnknown: return TEXT("Unknown");
case MEError: return TEXT("Error");
case MEExtendedType: return TEXT("Extended Type");
case MENonFatalError: return TEXT("Non-fatal Error");
case MESessionUnknown: return TEXT("Session Unknown");
case MESessionTopologySet: return TEXT("Session Topology Set");
case MESessionTopologiesCleared: return TEXT("Session Topologies Cleared");
case MESessionStarted: return TEXT("Session Started");
case MESessionPaused: return TEXT("Session Paused");
case MESessionStopped: return TEXT("Session Stopped");
case MESessionClosed: return TEXT("Session Closed");
case MESessionEnded: return TEXT("Session Ended");
case MESessionRateChanged: return TEXT("Session Rate Changed");
case MESessionScrubSampleComplete: return TEXT("Session Scrub Sample Complete");
case MESessionCapabilitiesChanged: return TEXT("Session Capabilities Changed");
case MESessionTopologyStatus: return TEXT("Session Topology Status");
case MESessionNotifyPresentationTime: return TEXT("Session Notify Presentation Time");
case MENewPresentation: return TEXT("New Presentation");
case MELicenseAcquisitionStart: return TEXT("License Acquisition Start");
case MELicenseAcquisitionCompleted: return TEXT("License Acquisition Completed");
case MEIndividualizationStart: return TEXT("Individualization Start");
case MEIndividualizationCompleted: return TEXT("Individualization Completed");
case MEEnablerProgress: return TEXT("Enabler Progress");
case MEEnablerCompleted: return TEXT("Enabler Completed");
case MEPolicyError: return TEXT("Policy Error");
case MEPolicyReport: return TEXT("Policy Report");
case MEBufferingStarted: return TEXT("Buffering Started");
case MEBufferingStopped: return TEXT("Buffering Stopped");
case MEConnectStart: return TEXT("Connect Start");
case MEConnectEnd: return TEXT("Connect End");
case MEReconnectStart: return TEXT("Reconnect Start");
case MEReconnectEnd: return TEXT("Reconnect End");
case MERendererEvent: return TEXT("Renderer Event");
case MESessionStreamSinkFormatChanged: return TEXT("Session Stream Sink Format Changed");
case MESourceUnknown: return TEXT("Source Unknown");
case MESourceStarted: return TEXT("Source Started");
case MEStreamStarted: return TEXT("Stream Started");
case MESourceSeeked: return TEXT("Source Seeked");
case MEStreamSeeked: return TEXT("Stream Seeked");
case MENewStream: return TEXT("New Stream");
case MEUpdatedStream: return TEXT("Updated Stream");
case MESourceStopped: return TEXT("Source Stopped");
case MEStreamStopped: return TEXT("Stream Stopped");
case MESourcePaused: return TEXT("Source Paused");
case MEStreamPaused: return TEXT("Stream Paused");
case MEEndOfPresentation: return TEXT("End of Presentation");
case MEEndOfStream: return TEXT("End of Stream");
case MEMediaSample: return TEXT("Media Sample");
case MEStreamTick: return TEXT("Stream Tick");
case MEStreamThinMode: return TEXT("Stream Thin Mode");
case MEStreamFormatChanged: return TEXT("Stream Format Changed");
case MESourceRateChanged: return TEXT("Source Rate Changed");
case MEEndOfPresentationSegment: return TEXT("End of Presentation Segment");
case MESourceCharacteristicsChanged: return TEXT("Source Characteristics Changed");
case MESourceRateChangeRequested: return TEXT("Source Rate Change Requested");
case MESourceMetadataChanged: return TEXT("Source Metadata Changed");
case MESequencerSourceTopologyUpdated: return TEXT("Sequencer Source Topology Updated");
case MESinkUnknown: return TEXT("Sink Unknown");
case MEStreamSinkStarted: return TEXT("Stream Sink Started");
case MEStreamSinkStopped: return TEXT("Stream Sink Stopped");
case MEStreamSinkPaused: return TEXT("Strema Sink Paused");
case MEStreamSinkRateChanged: return TEXT("Stream Sink Rate Changed");
case MEStreamSinkRequestSample: return TEXT("Stream Sink Request Sample");
case MEStreamSinkMarker: return TEXT("Stream Sink Marker");
case MEStreamSinkPrerolled: return TEXT("Stream Sink Prerolled");
case MEStreamSinkScrubSampleComplete: return TEXT("Stream Sink Scrub Sample Complete");
case MEStreamSinkFormatChanged: return TEXT("Stream Sink Format Changed");
case MEStreamSinkDeviceChanged: return TEXT("Stream Sink Device Changed");
case MEQualityNotify: return TEXT("Quality Notify");
case MESinkInvalidated: return TEXT("Sink Invalidated");
case MEAudioSessionNameChanged: return TEXT("Audio Session Name Changed");
case MEAudioSessionVolumeChanged: return TEXT("Audio Session Volume Changed");
case MEAudioSessionDeviceRemoved: return TEXT("Audio Session Device Removed");
case MEAudioSessionServerShutdown: return TEXT("Audio Session Server Shutdown");
case MEAudioSessionGroupingParamChanged: return TEXT("Audio Session Grouping Param Changed");
case MEAudioSessionIconChanged: return TEXT("Audio Session Icion Changed");
case MEAudioSessionFormatChanged: return TEXT("Audio Session Format Changed");
case MEAudioSessionDisconnected: return TEXT("Audio Session Disconnected");
case MEAudioSessionExclusiveModeOverride: return TEXT("Audio Session Exclusive Mode Override");
case MECaptureAudioSessionVolumeChanged: return TEXT("Capture Audio Session Volume Changed");
case MECaptureAudioSessionDeviceRemoved: return TEXT("Capture Audio Session Device Removed");
case MECaptureAudioSessionFormatChanged: return TEXT("Capture Audio Session Format Changed");
case MECaptureAudioSessionDisconnected: return TEXT("Capture Audio Session Disconnected");
case MECaptureAudioSessionExclusiveModeOverride: return TEXT("Capture Audio Session Exclusive Mode Override");
case MECaptureAudioSessionServerShutdown: return TEXT("Capture Audio Session Server Shutdown");
case METrustUnknown: return TEXT("Trust Unknown");
case MEPolicyChanged: return TEXT("Policy Changed");
case MEContentProtectionMessage: return TEXT("Content Protection Message");
case MEPolicySet: return TEXT("Policy Set");
case MEWMDRMLicenseBackupCompleted: return TEXT("WM DRM License Backup Completed");
case MEWMDRMLicenseBackupProgress: return TEXT("WM DRM License Backup Progress");
case MEWMDRMLicenseRestoreCompleted: return TEXT("WM DRM License Restore Completed");
case MEWMDRMLicenseRestoreProgress: return TEXT("WM DRM License Restore Progress");
case MEWMDRMLicenseAcquisitionCompleted: return TEXT("WM DRM License Acquisition Completed");
case MEWMDRMIndividualizationCompleted: return TEXT("WM DRM Individualization Completed");
case MEWMDRMIndividualizationProgress: return TEXT("WM DRM Individualization Progress");
case MEWMDRMProximityCompleted: return TEXT("WM DRM Proximity Completed");
case MEWMDRMLicenseStoreCleaned: return TEXT("WM DRM License Store Cleaned");
case MEWMDRMRevocationDownloadCompleted: return TEXT("WM DRM Revocation Download Completed");
case METransformUnknown: return TEXT("Transform Unkonwn");
case METransformNeedInput: return TEXT("Transform Need Input");
case METransformHaveOutput: return TEXT("Transform Have Output");
case METransformDrainComplete: return TEXT("Transform Drain Complete");
case METransformMarker: return TEXT("Transform Marker");
case MEByteStreamCharacteristicsChanged: return TEXT("Byte Stream Characteristics Changed");
case MEVideoCaptureDeviceRemoved: return TEXT("Video Capture Device Removed");
case MEVideoCaptureDevicePreempted: return TEXT("Video Capture Device Preempted");
default:
return FString::Printf(TEXT("Unknown event %i"), Event);
}
}
TComPtr<IMFMediaSource> ResolveMediaSource(TSharedPtr<FArchive, ESPMode::ThreadSafe> Archive, const FString& Url, bool Precache)
{
// load media source
if (!Archive.IsValid() && Url.StartsWith(TEXT("file://")))
{
const TCHAR* FilePath = &Url[7];
if (Precache)
{
FArrayReader* Reader = new FArrayReader;
if (FFileHelper::LoadFileToArray(*Reader, FilePath))
{
Archive = MakeShareable(Reader);
}
else
{
delete Reader;
}
}
else
{
Archive = MakeShareable(IFileManager::Get().CreateFileReader(FilePath));
}
if (!Archive.IsValid())
{
UE_LOG(LogMfMedia, Error, TEXT("Failed to open or read media file %s"), FilePath);
return NULL;
}
if (Archive->TotalSize() == 0)
{
UE_LOG(LogMfMedia, Error, TEXT("Cannot open media from empty file %s."), FilePath);
return NULL;
}
}
// create source resolver
TComPtr<IMFSourceResolver> SourceResolver;
{
const HRESULT Result = ::MFCreateSourceResolver(&SourceResolver);
if (FAILED(Result))
{
UE_LOG(LogMfMedia, Error, TEXT("Failed to create media source resolver: %s"), *MfMedia::ResultToString(Result));
return NULL;
}
}
// resolve media source
TComPtr<IUnknown> SourceObject;
{
MF_OBJECT_TYPE ObjectType;
if (Archive.IsValid())
{
TComPtr<FMfMediaByteStream> ByteStream = new FMfMediaByteStream(Archive.ToSharedRef());
const HRESULT Result = SourceResolver->CreateObjectFromByteStream(ByteStream, *Url, MF_RESOLUTION_MEDIASOURCE, NULL, &ObjectType, &SourceObject);
if (FAILED(Result))
{
UE_LOG(LogMfMedia, Error, TEXT("Failed to resolve byte stream %s: %s"), *Url, *MfMedia::ResultToString(Result));
return NULL;
}
}
else
{
const HRESULT Result = SourceResolver->CreateObjectFromURL(*Url, MF_RESOLUTION_MEDIASOURCE, NULL, &ObjectType, &SourceObject);
if (FAILED(Result))
{
UE_LOG(LogMfMedia, Error, TEXT("Failed to resolve URL %s: %s"), *Url, *MfMedia::ResultToString(Result));
return NULL;
}
}
}
// get media source interface
TComPtr<IMFMediaSource> MediaSource;
{
const HRESULT Result = SourceObject->QueryInterface(IID_PPV_ARGS(&MediaSource));
if (FAILED(Result))
{
UE_LOG(LogMfMedia, Error, TEXT("Failed to query media source interface: %s"), *MfMedia::ResultToString(Result));
return NULL;
}
}
return MediaSource;
}
FString ResultToString(HRESULT Result)
{
void* DllHandle = nullptr;
// load error resource library
if (HRESULT_FACILITY(Result) == FACILITY_MF)
{
const LONG Code = HRESULT_CODE(Result);
if (((Code >= 0) && (Code <= 1199)) || ((Code >= 3000) && (Code <= 13999)))
{
static void* WmErrorDll = nullptr;
if (WmErrorDll == nullptr)
{
WmErrorDll = FPlatformProcess::GetDllHandle(TEXT("wmerror.dll"));
}
DllHandle = WmErrorDll;
}
else if ((Code >= 2000) && (Code <= 2999))
{
static void* AsfErrorDll = nullptr;
if (AsfErrorDll == nullptr)
{
AsfErrorDll = FPlatformProcess::GetDllHandle(TEXT("asferror.dll"));
}
DllHandle = AsfErrorDll;
}
else if ((Code >= 14000) & (Code <= 44999))
{
static void* MfErrorDll = nullptr;
if (MfErrorDll == nullptr)
{
MfErrorDll = FPlatformProcess::GetDllHandle(TEXT("mferror.dll"));
}
DllHandle = MfErrorDll;
}
}
TCHAR Buffer[1024];
Buffer[0] = TEXT('\0');
DWORD BufferLength = 0;
// resolve error code
if (DllHandle != nullptr)
{
BufferLength = FormatMessage(FORMAT_MESSAGE_FROM_HMODULE | FORMAT_MESSAGE_IGNORE_INSERTS, DllHandle, Result, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), Buffer, 1024, NULL);
}
else
{
BufferLength = FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, Result, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), Buffer, 1024, NULL);
}
if (BufferLength == 0)
{
return FString::Printf(TEXT("0x%08x"), Result);
}
// remove line break
TCHAR* NewLine = FCString::Strchr(Buffer, TEXT('\r'));
if (NewLine != nullptr)
{
*NewLine = TEXT('\0');
}
return Buffer;
}
FString SubTypeToString(const GUID& SubType)
{
if (SubType == GUID_NULL) return TEXT("Null");
// image formats
if (SubType == MFImageFormat_JPEG) return TEXT("Jpeg");
if (SubType == MFImageFormat_RGB32) return TEXT("RGB32");
// stream formats
if (SubType == MFStreamFormat_MPEG2Transport) return TEXT("MPEG-2 Transport");
if (SubType == MFStreamFormat_MPEG2Program) return TEXT("MPEG-2 Program");
// video formats
if (SubType == MFVideoFormat_RGB32) return TEXT("RGB32");
if (SubType == MFVideoFormat_ARGB32) return TEXT("ARGB32");
if (SubType == MFVideoFormat_RGB24) return TEXT("RGB24");
if (SubType == MFVideoFormat_RGB555) return TEXT("RGB525");
if (SubType == MFVideoFormat_RGB565) return TEXT("RGB565");
if (SubType == MFVideoFormat_RGB8) return TEXT("RGB8");
if (SubType == MFVideoFormat_AI44) return TEXT("AI44");
if (SubType == MFVideoFormat_AYUV) return TEXT("AYUV");
if (SubType == MFVideoFormat_YUY2) return TEXT("YUY2");
if (SubType == MFVideoFormat_YVYU) return TEXT("YVYU");
if (SubType == MFVideoFormat_YVU9) return TEXT("YVU9");
if (SubType == MFVideoFormat_UYVY) return TEXT("UYVY");
if (SubType == MFVideoFormat_NV11) return TEXT("NV11");
if (SubType == MFVideoFormat_NV12) return TEXT("NV12");
if (SubType == MFVideoFormat_YV12) return TEXT("YV12");
if (SubType == MFVideoFormat_I420) return TEXT("I420");
if (SubType == MFVideoFormat_IYUV) return TEXT("IYUV");
if (SubType == MFVideoFormat_Y210) return TEXT("Y210");
if (SubType == MFVideoFormat_Y216) return TEXT("Y216");
if (SubType == MFVideoFormat_Y410) return TEXT("Y410");
if (SubType == MFVideoFormat_Y416) return TEXT("Y416");
if (SubType == MFVideoFormat_Y41P) return TEXT("Y41P");
if (SubType == MFVideoFormat_Y41T) return TEXT("Y41T");
if (SubType == MFVideoFormat_Y42T) return TEXT("Y42T");
if (SubType == MFVideoFormat_P210) return TEXT("P210");
if (SubType == MFVideoFormat_P216) return TEXT("P216");
if (SubType == MFVideoFormat_P010) return TEXT("P010");
if (SubType == MFVideoFormat_P016) return TEXT("P016");
if (SubType == MFVideoFormat_v210) return TEXT("v210");
if (SubType == MFVideoFormat_v216) return TEXT("v216");
if (SubType == MFVideoFormat_v410) return TEXT("v410");
if (SubType == MFVideoFormat_MP43) return TEXT("MP43");
if (SubType == MFVideoFormat_MP4S) return TEXT("MP4S");
if (SubType == MFVideoFormat_M4S2) return TEXT("M4S2");
if (SubType == MFVideoFormat_MP4V) return TEXT("MP4V");
if (SubType == MFVideoFormat_WMV1) return TEXT("WMV1");
if (SubType == MFVideoFormat_WMV2) return TEXT("WMV2");
if (SubType == MFVideoFormat_WMV3) return TEXT("WMV3");
if (SubType == MFVideoFormat_WVC1) return TEXT("WVC1");
if (SubType == MFVideoFormat_MSS1) return TEXT("MSS1");
if (SubType == MFVideoFormat_MSS2) return TEXT("MSS2");
if (SubType == MFVideoFormat_MPG1) return TEXT("MPG1");
if (SubType == MFVideoFormat_DVSL) return TEXT("DVSL");
if (SubType == MFVideoFormat_DVSD) return TEXT("DVSD");
if (SubType == MFVideoFormat_DVHD) return TEXT("DVHD");
if (SubType == MFVideoFormat_DV25) return TEXT("DV25");
if (SubType == MFVideoFormat_DV50) return TEXT("DV50");
if (SubType == MFVideoFormat_DVH1) return TEXT("DVH1");
if (SubType == MFVideoFormat_DVC) return TEXT("DVC");
if (SubType == MFVideoFormat_H264) return TEXT("H264");
if (SubType == MFVideoFormat_MJPG) return TEXT("MJPG");
if (SubType == MFVideoFormat_420O) return TEXT("420O");
#if (WINVER >= _WIN32_WINNT_WIN8)
if (SubType == MFVideoFormat_H263) return TEXT("H263");
#endif
if (SubType == MFVideoFormat_H264_ES) return TEXT("H264 ES");
if (SubType == MFVideoFormat_MPEG2) return TEXT("MPEG-2");
// audio formats
if ((FMemory::Memcmp(&SubType.Data2, &MFAudioFormat_Base.Data2, 12) == 0) ||
(FMemory::Memcmp(&SubType.Data2, &MFMPEG4Format_Base.Data2, 12) == 0))
{
if (SubType.Data1 == WAVE_FORMAT_UNKNOWN) return TEXT("Unknown Audio Format");
if (SubType.Data1 == WAVE_FORMAT_PCM) return TEXT("PCM");
if (SubType.Data1 == WAVE_FORMAT_ADPCM) return TEXT("ADPCM");
if (SubType.Data1 == WAVE_FORMAT_IEEE_FLOAT) return TEXT("IEEE Float");
if (SubType.Data1 == WAVE_FORMAT_VSELP) return TEXT("VSELP");
if (SubType.Data1 == WAVE_FORMAT_IBM_CVSD) return TEXT("IBM CVSD");
if (SubType.Data1 == WAVE_FORMAT_ALAW) return TEXT("aLaw");
if (SubType.Data1 == WAVE_FORMAT_MULAW) return TEXT("uLaw");
if (SubType.Data1 == WAVE_FORMAT_DTS) return TEXT("DTS");
if (SubType.Data1 == WAVE_FORMAT_DRM) return TEXT("DRM");
if (SubType.Data1 == WAVE_FORMAT_WMAVOICE9) return TEXT("WMA Voice 9");
if (SubType.Data1 == WAVE_FORMAT_WMAVOICE10) return TEXT("WMA Voice 10");
if (SubType.Data1 == WAVE_FORMAT_OKI_ADPCM) return TEXT("OKI ADPCM");
if (SubType.Data1 == WAVE_FORMAT_DVI_ADPCM) return TEXT("Intel DVI ADPCM");
if (SubType.Data1 == WAVE_FORMAT_IMA_ADPCM) return TEXT("Intel IMA ADPCM");
if (SubType.Data1 == WAVE_FORMAT_MEDIASPACE_ADPCM) return TEXT("Videologic ADPCM");
if (SubType.Data1 == WAVE_FORMAT_SIERRA_ADPCM) return TEXT("Sierra ADPCM");
if (SubType.Data1 == WAVE_FORMAT_G723_ADPCM) return TEXT("G723 ADPCM");
if (SubType.Data1 == WAVE_FORMAT_DIGISTD) return TEXT("DIGISTD");
if (SubType.Data1 == WAVE_FORMAT_DIGIFIX) return TEXT("DIGIFIX");
if (SubType.Data1 == WAVE_FORMAT_DIALOGIC_OKI_ADPCM) return TEXT("Dialogic ADPCM");
if (SubType.Data1 == WAVE_FORMAT_MEDIAVISION_ADPCM) return TEXT("Media Vision ADPCM");
if (SubType.Data1 == WAVE_FORMAT_CU_CODEC) return TEXT("HP CU Codec");
if (SubType.Data1 == WAVE_FORMAT_HP_DYN_VOICE) return TEXT("HP DynVoice");
if (SubType.Data1 == WAVE_FORMAT_YAMAHA_ADPCM) return TEXT("Yamaha ADPCM");
if (SubType.Data1 == WAVE_FORMAT_SONARC) return TEXT("Sonarc");
if (SubType.Data1 == WAVE_FORMAT_DSPGROUP_TRUESPEECH) return TEXT("DPS Group TrueSpeech");
if (SubType.Data1 == WAVE_FORMAT_ECHOSC1) return TEXT("Echo Speech 1");
if (SubType.Data1 == WAVE_FORMAT_AUDIOFILE_AF36) return TEXT("AF36");
if (SubType.Data1 == WAVE_FORMAT_APTX) return TEXT("APTX");
if (SubType.Data1 == WAVE_FORMAT_AUDIOFILE_AF10) return TEXT("AF10");
if (SubType.Data1 == WAVE_FORMAT_PROSODY_1612) return TEXT("Prosody 1622");
if (SubType.Data1 == WAVE_FORMAT_LRC) return TEXT("LRC");
if (SubType.Data1 == WAVE_FORMAT_DOLBY_AC2) return TEXT("Dolby AC2");
if (SubType.Data1 == WAVE_FORMAT_GSM610) return TEXT("GSM 610");
if (SubType.Data1 == WAVE_FORMAT_MSNAUDIO) return TEXT("MSN Audio");
if (SubType.Data1 == WAVE_FORMAT_ANTEX_ADPCME) return TEXT("Antex ADPCME");
if (SubType.Data1 == WAVE_FORMAT_CONTROL_RES_VQLPC) return TEXT("Control Resources VQLPC");
if (SubType.Data1 == WAVE_FORMAT_DIGIREAL) return TEXT("DigiReal");
if (SubType.Data1 == WAVE_FORMAT_DIGIADPCM) return TEXT("DigiADPCM");
if (SubType.Data1 == WAVE_FORMAT_CONTROL_RES_CR10) return TEXT("Control Resources CR10");
if (SubType.Data1 == WAVE_FORMAT_NMS_VBXADPCM) return TEXT("VBX ADPCM");
if (SubType.Data1 == WAVE_FORMAT_CS_IMAADPCM) return TEXT("Crystal IMA ADPCM");
if (SubType.Data1 == WAVE_FORMAT_ECHOSC3) return TEXT("Echo Speech 3");
if (SubType.Data1 == WAVE_FORMAT_ROCKWELL_ADPCM) return TEXT("Rockwell ADPCM");
if (SubType.Data1 == WAVE_FORMAT_ROCKWELL_DIGITALK) return TEXT("Rockwell DigiTalk");
if (SubType.Data1 == WAVE_FORMAT_XEBEC) return TEXT("Xebec");
if (SubType.Data1 == WAVE_FORMAT_G721_ADPCM) return TEXT("G721 ADPCM");
if (SubType.Data1 == WAVE_FORMAT_G728_CELP) return TEXT("G728 CELP");
if (SubType.Data1 == WAVE_FORMAT_MSG723) return TEXT("MSG723");
if (SubType.Data1 == WAVE_FORMAT_INTEL_G723_1) return TEXT("Intel G723.1");
if (SubType.Data1 == WAVE_FORMAT_INTEL_G729) return TEXT("Intel G729");
if (SubType.Data1 == WAVE_FORMAT_SHARP_G726) return TEXT("Sharp G726");
if (SubType.Data1 == WAVE_FORMAT_MPEG) return TEXT("MPEG");
if (SubType.Data1 == WAVE_FORMAT_RT24) return TEXT("InSoft RT24");
if (SubType.Data1 == WAVE_FORMAT_PAC) return TEXT("InSoft PAC");
if (SubType.Data1 == WAVE_FORMAT_MPEGLAYER3) return TEXT("MPEG Layer 3");
if (SubType.Data1 == WAVE_FORMAT_LUCENT_G723) return TEXT("Lucent G723");
if (SubType.Data1 == WAVE_FORMAT_CIRRUS) return TEXT("Cirrus Logic");
if (SubType.Data1 == WAVE_FORMAT_ESPCM) return TEXT("ESS PCM");
if (SubType.Data1 == WAVE_FORMAT_VOXWARE) return TEXT("Voxware");
if (SubType.Data1 == WAVE_FORMAT_CANOPUS_ATRAC) return TEXT("Canopus ATRAC");
if (SubType.Data1 == WAVE_FORMAT_G726_ADPCM) return TEXT("APICOM G726");
if (SubType.Data1 == WAVE_FORMAT_G722_ADPCM) return TEXT("APICOM G722");
if (SubType.Data1 == WAVE_FORMAT_DSAT) return TEXT("DSAT");
if (SubType.Data1 == WAVE_FORMAT_DSAT_DISPLAY) return TEXT("DSAT Display");
if (SubType.Data1 == WAVE_FORMAT_VOXWARE_BYTE_ALIGNED) return TEXT("Voxware Byte Aligned");
if (SubType.Data1 == WAVE_FORMAT_VOXWARE_AC8) return TEXT("Voxware AC8");
if (SubType.Data1 == WAVE_FORMAT_VOXWARE_AC10) return TEXT("Voxware AC10");
if (SubType.Data1 == WAVE_FORMAT_VOXWARE_AC16) return TEXT("Voxware AC16");
if (SubType.Data1 == WAVE_FORMAT_VOXWARE_AC20) return TEXT("Voxware AC20");
if (SubType.Data1 == WAVE_FORMAT_VOXWARE_RT24) return TEXT("Voxware RT24");
if (SubType.Data1 == WAVE_FORMAT_VOXWARE_RT29) return TEXT("Voxware RT29");
if (SubType.Data1 == WAVE_FORMAT_VOXWARE_RT29HW) return TEXT("Voxware RT29HW");
if (SubType.Data1 == WAVE_FORMAT_VOXWARE_VR12) return TEXT("Voxware VR12");
if (SubType.Data1 == WAVE_FORMAT_VOXWARE_VR18) return TEXT("Voxware VR18");
if (SubType.Data1 == WAVE_FORMAT_VOXWARE_TQ40) return TEXT("Voxware TQ40");
if (SubType.Data1 == WAVE_FORMAT_VOXWARE_SC3) return TEXT("Voxware SC3");
if (SubType.Data1 == WAVE_FORMAT_VOXWARE_SC3_1) return TEXT("Voxware SC3.1");
if (SubType.Data1 == WAVE_FORMAT_SOFTSOUND) return TEXT("Softsound");
if (SubType.Data1 == WAVE_FORMAT_VOXWARE_TQ60) return TEXT("Voxware TQ60");
if (SubType.Data1 == WAVE_FORMAT_MSRT24) return TEXT("MSRT24");
if (SubType.Data1 == WAVE_FORMAT_G729A) return TEXT("AT&T G729A");
if (SubType.Data1 == WAVE_FORMAT_MVI_MVI2) return TEXT("NVI2");
if (SubType.Data1 == WAVE_FORMAT_DF_G726) return TEXT("DataFusion G726");
if (SubType.Data1 == WAVE_FORMAT_DF_GSM610) return TEXT("DataFusion GSM610");
if (SubType.Data1 == WAVE_FORMAT_ISIAUDIO) return TEXT("Iterated Systems");
if (SubType.Data1 == WAVE_FORMAT_ONLIVE) return TEXT("OnLive!");
if (SubType.Data1 == WAVE_FORMAT_MULTITUDE_FT_SX20) return TEXT("Multitude FT SX20");
if (SubType.Data1 == WAVE_FORMAT_INFOCOM_ITS_G721_ADPCM) return TEXT("Infocom ITS G721 ADPCM");
if (SubType.Data1 == WAVE_FORMAT_CONVEDIA_G729) return TEXT("Convedia G729");
if (SubType.Data1 == WAVE_FORMAT_CONGRUENCY) return TEXT("Congruency");
if (SubType.Data1 == WAVE_FORMAT_SBC24) return TEXT("SBC24");
if (SubType.Data1 == WAVE_FORMAT_DOLBY_AC3_SPDIF) return TEXT("Dolby AC3 SPDIF");
if (SubType.Data1 == WAVE_FORMAT_MEDIASONIC_G723) return TEXT("MediaSonic G723");
if (SubType.Data1 == WAVE_FORMAT_PROSODY_8KBPS) return TEXT("Prosody 8kps");
if (SubType.Data1 == WAVE_FORMAT_ZYXEL_ADPCM) return TEXT("ZyXEL ADPCM");
if (SubType.Data1 == WAVE_FORMAT_PHILIPS_LPCBB) return TEXT("Philips LPCBB");
if (SubType.Data1 == WAVE_FORMAT_PACKED) return TEXT("Studer Packed");
if (SubType.Data1 == WAVE_FORMAT_MALDEN_PHONYTALK) return TEXT("Malden PhonyTalk");
if (SubType.Data1 == WAVE_FORMAT_RACAL_RECORDER_GSM) return TEXT("Racal GSM");
if (SubType.Data1 == WAVE_FORMAT_RACAL_RECORDER_G720_A) return TEXT("Racal G720.A");
if (SubType.Data1 == WAVE_FORMAT_RACAL_RECORDER_G723_1) return TEXT("Racal G723.1");
if (SubType.Data1 == WAVE_FORMAT_RACAL_RECORDER_TETRA_ACELP) return TEXT("Racal Tetra ACELP");
if (SubType.Data1 == WAVE_FORMAT_NEC_AAC) return TEXT("NEC AAC");
if (SubType.Data1 == WAVE_FORMAT_RAW_AAC1) return TEXT("Raw AAC-1");
if (SubType.Data1 == WAVE_FORMAT_RHETOREX_ADPCM) return TEXT("Rhetorex ADPCM");
if (SubType.Data1 == WAVE_FORMAT_IRAT) return TEXT("BeCubed IRAT");
if (SubType.Data1 == WAVE_FORMAT_VIVO_G723) return TEXT("Vivo G723");
if (SubType.Data1 == WAVE_FORMAT_VIVO_SIREN) return TEXT("vivo Siren");
if (SubType.Data1 == WAVE_FORMAT_PHILIPS_CELP) return TEXT("Philips Celp");
if (SubType.Data1 == WAVE_FORMAT_PHILIPS_GRUNDIG) return TEXT("Philips Grundig");
if (SubType.Data1 == WAVE_FORMAT_DIGITAL_G723) return TEXT("DEC G723");
if (SubType.Data1 == WAVE_FORMAT_SANYO_LD_ADPCM) return TEXT("Sanyo ADPCM");
if (SubType.Data1 == WAVE_FORMAT_SIPROLAB_ACEPLNET) return TEXT("Sipro Lab ACEPLNET");
if (SubType.Data1 == WAVE_FORMAT_SIPROLAB_ACELP4800) return TEXT("Sipro Lab ACELP4800");
if (SubType.Data1 == WAVE_FORMAT_SIPROLAB_ACELP8V3) return TEXT("Sipro Lab ACELP8v3");
if (SubType.Data1 == WAVE_FORMAT_SIPROLAB_G729) return TEXT("Spiro Lab G729");
if (SubType.Data1 == WAVE_FORMAT_SIPROLAB_G729A) return TEXT("Spiro Lab G729A");
if (SubType.Data1 == WAVE_FORMAT_SIPROLAB_KELVIN) return TEXT("Spiro Lab Kelvin");
if (SubType.Data1 == WAVE_FORMAT_VOICEAGE_AMR) return TEXT("VoiceAge AMR");
if (SubType.Data1 == WAVE_FORMAT_G726ADPCM) return TEXT("Dictaphone G726 ADPCM");
if (SubType.Data1 == WAVE_FORMAT_DICTAPHONE_CELP68) return TEXT("Dictaphone CELP68");
if (SubType.Data1 == WAVE_FORMAT_DICTAPHONE_CELP54) return TEXT("Dictaphone CELP54");
if (SubType.Data1 == WAVE_FORMAT_QUALCOMM_PUREVOICE) return TEXT("Qualcomm PureVoice");
if (SubType.Data1 == WAVE_FORMAT_QUALCOMM_HALFRATE) return TEXT("Qualcomm Half-Rate");
if (SubType.Data1 == WAVE_FORMAT_TUBGSM) return TEXT("Ring Zero Systems TUBGSM");
if (SubType.Data1 == WAVE_FORMAT_MSAUDIO1) return TEXT("Microsoft Audio 1");
if (SubType.Data1 == WAVE_FORMAT_WMAUDIO2) return TEXT("Windows Media Audio 2");
if (SubType.Data1 == WAVE_FORMAT_WMAUDIO3) return TEXT("Windows Media Audio 3");
if (SubType.Data1 == WAVE_FORMAT_WMAUDIO_LOSSLESS) return TEXT("Window Media Audio Lossless");
if (SubType.Data1 == WAVE_FORMAT_WMASPDIF) return TEXT("Windows Media Audio SPDIF");
if (SubType.Data1 == WAVE_FORMAT_UNISYS_NAP_ADPCM) return TEXT("Unisys ADPCM");
if (SubType.Data1 == WAVE_FORMAT_UNISYS_NAP_ULAW) return TEXT("Unisys uLaw");
if (SubType.Data1 == WAVE_FORMAT_UNISYS_NAP_ALAW) return TEXT("Unisys aLaw");
if (SubType.Data1 == WAVE_FORMAT_UNISYS_NAP_16K) return TEXT("Unisys 16k");
if (SubType.Data1 == WAVE_FORMAT_SYCOM_ACM_SYC008) return TEXT("SyCom ACM SYC008");
if (SubType.Data1 == WAVE_FORMAT_SYCOM_ACM_SYC701_G726L) return TEXT("SyCom ACM SYC701 G726L");
if (SubType.Data1 == WAVE_FORMAT_SYCOM_ACM_SYC701_CELP54) return TEXT("SyCom ACM SYC701 CELP54");
if (SubType.Data1 == WAVE_FORMAT_SYCOM_ACM_SYC701_CELP68) return TEXT("SyCom ACM SYC701 CELP68");
if (SubType.Data1 == WAVE_FORMAT_KNOWLEDGE_ADVENTURE_ADPCM) return TEXT("Knowledge Adventure ADPCM");
if (SubType.Data1 == WAVE_FORMAT_FRAUNHOFER_IIS_MPEG2_AAC) return TEXT("Fraunhofer MPEG-2 AAC");
if (SubType.Data1 == WAVE_FORMAT_DTS_DS) return TEXT("DTS DS");
if (SubType.Data1 == WAVE_FORMAT_CREATIVE_ADPCM) return TEXT("Creative Labs ADPCM");
if (SubType.Data1 == WAVE_FORMAT_CREATIVE_FASTSPEECH8) return TEXT("Creative Labs FastSpeech 8");
if (SubType.Data1 == WAVE_FORMAT_CREATIVE_FASTSPEECH10) return TEXT("Creative Labs FastSpeech 10");
if (SubType.Data1 == WAVE_FORMAT_UHER_ADPCM) return TEXT("UHER ADPCM");
if (SubType.Data1 == WAVE_FORMAT_ULEAD_DV_AUDIO) return TEXT("Ulead DV Audio");
if (SubType.Data1 == WAVE_FORMAT_ULEAD_DV_AUDIO_1) return TEXT("Ulead DV Audio.1");
if (SubType.Data1 == WAVE_FORMAT_QUARTERDECK) return TEXT("Quarterdeck");
if (SubType.Data1 == WAVE_FORMAT_ILINK_VC) return TEXT("I-link VC");
if (SubType.Data1 == WAVE_FORMAT_RAW_SPORT) return TEXT("RAW SPORT");
if (SubType.Data1 == WAVE_FORMAT_ESST_AC3) return TEXT("ESS Technology AC3");
if (SubType.Data1 == WAVE_FORMAT_GENERIC_PASSTHRU) return TEXT("Generic Passthrough");
if (SubType.Data1 == WAVE_FORMAT_IPI_HSX) return TEXT("IPI HSX");
if (SubType.Data1 == WAVE_FORMAT_IPI_RPELP) return TEXT("IPI RPELP");
if (SubType.Data1 == WAVE_FORMAT_CS2) return TEXT("Consistent Software 2");
if (SubType.Data1 == WAVE_FORMAT_SONY_SCX) return TEXT("Sony SCX");
if (SubType.Data1 == WAVE_FORMAT_SONY_SCY) return TEXT("Sony SCY");
if (SubType.Data1 == WAVE_FORMAT_SONY_ATRAC3) return TEXT("Sony ATRAC3");
if (SubType.Data1 == WAVE_FORMAT_SONY_SPC) return TEXT("Sony SPC");
if (SubType.Data1 == WAVE_FORMAT_TELUM_AUDIO) return TEXT("Telum Audio");
if (SubType.Data1 == WAVE_FORMAT_TELUM_IA_AUDIO) return TEXT("Telum IA Audio");
if (SubType.Data1 == WAVE_FORMAT_NORCOM_VOICE_SYSTEMS_ADPCM) return TEXT("Norcom ADPCM");
if (SubType.Data1 == WAVE_FORMAT_FM_TOWNS_SND) return TEXT("Fujitsu Towns Sound");
if (SubType.Data1 == WAVE_FORMAT_MICRONAS) return TEXT("Micronas");
if (SubType.Data1 == WAVE_FORMAT_MICRONAS_CELP833) return TEXT("Micronas CELP833");
if (SubType.Data1 == WAVE_FORMAT_BTV_DIGITAL) return TEXT("Brooktree Digital");
if (SubType.Data1 == WAVE_FORMAT_INTEL_MUSIC_CODER) return TEXT("Intel Music Coder");
if (SubType.Data1 == WAVE_FORMAT_INDEO_AUDIO) return TEXT("Indeo Audio");
if (SubType.Data1 == WAVE_FORMAT_QDESIGN_MUSIC) return TEXT("QDesign Music");
if (SubType.Data1 == WAVE_FORMAT_ON2_VP7_AUDIO) return TEXT("On2 VP7");
if (SubType.Data1 == WAVE_FORMAT_ON2_VP6_AUDIO) return TEXT("On2 VP6");
if (SubType.Data1 == WAVE_FORMAT_VME_VMPCM) return TEXT("AT&T VME VMPCM");
if (SubType.Data1 == WAVE_FORMAT_TPC) return TEXT("AT&T TPC");
if (SubType.Data1 == WAVE_FORMAT_LIGHTWAVE_LOSSLESS) return TEXT("Lightwave Lossless");
if (SubType.Data1 == WAVE_FORMAT_OLIGSM) return TEXT("Olivetti GSM");
if (SubType.Data1 == WAVE_FORMAT_OLIADPCM) return TEXT("Olivetti ADPCM");
if (SubType.Data1 == WAVE_FORMAT_OLICELP) return TEXT("Olivetti CELP");
if (SubType.Data1 == WAVE_FORMAT_OLISBC) return TEXT("Olivetti SBC");
if (SubType.Data1 == WAVE_FORMAT_OLIOPR) return TEXT("Olivetti OPR");
if (SubType.Data1 == WAVE_FORMAT_LH_CODEC) return TEXT("Lernout & Hauspie");
if (SubType.Data1 == WAVE_FORMAT_LH_CODEC_CELP) return TEXT("Lernout & Hauspie CELP");
if (SubType.Data1 == WAVE_FORMAT_LH_CODEC_SBC8) return TEXT("Lernout & Hauspie SBC8");
if (SubType.Data1 == WAVE_FORMAT_LH_CODEC_SBC12) return TEXT("Lernout & Hauspie SBC12");
if (SubType.Data1 == WAVE_FORMAT_LH_CODEC_SBC16) return TEXT("Lernout & Hauspie SBC16");
if (SubType.Data1 == WAVE_FORMAT_NORRIS) return TEXT("Norris");
if (SubType.Data1 == WAVE_FORMAT_ISIAUDIO_2) return TEXT("ISIAudio 2");
if (SubType.Data1 == WAVE_FORMAT_SOUNDSPACE_MUSICOMPRESS) return TEXT("AT&T SoundSpace Musicompress");
if (SubType.Data1 == WAVE_FORMAT_MPEG_ADTS_AAC) return TEXT("MPEG ADT5 AAC");
if (SubType.Data1 == WAVE_FORMAT_MPEG_RAW_AAC) return TEXT("MPEG RAW AAC");
if (SubType.Data1 == WAVE_FORMAT_MPEG_LOAS) return TEXT("MPEG LOAS");
if (SubType.Data1 == WAVE_FORMAT_NOKIA_MPEG_ADTS_AAC) return TEXT("Nokia MPEG ADT5 AAC");
if (SubType.Data1 == WAVE_FORMAT_NOKIA_MPEG_RAW_AAC) return TEXT("Nokia MPEG RAW AAC");
if (SubType.Data1 == WAVE_FORMAT_VODAFONE_MPEG_ADTS_AAC) return TEXT("Vodafone MPEG ADTS AAC");
if (SubType.Data1 == WAVE_FORMAT_VODAFONE_MPEG_RAW_AAC) return TEXT("Vodafone MPEG RAW AAC");
if (SubType.Data1 == WAVE_FORMAT_MPEG_HEAAC) return TEXT("MPEG HEAAC");
if (SubType.Data1 == WAVE_FORMAT_VOXWARE_RT24_SPEECH) return TEXT("voxware RT24 Speech");
if (SubType.Data1 == WAVE_FORMAT_SONICFOUNDRY_LOSSLESS) return TEXT("Sonic Foundry Lossless");
if (SubType.Data1 == WAVE_FORMAT_INNINGS_TELECOM_ADPCM) return TEXT("Innings ADPCM");
if (SubType.Data1 == WAVE_FORMAT_LUCENT_SX8300P) return TEXT("Lucent SX8300P");
if (SubType.Data1 == WAVE_FORMAT_LUCENT_SX5363S) return TEXT("Lucent SX5363S");
if (SubType.Data1 == WAVE_FORMAT_CUSEEME) return TEXT("CUSeeMe");
if (SubType.Data1 == WAVE_FORMAT_NTCSOFT_ALF2CM_ACM) return TEXT("NTCSoft ALF2CM ACM");
if (SubType.Data1 == WAVE_FORMAT_DVM) return TEXT("FAST Multimedia DVM");
if (SubType.Data1 == WAVE_FORMAT_DTS2) return TEXT("DTS2");
if (SubType.Data1 == WAVE_FORMAT_MAKEAVIS) return TEXT("MAKEAVIS");
if (SubType.Data1 == WAVE_FORMAT_DIVIO_MPEG4_AAC) return TEXT("Divio MPEG-4 AAC");
if (SubType.Data1 == WAVE_FORMAT_NOKIA_ADAPTIVE_MULTIRATE) return TEXT("Nokia Adaptive Multirate");
if (SubType.Data1 == WAVE_FORMAT_DIVIO_G726) return TEXT("Divio G726");
if (SubType.Data1 == WAVE_FORMAT_LEAD_SPEECH) return TEXT("LEAD Speech");
if (SubType.Data1 == WAVE_FORMAT_LEAD_VORBIS) return TEXT("LEAD Vorbis");
if (SubType.Data1 == WAVE_FORMAT_WAVPACK_AUDIO) return TEXT("xiph.org WavPack");
if (SubType.Data1 == WAVE_FORMAT_OGG_VORBIS_MODE_1) return TEXT("Ogg Vorbis Mode 1");
if (SubType.Data1 == WAVE_FORMAT_OGG_VORBIS_MODE_2) return TEXT("Ogg Vorbis Mode 2");
if (SubType.Data1 == WAVE_FORMAT_OGG_VORBIS_MODE_3) return TEXT("Ogg Vorbis Mode 3");
if (SubType.Data1 == WAVE_FORMAT_OGG_VORBIS_MODE_1_PLUS) return TEXT("Ogg Vorbis Mode 1 Plus");
if (SubType.Data1 == WAVE_FORMAT_OGG_VORBIS_MODE_2_PLUS) return TEXT("Ogg Vorbis Mode 2 Plus");
if (SubType.Data1 == WAVE_FORMAT_OGG_VORBIS_MODE_3_PLUS) return TEXT("Ogg Vorbis Mode 3 Plus");
if (SubType.Data1 == WAVE_FORMAT_3COM_NBX) return TEXT("3COM NBX");
if (SubType.Data1 == WAVE_FORMAT_FAAD_AAC) return TEXT("FAAD AAC");
if (SubType.Data1 == WAVE_FORMAT_GSM_AMR_CBR) return TEXT("GSMA/3GPP CBR");
if (SubType.Data1 == WAVE_FORMAT_GSM_AMR_VBR_SID) return TEXT("GSMA/3GPP VBR SID");
if (SubType.Data1 == WAVE_FORMAT_COMVERSE_INFOSYS_G723_1) return TEXT("Converse Infosys G723.1");
if (SubType.Data1 == WAVE_FORMAT_COMVERSE_INFOSYS_AVQSBC) return TEXT("Converse Infosys AVQSBC");
if (SubType.Data1 == WAVE_FORMAT_COMVERSE_INFOSYS_SBC) return TEXT("Converse Infosys SBC");
if (SubType.Data1 == WAVE_FORMAT_SYMBOL_G729_A) return TEXT("Symbol Technologies G729.A");
if (SubType.Data1 == WAVE_FORMAT_VOICEAGE_AMR_WB) return TEXT("VoiceAge AMR Wideband");
if (SubType.Data1 == WAVE_FORMAT_INGENIENT_G726) return TEXT("Ingenient G726");
if (SubType.Data1 == WAVE_FORMAT_MPEG4_AAC) return TEXT("MPEG-4 AAC");
if (SubType.Data1 == WAVE_FORMAT_ENCORE_G726) return TEXT("Encore G726");
if (SubType.Data1 == WAVE_FORMAT_ZOLL_ASAO) return TEXT("ZOLL Medical ASAO");
if (SubType.Data1 == WAVE_FORMAT_SPEEX_VOICE) return TEXT("xiph.org Speex Voice");
if (SubType.Data1 == WAVE_FORMAT_VIANIX_MASC) return TEXT("Vianix MASC");
if (SubType.Data1 == WAVE_FORMAT_WM9_SPECTRUM_ANALYZER) return TEXT("Windows Media 9 Spectrum Analyzer");
if (SubType.Data1 == WAVE_FORMAT_WMF_SPECTRUM_ANAYZER) return TEXT("Windows Media Foundation Spectrum Analyzer");
if (SubType.Data1 == WAVE_FORMAT_GSM_610) return TEXT("GSM 610");
if (SubType.Data1 == WAVE_FORMAT_GSM_620) return TEXT("GSM 620");
if (SubType.Data1 == WAVE_FORMAT_GSM_660) return TEXT("GSM 660");
if (SubType.Data1 == WAVE_FORMAT_GSM_690) return TEXT("GSM 690");
if (SubType.Data1 == WAVE_FORMAT_GSM_ADAPTIVE_MULTIRATE_WB) return TEXT("GSM Adaptive Multirate Wideband");
if (SubType.Data1 == WAVE_FORMAT_POLYCOM_G722) return TEXT("Polycom G722");
if (SubType.Data1 == WAVE_FORMAT_POLYCOM_G728) return TEXT("Polycom G728");
// if (SubType.Data1 == WAVE_FORMAT_POLYCOM_G729_A) return TEXT("Polycom G729.A"); // misspelled in XDK header
if (SubType.Data1 == WAVE_FORMAT_POLYCOM_SIREN) return TEXT("Polycom Siren");
if (SubType.Data1 == WAVE_FORMAT_GLOBAL_IP_ILBC) return TEXT("Global IP ILBC");
if (SubType.Data1 == WAVE_FORMAT_RADIOTIME_TIME_SHIFT_RADIO) return TEXT("RadioTime");
if (SubType.Data1 == WAVE_FORMAT_NICE_ACA) return TEXT("Nice Systems ACA");
if (SubType.Data1 == WAVE_FORMAT_NICE_ADPCM) return TEXT("Nice Systems ADPCM");
if (SubType.Data1 == WAVE_FORMAT_VOCORD_G721) return TEXT("Vocord G721");
if (SubType.Data1 == WAVE_FORMAT_VOCORD_G726) return TEXT("Vocord G726");
if (SubType.Data1 == WAVE_FORMAT_VOCORD_G722_1) return TEXT("Vocord G722.1");
if (SubType.Data1 == WAVE_FORMAT_VOCORD_G728) return TEXT("Vocord G728");
if (SubType.Data1 == WAVE_FORMAT_VOCORD_G729) return TEXT("Vocord G729");
if (SubType.Data1 == WAVE_FORMAT_VOCORD_G729_A) return TEXT("Vocord G729.A");
if (SubType.Data1 == WAVE_FORMAT_VOCORD_G723_1) return TEXT("Vocord G723.1");
if (SubType.Data1 == WAVE_FORMAT_VOCORD_LBC) return TEXT("Vocord LBC");
if (SubType.Data1 == WAVE_FORMAT_NICE_G728) return TEXT("Nice Systems G728");
if (SubType.Data1 == WAVE_FORMAT_FRACE_TELECOM_G729) return TEXT("France Telecom G729");
if (SubType.Data1 == WAVE_FORMAT_CODIAN) return TEXT("CODIAN");
if (SubType.Data1 == WAVE_FORMAT_FLAC) return TEXT("flac.sourceforge.net");
}
// unknown type
return FString::Printf(TEXT("%s (%s)"), *GuidToString(SubType), *FourccToString(SubType.Data1));
}
}
#if PLATFORM_WINDOWS
#include "HideWindowsPlatformTypes.h"
#else
#include "XboxOneHidePlatformTypes.h"
#endif
#endif //MFMEDIA_SUPPORTED_PLATFORM
| 51.137773 | 178 | 0.733773 | [
"transform"
] |
07de35af8bfce94410ff9799c90cdf812718a89e | 59,141 | hpp | C++ | include/bio_ik/forward_kinematics.hpp | SammyRamone/bio_ik | f903cd3190f4acf15342aef70cddcef6cbbf8819 | [
"BSD-3-Clause"
] | 1 | 2022-03-24T09:26:46.000Z | 2022-03-24T09:26:46.000Z | include/bio_ik/forward_kinematics.hpp | SammyRamone/bio_ik | f903cd3190f4acf15342aef70cddcef6cbbf8819 | [
"BSD-3-Clause"
] | 9 | 2022-01-03T18:59:17.000Z | 2022-02-05T20:06:22.000Z | include/bio_ik/forward_kinematics.hpp | SammyRamone/bio_ik | f903cd3190f4acf15342aef70cddcef6cbbf8819 | [
"BSD-3-Clause"
] | 2 | 2022-01-11T23:57:32.000Z | 2022-02-26T10:27:02.000Z | // Copyright (c) 2016-2017, Philipp Sebastian Ruppel
//
// 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 Universität Hamburg 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.
#pragma once
#include <bio_ik/goal.hpp>
#include <bio_ik/robot_info.hpp>
#include <bio_ik/utils.hpp>
#include <kdl/treefksolverpos_recursive.hpp>
#include <kdl_parser/kdl_parser.hpp>
#if defined(__x86_64__) || defined(__i386__)
#include <emmintrin.h>
#include <immintrin.h>
#include <x86intrin.h>
#if (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 9))
#define FUNCTION_MULTIVERSIONING 1
#else
#define FUNCTION_MULTIVERSIONING 0
#endif
#else
#define FUNCTION_MULTIVERSIONING 0
#endif
namespace bio_ik {
// computes and caches local joint frames
class RobotJointEvaluator {
private:
std::vector<double> joint_cache_variables_;
std::vector<Frame> joint_cache_frames_;
std::vector<Frame> link_frames_;
protected:
std::vector<Vector3> joint_axis_list_;
moveit::core::RobotModelConstPtr robot_model_;
std::vector<double> variables_;
public:
inline void getJointFrame(const moveit::core::JointModel* joint_model,
const double* variables, Frame& frame) {
auto joint_type = joint_model->getType();
if (joint_type == moveit::core::JointModel::FIXED) {
frame = Frame::identity();
return;
}
size_t joint_index = joint_model->getJointIndex();
switch (joint_type) {
case moveit::core::JointModel::REVOLUTE: {
auto axis = joint_axis_list_[joint_index];
auto v = variables[joint_model->getFirstVariableIndex()];
/*v *= 1.0 / (2 * M_PI);
v -= std::floor(v);
v *= (2 * M_PI);*/
auto half_angle = v * 0.5;
// TODO: optimize sin cos
auto fcos = cos(half_angle);
auto fsin = sin(half_angle);
// auto fsin = half_angle;
// auto fcos = 1.0 - half_angle * half_angle * 0.5;
frame = Frame(Vector3(0.0, 0.0, 0.0),
Quaternion(axis.x() * fsin, axis.y() * fsin,
axis.z() * fsin, fcos));
break;
}
case moveit::core::JointModel::PRISMATIC: {
auto axis = joint_axis_list_[joint_index];
auto v = variables[joint_model->getFirstVariableIndex()];
frame = Frame(axis * v, Quaternion(0.0, 0.0, 0.0, 1.0));
break;
}
case moveit::core::JointModel::FLOATING: {
auto* vv = variables + joint_model->getFirstVariableIndex();
frame.pos = Vector3(vv[0], vv[1], vv[2]);
frame.rot = Quaternion(vv[3], vv[4], vv[5], vv[6]).normalized();
// LOG("floating", joint_model->getFirstVariableIndex(), vv[0], vv[1],
// vv[2], vv[3], vv[4], vv[5], vv[6]);
break;
}
default: {
auto* joint_variables =
variables + joint_model->getFirstVariableIndex();
Eigen::Isometry3d joint_transform;
joint_model->computeTransform(joint_variables, joint_transform);
frame = Frame(joint_transform);
break;
}
}
// LOG("local joint frame", joint_model->getType(), joint_model->getName(),
// frame);
}
inline void getJointFrame(const moveit::core::JointModel* joint_model,
const std::vector<double>& variables,
Frame& frame) {
getJointFrame(joint_model, variables.data(), frame);
}
protected:
inline const Frame& getLinkFrame(const moveit::core::LinkModel* link_model) {
return link_frames_[link_model->getLinkIndex()];
}
inline bool checkJointMoved(const moveit::core::JointModel* joint_model) {
size_t i0 = joint_model->getFirstVariableIndex();
size_t cnt = joint_model->getVariableCount();
if (cnt == 0) return true;
if (cnt == 1) return !(variables_[i0] == joint_cache_variables_[i0]);
for (size_t i = i0; i < i0 + cnt; i++)
if (!(variables_[i] == joint_cache_variables_[i])) return true;
return false;
}
inline void putJointCache(const moveit::core::JointModel* joint_model,
const Frame& frame) {
joint_cache_frames_[joint_model->getJointIndex()] = frame;
size_t i0 = joint_model->getFirstVariableIndex();
size_t cnt = joint_model->getVariableCount();
for (size_t i = i0; i < i0 + cnt; i++)
joint_cache_variables_[i] = variables_[i];
}
inline const Frame& getJointFrame(
const moveit::core::JointModel* joint_model) {
size_t joint_index = joint_model->getJointIndex();
if (!checkJointMoved(joint_model)) return joint_cache_frames_[joint_index];
getJointFrame(joint_model, variables_, joint_cache_frames_[joint_index]);
size_t cnt = joint_model->getVariableCount();
if (cnt) {
size_t i0 = joint_model->getFirstVariableIndex();
if (cnt == 1)
joint_cache_variables_[i0] = variables_[i0];
else
for (size_t i = i0; i < i0 + cnt; i++)
joint_cache_variables_[i] = variables_[i];
}
// TODO: optimize copy
/*size_t cnt = joint_model->getVariableCount();
size_t i0 = joint_model->getFirstVariableIndex();
memcpy(joint_cache_variables_.data() + i0, variables_.data() + i0, cnt *
8);*/
return joint_cache_frames_[joint_index];
}
public:
RobotJointEvaluator(moveit::core::RobotModelConstPtr model)
: robot_model_(model) {
joint_cache_variables_.clear();
joint_cache_variables_.resize(model->getVariableCount(), DBL_MAX);
joint_cache_frames_.clear();
joint_cache_frames_.resize(model->getJointModelCount());
link_frames_.clear();
for (auto* link_model : model->getLinkModels())
link_frames_.push_back(Frame(link_model->getJointOriginTransform()));
joint_axis_list_.clear();
joint_axis_list_.resize(robot_model_->getJointModelCount());
for (size_t i = 0; i < joint_axis_list_.size(); ++i) {
auto* joint_model = robot_model_->getJointModel(i);
if (auto* j = dynamic_cast<const moveit::core::RevoluteJointModel*>(
joint_model))
joint_axis_list_[i] =
Vector3(j->getAxis().x(), j->getAxis().y(), j->getAxis().z());
if (auto* j = dynamic_cast<const moveit::core::PrismaticJointModel*>(
joint_model))
joint_axis_list_[i] =
Vector3(j->getAxis().x(), j->getAxis().y(), j->getAxis().z());
}
}
};
// fast tree fk
class RobotFK_Fast_Base : protected RobotJointEvaluator {
protected:
std::vector<std::string> tip_names;
std::vector<Frame> tip_frames;
std::vector<const moveit::core::LinkModel*> tip_links;
std::vector<const moveit::core::LinkModel*> link_schedule;
std::vector<Frame> global_frames;
std::vector<std::vector<const moveit::core::LinkModel*>> link_chains;
std::vector<size_t> active_variables;
std::vector<std::pair<size_t, size_t>> variable_to_link_map;
std::vector<size_t> variable_to_link_map_2;
std::vector<std::pair<size_t, size_t>> variable_to_link_chain_map;
inline void updateMimic(std::vector<double>& values) {
for (auto* joint : robot_model_->getMimicJointModels()) {
auto src = joint->getMimic()->getFirstVariableIndex();
auto dest = joint->getFirstVariableIndex();
// TODO: more dimensions ???
values[dest] =
values[src] * joint->getMimicFactor() + joint->getMimicOffset();
// moveit doesn't seem to support multiple mimic dimensions either... ???
// TODO: ok???
// for(size_t base = 0; base < joint->getVariableCount(); base++)
// values[base + dest] = values[base + src] * joint->getMimicFactor() +
// joint->getMimicOffset();
}
}
public:
RobotFK_Fast_Base(moveit::core::RobotModelConstPtr model)
: RobotJointEvaluator(model) {}
void initialize(const std::vector<size_t>& tip_link_indices) {
tip_names.resize(tip_link_indices.size());
for (size_t i = 0; i < tip_link_indices.size(); i++)
tip_names[i] = robot_model_->getLinkModelNames()[tip_link_indices[i]];
tip_frames.resize(tip_names.size());
tip_links.clear();
for (const auto& n : tip_names)
tip_links.push_back(robot_model_->getLinkModel(n));
global_frames.resize(robot_model_->getLinkModelCount());
link_chains.clear();
link_schedule.clear();
for (auto* tip_link : tip_links) {
std::vector<const moveit::core::LinkModel*> chain;
for (auto* link = tip_link; link; link = link->getParentLinkModel())
chain.push_back(link);
reverse(chain.begin(), chain.end());
link_chains.push_back(chain);
for (auto* link : chain) {
if (find(link_schedule.begin(), link_schedule.end(), link) !=
link_schedule.end())
continue;
link_schedule.push_back(link);
}
}
active_variables.clear();
variable_to_link_map.clear();
for (auto* link_model : link_schedule) {
auto link_index = link_model->getLinkIndex();
auto* joint_model = link_model->getParentJointModel();
size_t vstart = joint_model->getFirstVariableIndex();
size_t vcount = joint_model->getVariableCount();
for (size_t vi = vstart; vi < vstart + vcount; vi++) {
variable_to_link_map.push_back(std::make_pair(vi, link_index));
if (find(active_variables.begin(), active_variables.end(), vi) !=
active_variables.end())
continue;
active_variables.push_back(vi);
}
}
variable_to_link_map_2.resize(robot_model_->getVariableCount());
for (auto* link_model : link_schedule) {
auto link_index = link_model->getLinkIndex();
auto* joint_model = link_model->getParentJointModel();
size_t vstart = joint_model->getFirstVariableIndex();
size_t vcount = joint_model->getVariableCount();
for (size_t vi = vstart; vi < vstart + vcount; vi++) {
variable_to_link_map_2[vi] = link_index;
}
}
variable_to_link_chain_map.resize(robot_model_->getVariableCount());
for (size_t chain_index = 0; chain_index < link_chains.size();
chain_index++) {
auto& link_chain = link_chains[chain_index];
for (size_t ipos = 0; ipos < link_chain.size(); ipos++) {
auto* link_model = link_chain[ipos];
auto* joint_model = link_model->getParentJointModel();
size_t vstart = joint_model->getFirstVariableIndex();
size_t vcount = joint_model->getVariableCount();
for (size_t vi = vstart; vi < vstart + vcount; vi++) {
variable_to_link_chain_map[vi] = std::make_pair(chain_index, ipos);
}
}
}
}
void applyConfiguration(const std::vector<double>& jj0) {
FNPROFILER();
variables_ = jj0;
updateMimic(variables_);
for (auto* link_model : link_schedule) {
auto* joint_model = link_model->getParentJointModel();
auto* parent_link_model = joint_model->getParentLinkModel();
if (parent_link_model) {
concat(global_frames[parent_link_model->getLinkIndex()],
getLinkFrame(link_model), getJointFrame(joint_model),
global_frames[link_model->getLinkIndex()]);
} else {
concat(getLinkFrame(link_model), getJointFrame(joint_model),
global_frames[link_model->getLinkIndex()]);
}
// if(linkModel->getParentLinkModel() &&
// linkModel->getParentLinkModel()->getLinkIndex() >
// linkModel->getLinkIndex()) { LOG("wrong link order"); throw
// runtime_error("wrong link order"); }
}
for (size_t itip = 0; itip < tip_links.size(); itip++) {
tip_frames[itip] = global_frames[tip_links[itip]->getLinkIndex()];
}
}
inline const Frame& getTipFrame(size_t fi) const { return tip_frames[fi]; }
inline const std::vector<Frame>& getTipFrames() const { return tip_frames; }
inline void incrementalBegin(const std::vector<double>& jj) {
applyConfiguration(jj);
}
inline void incrementalEnd() {}
inline const Frame& getJointVariableFrame(size_t variable_index) {
return global_frames[variable_to_link_map_2[variable_index]];
}
};
// incremental tip frame updates without full recomputation
class RobotFK_Fast : public RobotFK_Fast_Base {
protected:
std::vector<std::vector<Frame>> chain_cache;
std::vector<double> vars, variables0;
std::vector<Frame> test_tips;
std::vector<uint8_t> links_changed;
bool use_incremental;
bool last_use_incremental;
void updateIncremental(const std::vector<double>& vars0) {
FNPROFILER();
// PROFILER_COUNTER("incremental update count");
// init variable lists
vars = vars0;
updateMimic(vars);
for (auto& vi : active_variables) {
// vars[vi] = vars0[vi];
variables0[vi] = variables_[vi];
}
// find moved links
for (auto* link_model : link_schedule)
links_changed[link_model->getLinkIndex()] = false;
for (auto& x : variable_to_link_map) {
auto variable_index = x.first;
auto link_index = x.second;
if (vars[variable_index] != variables_[variable_index])
links_changed[link_index] = true;
}
// update
for (size_t ichain = 0; ichain < link_chains.size(); ichain++) {
auto& link_chain = link_chains[ichain];
auto& cache_chain = chain_cache[ichain];
size_t iposmax = 0;
for (size_t ipos = 0; ipos < link_chain.size(); ipos++) {
auto* link_model = link_chain[ipos];
bool changed = links_changed[link_model->getLinkIndex()];
if (changed) iposmax = ipos;
}
for (size_t ipos = 0; ipos <= iposmax; ipos++) {
auto* link_model = link_chain[ipos];
auto* joint_model = link_model->getParentJointModel();
bool changed = links_changed[link_model->getLinkIndex()];
if (cache_chain.size() <= ipos || changed) {
Frame before, after;
if (ipos < cache_chain.size()) {
before = cache_chain[ipos];
} else {
if (ipos > 0) {
concat(cache_chain[ipos - 1], getLinkFrame(link_model),
getJointFrame(joint_model), before);
} else {
concat(getLinkFrame(link_model), getJointFrame(joint_model),
before);
}
}
chain_cache[ichain].resize(ipos + 1, Frame::identity());
if (changed) {
if (ichain > 0 && ipos < link_chains[ichain - 1].size() &&
link_chains[ichain][ipos] == link_chains[ichain - 1][ipos]) {
after = chain_cache[ichain - 1][ipos];
} else {
size_t vstart = joint_model->getFirstVariableIndex();
size_t vcount = joint_model->getVariableCount();
if (vcount == 1)
variables_[vstart] = vars[vstart];
else
for (size_t vi = vstart; vi < vstart + vcount; vi++)
variables_[vi] = vars[vi];
if (ipos > 0) {
concat(cache_chain[ipos - 1], getLinkFrame(link_model),
getJointFrame(joint_model), after);
} else {
concat(getLinkFrame(link_model), getJointFrame(joint_model),
after);
}
if (vcount == 1)
variables_[vstart] = variables0[vstart];
else
for (size_t vi = vstart; vi < vstart + vcount; vi++)
variables_[vi] = variables0[vi];
// PROFILER_COUNTER("incremental update transforms");
}
chain_cache[ichain][ipos] = after;
// tipFrames[ichain] = inverse(before) * tipFrames[ichain];
// tipFrames[ichain] = after * tipFrames[ichain];
/*Frame before_inverse;
invert(before, before_inverse);
//tipFrames[ichain] = after * before_inverse * tipFrames[ichain];
{
concat(after, before_inverse, tip_frames[ichain],
tip_frames[ichain]);
}*/
change(after, before, tip_frames[ichain], tip_frames[ichain]);
} else {
after = before;
chain_cache[ichain][ipos] = after;
}
}
}
}
// set new vars
// variables_ = vars;
for (auto& vi : active_variables) variables_[vi] = vars[vi];
// test
if (0) {
test_tips = tip_frames;
RobotFK_Fast_Base::applyConfiguration(vars);
for (size_t i = 0; i < tip_frames.size(); i++) {
auto dist = tip_frames[i].pos.distance(test_tips[i].pos);
LOG_VAR(dist);
if (dist > 0.001) {
LOG(tip_frames[i].pos.x(), tip_frames[i].pos.y(),
tip_frames[i].pos.z());
LOG(test_tips[i].pos.x(), test_tips[i].pos.y(), test_tips[i].pos.z());
ERROR("incremental update error");
}
}
}
}
public:
RobotFK_Fast(moveit::core::RobotModelConstPtr model)
: RobotFK_Fast_Base(model), use_incremental(false) {}
inline void incrementalBegin(const std::vector<double>& jj) {
applyConfiguration(jj);
chain_cache.clear();
chain_cache.resize(tip_frames.size());
links_changed.resize(robot_model_->getLinkModelCount());
vars.resize(jj.size());
variables0.resize(jj.size());
use_incremental = true;
}
inline void incrementalEnd() {
use_incremental = false;
// applyConfiguration(variables_);
}
inline void applyConfiguration(const std::vector<double>& jj) {
if (use_incremental)
updateIncremental(jj);
else
RobotFK_Fast_Base::applyConfiguration(jj);
}
};
// fast tree fk jacobian
class RobotFK_Jacobian : public RobotFK_Fast {
typedef RobotFK_Fast Base;
protected:
std::vector<std::vector<const moveit::core::JointModel*>> joint_dependencies;
std::vector<int> tip_dependencies;
public:
RobotFK_Jacobian(moveit::core::RobotModelConstPtr model)
: RobotFK_Fast(model) {}
void initialize(const std::vector<size_t>& tip_link_indices) {
Base::initialize(tip_link_indices);
auto tip_count = tip_names.size();
joint_dependencies.resize(robot_model_->getJointModelCount());
for (auto& x : joint_dependencies) x.clear();
for (auto* link_model : link_schedule) {
auto* joint_model = link_model->getParentJointModel();
joint_dependencies[joint_model->getJointIndex()].push_back(joint_model);
}
for (auto* link_model : link_schedule) {
auto* joint_model = link_model->getParentJointModel();
if (auto* mimic = joint_model->getMimic()) {
while (mimic->getMimic() && mimic->getMimic() != joint_model)
mimic = mimic->getMimic();
joint_dependencies[mimic->getJointIndex()].push_back(joint_model);
}
}
tip_dependencies.resize(robot_model_->getJointModelCount() * tip_count);
for (auto& x : tip_dependencies) x = 0;
for (size_t tip_index = 0; tip_index < tip_count; tip_index++) {
for (auto* link_model = tip_links[tip_index]; link_model;
link_model = link_model->getParentLinkModel()) {
auto* joint_model = link_model->getParentJointModel();
tip_dependencies[joint_model->getJointIndex() * tip_count + tip_index] =
1;
}
}
}
void computeJacobian(const std::vector<size_t>& variable_indices,
Eigen::MatrixXd& jacobian) {
double step_size = 0.00001;
// double half_step_size = step_size * 0.5;
double inv_step_size = 1.0 / step_size;
auto tip_count = tip_frames.size();
jacobian.resize(static_cast<Eigen::Index>(tip_count * 6),
static_cast<Eigen::Index>(variable_indices.size()));
for (Eigen::Index icol = 0;
icol < static_cast<Eigen::Index>(variable_indices.size()); ++icol) {
for (Eigen::Index itip = 0; itip < static_cast<Eigen::Index>(tip_count);
++itip) {
jacobian(itip * 6 + 0, icol) = 0;
jacobian(itip * 6 + 1, icol) = 0;
jacobian(itip * 6 + 2, icol) = 0;
jacobian(itip * 6 + 3, icol) = 0;
jacobian(itip * 6 + 4, icol) = 0;
jacobian(itip * 6 + 5, icol) = 0;
}
}
for (size_t icol = 0; icol < variable_indices.size(); icol++) {
auto ivar = variable_indices[icol];
auto* var_joint_model =
robot_model_->getJointOfVariable(static_cast<int>(ivar));
if (var_joint_model->getMimic()) continue;
for (auto* joint_model :
joint_dependencies[var_joint_model->getJointIndex()]) {
double scale = 1;
for (auto* m = joint_model;
m->getMimic() && m->getMimic() != joint_model; m = m->getMimic()) {
scale *= m->getMimicFactor();
}
auto* link_model = joint_model->getChildLinkModel();
switch (joint_model->getType()) {
case moveit::core::JointModel::FIXED: {
// fixed joint: zero gradient (do nothing)
continue;
}
case moveit::core::JointModel::REVOLUTE: {
auto& link_frame = global_frames[link_model->getLinkIndex()];
for (size_t itip = 0; itip < tip_count; itip++) {
if (!tip_dependencies[joint_model->getJointIndex() * tip_count +
itip])
continue;
auto& tip_frame = tip_frames[itip];
auto q = link_frame.rot.inverse() * tip_frame.rot;
q = q.inverse();
auto rot = joint_axis_list_[joint_model->getJointIndex()];
quat_mul_vec(q, rot, rot);
auto vel = link_frame.pos - tip_frame.pos;
quat_mul_vec(tip_frame.rot.inverse(), vel, vel);
vel = vel.cross(rot);
auto eigen_itip = static_cast<Eigen::Index>(itip);
auto eigen_icol = static_cast<Eigen::Index>(icol);
jacobian(eigen_itip * 6 + 0, eigen_icol) += vel.x() * scale;
jacobian(eigen_itip * 6 + 1, eigen_icol) += vel.y() * scale;
jacobian(eigen_itip * 6 + 2, eigen_icol) += vel.z() * scale;
jacobian(eigen_itip * 6 + 3, eigen_icol) += rot.x() * scale;
jacobian(eigen_itip * 6 + 4, eigen_icol) += rot.y() * scale;
jacobian(eigen_itip * 6 + 5, eigen_icol) += rot.z() * scale;
// LOG("a", vel.x(), vel.y(), vel.z(), rot.x(), rot.y(), rot.z());
}
continue;
}
case moveit::core::JointModel::PRISMATIC: {
auto& link_frame = global_frames[link_model->getLinkIndex()];
for (size_t itip = 0; itip < tip_count; itip++) {
if (!tip_dependencies[joint_model->getJointIndex() * tip_count +
itip])
continue;
auto& tip_frame = tip_frames[itip];
auto q = link_frame.rot.inverse() * tip_frame.rot;
q = q.inverse();
auto axis = joint_axis_list_[joint_model->getJointIndex()];
auto v = axis;
quat_mul_vec(q, axis, v);
auto eigen_itip = static_cast<Eigen::Index>(itip);
auto eigen_icol = static_cast<Eigen::Index>(icol);
jacobian(eigen_itip * 6 + 0, eigen_icol) += v.x() * scale;
jacobian(eigen_itip * 6 + 1, eigen_icol) += v.y() * scale;
jacobian(eigen_itip * 6 + 2, eigen_icol) += v.z() * scale;
// LOG("a", v.x(), v.y(), v.z(), 0, 0, 0);
}
continue;
}
default: {
// numeric differentiation for joint types that are not yet
// implemented / or joint types that might be added to moveit in the
// future
auto ivar2 = ivar;
if (joint_model->getMimic())
ivar2 = ivar2 - var_joint_model->getFirstVariableIndex() +
joint_model->getFirstVariableIndex();
auto& link_frame_1 = global_frames[link_model->getLinkIndex()];
auto v0 = variables_[ivar2];
// auto joint_frame_1 = getJointFrame(joint_model);
variables_[ivar2] = v0 + step_size;
auto joint_frame_2 = getJointFrame(joint_model);
variables_[ivar2] = v0;
Frame link_frame_2;
if (auto* parent_link_model = joint_model->getParentLinkModel())
concat(global_frames[parent_link_model->getLinkIndex()],
getLinkFrame(link_model), joint_frame_2, link_frame_2);
else
concat(getLinkFrame(link_model), joint_frame_2, link_frame_2);
for (size_t itip = 0; itip < tip_count; itip++) {
if (!tip_dependencies[joint_model->getJointIndex() * tip_count +
itip])
continue;
auto tip_frame_1 = tip_frames[itip];
Frame tip_frame_2;
change(link_frame_2, link_frame_1, tip_frame_1, tip_frame_2);
auto twist = frameTwist(tip_frame_1, tip_frame_2);
auto eigen_itip = static_cast<Eigen::Index>(itip);
auto eigen_icol = static_cast<Eigen::Index>(icol);
jacobian(eigen_itip * 6 + 0, eigen_icol) +=
twist.vel.x() * inv_step_size * scale;
jacobian(eigen_itip * 6 + 1, eigen_icol) +=
twist.vel.y() * inv_step_size * scale;
jacobian(eigen_itip * 6 + 2, eigen_icol) +=
twist.vel.z() * inv_step_size * scale;
jacobian(eigen_itip * 6 + 3, eigen_icol) +=
twist.rot.x() * inv_step_size * scale;
jacobian(eigen_itip * 6 + 4, eigen_icol) +=
twist.rot.y() * inv_step_size * scale;
jacobian(eigen_itip * 6 + 5, eigen_icol) +=
twist.rot.z() * inv_step_size * scale;
}
continue;
}
}
}
}
}
};
#if 0
struct RobotFK : public RobotFK_Jacobian
{
std::vector<size_t> mutation_variable_indices;
std::vector<double> mutation_initial_variable_positions;
std::vector<double> mutation_temp;
RobotFK(moveit::core::RobotModelConstPtr model)
: RobotFK_Jacobian(model)
{
}
void initializeMutationApproximator(const std::vector<size_t>& variable_indices)
{
mutation_variable_indices = variable_indices;
mutation_initial_variable_positions = variables_;
}
void computeApproximateMutation1(size_t variable_index, double variable_delta, const aligned_vector<Frame>& input, aligned_vector<Frame>& output)
{
mutation_temp = mutation_initial_variable_positions;
mutation_temp[variable_index] += variable_delta;
applyConfiguration(mutation_temp);
output.clear();
for(auto& f : tip_frames) output.push_back(f);
}
void computeApproximateMutations(size_t mutation_count, const double* const* mutation_values, std::vector<aligned_vector<Frame>>& tip_frame_mutations)
{
auto tip_count = tip_names.size();
tip_frame_mutations.resize(mutation_count);
for(auto& m : tip_frame_mutations)
m.resize(tip_count);
for(size_t mutation_index = 0; mutation_index < mutation_count; mutation_index++)
{
mutation_temp = mutation_initial_variable_positions;
for(size_t i = 0; i < mutation_variable_indices.size(); i++)
{
mutation_temp[mutation_variable_indices[i]] = mutation_values[mutation_index][i];
}
applyConfiguration(mutation_temp);
for(size_t tip_index = 0; tip_index < tip_count; tip_index++)
{
tip_frame_mutations[mutation_index][tip_index] = tip_frames[tip_index];
}
}
}
};
#else
#define USE_QUADRATIC_EXTRAPOLATION 0
class RobotFK_Mutator : public RobotFK_Jacobian {
typedef RobotFK_Jacobian Base;
Eigen::MatrixXd mutation_approx_jacobian;
std::vector<aligned_vector<Frame>> mutation_approx_frames;
#if USE_QUADRATIC_EXTRAPOLATION
std::vector<aligned_vector<Frame>> mutation_approx_quadratics;
#endif
std::vector<size_t> mutation_approx_variable_indices;
std::vector<std::vector<int>> mutation_approx_mask;
std::vector<std::vector<size_t>> mutation_approx_map;
aligned_vector<Frame> tip_frames_aligned;
public:
RobotFK_Mutator(moveit::core::RobotModelConstPtr model)
: RobotFK_Jacobian(model) {}
void initializeMutationApproximator(
const std::vector<size_t>& variable_indices) {
FNPROFILER();
mutation_approx_variable_indices = variable_indices;
auto tip_count = tip_names.size();
tip_frames_aligned.resize(tip_frames.size());
for (size_t i = 0; i < tip_frames.size(); i++)
tip_frames_aligned[i] = tip_frames[i];
// init first order approximators
{
if (mutation_approx_frames.size() < tip_count)
mutation_approx_frames.resize(tip_count);
for (size_t itip = 0; itip < tip_count; itip++)
mutation_approx_frames[itip].resize(robot_model_->getVariableCount());
for (size_t itip = 0; itip < tip_count; itip++)
for (auto ivar : variable_indices)
mutation_approx_frames[itip][ivar] = Frame::identity();
computeJacobian(variable_indices, mutation_approx_jacobian);
for (size_t icol = 0; icol < variable_indices.size(); icol++) {
size_t ivar = variable_indices[icol];
for (size_t itip = 0; itip < tip_count; itip++) {
{
Vector3 t;
auto eigen_itip = static_cast<Eigen::Index>(itip);
auto eigen_icol = static_cast<Eigen::Index>(icol);
t.setX(mutation_approx_jacobian(eigen_itip * 6 + 0, eigen_icol));
t.setY(mutation_approx_jacobian(eigen_itip * 6 + 1, eigen_icol));
t.setZ(mutation_approx_jacobian(eigen_itip * 6 + 2, eigen_icol));
quat_mul_vec(tip_frames[itip].rot, t, t);
mutation_approx_frames[itip][ivar].pos = t;
}
{
Quaternion q;
auto eigen_itip = static_cast<Eigen::Index>(itip);
auto eigen_icol = static_cast<Eigen::Index>(icol);
q.setX(mutation_approx_jacobian(eigen_itip * 6 + 3, eigen_icol) *
0.5);
q.setY(mutation_approx_jacobian(eigen_itip * 6 + 4, eigen_icol) *
0.5);
q.setZ(mutation_approx_jacobian(eigen_itip * 6 + 5, eigen_icol) *
0.5);
q.setW(1.0);
quat_mul_quat(tip_frames[itip].rot, q, q);
q -= tip_frames[itip].rot;
mutation_approx_frames[itip][ivar].rot = q;
}
}
}
}
// init second order approximators
#if USE_QUADRATIC_EXTRAPOLATION
{
if (mutation_approx_quadratics.size() < tip_count)
mutation_approx_quadratics.resize(tip_count);
for (size_t itip = 0; itip < tip_count; itip++)
mutation_approx_quadratics[itip].resize(
robot_model_->getVariableCount());
for (size_t itip = 0; itip < tip_count; itip++)
for (auto ivar : variable_indices)
mutation_approx_quadratics[itip][ivar].pos = Vector3(0, 0, 0);
for (auto ivar : variable_indices) {
auto* var_joint_model = robot_model_->getJointOfVariable(ivar);
if (var_joint_model->getMimic()) continue;
for (auto* joint_model :
joint_dependencies[var_joint_model->getJointIndex()]) {
double scale = 1;
for (auto* m = joint_model;
m->getMimic() && m->getMimic() != joint_model;
m = m->getMimic()) {
scale *= m->getMimicFactor();
}
auto* link_model = joint_model->getChildLinkModel();
switch (joint_model->getType()) {
case moveit::core::JointModel::REVOLUTE: {
auto& link_frame = global_frames[link_model->getLinkIndex()];
for (size_t itip = 0; itip < tip_count; itip++) {
if (!tip_dependencies[joint_model->getJointIndex() * tip_count +
itip])
continue;
auto& tip_frame = tip_frames[itip];
auto axis = joint_axis_list_[joint_model->getJointIndex()];
quat_mul_vec(link_frame.rot, axis, axis);
auto v = link_frame.pos - tip_frame.pos;
v -= axis * v.dot(axis);
mutation_approx_quadratics[itip][ivar].pos =
v * 0.5 * (scale * scale);
}
continue;
}
default: {
continue;
}
}
}
}
}
#endif
// init mask
if (mutation_approx_mask.size() < tip_count)
mutation_approx_mask.resize(tip_count);
if (mutation_approx_map.size() < tip_count)
mutation_approx_map.resize(tip_count);
for (size_t itip = 0; itip < tip_count; itip++) {
if (mutation_approx_mask[itip].size() < robot_model_->getVariableCount())
mutation_approx_mask[itip].resize(robot_model_->getVariableCount());
mutation_approx_map[itip].clear();
for (size_t ii = 0; ii < variable_indices.size(); ii++)
// for(size_t ivar : variable_indices)
{
auto ivar = variable_indices[ii];
auto& frame = mutation_approx_frames[itip][ivar];
bool b = false;
b |= (frame.pos.x() != 0.0);
b |= (frame.pos.y() != 0.0);
b |= (frame.pos.z() != 0.0);
b |= (frame.rot.x() != 0.0);
b |= (frame.rot.y() != 0.0);
b |= (frame.rot.z() != 0.0);
mutation_approx_mask[itip][ivar] = b;
if (b) mutation_approx_map[itip].push_back(ii);
}
}
}
#if FUNCTION_MULTIVERSIONING
__attribute__((hot)) __attribute__((noinline))
__attribute__((target("fma", "avx"))) void
computeApproximateMutation1(size_t variable_index, double variable_delta,
const aligned_vector<Frame>& input,
aligned_vector<Frame>& output) const {
// BLOCKPROFILER("computeApproximateMutations C");
auto tip_count = tip_names.size();
output.resize(tip_count);
for (size_t itip = 0; itip < tip_count; itip++) {
if (mutation_approx_mask[itip][variable_index] == 0) continue;
auto& joint_delta = mutation_approx_frames[itip][variable_index];
const Frame& tip_frame = input[itip];
const double* tip_frame_ptr = reinterpret_cast<const double*>(&tip_frame);
__m256d p = _mm256_load_pd(tip_frame_ptr + 0);
__m256d r = _mm256_load_pd(tip_frame_ptr + 4);
{
auto joint_delta_ptr =
reinterpret_cast<const double* __restrict__>(&joint_delta);
__m256d ff = _mm256_set1_pd(variable_delta);
p = _mm256_fmadd_pd(ff, _mm256_load_pd(joint_delta_ptr + 0), p);
r = _mm256_fmadd_pd(ff, _mm256_load_pd(joint_delta_ptr + 4), r);
}
#if USE_QUADRATIC_EXTRAPOLATION
{
auto joint_delta_ptr = static_cast<const double* __restrict__>(
&mutation_approx_quadratics[itip][variable_index]);
__m256d ff = _mm256_set1_pd(variable_delta * variable_delta);
p = _mm256_fmadd_pd(ff, _mm256_load_pd(joint_delta_ptr + 0), p);
}
#endif
auto& tip_mutation = output[itip];
double* __restrict__ tip_mutation_ptr =
reinterpret_cast<double*>(&tip_mutation);
_mm256_store_pd(tip_mutation_ptr + 0, p);
_mm256_store_pd(tip_mutation_ptr + 4, r);
}
}
__attribute__((hot)) __attribute__((noinline))
__attribute__((target("sse2"))) void
computeApproximateMutation1(size_t variable_index, double variable_delta,
const aligned_vector<Frame>& input,
aligned_vector<Frame>& output) const {
// BLOCKPROFILER("computeApproximateMutations C");
auto tip_count = tip_names.size();
output.resize(tip_count);
for (size_t itip = 0; itip < tip_count; itip++) {
if (mutation_approx_mask[itip][variable_index] == 0) continue;
auto& joint_delta = mutation_approx_frames[itip][variable_index];
const Frame& tip_frame = input[itip];
const double* tip_frame_ptr = reinterpret_cast<const double*>(&tip_frame);
__m128d pxy = _mm_load_pd(tip_frame_ptr + 0);
__m128d pzw = _mm_load_sd(tip_frame_ptr + 2);
__m128d rxy = _mm_load_pd(tip_frame_ptr + 4);
__m128d rzw = _mm_load_pd(tip_frame_ptr + 6);
{
auto joint_delta_ptr =
reinterpret_cast<const double* __restrict__>(&joint_delta);
__m128d ff = _mm_set1_pd(variable_delta);
pxy = _mm_add_pd(pxy, _mm_mul_pd(ff, _mm_load_pd(joint_delta_ptr + 0)));
pzw = _mm_add_sd(pzw, _mm_mul_sd(ff, _mm_load_sd(joint_delta_ptr + 2)));
rxy = _mm_add_pd(rxy, _mm_mul_pd(ff, _mm_load_pd(joint_delta_ptr + 4)));
rzw = _mm_add_pd(rzw, _mm_mul_pd(ff, _mm_load_pd(joint_delta_ptr + 6)));
}
#if USE_QUADRATIC_EXTRAPOLATION
{
auto joint_delta_ptr = static_cast<const double* __restrict__>(
&mutation_approx_quadratics[itip][variable_index]);
__m128d ff = _mm_set1_pd(variable_delta * variable_delta);
pxy = _mm_add_pd(pxy, _mm_mul_pd(ff, _mm_load_pd(joint_delta_ptr + 0)));
pzw = _mm_add_sd(pzw, _mm_mul_sd(ff, _mm_load_sd(joint_delta_ptr + 2)));
}
#endif
auto& tip_mutation = output[itip];
double* __restrict__ tip_mutation_ptr =
reinterpret_cast<double*>(&tip_mutation);
_mm_store_pd(tip_mutation_ptr + 0, pxy);
_mm_store_sd(tip_mutation_ptr + 2, pzw);
_mm_store_pd(tip_mutation_ptr + 4, rxy);
_mm_store_pd(tip_mutation_ptr + 6, rzw);
}
}
__attribute__((hot)) __attribute__((noinline))
__attribute__((target("default")))
#endif
void
computeApproximateMutation1(size_t variable_index, double variable_delta,
const aligned_vector<Frame>& input,
aligned_vector<Frame>& output) const {
// BLOCKPROFILER("computeApproximateMutations C");
auto tip_count = tip_names.size();
output.resize(tip_count);
for (size_t itip = 0; itip < tip_count; itip++) {
if (mutation_approx_mask[itip][variable_index] == 0) continue;
auto& joint_delta = mutation_approx_frames[itip][variable_index];
const Frame& tip_frame = input[itip];
double px = tip_frame.pos.x();
double py = tip_frame.pos.y();
double pz = tip_frame.pos.z();
double rx = tip_frame.rot.x();
double ry = tip_frame.rot.y();
double rz = tip_frame.rot.z();
double rw = tip_frame.rot.w();
px += joint_delta.pos.x() * variable_delta;
py += joint_delta.pos.y() * variable_delta;
pz += joint_delta.pos.z() * variable_delta;
#if USE_QUADRATIC_EXTRAPOLATION
double variable_delta_sq = variable_delta * variable_delta;
px += mutation_approx_quadratics[itip][variable_index].pos.x() *
variable_delta_sq;
py += mutation_approx_quadratics[itip][variable_index].pos.y() *
variable_delta_sq;
pz += mutation_approx_quadratics[itip][variable_index].pos.z() *
variable_delta_sq;
#endif
rx += joint_delta.rot.x() * variable_delta;
ry += joint_delta.rot.y() * variable_delta;
rz += joint_delta.rot.z() * variable_delta;
rw += joint_delta.rot.w() * variable_delta;
auto& tip_mutation = output[itip];
tip_mutation.pos.setX(px);
tip_mutation.pos.setY(py);
tip_mutation.pos.setZ(pz);
tip_mutation.rot.setX(rx);
tip_mutation.rot.setY(ry);
tip_mutation.rot.setZ(rz);
tip_mutation.rot.setW(rw);
}
}
#if FUNCTION_MULTIVERSIONING
__attribute__((hot)) __attribute__((noinline))
__attribute__((target("fma", "avx"))) void
computeApproximateMutations(
size_t mutation_count, const double* const* mutation_values,
std::vector<aligned_vector<Frame>>& tip_frame_mutations) const {
const double* p_variables = variables_.data();
auto tip_count = tip_names.size();
tip_frame_mutations.resize(mutation_count);
for (auto& m : tip_frame_mutations) m.resize(tip_count);
for (size_t itip = 0; itip < tip_count; itip++) {
auto& joint_deltas = mutation_approx_frames[itip];
const Frame& tip_frame = tip_frames_aligned[itip];
const double* tip_frame_ptr = reinterpret_cast<const double*>(&tip_frame);
__m256d p0 = _mm256_load_pd(tip_frame_ptr + 0);
__m256d r0 = _mm256_load_pd(tip_frame_ptr + 4);
for (size_t imutation = 0; imutation < mutation_count; imutation++) {
auto p = p0;
auto r = r0;
for (size_t vii : mutation_approx_map[itip]) {
size_t variable_index = mutation_approx_variable_indices[vii];
double variable_delta =
mutation_values[imutation][vii] - p_variables[variable_index];
{
auto joint_delta_ptr = reinterpret_cast<const double* __restrict__>(
&joint_deltas[variable_index]);
__m256d ff = _mm256_set1_pd(variable_delta);
p = _mm256_fmadd_pd(ff, _mm256_load_pd(joint_delta_ptr + 0), p);
r = _mm256_fmadd_pd(ff, _mm256_load_pd(joint_delta_ptr + 4), r);
}
#if USE_QUADRATIC_EXTRAPOLATION
{
auto joint_delta_ptr = reinterpret_cast<const double* __restrict__>(
&mutation_approx_quadratics[itip][variable_index]);
__m256d ff = _mm256_set1_pd(variable_delta * variable_delta);
p = _mm256_fmadd_pd(ff, _mm256_load_pd(joint_delta_ptr + 0), p);
}
#endif
}
auto& tip_mutation = tip_frame_mutations[imutation][itip];
double* __restrict__ tip_mutation_ptr =
reinterpret_cast<double*>(&tip_mutation);
_mm256_store_pd(tip_mutation_ptr + 0, p);
_mm256_store_pd(tip_mutation_ptr + 4, r);
}
}
}
__attribute__((hot)) __attribute__((noinline))
__attribute__((target("sse2"))) void
computeApproximateMutations(
size_t mutation_count, const double* const* mutation_values,
std::vector<aligned_vector<Frame>>& tip_frame_mutations) const {
const double* p_variables = variables_.data();
auto tip_count = tip_names.size();
tip_frame_mutations.resize(mutation_count);
for (auto& m : tip_frame_mutations) m.resize(tip_count);
for (size_t itip = 0; itip < tip_count; itip++) {
auto& joint_deltas = mutation_approx_frames[itip];
const Frame& tip_frame = tip_frames_aligned[itip];
const double* tip_frame_ptr = reinterpret_cast<const double*>(&tip_frame);
__m128d pxy0 = _mm_load_pd(tip_frame_ptr + 0);
__m128d pzw0 = _mm_load_sd(tip_frame_ptr + 2);
__m128d rxy0 = _mm_load_pd(tip_frame_ptr + 4);
__m128d rzw0 = _mm_load_pd(tip_frame_ptr + 6);
for (size_t imutation = 0; imutation < mutation_count; imutation++) {
auto pxy = pxy0;
auto pzw = pzw0;
auto rxy = rxy0;
auto rzw = rzw0;
for (size_t vii : mutation_approx_map[itip]) {
size_t variable_index = mutation_approx_variable_indices[vii];
double variable_delta =
mutation_values[imutation][vii] - p_variables[variable_index];
{
auto joint_delta_ptr = reinterpret_cast<const double* __restrict__>(
&joint_deltas[variable_index]);
__m128d ff = _mm_set1_pd(variable_delta);
pxy = _mm_add_pd(_mm_mul_pd(ff, _mm_load_pd(joint_delta_ptr + 0)),
pxy);
pzw = _mm_add_sd(_mm_mul_sd(ff, _mm_load_sd(joint_delta_ptr + 2)),
pzw);
rxy = _mm_add_pd(_mm_mul_pd(ff, _mm_load_pd(joint_delta_ptr + 4)),
rxy);
rzw = _mm_add_pd(_mm_mul_pd(ff, _mm_load_pd(joint_delta_ptr + 6)),
rzw);
}
#if USE_QUADRATIC_EXTRAPOLATION
{
auto joint_delta_ptr = reinterpret_cast<const double* __restrict__>(
&mutation_approx_quadratics[itip][variable_index]);
__m128d ff = _mm_set1_pd(variable_delta * variable_delta);
pxy = _mm_add_pd(_mm_mul_pd(ff, _mm_load_pd(joint_delta_ptr + 0)),
pxy);
pzw = _mm_add_sd(_mm_mul_sd(ff, _mm_load_sd(joint_delta_ptr + 2)),
pzw);
}
#endif
}
auto& tip_mutation = tip_frame_mutations[imutation][itip];
double* __restrict__ tip_mutation_ptr =
reinterpret_cast<double*>(&tip_mutation);
_mm_store_pd(tip_mutation_ptr + 0, pxy);
_mm_store_sd(tip_mutation_ptr + 2, pzw);
_mm_store_pd(tip_mutation_ptr + 4, rxy);
_mm_store_pd(tip_mutation_ptr + 6, rzw);
}
}
}
__attribute__((hot)) __attribute__((noinline))
__attribute__((target("default")))
#endif
void
computeApproximateMutations(
size_t mutation_count, const double* const* mutation_values,
std::vector<aligned_vector<Frame>>& tip_frame_mutations) const {
const double* p_variables = variables_.data();
auto tip_count = tip_names.size();
tip_frame_mutations.resize(mutation_count);
for (auto& m : tip_frame_mutations) m.resize(tip_count);
for (size_t itip = 0; itip < tip_count; itip++) {
auto& joint_deltas = mutation_approx_frames[itip];
const Frame& tip_frame = tip_frames[itip];
for (size_t imutation = 0; imutation < mutation_count; imutation++) {
double px = tip_frame.pos.x();
double py = tip_frame.pos.y();
double pz = tip_frame.pos.z();
double rx = tip_frame.rot.x();
double ry = tip_frame.rot.y();
double rz = tip_frame.rot.z();
double rw = tip_frame.rot.w();
for (size_t vii : mutation_approx_map[itip]) {
size_t variable_index = mutation_approx_variable_indices[vii];
double variable_delta =
mutation_values[imutation][vii] - p_variables[variable_index];
px += joint_deltas[variable_index].pos.x() * variable_delta;
py += joint_deltas[variable_index].pos.y() * variable_delta;
pz += joint_deltas[variable_index].pos.z() * variable_delta;
#if USE_QUADRATIC_EXTRAPOLATION
double variable_delta_sq = variable_delta * variable_delta;
px += mutation_approx_quadratics[itip][variable_index].pos.x() *
variable_delta_sq;
py += mutation_approx_quadratics[itip][variable_index].pos.y() *
variable_delta_sq;
pz += mutation_approx_quadratics[itip][variable_index].pos.z() *
variable_delta_sq;
#endif
rx += joint_deltas[variable_index].rot.x() * variable_delta;
ry += joint_deltas[variable_index].rot.y() * variable_delta;
rz += joint_deltas[variable_index].rot.z() * variable_delta;
rw += joint_deltas[variable_index].rot.w() * variable_delta;
}
auto& tip_mutation = tip_frame_mutations[imutation][itip];
tip_mutation.pos.setX(px);
tip_mutation.pos.setY(py);
tip_mutation.pos.setZ(pz);
tip_mutation.rot.setX(rx);
tip_mutation.rot.setY(ry);
tip_mutation.rot.setZ(rz);
tip_mutation.rot.setW(rw);
}
}
}
};
#if 0
class RobotFK_Mutator_2 : public RobotFK_Mutator
{
struct JointApprox
{
ssize_t mutation_index;
ssize_t variable_index;
Vector3 delta_position;
Vector3 delta_rotation;
size_t link_index;
size_t parent_link_index;
Vector3 link_position;
};
std::vector<JointApprox> joint_approximators;
struct LinkApprox
{
Vector3 position;
Vector3 rotation;
};
std::vector<LinkApprox> link_approximators;
std::vector<int> link_approx_mask;
std::vector<std::vector<size_t>> variable_to_approximator_index_map;
public:
RobotFK_Mutator_2(moveit::core::RobotModelConstPtr model)
: RobotFK_Mutator(model)
{
}
void initializeMutationApproximator(const std::vector<size_t>& variable_indices)
{
RobotFK_Mutator::initializeMutationApproximator(variable_indices);
BLOCKPROFILER("initializeMutationApproximator tree");
auto tip_count = tip_names.size();
link_approximators.resize(robot_model_->getLinkModelCount() + 1);
for(auto& l : link_approximators)
{
l.position = Vector3(0, 0, 0);
l.rotation = Vector3(0, 0, 0);
}
link_approx_mask.clear();
link_approx_mask.resize(robot_model_->getLinkModelCount(), 0);
joint_approximators.clear();
// build joint approximators
for(size_t imut = 0; imut < variable_indices.size(); imut++)
{
size_t ivar = variable_indices[imut];
auto* joint_model = robot_model_->getJointOfVariable(ivar);
{
auto* link_model = joint_model->getChildLinkModel();
// if(link_approx_mask[link_model->getLinkIndex()]) continue;
joint_approximators.emplace_back();
auto& joint = joint_approximators.back();
joint.mutation_index = imut;
joint.variable_index = ivar;
joint.link_index = link_model->getLinkIndex();
link_approx_mask[link_model->getLinkIndex()] = 1;
}
for(auto* mimic_joint_model : joint_model->getMimicRequests())
{
// LOG("mimic", mimic_joint_model);
auto* joint_model = mimic_joint_model;
auto* link_model = joint_model->getChildLinkModel();
// if(link_approx_mask[link_model->getLinkIndex()]) continue;
joint_approximators.emplace_back();
auto& joint = joint_approximators.back();
joint.mutation_index = imut;
joint.variable_index = ivar;
joint.link_index = link_model->getLinkIndex();
link_approx_mask[link_model->getLinkIndex()] = 1;
}
}
for(auto& joint : joint_approximators)
{
// size_t imut = joint.mutation_index;
// size_t ivar = joint.variable_index;
auto* link_model = robot_model_->getLinkModel(joint.link_index);
auto* joint_model = link_model->getParentJointModel();
joint.delta_position = Vector3(0, 0, 0);
joint.delta_rotation = Vector3(0, 0, 0);
auto& link_frame = global_frames[link_model->getLinkIndex()];
switch(joint_model->getType())
{
case moveit::core::JointModel::REVOLUTE:
quat_mul_vec(link_frame.rot, joint_axis_list_[joint_model->getJointIndex()], joint.delta_rotation);
break;
case moveit::core::JointModel::PRISMATIC:
quat_mul_vec(link_frame.rot, joint_axis_list_[joint_model->getJointIndex()], joint.delta_position);
break;
}
for(auto* j = joint_model; j->getMimic(); j = j->getMimic())
{
joint.delta_rotation *= j->getMimicFactor();
joint.delta_position *= j->getMimicFactor();
break;
}
}
// continue extrapolation to tip frames, if not already done
for(auto* link_model : tip_links)
{
if(link_approx_mask[link_model->getLinkIndex()]) continue;
joint_approximators.emplace_back();
auto& joint = joint_approximators.back();
joint.mutation_index = 0;
joint.variable_index = 0;
joint.link_index = link_model->getLinkIndex();
joint.delta_position = Vector3(0, 0, 0);
joint.delta_rotation = Vector3(0, 0, 0);
link_approx_mask[link_model->getLinkIndex()] = 1;
}
std::sort(joint_approximators.begin(), joint_approximators.end(), [](const JointApprox& a, const JointApprox& b) { return a.link_index < b.link_index; });
for(auto& joint : joint_approximators)
{
for(auto* link_model = robot_model_->getLinkModel(joint.link_index); link_model;)
{
if(link_approx_mask[link_model->getLinkIndex()] >= 2)
{
joint.parent_link_index = link_model->getLinkIndex();
joint.link_position = global_frames[joint.link_index].pos - global_frames[joint.parent_link_index].pos;
link_approx_mask[joint.link_index] = 2;
break;
}
link_model = link_model->getParentLinkModel();
if(link_model == 0)
{
joint.parent_link_index = robot_model_->getLinkModelCount();
joint.link_position = global_frames[joint.link_index].pos;
link_approx_mask[joint.link_index] = 2;
break;
}
}
}
variable_to_approximator_index_map.resize(robot_model_->getVariableCount());
for(auto& l : variable_to_approximator_index_map)
l.clear();
for(size_t approximator_index = 0; approximator_index < joint_approximators.size(); approximator_index++)
{
if(joint_approximators[approximator_index].variable_index < 0) continue;
variable_to_approximator_index_map[joint_approximators[approximator_index].variable_index].push_back(approximator_index);
}
}
void computeApproximateMutations(size_t mutation_count, const double* const* mutation_values, std::vector<aligned_vector<Frame>>& tip_frame_mutations)
{
auto tip_count = tip_names.size();
tip_frame_mutations.resize(mutation_count);
for(auto& m : tip_frame_mutations)
m.resize(tip_count);
for(size_t imutation = 0; imutation < mutation_count; imutation++)
{
for(auto& joint : joint_approximators)
{
double dvar;
/*if(joint.mutation_index < 0)
dvar = 0;
else*/
dvar = mutation_values[imutation][joint.mutation_index] - variables_[joint.variable_index];
Vector3 dpos = joint.delta_position * dvar + joint.link_position;
auto& parent = link_approximators[joint.parent_link_index];
// if(dpos.x() || dpos.y() || dpos.z())
{
Vector3 dpos1 = Vector3(parent.rotation.y() * dpos.z() - parent.rotation.z() * dpos.y(), parent.rotation.z() * dpos.x() - parent.rotation.x() * dpos.z(), parent.rotation.x() * dpos.y() - parent.rotation.y() * dpos.x());
/*double xx = 0.5 * parent.rotation.x() * parent.rotation.x();
double yy = 0.5 * parent.rotation.y() * parent.rotation.y();
double zz = 0.5 * parent.rotation.z() * parent.rotation.z();
Vector3 dpos2 = Vector3(
dpos.x() * (yy + zz),
dpos.y() * (xx + zz),
dpos.z() * (xx + yy)
);*/
dpos += dpos1;
}
// dpos -= dpos2;
auto& link = link_approximators[joint.link_index];
link.position = parent.position + dpos;
link.rotation = parent.rotation + joint.delta_rotation * dvar;
}
for(size_t itip = 0; itip < tip_count; itip++)
{
const Frame& tip_frame = tip_frames[itip];
auto& tip_mutation = tip_frame_mutations[imutation][itip];
auto& link = link_approximators[tip_links[itip]->getLinkIndex()];
tip_mutation.pos = link.position;
tip_mutation.rot = tf2::Quaternion(link.rotation.x() * 0.5, link.rotation.y() * 0.5, link.rotation.z() * 0.5, 1.0) * tip_frame.rot;
/*tip_mutation.rot = tf2::Quaternion(
link.rotation.x() * 0.5,
link.rotation.y() * 0.5,
link.rotation.z() * 0.5,
1.0
- link.rotation.length2() * 0.125
) * tip_frame.rot;*/
}
}
}
};
typedef RobotFK_Mutator_2 RobotFK;
#else
typedef RobotFK_Mutator RobotFK;
#endif
#endif
// for comparison
class RobotFK_MoveIt {
moveit::core::RobotModelConstPtr robot_model_;
moveit::core::RobotState robot_state;
std::vector<Frame> tipFrames;
std::vector<const moveit::core::LinkModel*> tipLinks;
std::vector<double> jj;
public:
RobotFK_MoveIt(moveit::core::RobotModelConstPtr model)
: robot_model_(model), robot_state(model) {}
void initialize(const std::vector<size_t>& tip_link_indices) {
tipFrames.resize(tip_link_indices.size());
tipLinks.resize(tip_link_indices.size());
for (size_t i = 0; i < tip_link_indices.size(); i++)
tipLinks[i] = robot_model_->getLinkModel(tip_link_indices[i]);
}
void applyConfiguration(const std::vector<double>& jj0) {
BLOCKPROFILER("RobotFK_MoveIt applyConfiguration");
jj = jj0;
robot_model_->interpolate(jj0.data(), jj0.data(), 0.5,
jj.data()); // force mimic update
robot_state.setVariablePositions(jj);
robot_state.update();
for (size_t i = 0; i < tipFrames.size(); i++)
tipFrames[i] = Frame(robot_state.getGlobalLinkTransform(tipLinks[i]));
}
inline void incrementalBegin([[maybe_unused]] const std::vector<double>&) {}
inline void incrementalEnd() {}
const Frame& getTipFrame(size_t fi) const { return tipFrames[fi]; }
const std::vector<Frame>& getTipFrames() const { return tipFrames; }
};
} // namespace bio_ik
| 39.140304 | 239 | 0.616983 | [
"vector",
"model"
] |
07e17d721a02d810e1248226f1f81237cfb002d1 | 23,366 | cpp | C++ | examples/GwenGUISupport/gwenInternalData.cpp | ousttrue/bullet3 | 8ad206dd144b94767718cd71cf21f0d37ea89268 | [
"Zlib"
] | null | null | null | examples/GwenGUISupport/gwenInternalData.cpp | ousttrue/bullet3 | 8ad206dd144b94767718cd71cf21f0d37ea89268 | [
"Zlib"
] | null | null | null | examples/GwenGUISupport/gwenInternalData.cpp | ousttrue/bullet3 | 8ad206dd144b94767718cd71cf21f0d37ea89268 | [
"Zlib"
] | null | null | null | #include "gwenInternalData.h"
#include "Gwen/Controls/TreeNode.h"
#include "GwenTextureWindow.h"
#include "GraphingTexture.h"
#include "opengl_fontstashcallbacks.h"
#include <memory>
#include <tuple>
#include <functional>
#include <Common2dCanvasInterface.h>
#include <CommonExampleInterface.h>
#include <Bullet3Common/b3HashMap.h>
#define MAX_GRAPH_WINDOWS 5
class MyMenuItems : public Gwen::Controls::Base
{
public:
b3FileOpenCallback m_fileOpenCallback;
b3QuitCallback m_quitCallback;
MyMenuItems() : Gwen::Controls::Base(0), m_fileOpenCallback(0)
{
}
void myQuitApp(Gwen::Controls::Base* pControl)
{
if (m_quitCallback)
{
(m_quitCallback)();
}
}
void fileOpen(Gwen::Controls::Base* pControl)
{
if (m_fileOpenCallback)
{
(m_fileOpenCallback)();
}
}
};
struct MyTestMenuBar : public Gwen::Controls::MenuStrip
{
Gwen::Controls::MenuItem* m_fileMenu;
Gwen::Controls::MenuItem* m_viewMenu;
MyMenuItems* m_menuItems;
MyTestMenuBar(Gwen::Controls::Base* pParent)
: Gwen::Controls::MenuStrip(pParent)
{
// Gwen::Controls::MenuStrip* menu = new Gwen::Controls::MenuStrip( pParent );
{
m_menuItems = new MyMenuItems();
m_menuItems->m_fileOpenCallback = 0;
m_menuItems->m_quitCallback = 0;
m_fileMenu = AddItem(L"File");
m_fileMenu->GetMenu()->AddItem(L"Open", m_menuItems, (Gwen::Event::Handler::Function)&MyMenuItems::fileOpen);
m_fileMenu->GetMenu()->AddItem(L"Quit", m_menuItems, (Gwen::Event::Handler::Function)&MyMenuItems::myQuitApp);
m_viewMenu = AddItem(L"View");
}
}
virtual ~MyTestMenuBar()
{
delete m_menuItems;
}
};
struct GL3TexLoader : public MyTextureLoader
{
b3HashMap<b3HashString, GLint> m_hashMap;
virtual void LoadTexture(Gwen::Texture* pTexture)
{
Gwen::String namestr = pTexture->name.Get();
const char* n = namestr.c_str();
GLint* texIdPtr = m_hashMap[n];
if (texIdPtr)
{
pTexture->m_intData = *texIdPtr;
}
}
virtual void FreeTexture(Gwen::Texture* pTexture)
{
}
};
using OnButton = std::function<void()>;
struct MyMenuItemHander : public Gwen::Event::Handler
{
int m_buttonId;
OnButton m_onButtonB;
OnButton m_onButtonD;
std::function<void(int)> m_onButtonE;
MyMenuItemHander(int buttonId,
const OnButton& onButtonB,
const OnButton& onButtonD,
const std::function<void(int)>& onButtonE)
: m_buttonId(buttonId), m_onButtonB(onButtonB), m_onButtonD(onButtonD), m_onButtonE(onButtonE)
{
}
void onButtonA(Gwen::Controls::Base* pControl)
{
//const Gwen::String& name = pControl->GetName();
Gwen::Controls::TreeNode* node = (Gwen::Controls::TreeNode*)pControl;
// Gwen::Controls::Label* l = node->GetButton();
Gwen::UnicodeString la = node->GetButton()->GetText(); // node->GetButton()->GetName();// GetText();
Gwen::String laa = Gwen::Utility::UnicodeToString(la);
// const char* ha = laa.c_str();
//printf("selected %s\n", ha);
//int dep = but->IsDepressed();
//int tog = but->GetToggleState();
// if (m_toggleButtonCallback)
// (*m_toggleButtonCallback)(m_buttonId, tog);
}
void onButtonB(Gwen::Controls::Base* pControl)
{
Gwen::Controls::Label* label = (Gwen::Controls::Label*)pControl;
Gwen::UnicodeString la = label->GetText(); // node->GetButton()->GetName();// GetText();
Gwen::String laa = Gwen::Utility::UnicodeToString(la);
//const char* ha = laa.c_str();
m_onButtonB();
}
void onButtonC(Gwen::Controls::Base* pControl)
{
/*Gwen::Controls::Label* label = (Gwen::Controls::Label*) pControl;
Gwen::UnicodeString la = label->GetText();// node->GetButton()->GetName();// GetText();
Gwen::String laa = Gwen::Utility::UnicodeToString(la);
const char* ha = laa.c_str();
printf("onButtonC ! %s\n", ha);
*/
}
void onButtonD(Gwen::Controls::Base* pControl)
{
/* Gwen::Controls::Label* label = (Gwen::Controls::Label*) pControl;
Gwen::UnicodeString la = label->GetText();// node->GetButton()->GetName();// GetText();
Gwen::String laa = Gwen::Utility::UnicodeToString(la);
const char* ha = laa.c_str();
*/
// printf("onKeyReturn ! \n");
m_onButtonD();
}
void onButtonE(Gwen::Controls::Base* pControl)
{
// printf("select %d\n",m_buttonId);
m_onButtonE(m_buttonId);
}
void onButtonF(Gwen::Controls::Base* pControl)
{
//printf("selection changed!\n");
}
void onButtonG(Gwen::Controls::Base* pControl)
{
//printf("onButtonG !\n");
}
};
struct QuickCanvas : public Common2dCanvasInterface
{
GwenInternalData* m_internalData;
GL3TexLoader* m_myTexLoader;
MyGraphWindow* m_gw[MAX_GRAPH_WINDOWS];
GraphingTexture* m_gt[MAX_GRAPH_WINDOWS];
int m_curNumGraphWindows;
QuickCanvas(GwenInternalData* internalData, GL3TexLoader* myTexLoader)
: m_internalData(internalData),
m_myTexLoader(myTexLoader),
m_curNumGraphWindows(0)
{
for (int i = 0; i < MAX_GRAPH_WINDOWS; i++)
{
m_gw[i] = 0;
m_gt[i] = 0;
}
}
virtual ~QuickCanvas() {}
virtual int createCanvas(const char* canvasName, int width, int height, int xPos, int yPos)
{
if (m_curNumGraphWindows < MAX_GRAPH_WINDOWS)
{
//find a slot
int slot = m_curNumGraphWindows;
btAssert(slot < MAX_GRAPH_WINDOWS);
if (slot >= MAX_GRAPH_WINDOWS)
return 0; //don't crash
m_curNumGraphWindows++;
MyGraphInput input(m_internalData);
input.m_width = width;
input.m_height = height;
input.m_xPos = xPos;
input.m_yPos = yPos;
input.m_name = canvasName;
input.m_texName = canvasName;
m_gt[slot] = new GraphingTexture;
m_gt[slot]->create(width, height);
int texId = m_gt[slot]->getTextureId();
m_myTexLoader->m_hashMap.insert(canvasName, texId);
m_gw[slot] = setupTextureWindow(input);
return slot;
}
return -1;
}
virtual void destroyCanvas(int canvasId)
{
btAssert(canvasId >= 0);
delete m_gt[canvasId];
m_gt[canvasId] = 0;
destroyTextureWindow(m_gw[canvasId]);
m_gw[canvasId] = 0;
m_curNumGraphWindows--;
}
virtual void setPixel(int canvasId, int x, int y, unsigned char red, unsigned char green, unsigned char blue, unsigned char alpha)
{
btAssert(canvasId >= 0);
btAssert(canvasId < m_curNumGraphWindows);
m_gt[canvasId]->setPixel(x, y, red, green, blue, alpha);
}
virtual void getPixel(int canvasId, int x, int y, unsigned char& red, unsigned char& green, unsigned char& blue, unsigned char& alpha)
{
btAssert(canvasId >= 0);
btAssert(canvasId < m_curNumGraphWindows);
m_gt[canvasId]->getPixel(x, y, red, green, blue, alpha);
}
virtual void refreshImageData(int canvasId)
{
m_gt[canvasId]->uploadImageData();
}
};
struct MyComboBoxHander : public Gwen::Event::Handler
{
GwenInternalData* m_data;
int m_buttonId;
MyComboBoxHander(GwenInternalData* data, int buttonId)
: m_data(data),
m_buttonId(buttonId)
{
}
void onSelect(Gwen::Controls::Base* pControl)
{
Gwen::Controls::ComboBox* but = (Gwen::Controls::ComboBox*)pControl;
Gwen::String str = Gwen::Utility::UnicodeToString(but->GetSelectedItem()->GetText());
if (m_data->m_comboBoxCallback)
(m_data->m_comboBoxCallback)(m_buttonId, str.c_str());
}
};
struct MyButtonHander : public Gwen::Event::Handler
{
GwenInternalData* m_data;
int m_buttonId;
MyButtonHander(GwenInternalData* data, int buttonId)
: m_data(data),
m_buttonId(buttonId)
{
}
void onButtonA(Gwen::Controls::Base* pControl)
{
Gwen::Controls::Button* but = (Gwen::Controls::Button*)pControl;
// int dep = but->IsDepressed();
int tog = but->GetToggleState();
if (m_data->m_toggleButtonCallback)
(m_data->m_toggleButtonCallback)(m_buttonId, tog);
}
};
//
// GwenInternalData
//
GwenInternalData::GwenInternalData(int width, int height, float retinaScale)
{
m_myTexLoader.reset(new GL3TexLoader);
m_curYposition = 20;
m_primRenderer = new GLPrimitiveRenderer();
m_primRenderer->setScreenSize(width, height);
m_renderCallbacks = new OpenGL2RenderCallbacks(m_primRenderer->getData());
auto fontstash = std::make_shared<FontStash>(512, 512, m_renderCallbacks); //256,256);//,1024);//512,512);
pRenderer.reset(new GwenOpenGL3CoreRenderer(m_primRenderer, fontstash, width, height, retinaScale, m_myTexLoader.get()));
skin.SetRender(pRenderer.get());
pCanvas.reset(new Gwen::Controls::Canvas(&skin));
pCanvas->SetSize(width, height);
pCanvas->SetDrawBackground(false);
pCanvas->SetBackgroundColor(Gwen::Color(150, 170, 170, 255));
m_menubar.reset(new MyTestMenuBar(pCanvas.get()));
m_viewMenu = m_menubar->m_viewMenu;
m_menuItems = m_menubar->m_menuItems;
m_bar.reset(new Gwen::Controls::StatusBar(pCanvas.get()));
m_rightStatusBar.reset(new Gwen::Controls::Label(m_bar.get()));
m_rightStatusBar->SetWidth(width / 2);
//m_rightStatusBar->SetText( L"Label Added to Right" );
m_bar->AddControl(m_rightStatusBar.get(), true);
m_TextOutput.reset(new Gwen::Controls::ListBox(pCanvas.get()));
m_TextOutput->Dock(Gwen::Pos::Bottom);
m_TextOutput->SetHeight(100);
m_leftStatusBar.reset(new Gwen::Controls::Label(m_bar.get()));
//m_leftStatusBar->SetText( L"Label Added to Left" );
m_leftStatusBar->SetWidth(width / 2);
m_bar->AddControl(m_leftStatusBar.get(), false);
//Gwen::KeyboardFocus
/*Gwen::Controls::GroupBox* box = new Gwen::Controls::GroupBox(pCanvas);
box->SetText("text");
box->SetName("name");
box->SetHeight(500);
*/
m_windowRight.reset(new Gwen::Controls::ScrollControl(pCanvas.get()));
m_windowRight->Dock(Gwen::Pos::Right);
m_windowRight->SetWidth(250);
m_windowRight->SetHeight(250);
m_windowRight->SetScroll(false, true);
//windowLeft->SetSkin(
m_tab.reset(new Gwen::Controls::TabControl(m_windowRight.get()));
//tab->SetHeight(300);
m_tab->SetWidth(240);
m_tab->SetHeight(13250);
//tab->Dock(Gwen::Pos::Left);
m_tab->Dock(Gwen::Pos::Fill);
//tab->SetMargin( Gwen::Margin( 2, 2, 2, 2 ) );
Gwen::UnicodeString str1(L"Params");
m_demoPage = m_tab->AddPage(str1);
// Gwen::UnicodeString str2(L"OpenCL");
// tab->AddPage(str2);
//Gwen::UnicodeString str3(L"page3");
// tab->AddPage(str3);
//but->onPress.Add(handler, &MyHander::onButtonA);
//box->Dock(Gwen::Pos::Left);
/*Gwen::Controls::WindowControl* windowBottom = new Gwen::Controls::WindowControl(pCanvas);
windowBottom->SetHeight(100);
windowBottom->Dock(Gwen::Pos::Bottom);
windowBottom->SetTitle("bottom");
*/
// Gwen::Controls::Property::Text* prop = new Gwen::Controls::Property::Text(pCanvas);
//prop->Dock(Gwen::Pos::Bottom);
/*Gwen::Controls::SplitterBar* split = new Gwen::Controls::SplitterBar(pCanvas);
split->Dock(Gwen::Pos::Center);
split->SetHeight(300);
split->SetWidth(300);
*/
/*
*/
Gwen::Controls::ScrollControl* windowLeft = new Gwen::Controls::ScrollControl(pCanvas.get());
windowLeft->Dock(Gwen::Pos::Left);
// windowLeft->SetTitle("title");
windowLeft->SetScroll(false, false);
windowLeft->SetWidth(250);
windowLeft->SetPos(50, 50);
windowLeft->SetHeight(500);
//windowLeft->SetClosable(false);
// windowLeft->SetShouldDrawBackground(true);
windowLeft->SetTabable(true);
Gwen::Controls::TabControl* explorerTab = new Gwen::Controls::TabControl(windowLeft);
//tab->SetHeight(300);
// explorerTab->SetWidth(230);
explorerTab->SetHeight(250);
//tab->Dock(Gwen::Pos::Left);
explorerTab->Dock(Gwen::Pos::Fill);
//m_exampleInfoTextOutput->SetBounds(2, 10, 236, 400);
//windowRight
Gwen::UnicodeString explorerStr1(L"Explorer");
m_explorerPage = explorerTab->AddPage(explorerStr1);
Gwen::UnicodeString shapesStr1(L"Test");
Gwen::Controls::TabButton* shapes = explorerTab->AddPage(shapesStr1);
///todo(erwincoumans) figure out why the HSV color picker is extremely slow
//Gwen::Controls::HSVColorPicker* color = new Gwen::Controls::HSVColorPicker(shapes->GetPage());
Gwen::Controls::ColorPicker* color = new Gwen::Controls::ColorPicker(shapes->GetPage());
color->SetKeyboardInputEnabled(true);
Gwen::Controls::TreeControl* ctrl = new Gwen::Controls::TreeControl(m_explorerPage->GetPage());
m_explorerTreeCtrl = ctrl;
ctrl->SetKeyboardInputEnabled(true);
ctrl->Focus();
ctrl->SetBounds(2, 10, 236, 300);
m_exampleInfoGroupBox = new Gwen::Controls::Label(m_explorerPage->GetPage());
m_exampleInfoGroupBox->SetPos(2, 314);
m_exampleInfoGroupBox->SetHeight(15);
m_exampleInfoGroupBox->SetWidth(234);
m_exampleInfoGroupBox->SetText("Example Description");
m_exampleInfoTextOutput = new Gwen::Controls::ListBox(m_explorerPage->GetPage());
//m_exampleInfoTextOutput->Dock( Gwen::Pos::Bottom );
m_exampleInfoTextOutput->SetPos(2, 332);
m_exampleInfoTextOutput->SetHeight(150);
m_exampleInfoTextOutput->SetWidth(233);
setFocus();
}
GwenInternalData::~GwenInternalData()
{
}
int GwenInternalData::setup(ExampleEntries* gAllExamples, const char* demoNameFromCommandOption,
const std::function<void()>& onB, const std::function<void()>& onD, const std::function<void(int)>& onE)
{
auto tree = m_explorerTreeCtrl;
m_handler2.reset(new MyMenuItemHander(-1, onB, onD, onE));
auto curNode = (Gwen::Controls::TreeNode*)tree;
tree->onReturnKeyDown.Add(m_handler2.get(), &MyMenuItemHander::onButtonD);
int numDemos = gAllExamples->getNumRegisteredExamples();
int selectedDemo = 0;
if (demoNameFromCommandOption)
{
selectedDemo = -1;
}
int firstAvailableDemoIndex = -1;
Gwen::Controls::TreeNode* firstNode = 0;
for (int d = 0; d < numDemos; d++)
{
if (demoNameFromCommandOption)
{
const char* demoName = gAllExamples->getExampleName(d);
int res = strcmp(demoName, demoNameFromCommandOption);
if (res == 0)
{
selectedDemo = d;
}
}
// bool selected = m_gwen->AddDemo(d, gAllExamples->getExampleName(d), gAllExamples->getExampleCreateFunc(d), selectedDemo,
// onB, onD, onE);
bool isSelected = false;
// sprintf(nodeText, "Node %d", i);
Gwen::UnicodeString nodeUText = Gwen::Utility::StringToUnicode(gAllExamples->getExampleName(d));
auto f = gAllExamples->getExampleCreateFunc(d);
if (f) //was test for gAllExamples[d].m_menuLevel==1
{
Gwen::Controls::TreeNode* pNode = curNode->AddNode(nodeUText);
if (!firstNode)
{
firstNode = pNode;
isSelected = true;
}
if (d == selectedDemo)
{
firstNode = pNode;
isSelected = true;
//pNode->SetSelected(true);
//tree->ExpandAll();
// tree->ForceUpdateScrollBars();
//tree->OnKeyLeft(true);
// tree->OnKeyRight(true);
//tree->ExpandAll();
// selectDemo(d);
}
#if 1
std::unique_ptr<MyMenuItemHander> handler;
handler.reset(new MyMenuItemHander(d,
onB,
onD,
onE));
pNode->onNamePress.Add(handler.get(), &MyMenuItemHander::onButtonA);
pNode->GetButton()->onDoubleClick.Add(handler.get(), &MyMenuItemHander::onButtonB);
pNode->GetButton()->onDown.Add(handler.get(), &MyMenuItemHander::onButtonC);
pNode->onSelect.Add(handler.get(), &MyMenuItemHander::onButtonE);
pNode->onReturnKeyDown.Add(handler.get(), &MyMenuItemHander::onButtonG);
pNode->onSelectChange.Add(handler.get(), &MyMenuItemHander::onButtonF);
m_nodeHandlers.push_back(std::move(handler));
#endif
// pNode->onKeyReturn.Add(handler, &MyMenuItemHander::onButtonD);
// pNode->GetButton()->onKeyboardReturn.Add(handler, &MyMenuItemHander::onButtonD);
// pNode->onNamePress.Add(handler, &MyMenuItemHander::onButtonD);
// pNode->onKeyboardPressed.Add(handler, &MyMenuItemHander::onButtonD);
// pNode->OnKeyPress
}
else
{
curNode = tree->AddNode(nodeUText);
}
if (isSelected)
{
firstAvailableDemoIndex = d;
}
}
// if (sCurrentDemo == 0)
{
if (firstAvailableDemoIndex >= 0)
{
// m_gwen->ExpandSelected();
firstNode->SetSelected(true);
while (firstNode != tree)
{
firstNode->ExpandAll();
firstNode = (Gwen::Controls::TreeNode*)firstNode->GetParent();
}
}
}
// btAssert(sCurrentDemo != 0);
// if (sCurrentDemo == 0)
// {
// printf("Error, no demo/example\n");
// exit(0);
// }
return firstAvailableDemoIndex;
}
void GwenInternalData::resize(int width, int height)
{
pCanvas->SetSize(width, height);
}
void GwenInternalData::textOutput(const char* message)
{
Gwen::UnicodeString msg = Gwen::Utility::StringToUnicode(message);
m_TextOutput->AddItem(msg);
m_TextOutput->Scroller()->ScrollToBottom();
}
void GwenInternalData::setExampleDescription(const char* message)
{
//Gwen apparently doesn't have text/word wrap, so do rudimentary brute-force implementation here.
std::string wrapmessage = message;
int startPos = 0;
std::string lastFit = "";
bool hasSpace = false;
std::string lastFitSpace = "";
int spacePos = 0;
m_exampleInfoTextOutput->Clear();
int fixedWidth = m_exampleInfoTextOutput->GetBounds().w - 25;
int wrapLen = int(wrapmessage.length());
for (int endPos = 0; endPos <= wrapLen; endPos++)
{
std::string sub = wrapmessage.substr(startPos, (endPos - startPos));
Gwen::Point pt = pRenderer->MeasureText(pCanvas->GetSkin()->GetDefaultFont(), sub);
if (pt.x <= fixedWidth)
{
lastFit = sub;
if (message[endPos] == ' ' || message[endPos] == '.' || message[endPos] == ',')
{
hasSpace = true;
lastFitSpace = sub;
spacePos = endPos;
}
}
else
{
//submit and
if (hasSpace)
{
endPos = spacePos + 1;
hasSpace = false;
lastFit = lastFitSpace;
startPos = endPos;
}
else
{
startPos = endPos - 1;
}
Gwen::UnicodeString msg = Gwen::Utility::StringToUnicode(lastFit);
m_exampleInfoTextOutput->AddItem(msg);
m_exampleInfoTextOutput->Scroller()->ScrollToBottom();
}
}
if (lastFit.length())
{
Gwen::UnicodeString msg = Gwen::Utility::StringToUnicode(lastFit);
m_exampleInfoTextOutput->AddItem(msg);
m_exampleInfoTextOutput->Scroller()->ScrollToBottom();
}
}
void GwenInternalData::registerFileOpen(const std::function<void()>& callback)
{
m_menuItems->m_fileOpenCallback = callback;
}
void GwenInternalData::registerQuit(const std::function<void()>& callback)
{
m_menuItems->m_quitCallback = callback;
}
void GwenInternalData::forceUpdateScrollBars()
{
b3Assert(m_explorerTreeCtrl);
if (m_explorerTreeCtrl)
{
m_explorerTreeCtrl->ForceUpdateScrollBars();
}
}
void GwenInternalData::setFocus()
{
b3Assert(m_explorerTreeCtrl);
if (m_explorerTreeCtrl)
{
m_explorerTreeCtrl->Focus();
}
}
b3ToggleButtonCallback GwenInternalData::getToggleButtonCallback()
{
return m_toggleButtonCallback;
}
void GwenInternalData::setToggleButtonCallback(b3ToggleButtonCallback callback)
{
m_toggleButtonCallback = callback;
}
void GwenInternalData::registerToggleButton2(int buttonId, const char* name)
{
assert(m_demoPage);
Gwen::Controls::Button* but = new Gwen::Controls::Button(m_demoPage->GetPage());
///some heuristic to find the button location
int ypos = m_curYposition;
but->SetPos(10, ypos);
but->SetWidth(200);
//but->SetBounds( 200, 30, 300, 200 );
std::unique_ptr<MyButtonHander> handler;
handler.reset(new MyButtonHander(this, buttonId));
m_handlers.push_back(std::move(handler));
m_curYposition += 22;
but->onToggle.Add(handler.get(), &MyButtonHander::onButtonA);
but->SetIsToggle(true);
but->SetToggleState(false);
but->SetText(name);
}
void GwenInternalData::setComboBoxCallback(b3ComboBoxCallback callback)
{
m_comboBoxCallback = callback;
}
b3ComboBoxCallback GwenInternalData::getComboBoxCallback()
{
return m_comboBoxCallback;
}
void GwenInternalData::registerComboBox2(int comboboxId, int numItems, const char** items, int startItem)
{
Gwen::Controls::ComboBox* combobox = new Gwen::Controls::ComboBox(m_demoPage->GetPage());
std::unique_ptr<MyComboBoxHander> handler;
handler.reset(new MyComboBoxHander(this, comboboxId));
m_handlers.push_back(std::move(handler));
combobox->onSelection.Add(handler.get(), &MyComboBoxHander::onSelect);
int ypos = m_curYposition;
combobox->SetPos(10, ypos);
combobox->SetWidth(100);
//box->SetPos(120,130);
for (int i = 0; i < numItems; i++)
{
Gwen::Controls::MenuItem* item = combobox->AddItem(Gwen::Utility::StringToUnicode(items[i]));
if (i == startItem)
combobox->OnItemSelected(item);
}
m_curYposition += 22;
}
void GwenInternalData::render(int width, int height)
{
// printf("width = %d, height=%d\n", width,height);
if (pCanvas)
{
pCanvas->SetSize(width, height);
//m_primRenderer->setScreenSize(width,height);
pRenderer->Resize(width, height);
pCanvas->RenderCanvas();
//restoreOpenGLState();
}
}
Common2dCanvasInterface* GwenInternalData::createCommon2dCanvasInterface()
{
return new QuickCanvas(this, m_myTexLoader.get());
}
bool GwenInternalData::onMouseMove(int x, int y)
{
bool handled = false;
static int m_lastmousepos[2] = {0, 0};
static bool isInitialized = false;
if (pCanvas)
{
if (!isInitialized)
{
isInitialized = true;
m_lastmousepos[0] = x + 1;
m_lastmousepos[1] = y + 1;
}
handled = pCanvas->InputMouseMoved(x, y, m_lastmousepos[0], m_lastmousepos[1]);
}
return handled;
}
bool GwenInternalData::onKeyboard(int bulletKey, int state)
{
int gwenKey = -1;
if (pCanvas)
{
//convert 'Bullet' keys into 'Gwen' keys
switch (bulletKey)
{
case B3G_RETURN:
{
gwenKey = Gwen::Key::Return;
break;
}
case B3G_LEFT_ARROW:
{
gwenKey = Gwen::Key::Left;
break;
}
case B3G_RIGHT_ARROW:
{
gwenKey = Gwen::Key::Right;
break;
}
case B3G_UP_ARROW:
{
gwenKey = Gwen::Key::Up;
break;
}
case B3G_DOWN_ARROW:
{
gwenKey = Gwen::Key::Down;
break;
}
case B3G_BACKSPACE:
{
gwenKey = Gwen::Key::Backspace;
break;
}
case B3G_DELETE:
{
gwenKey = Gwen::Key::Delete;
break;
}
case B3G_HOME:
{
gwenKey = Gwen::Key::Home;
break;
}
case B3G_END:
{
gwenKey = Gwen::Key::End;
break;
}
case B3G_SHIFT:
{
gwenKey = Gwen::Key::Shift;
break;
}
case B3G_CONTROL:
{
gwenKey = Gwen::Key::Control;
break;
}
default:
{
}
};
if (gwenKey >= 0)
{
return pCanvas->InputKey(gwenKey, state == 1);
}
else
{
if (bulletKey < 256 && state)
{
Gwen::UnicodeChar c = (Gwen::UnicodeChar)bulletKey;
return pCanvas->InputCharacter(c);
}
}
}
return false;
}
bool GwenInternalData::onMouseButton(int button, int state, int x, int y)
{
bool handled = false;
if (pCanvas)
{
handled = pCanvas->InputMouseMoved(x, y, x, y);
if (button >= 0)
{
handled = pCanvas->InputMouseButton(button, (bool)state);
if (handled)
{
//if (!state)
// return false;
}
}
}
return handled;
}
| 26.826636 | 136 | 0.670804 | [
"render"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.